branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>JMainard/CRAB<file_sep>/CRAB/jeuenregistrement.h #ifndef JEUENREGISTREMENT_H #define JEUENREGISTREMENT_H #include <QSqlQuery> #include <QDebug> #include <QVariant> #include <QString> class jeuEnregistrement : public QSqlQuery { private: bool fin; public: jeuEnregistrement(QString laRequete); void suivant(); bool finReq(); QVariant getValeur(QString nomChamp); void fermer(); }; #endif // JEUENREGISTREMENT_H <file_sep>/CRAB/DOXYGEN/html/search/functions_9.js var searchData= [ ['technicien',['Technicien',['../class_technicien.html#a2b13414c79a7a4f040522c34e0fd0aa6',1,'Technicien']]] ]; <file_sep>/CRAB/DOXYGEN/html/class_maintenance.js var class_maintenance = [ [ "Maintenance", "class_maintenance.html#a8b51c17cc3e17405ce39fb2ec973df99", null ], [ "affecterVisites", "class_maintenance.html#a1f6bef0a1a529beeaea5ab622f473782", null ], [ "afficherTout", "class_maintenance.html#a68a453b1f48630a776c1f1b6605dd707", null ], [ "reviser", "class_maintenance.html#a626bf6af87da611c75d0d83d1630dac1", null ] ];<file_sep>/CRAB/passerelle.cpp #include "passerelle.h" #include"jeuenregistrement.h" #include <QDebug> Passerelle::Passerelle() { } /// /// \brief Passerelle::chargerLesTechniciens /// \return Charge les techniciens dans un vecteur /// QVector<Technicien*> Passerelle::chargerLesTechniciens() { qDebug() << "ChargerLesTechniciens"; QVector <Technicien*> lesTechniciens; QString requeteSQl = "select techNum,techNom,techPrenom from technicien;"; jeuEnregistrement rechTechniciens (requeteSQl); while(!rechTechniciens.finReq()){ int matriculeTech = rechTechniciens.getValeur("techNum").toInt(); QString nomTech = rechTechniciens.getValeur("techNom").toString(); QString prenomTech = rechTechniciens.getValeur("techPrenom").toString(); lesTechniciens.push_back(new Technicien(matriculeTech,nomTech,prenomTech)); rechTechniciens.suivant(); } qDebug() << "nb De techniciens " <<lesTechniciens.size(); return (lesTechniciens); } /// /// \brief Passerelle::chargerLesBornes /// \return charges les bornes des stations dans un vecteur /// QVector<Borne> Passerelle::chargerLesBornes( int unIdStation) { qDebug() << "Charger LesBornes"; QVector <Borne> lesBornes; QString reqSQLBornes="select borneNum,borneDerniereRevision,borneIndiceCompteurUnite, typeBorne.typeBorneCode,dureeRevision,nbJoursEntreRevision,nbUnitesEntreRevision"; reqSQLBornes+=" from borne inner join station on borne.statNum=station.statNum inner join typeBorne on typeBorne.typeBorneCode= borne.typeBorneCode"; reqSQLBornes+=" where station.statNum="+QString::number(unIdStation)+";"; qDebug()<<reqSQLBornes; jeuEnregistrement rechBorne (reqSQLBornes); while(!rechBorne.finReq()){ int numBorne = rechBorne.getValeur("borneNum").toInt(); QDate derniereRevision = rechBorne.getValeur("borneIndiceCompteurUnite").toDate(); Date derniereRevisionDate(derniereRevision.year(), derniereRevision.month(), derniereRevision.day()); int indiceCompteur = rechBorne.getValeur("borneIndiceCompteurUnite").toInt(); QString codeTypeBorne = rechBorne.getValeur("typeBorneCode").toString(); int dureeRevision = rechBorne.getValeur("dureeRevision").toInt(); int nbJoursEntreRevision = rechBorne.getValeur("nbJoursEntreRevision").toInt(); int nbUnitesEntreRevision = rechBorne.getValeur("nbUnitesEntreRevision").toInt(); TypeBorne leType (codeTypeBorne,dureeRevision,nbJoursEntreRevision,nbUnitesEntreRevision); Borne borneInfos (numBorne,derniereRevisionDate,indiceCompteur,leType); lesBornes.push_back(borneInfos); rechBorne.suivant(); } return(lesBornes); } /// /// \brief Passerelle::chargerLesStations /// \return charge les sations de la bdd /// QVector<Station> Passerelle::chargerLesStations() { QVector <Station> lesStations; QString requeteSQLStation="select statNum,statRue from station;"; qDebug() << "select statNum,statRue from station;"; jeuEnregistrement rechStation (requeteSQLStation); while(!rechStation.finReq()){ int numStat = rechStation.getValeur("statNum").toInt(); QString rueStat = rechStation.getValeur("statRue").toString(); QVector<Borne> lesBornes = chargerLesBornes(numStat); Station stationInfos(numStat,rueStat,lesBornes); lesStations.push_back(stationInfos); rechStation.suivant(); } qDebug () << "nb De Station" << lesStations.size(); return(lesStations); } /// /// \brief Passerelle::enregistrerVisite /// \param uneVisite : Vecteur des visites du technicien /// \param matLeTechnicien : Matricule du technicien /// \param compteurVisiteId : Id Visite /// Implémente les visites dans la bdd et créer un ID et les relie a techniciens et Bornes. /// void Passerelle::enregistrerVisite(visite uneVisite, int matLeTechnicien, qint64 compteurVisiteId) { QString requeteEnregistrerVisite = " insert into visite values ("uneVisite."; } <file_sep>/CRAB/main.cpp #include "mainwindow.h" #include <QApplication> #include <QSqlDatabase> #include "maintenance.h" #include <QDebug> int main(int argc, char *argv[]) { QApplication a(argc, argv); /// /// \brief maBase /// Configuration et ouverture à la base SQL pour pouvoir récuperer les informations QSqlDatabase maBase = QSqlDatabase::addDatabase("QMYSQL"); maBase.setHostName("localhost"); maBase.setDatabaseName("CRAB"); maBase.setUserName("jeremy"); maBase.setPassword("<PASSWORD>"); bool bddOk = maBase.open(); if (bddOk) { Maintenance laMaintenance; qDebug() << "On passe a afficher tout()"; laMaintenance.afficherTout(); //return a.exec(); On a pas le besoin d'afficher l'interface graphique return 0; } else{ return 1 ; } } <file_sep>/CRAB/DOXYGEN/html/search/classes_6.js var searchData= [ ['technicien',['Technicien',['../class_technicien.html',1,'']]], ['typeborne',['TypeBorne',['../class_type_borne.html',1,'']]] ]; <file_sep>/CRAB/station.cpp #include "station.h" #include <QDebug> Station::Station() { } Station::Station(int unIdStation, QString unLibelleEmplacement, QVector<Borne> unVecteurBorne) { idStation=unIdStation; libelleEmplacement=unLibelleEmplacement; lesBornes=unVecteurBorne; //Doit appeler la fonction de passerelle avec les info de borne et de type Bornes en fonction de l'id de la station } /// /// \brief Station::getId /// \return retourne l'identifiant de la station /// Fonctions retournant l'identifiant de la Station en int int Station::getId() { return(idStation); } /// /// \brief Station::getLibelleEmplacement /// \return retourne le libellé de l'emplacement /// Fonctions retournant les informations des Emplacements des Stations QString Station::getLibelleEmplacement() { return(libelleEmplacement); } /// /// \brief Station::getVisiteAFaire /// \return retourne une instance de classe Visite /// retourne une instance de classe Visite recensant toutes les bornes de la station /// qui nécessitent d'être révisées, ou null s'il n'y a aucune borne à réviser /// visite* Station::getVisiteAFaire() { qDebug() << "Je passe getVisiteAFaire"; QVector <Borne> lesBornesAReviser; for(int numBorne=0; numBorne<lesBornes.size(); numBorne++) { if(lesBornes[numBorne].estAReviser()==true){ lesBornesAReviser.push_back(lesBornes[numBorne]); } } if(lesBornesAReviser.size() !=0) { //Doit donc renvoyer un vecteur et une variable de Station return(new visite(lesBornesAReviser, this)); } else { return(NULL); } } <file_sep>/CRAB/borne.h #ifndef BORNE_H #define BORNE_H #include "typeborne.h" #include "date.h" /// /// \brief The Borne class /// Permet de connaitre les bornes à réviser et leur durée class Borne { private: /// /// \brief idBorne /// identifiant de la borne /// int idBorne; /// /// \brief dateDerniereRevision /// date de la dernière révision effectuée sur la borne Date dateDerniereRevision; /// /// \brief indiceCompteurUnites /// nombre d'unités de recharge délivrées depuis la dernière révision, /// ce compteur étant remis à zéro suite à chaque révision int indiceCompteurUnites; /// /// \brief leType /// type de la borne TypeBorne leType; public: Borne(); Borne(int unIdBorne, Date uneDateDerniereRevision, int unIndiceCompteurUnites, TypeBorne unType); int getDureeRevision(); // retourne la durée en minutes requise pour réaliser la révision sur la borne, // cette durée étant fonction du type de la borne bool estAReviser(); }; #endif // BORNE_H <file_sep>/CRAB/maintenance.cpp #include "maintenance.h" #include <QDebug> /// /// \brief Maintenance::Maintenance /// Constructeur permettant de créer des vecteur qui ne sont plus vide afin de les utiliser dans les 2 porchaines procédures /// Maintenance::Maintenance() { lesStations=Passerelle::chargerLesStations(); lesTechniciens=Passerelle::chargerLesTechniciens(); reviser(); affecterVisites(); } /// /// \brief Maintenance::reviser /// Procédure permettant d'établir l'ensemble des visites à réaliser sur les stations void Maintenance::reviser() { qDebug() << "reviser() je passe"; for (int noStation=0; noStation<lesStations.size(); noStation++) { if (lesStations[noStation].getVisiteAFaire()!=NULL) { lesVisites.push_back(lesStations[noStation].getVisiteAFaire()); } } } /// /// \brief Maintenance::affecterVisites /// Affecte les visites à réaliser aux techniciens, en répartissant équitablement le travail /// entre les techniciens. Chaque visite est affectée au technicien le moins occupé en temps /// total de maintenance préventive. L'état de chaque visite doit alors être mis à jour. /// void Maintenance::affecterVisites() { qDebug() << "affecterVisite je passe"; qint64 idVisite = QDateTime::currentDateTime().toTime_t(); qDebug() << idVisite; for ( int noVisite=0; noVisite<lesVisites.size(); noVisite++) { qDebug() << "Crash ?"; qDebug() << "noVisite" << noVisite; int tempTech=lesTechniciens[0]->getTempsOccupe(); qDebug()<< "eho"; Technicien* TechMoinsOccuper = lesTechniciens[0]; qDebug() << "Toujours pas crash"; for ( int noTechnicien=1; noTechnicien<lesTechniciens.size(); noTechnicien++) { if (lesTechniciens[noTechnicien]->getTempsOccupe()<tempTech) { qDebug() << "no Technicien" << noTechnicien; TechMoinsOccuper = lesTechniciens[noTechnicien]; tempTech = lesTechniciens[noTechnicien]->getTempsOccupe(); } } TechMoinsOccuper->affecterVisite(lesVisites[noVisite]); Passerelle::enregistrerVisite(lesVisites[noVisite],TechMoinsOccuper->getMatricule(),idVisite); idVisite++; } } /** * @brief Maintenance::afficherTout */ void Maintenance::afficherTout() { for (int i = 0 ; i<lesTechniciens.size() ; i++) { qDebug()<<lesTechniciens[i]->getInfo(); } } <file_sep>/CRAB/DOXYGEN/html/search/functions_0.js var searchData= [ ['affectervisite',['affecterVisite',['../class_technicien.html#ae214082b07ffa459ebfb99e9efd4da20',1,'Technicien']]], ['affectervisites',['affecterVisites',['../class_maintenance.html#a1f6bef0a1a529beeaea5ab622f473782',1,'Maintenance']]], ['affichertout',['afficherTout',['../class_maintenance.html#a68a453b1f48630a776c1f1b6605dd707',1,'Maintenance']]], ['aujourdhui',['aujourdhui',['../class_date.html#a4712c0d9ecfeb49472a847a905f62150',1,'Date']]] ]; <file_sep>/CRAB/DOXYGEN/html/hierarchy.js var hierarchy = [ [ "Borne", "class_borne.html", null ], [ "Maintenance", "class_maintenance.html", null ], [ "Passerelle", "class_passerelle.html", null ], [ "QDate", null, [ [ "Date", "class_date.html", null ] ] ], [ "QMainWindow", null, [ [ "MainWindow", "class_main_window.html", null ] ] ], [ "QSqlQuery", null, [ [ "jeuEnregistrement", "classjeu_enregistrement.html", null ] ] ], [ "Station", "class_station.html", null ], [ "Technicien", "class_technicien.html", null ], [ "TypeBorne", "class_type_borne.html", null ], [ "visite", "classvisite.html", null ] ];<file_sep>/CRAB/visite.h #ifndef VISITE_H #define VISITE_H #include "station.h" #include <QVector> class Station; /// /// \brief The visite class /// Permet de référencé les visites à réaliser à partir de la base de données. class visite { private: char etat; int dureeTotale; Station* laStation; QVector <Borne> lesBornes; public: visite(); visite(QVector<Borne> lesBornesAVisiter, Station* uneStation); int getDureeTotale(); char getEtat(); void changerEtat(); QString getInfoVisite(); }; #endif // VISITE_H <file_sep>/CRAB/station.h #ifndef STATION_H #define STATION_H #include <QString> #include <QVector> #include "borne.h" #include "visite.h" class visite; /// /// \brief The Station class ///Permet de savoir dans qu'elle sation il faut faire de la maintenance class Station { private: int idStation; QString libelleEmplacement; QVector <Borne> lesBornes; public: Station(); Station(int unIdStation, QString unLibelleEmplacement, QVector<Borne> unVecteurBorne); int getId(); QString getLibelleEmplacement(); visite *getVisiteAFaire(); }; #endif // STATION_H <file_sep>/CRAB/DOXYGEN/html/classjeu_enregistrement.js var classjeu_enregistrement = [ [ "jeuEnregistrement", "classjeu_enregistrement.html#a941dbc3f9dd9c1c196ead81d045850bf", null ], [ "fermer", "classjeu_enregistrement.html#adee0dc84769c49230dbd6b32ec0bd946", null ], [ "finReq", "classjeu_enregistrement.html#ad4689ab49e4a51fde86e3b00e15e473e", null ], [ "getValeur", "classjeu_enregistrement.html#acd8e0e1bc08d6b1a5c5966d565e134a2", null ], [ "suivant", "classjeu_enregistrement.html#aa26dd78c24b4fbaec948380d8907d4d9", null ] ];<file_sep>/CRAB/DOXYGEN/html/class_borne.js var class_borne = [ [ "Borne", "class_borne.html#af74c409e55758db3254bf58c49dd9737", null ], [ "Borne", "class_borne.html#aba0be924c6cb39fe8cdeffe27407fc3f", null ], [ "estAReviser", "class_borne.html#a40c1a1a990a10b8bc1421a1a39b7300a", null ], [ "getDureeRevision", "class_borne.html#aba8f90c81ef4efbe239e67e12015bb44", null ] ];<file_sep>/CRAB/jeuenregistrement.cpp #include "jeuenregistrement.h" jeuEnregistrement::jeuEnregistrement(QString laRequete) :QSqlQuery(laRequete) { fin =!first(); //Retourne false ou true } /** * @brief jeuEnregistrement::suivant * Avance le curseur sur l'enregistrement suivant */ void jeuEnregistrement::suivant() { fin =! next(); //Vas savoir si il y a d'autre donnée après en retourant false ou true } /** * @brief jeuEnregistrement::finReq * @return Un bool false or true si la requête est finie ou non */ bool jeuEnregistrement::finReq() { return(fin); } /** * @brief jeuEnregistrement::getValeur * @param nomChamp variable de SQL * @return la valeur correspondant a nomChamp */ QVariant jeuEnregistrement::getValeur(QString nomChamp) { return (value(nomChamp)); } /** * @brief jeuEnregistrement::fermer * Ferme le curseur et libère les ressources. */ void jeuEnregistrement::fermer() { finish(); } <file_sep>/CRAB/DOXYGEN/html/annotated_dup.js var annotated_dup = [ [ "Borne", "class_borne.html", "class_borne" ], [ "Date", "class_date.html", "class_date" ], [ "jeuEnregistrement", "classjeu_enregistrement.html", "classjeu_enregistrement" ], [ "Maintenance", "class_maintenance.html", "class_maintenance" ], [ "MainWindow", "class_main_window.html", "class_main_window" ], [ "Passerelle", "class_passerelle.html", "class_passerelle" ], [ "Station", "class_station.html", "class_station" ], [ "Technicien", "class_technicien.html", "class_technicien" ], [ "TypeBorne", "class_type_borne.html", "class_type_borne" ], [ "visite", "classvisite.html", "classvisite" ] ];<file_sep>/CRAB/technicien.cpp #include "technicien.h" Technicien::Technicien() { } /// /// \brief Technicien::Technicien /// \param unNom le nom du technicien /// \param unPrenom le prenom du technicien /// Constructeur permettant affecter des vistes au technicien pour le vecteur lesVisites Technicien::Technicien(int unMatricule,QString unNom, QString unPrenom) { matricule=unMatricule; nom=unNom; prenom=unPrenom; } /// /// \brief Technicien::getTempsOccupe /// \return Retourne la durée totale en minutes des visites affectées au technicien /// int Technicien::getTempsOccupe() { int temps=0; //On recupère le vector visite pour ensuite additionner le temp total for (int noVisite=0; noVisite<lesVisites.size(); noVisite++) { //On doit recupérer les temps de chaque intervention temps+= lesVisites[noVisite]->getDureeTotale(); } return(temps); } /// /// \brief Technicien::affecterVisite /// \param uneVisite pointeur de visite afin de determiner de quelle visite on parle /// ajoute la visite uneVisite dans les visites affectées au technicien void Technicien::affecterVisite(visite *uneVisite) { lesVisites.push_back(uneVisite); } /// /// \brief Technicien::getLesVisites /// \return retourne l'ensemble des visites affectées au technicien /// Permet de savoir quel technicien a quel visites de programmé QVector<visite*> Technicien::getLesVisites() { return(lesVisites); } QString Technicien::getInfo() { QString info = "Matricule : "+QString::number(matricule)+" \n" +"Nom : "+nom+"\n" +"Prenom : "+prenom+"\n" +"Temps occupé : "+QString::number(getTempsOccupe()) +"PROCHAINE VISITES : "; for(int i = 0 ; i<lesVisites.size() ; i++) { info+= lesVisites[i]->getInfoVisite()+"\n"; } return info; } int Technicien::getMatricule() { return(matricule); } <file_sep>/CRAB/maintenance.h #ifndef MAINTENANCE_H #define MAINTENANCE_H #include <QVector> #include "passerelle.h" #include <QDebug> /// /// \brief The Maintenance class /// Permet d'affecter chaque maintenance à faire à des techniciens class Maintenance { private: QVector <Station> lesStations; QVector <Technicien*> lesTechniciens; QVector <visite*> lesVisites; public: Maintenance(); void reviser(); void affecterVisites(); void afficherTout(); }; #endif // MAINTENANCE_H <file_sep>/CRAB/DOXYGEN/html/class_technicien.js var class_technicien = [ [ "Technicien", "class_technicien.html#a1d6b9adf3ef9e61ad5dd8d2c17040cbc", null ], [ "Technicien", "class_technicien.html#a2b13414c79a7a4f040522c34e0fd0aa6", null ], [ "affecterVisite", "class_technicien.html#ae214082b07ffa459ebfb99e9efd4da20", null ], [ "getInfo", "class_technicien.html#a82c56619d7835292c0cfe48ceb05fa21", null ], [ "getLesVisites", "class_technicien.html#a8ad18bf2c5758dbb6261594c544e47f9", null ], [ "getMatricule", "class_technicien.html#a6fe07be5429f9239023e4a8f551505ad", null ], [ "getTempsOccupe", "class_technicien.html#af111a0a23ae6ce1dbcb552817266744e", null ] ];<file_sep>/CRAB/DOXYGEN/html/class_date.js var class_date = [ [ "Date", "class_date.html#a4e59ed4ba66eec61c27460c5d09fa1bd", null ], [ "Date", "class_date.html#a2e0c4707435a4c3390e138b9ac6ee3f5", null ], [ "difference", "class_date.html#a45f1086b5028cdc71f7645f0a91d7731", null ], [ "getAnnee", "class_date.html#a99c5677274bdaffadaedad4c888ccbca", null ], [ "getJour", "class_date.html#a961e64bff2fdff7ee95bc335ca400d2f", null ], [ "getMois", "class_date.html#a6b16211abaa2c22418e82b8cd9d08bfe", null ] ];<file_sep>/CRAB/DOXYGEN/html/class_station.js var class_station = [ [ "Station", "class_station.html#a73d335726aad1d844d81cda6d9fd74e6", null ], [ "Station", "class_station.html#ab3ce87c57bdf6c30fa057764a195c4a3", null ], [ "getId", "class_station.html#a55b1b6e24c949165ca96d038125b72a6", null ], [ "getLibelleEmplacement", "class_station.html#a6d4fa8bd0c2afa28aae831cd04938394", null ], [ "getVisiteAFaire", "class_station.html#a0f0c47ed8e52e6d506c50512b915049a", null ] ];<file_sep>/CRAB/DOXYGEN/html/search/functions_7.js var searchData= [ ['reviser',['reviser',['../class_maintenance.html#a626bf6af87da611c75d0d83d1630dac1',1,'Maintenance']]] ]; <file_sep>/CRAB/date.h #ifndef DATE_H #define DATE_H #include <QDate> /// /// \brief The Date class /// Permet de savoir la date afin de vérifier si il y aura besoin de maintenance ou non class Date : public QDate { private: int annee; int mois; int jour; public: Date(); Date(int uneAnne, int unMois, int unJour); static Date aujourdhui(); int getAnnee(); int getMois(); int getJour(); int difference(Date uneDate); }; #endif // DATE_H <file_sep>/CRAB/DOXYGEN/html/search/all_8.js var searchData= [ ['maintenance',['Maintenance',['../class_maintenance.html',1,'Maintenance'],['../class_maintenance.html#a8b51c17cc3e17405ce39fb2ec973df99',1,'Maintenance::Maintenance()']]], ['mainwindow',['MainWindow',['../class_main_window.html',1,'']]] ]; <file_sep>/CRAB/visite.cpp #include "visite.h" visite::visite() { } /// /// \brief visite::visite /// \param lesBornesAVisiter vecteur recensant les bornes à visiter /// \param uneStation station sur lesquelle le vetuer ce base pour savoir quelle borne est à visiter /// ce constructeur valorise tous les attributs privés de la classe Visite, y compris l'état et la /// durée totale de la visite /// visite::visite(QVector<Borne> lesBornesAVisiter, Station *uneStation) { // ce constructeur valorise tous les attributs privés de la classe Visite, y compris l'état et la // durée totale de la visite lesBornes=lesBornesAVisiter; laStation=uneStation; dureeTotale=0; for (int i=0;i<lesBornesAVisiter.size();i++){ dureeTotale+=lesBornesAVisiter[i].getDureeRevision(); } } /// /// \brief visite::getDureeTotale /// \return /// Fonction retournant la durée totale en minutes requise pour réaliser l'ensemble /// des révisions prévues sur les bornes de la station int visite::getDureeTotale() { return(dureeTotale); } /// /// \brief visite::getEtat /// \return retourne l'état de la visite /// Soit il retourne si oui ou non la visite à était fait char visite::getEtat() { return(etat); } /// /// \brief visite::changerEtat /// Procédure modifiant l'état de la visite, de 'p' programmée à 'a' affectée, ou de 'a' affectée à 'r' réalisé void visite::changerEtat() { // modifie l'état de la visite, de 'p' programmée à 'a' affectée, ou de 'a' affectée à 'r' réalisée if (etat=='a') { etat='r'; } if(etat=='p') { etat='a'; } } /** * @brief Visite::getInfo Fonction qui renvoie les informations d'une visite * @return Chaine(QString) : information au format texte de la visite (Etat,Durée,Station) */ QString visite::getInfoVisite() { QString info = "Etat : \n Durée : "+QString::number(dureeTotale)+"\n Station : " +laStation->getLibelleEmplacement(); return info; } <file_sep>/CRAB/passerelle.h #ifndef PASSERELLE_H #define PASSERELLE_H #include <QVector> #include <QString> #include <QSqlQuery> #include "technicien.h" #include "borne.h" #include "typeborne.h" #include "station.h" /// /// \brief The Passerelle class /// Permet d'effectuer toutes les requêtes sql. class Passerelle { public: Passerelle(); static QVector <Technicien*> chargerLesTechniciens(); static QVector <Borne> chargerLesBornes(int unIdStation); static QVector <Station> chargerLesStations(); static void enregistrerVisite(visite uneVisite, int matLeTechnicien, qint64 compteurVisiteId); }; #endif // PASSERELLE_H <file_sep>/CRAB/typeborne.h #ifndef TYPEBORNE_H #define TYPEBORNE_H #include <QString> /// /// \brief The TypeBorne class /// Permet de référence les type de borne stocké dand la bdd class TypeBorne { private: QString codeTypeBorne; int dureeRevision; int nbJoursEntreRevisions; int nbUnitesEntreRevisions; public: TypeBorne(); TypeBorne(QString unCodeTypeBorne, int uneDureeRevision, int unNbJoursEntreRevisions, int unNbUniteEntreRevisions); int getDureeRevision(); int getNbJoursEntreRevisions(); int getNbUnitesEntreRevisions(); }; #endif // TYPEBORNE_H <file_sep>/CRAB/date.cpp #include "date.h" Date::Date() { } /// /// \brief Date::Date /// \param uneAnne /// \param unMois /// \param unJour /// Constructeur permettant de récuperer la Date du jour /// Date::Date(int uneAnne, int unMois, int unJour) : QDate(uneAnne,unMois,unJour) { annee=uneAnne; mois=unMois; jour=unJour; } /// /// \brief Date::aujourdhui /// \return Retourne la date du jour /// Retourne la date du jour grace à la fonction QDate sous forme YY-MM-DDDD Date Date::aujourdhui() { return(Date(QDate::currentDate().year(),QDate::currentDate().month(),QDate::currentDate().day())); } /// /// \brief Date::getAnnee /// \return Retourne une variable int qui représente une année /// int Date::getAnnee() { return(annee); } /// /// \brief Date::getMois /// \return Retourne une variable int qui représente un Mois /// int Date::getMois() { return(mois); } /// /// \brief Date::getJour /// \return Retourne une variable int qui représente un Jour /// int Date::getJour() { return(jour); } /// /// \brief Date::difference /// \param uneDate représente la date de la dernière revision de la borne /// \return retourne un int pour avoir une différence entre 2 jour /// Fonction permettant de savoir combien de jour /mois /année il y a de différence entre 2 date date à rentrer et uneDate (Date de révision ici) /// int Date::difference(Date uneDate) { return(-daysTo(uneDate)); } <file_sep>/CRAB/borne.cpp #include "borne.h" Borne::Borne() { } Borne::Borne(int unIdBorne, Date uneDateDerniereRevision, int unIndiceCompteurUnites, TypeBorne unType) { idBorne=unIdBorne; dateDerniereRevision=uneDateDerniereRevision; indiceCompteurUnites=unIndiceCompteurUnites; leType=unType; } /// /// \brief Borne::getDureeRevision /// \return retourne un int indiquant la durée de revision /// Procédure retournant la durée en minutes requise pour réaliser la révision sur la borne, /// cette durée étant fonction du type de la borne /// int Borne::getDureeRevision() { return(leType.getDureeRevision()); } /// /// \brief Borne::estAReviser /// \return retourne si oui ou non la borne est à réviser /// Procédure permettant de savoir par un bool si la borne doit etre réviser en fonction du nombre de jour ou de ce qu'il y a eu de consommée en WATTS. /// bool Borne::estAReviser() { // retourne vrai lorsque la borne doit être révisée, soit parce que le temps qui sépare // deux révisions pour ce type de borne s'est écoulé depuis la date de la dernière révision, // soit parce que le nombre d'unités de recharge délivrées par la borne // depuis la dernière révision a atteint le seuil établi pour ce type de borne ; // retourne faux sinon //On fait Date::puis le nom de la fonction car aujourdhui() est static if (Date::aujourdhui().difference(dateDerniereRevision)>leType.getNbJoursEntreRevisions()|| indiceCompteurUnites-leType.getNbUnitesEntreRevisions()<0) { //Alors il faut effectuer une revision return(true); } else{ return(false); } } <file_sep>/CRAB/typeborne.cpp #include "typeborne.h" TypeBorne::TypeBorne() { } TypeBorne::TypeBorne(QString unCodeTypeBorne, int uneDureeRevision, int unNbJoursEntreRevisions, int unNbUniteEntreRevisions) { codeTypeBorne=unCodeTypeBorne; dureeRevision=uneDureeRevision; nbJoursEntreRevisions=unNbJoursEntreRevisions; nbUnitesEntreRevisions=unNbUniteEntreRevisions; } /// /// \brief TypeBorne::getDureeRevision /// \return un int qui correspond à la durée standard de révision d'une borne de ce type /// Retourne la durée en minutes requise pour réaliser la révision sur les bornes de ce type int TypeBorne::getDureeRevision() { return(dureeRevision); } /// /// \brief TypeBorne::getNbJoursEntreRevisions /// \return un int du nb de jour qu'il faut entre 2 révisions /// retourne le nombre de jours au-delà duquel il faut envisager une révision /// sur les bornes de ce type /// int TypeBorne::getNbJoursEntreRevisions() { return(nbJoursEntreRevisions); } /// /// \brief TypeBorne::getNbUnitesEntreRevisions /// \return /// Retourne le nombre d'unités de recharge au-delà duquel il faut envisager une révision /// sur les bornes de ce type /// int TypeBorne::getNbUnitesEntreRevisions() { return(nbUnitesEntreRevisions); } <file_sep>/CRAB/DOXYGEN/html/search/all_c.js var searchData= [ ['technicien',['Technicien',['../class_technicien.html',1,'Technicien'],['../class_technicien.html#a2b13414c79a7a4f040522c34e0fd0aa6',1,'Technicien::Technicien()']]], ['typeborne',['TypeBorne',['../class_type_borne.html',1,'']]] ]; <file_sep>/CRAB/DOXYGEN/html/search/functions_6.js var searchData= [ ['maintenance',['Maintenance',['../class_maintenance.html#a8b51c17cc3e17405ce39fb2ec973df99',1,'Maintenance']]] ]; <file_sep>/CRAB/DOXYGEN/html/search/classes_3.js var searchData= [ ['maintenance',['Maintenance',['../class_maintenance.html',1,'']]], ['mainwindow',['MainWindow',['../class_main_window.html',1,'']]] ]; <file_sep>/CRAB/DOXYGEN/html/navtreeindex0.js var NAVTREEINDEX0 = { "annotated.html":[1,0], "borne_8h_source.html":[2,0,0], "class_borne.html":[1,0,0], "class_borne.html#a40c1a1a990a10b8bc1421a1a39b7300a":[1,0,0,2], "class_borne.html#aba0be924c6cb39fe8cdeffe27407fc3f":[1,0,0,1], "class_borne.html#aba8f90c81ef4efbe239e67e12015bb44":[1,0,0,3], "class_borne.html#af74c409e55758db3254bf58c49dd9737":[1,0,0,0], "class_date.html":[1,0,1], "class_date.html#a2e0c4707435a4c3390e138b9ac6ee3f5":[1,0,1,1], "class_date.html#a45f1086b5028cdc71f7645f0a91d7731":[1,0,1,2], "class_date.html#a4e59ed4ba66eec61c27460c5d09fa1bd":[1,0,1,0], "class_date.html#a6b16211abaa2c22418e82b8cd9d08bfe":[1,0,1,5], "class_date.html#a961e64bff2fdff7ee95bc335ca400d2f":[1,0,1,4], "class_date.html#a99c5677274bdaffadaedad4c888ccbca":[1,0,1,3], "class_main_window.html":[1,0,4], "class_main_window.html#a8b244be8b7b7db1b08de2a2acb9409db":[1,0,4,0], "class_main_window.html#ae98d00a93bc118200eeef9f9bba1dba7":[1,0,4,1], "class_maintenance.html":[1,0,3], "class_maintenance.html#a1f6bef0a1a529beeaea5ab622f473782":[1,0,3,1], "class_maintenance.html#a626bf6af87da611c75d0d83d1630dac1":[1,0,3,3], "class_maintenance.html#a68a453b1f48630a776c1f1b6605dd707":[1,0,3,2], "class_maintenance.html#a8b51c17cc3e17405ce39fb2ec973df99":[1,0,3,0], "class_passerelle.html":[1,0,5], "class_passerelle.html#ab70aa7f8273e11735416362091d6c5f4":[1,0,5,0], "class_station.html":[1,0,6], "class_station.html#a0f0c47ed8e52e6d506c50512b915049a":[1,0,6,4], "class_station.html#a55b1b6e24c949165ca96d038125b72a6":[1,0,6,2], "class_station.html#a6d4fa8bd0c2afa28aae831cd04938394":[1,0,6,3], "class_station.html#a73d335726aad1d844d81cda6d9fd74e6":[1,0,6,0], "class_station.html#ab3ce87c57bdf6c30fa057764a195c4a3":[1,0,6,1], "class_technicien.html":[1,0,7], "class_technicien.html#a1d6b9adf3ef9e61ad5dd8d2c17040cbc":[1,0,7,0], "class_technicien.html#a2b13414c79a7a4f040522c34e0fd0aa6":[1,0,7,1], "class_technicien.html#a6fe07be5429f9239023e4a8f551505ad":[1,0,7,5], "class_technicien.html#a82c56619d7835292c0cfe48ceb05fa21":[1,0,7,3], "class_technicien.html#a8ad18bf2c5758dbb6261594c544e47f9":[1,0,7,4], "class_technicien.html#ae214082b07ffa459ebfb99e9efd4da20":[1,0,7,2], "class_technicien.html#af111a0a23ae6ce1dbcb552817266744e":[1,0,7,6], "class_type_borne.html":[1,0,8], "class_type_borne.html#a32f9c836b0f0b34e86a53520a8f23674":[1,0,8,1], "class_type_borne.html#a4921b40e0c20ec1c98ea167cb787e605":[1,0,8,3], "class_type_borne.html#a6b327edc5640195ed7026777da66d8f4":[1,0,8,0], "class_type_borne.html#aa99a6c098973997a77699bea1244a94f":[1,0,8,4], "class_type_borne.html#aee58fc4a65b54cf00376c72df39ac0d9":[1,0,8,2], "classes.html":[1,1], "classjeu_enregistrement.html":[1,0,2], "classjeu_enregistrement.html#a941dbc3f9dd9c1c196ead81d045850bf":[1,0,2,0], "classjeu_enregistrement.html#aa26dd78c24b4fbaec948380d8907d4d9":[1,0,2,4], "classjeu_enregistrement.html#acd8e0e1bc08d6b1a5c5966d565e134a2":[1,0,2,3], "classjeu_enregistrement.html#ad4689ab49e4a51fde86e3b00e15e473e":[1,0,2,2], "classjeu_enregistrement.html#adee0dc84769c49230dbd6b32ec0bd946":[1,0,2,1], "classvisite.html":[1,0,9], "classvisite.html#a197936c1244f7c9fd0a2eca7038533f9":[1,0,9,1], "classvisite.html#a608738dbddc358c0805228e0aac5818c":[1,0,9,3], "classvisite.html#a6da950d2a01048158c7abcc1ebdfec22":[1,0,9,4], "classvisite.html#a731243b15c082ddff3294c09524c39e4":[1,0,9,2], "classvisite.html#a7a948dd8b5c805a1f2a7d62c9268cb97":[1,0,9,5], "classvisite.html#aa6c0954118b1abfd819ae996767fd5d2":[1,0,9,0], "date_8h_source.html":[2,0,1], "files.html":[2,0], "functions.html":[1,3,0], "functions_func.html":[1,3,1], "hierarchy.html":[1,2], "index.html":[], "jeuenregistrement_8h_source.html":[2,0,2], "maintenance_8h_source.html":[2,0,3], "mainwindow_8h_source.html":[2,0,4], "namespace_ui.html":[0,0,0], "namespaces.html":[0,0], "pages.html":[], "passerelle_8h_source.html":[2,0,5], "station_8h_source.html":[2,0,6], "technicien_8h_source.html":[2,0,7], "typeborne_8h_source.html":[2,0,8], "visite_8h_source.html":[2,0,9] }; <file_sep>/CRAB/DOXYGEN/html/search/all_b.js var searchData= [ ['station',['Station',['../class_station.html',1,'']]], ['suivant',['suivant',['../classjeu_enregistrement.html#aa26dd78c24b4fbaec948380d8907d4d9',1,'jeuEnregistrement']]] ]; <file_sep>/CRAB/CRAB_Base/crab_data.sql -- Jeux d'essais Projet CRAB -- Creer le 20-11-2019 par J.Mainard insert into station values (1,'1 Rue carnot',82.5,41.268,'2018-05-19','2019-11-14'), (2,'34 rue jacqueline Auriol',40.5,4.2,'2018-10-19','2019-11-05'), (3,'3 rue du Marechal Ferrand',52.5,41.2,'2018-01-05','2019-10-25'); insert into typeBorne values ('V1',4,30,1500), ('V2',2,30,2000), ('V3',2,25,2000), ('V4',3,25,2000); insert into typeCharge values (1,'Normal',4), (2,'Semi-Rapide',15), (3,'Rapide',33); insert into borne values (1,'ES','2018-05-22','2018-11-14',1300,1,'V1',1), (2,'HS','2018-05-23','2018-11-14',2000,1,'V2',2), (3,'ES','2018-10-20','2018-11-06',1400,2,'V3',2), (4,'ES','2018-10-22','2018-11-06',2200,2,'V4',3); insert into technicien values (1,'Calamone','Yoan','5f4dcc3b5aa765d61d8327deb882cf99','jesaispastrop'), (2,'Brocier','Anto','5f4dcc3b5<KEY>9','anto'), (3,'Meosie','Teo','5f4dcc3b5aa765d61d8327deb882cf99','teo'), (4,'Du-rent','Luka','5f4dcc3b5aa765d61d8327deb882cf99','luka'), (5,'BourgBouce','Silvin','5f4dcc3b5aa765d61d8327deb882cf99','silvin'); <file_sep>/CRAB/technicien.h #ifndef TECHNICIEN_H #define TECHNICIEN_H #include <QString> #include <QVector> #include "visite.h" /// /// \brief The Technicien class /// Permet de récupérer les informations des techniciens afin de les affecter à des visites équitablement class Technicien { private: int matricule; QString nom; QString prenom; QVector <visite*> lesVisites; public: Technicien(); Technicien(int unMatricule, QString unNom, QString unPrenom); int getTempsOccupe(); void affecterVisite(visite* uneVisite); QVector <visite*> getLesVisites(); QString getInfo(); int getMatricule(); }; #endif // TECHNICIEN_H <file_sep>/CRAB/DOXYGEN/html/class_type_borne.js var class_type_borne = [ [ "TypeBorne", "class_type_borne.html#a6b327edc5640195ed7026777da66d8f4", null ], [ "TypeBorne", "class_type_borne.html#a32f9c836b0f0b34e86a53520a8f23674", null ], [ "getDureeRevision", "class_type_borne.html#aee58fc4a65b54cf00376c72df39ac0d9", null ], [ "getNbJoursEntreRevisions", "class_type_borne.html#a4921b40e0c20ec1c98ea167cb787e605", null ], [ "getNbUnitesEntreRevisions", "class_type_borne.html#aa99a6c098973997a77699bea1244a94f", null ] ];<file_sep>/CRAB/DOXYGEN/html/search/all_7.js var searchData= [ ['jeuenregistrement',['jeuEnregistrement',['../classjeu_enregistrement.html',1,'']]] ]; <file_sep>/CRAB/DOXYGEN/html/search/classes_0.js var searchData= [ ['borne',['Borne',['../class_borne.html',1,'']]] ];
937424ed3e7db4109efe578d64c6cbff603cbca0
[ "JavaScript", "SQL", "C++" ]
41
C++
JMainard/CRAB
5880bb5aa6e46dd6cb3f7b55ecbbefb3280f9cb0
a2d7fca1bc9b4ab958c316a82980bc8a9e485178
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Listas_Enlazadas { class Estructura { //List<ClaseBase> vector = new List<ClaseBase>(); ClaseBase inicio = null,final = null; //public void agregar(ClaseBase nuevo) //{ // if(inicio==null) // { // inicio = nuevo; // } // else // { // //ClaseBase t = inicio; // //while (t.Siguiente != null) // // t = t.Siguiente; // //t.Siguiente = nuevo; // agregar(nuevo, inicio); // } //} //private void agregar(ClaseBase nuevo,ClaseBase quien) //{ // if (quien.Siguiente != null) // agregar(nuevo, quien.Siguiente); // else // { // quien.Siguiente = nuevo; // final = quien.Siguiente; // } //} /*public void eliminar() { if(inicio!=null) { inicio = inicio.Siguiente; } }*/ /// <summary> //agregar ordenado en doble //terminar los programas /// </summary> /// <param name="nuevo"></param> public void agregar(ClaseBase nuevo) { if (inicio == null) inicio = nuevo; else if (nuevo.Dato<inicio.Dato) { inicio.Anterior = nuevo; nuevo.Siguiente = inicio; inicio = nuevo; } else { ClaseBase temp = inicio; while (temp.Dato < nuevo.Dato && temp.Siguiente!=null) temp = temp.Siguiente; if (temp.Dato > nuevo.Dato) { nuevo.Siguiente = temp; nuevo.Anterior = temp.Anterior; temp.Anterior.Siguiente = nuevo; temp.Anterior = nuevo; } else { temp.Siguiente = nuevo; nuevo.Anterior = temp; } } } /// <summary> /// Nueva funcion de listas enlazadas /// </summary> /// <param name="dato"></param> /// <returns></returns> public int buscar(int dato) { ClaseBase temp = inicio; while(temp.Siguiente !=null) { if(temp.Dato==dato) { return temp.Dato; } temp = temp.Siguiente; } return 0; } /// <summary> /// nueva funcion de listas enlazadas /// </summary> /// <param name="numero"></param> public void Elimi(int numero) { bool sup=true; ClaseBase temp = inicio; while(sup) { if(temp.Dato == numero) { if (temp.Siguiente != null && temp.Anterior != null) { temp.Anterior.Siguiente = temp.Siguiente; temp.Siguiente.Anterior = temp.Anterior; break; } else if (temp.Anterior != null) { temp.Anterior.Siguiente = null; break; } else if (temp.Siguiente != null) { inicio = inicio.Siguiente; break; }else { inicio = null; break; } }else if(temp.Siguiente == null) { sup = false; } temp = temp.Siguiente; } } public void eliminarInicio() { if (inicio != null) { inicio = inicio.Siguiente; } } public void eliminarUltimo() { ClaseBase te = inicio; ClaseBase t=null; while(te.Siguiente !=null) { t = te; te = te.Siguiente; } t.Siguiente = null; } public string listarInverso() { string output = ""; ClaseBase t = inicio; while (t != null) { output = t.ToString() + "\r\n" + output; t = t.Siguiente; } return output; } public string listar() { string res = ""; ClaseBase t=inicio; while (t != null) { res += t.ToString()+"\r\n"; t = t.Siguiente; } return res; } public void invertirlista() { ClaseBase t=inicio; ClaseBase temp=null,vali=null; while (t != null) { temp = t.Siguiente; t.Siguiente = vali; vali = t; t = temp; } inicio = vali; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Listas_Enlazadas { public partial class Form1 : Form { Estructura catalogo = new Estructura(); public Form1() { InitializeComponent(); } private void btnAgregar_Click(object sender, EventArgs e) { ClaseBase nuevo; nuevo = new ClaseBase(Convert.ToInt32(txtDato.Text)); catalogo.agregar(nuevo); } private void btnListar_Click(object sender, EventArgs e) { txtResultado.Text = catalogo.listar(); } private void btnEliminar_Click(object sender, EventArgs e) { catalogo.eliminarInicio(); } private void btnEliminaUltimo_Click(object sender, EventArgs e) { catalogo.eliminarUltimo(); } private void btnInvLista_Click(object sender, EventArgs e) { catalogo.invertirlista(); } private void btnElimninardato_Click(object sender, EventArgs e) { catalogo.Elimi(Convert.ToInt32(txtDato.Text)); } private void btnBuscar_Click(object sender, EventArgs e) { lblRes.Text=Convert.ToString( catalogo.buscar (Convert.ToInt32(txtDato.Text)))+"encontrado"; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Listas_Enlazadas { class ClaseBase { private int _dato; public int Dato { get { return _dato; } set { _dato = value; } } private ClaseBase _siguiente; public ClaseBase Siguiente { get { return _siguiente; } set { _siguiente = value; } } private ClaseBase _anterior; public ClaseBase Anterior { get { return _anterior; } set { _anterior = value; } } public ClaseBase(int dato) { _dato = dato; } public override string ToString() { return "dato " + _dato; } } }
85c0def4cd3f27cb4520bfa40b050b31c7699048
[ "C#" ]
3
C#
DanielUlises9/Listas_Enlazadas
11a82a4af92ab21a7c512656abe95a5cbd62e6c0
37b5c22aa1a9a495c8e90b496e2a7fb6e5cfb3f3
refs/heads/master
<repo_name>kartungquek/ios-course-super-cool-app<file_sep>/test.swift var myFirstVariable = 3.0<file_sep>/README.md # ios-course-super-cool-app This is the first app we built in the iuos course
e74f1eaf429ae1bb5935efe947b9980a356b3df4
[ "Swift", "Markdown" ]
2
Swift
kartungquek/ios-course-super-cool-app
f8cded2a626c3ec18bb79cb04911e52d24ff171d
b5cc45636aebd1eb337ff3eec2322d60175ebce1
refs/heads/master
<repo_name>webdev23/phpCorsair<file_sep>/daemon.php #!/usr/bin/php <?php // header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); error_reporting(0); $eqdata = $_GET['eqdata']; $eqbColor = $_GET['eqbColor']; $eqhColor = $_GET['eqhColor']; $eqoColor = $_GET['eqoColor']; $eqfps = $_GET['eqfps']; $rainbowRatio = $_GET['rainRate']; $pwn = $_GET['matrix']; $pot = $_GET['pot']; $randpwn = $_GET['rand']; //~ echo $eqdata; $eq1 = $_GET['eq1']; $eq2 = $_GET['eq2']; $eq3 = $_GET['eq3']; $eq4 = $_GET['eq4']; $eq5 = $_GET['eq5']; $eq6 = $_GET['eq6']; $eq7 = $_GET['eq7']; $eq8 = $_GET['eq8']; //~ echo $eq1; //~ echo exec("echo hzload > /dev/input/ckb1/cmd"); echo exec("echo active > /dev/input/ckb1/cmd"); echo exec("echo fps ".$eqfps." > /dev/input/ckb1/cmd"); //~ echo exec("echo pollrate 8 > /dev/input/ckb1/cmd"); $keys = ['esc','f1','f2','f3','f4','f5','f6','f7','f8','f9', 'f1','f11','f10','grave','0','1','2','3','4','5','6','7','8','9','minus', 'tab','q','w','e','r','t','y','u','i','o','p','lbrace','caps', 'a','s','d','f','g','h','j','k','l','colon','quote','lshift', 'bslash_iso','z','x','c','v','b','n','m','comma','dot','slash', 'lctrl','lwin','lalt','space','light','f12','prtscn','scroll', 'pause','ins','home','pgup','rbrace','bslash','hash','enter', 'equal','bspace','del','end','pgdn','ralt','rshift','rwin','rctrl','up','left', 'down','right','lock','mute','stop','prev','play','next','numlock', 'numslash','numstar','numminus','numplus','numenter','num7','num8', 'num9','num4','num5','num6','num1','num2','num3','num0']; $world = ['ff0000','ff3300','ff6600','ff9900','ccff00', '66ff00','33ff00','00ff00','00ff33','99ff00','ffcc00','ffff00', '00ff66','00ff99','00ffcc','00ffff','00ccff','0099ff','0066ff', '0033ff','0000ff','3300ff','6600ff','9900ff','cc00ff','ff00ff', 'ff00cc','ff0099','ff0066','ff0033','ff0000','ff3300','ff6600', 'ffff00','ccff00','99ff00','66ff00','33ff00','00ff00','00ff33', '00ff66','00ff99','00ffcc','00ffff','00ccff','0099ff','0066ff', '0033ff','0000ff','3300ff','6600ff','ff0000','ff3300','ff6600', 'ffff00','ccff00','99ff00','66ff00','33ff00','00ff00','00ff33', '00ff66','00ff99','00ffcc','00ffff','00ccff','0099ff','0066ff', '0033ff','0000ff','3300ff','6600ff','9900ff','cc00ff','ff00ff', 'ff00cc','ff0099','ff0066','ff0033','ff0000','ff3300','ff6600']; $whiteRabbit = ['02E148','086213','67F383','044A0B']; if ($eqdata > $rainbowRatio ) { if ($eq1 || $eq2 || eq3 || $eq4 || $eq5 || $eq6 || $eq7 || $eq8 > "72") { // echo exec("echo rgb ".$eq0Color." 111111 > /dev/input/ckb1/cmd"); echo exec("echo rgb ".$eqoColor." lctrl,lwin,lalt,lbrace:".$eqbColor." x,c:".$eqbColor." v,b:".$eqbColor." comma,dot:".$eqbColor." slash,rshift:".$eqbColor." rwin,rctrl:".$eqbColor." up,left,right,down:".$eqbColor." num0,numdot,numenter:".$eqbColor." > /dev/input/ckb1/cmd"); }; if ($eq1 || $eq2 || eq3 || $eq4 || $eq5 || $eq6 || $eq7 || $eq8 > "78") { // echo exec("echo rgb ".$eq0Color." 111111 > /dev/input/ckb1/cmd"); echo exec("echo rgb ".$eqoColor." lctrl,lwin,lalt:".$eqbColor." x,c:".$eqbColor." v,b:".$eqbColor." comma,dot:".$eqbColor." slash,rshift:".$eqbColor." rwin,rctrl:".$eqbColor." up,left,right,down:".$eqbColor." num0,numdot,numenter:".$eqbColor." > /dev/input/ckb1/cmd"); }; if ($eq1 || $eq2 || eq3 || $eq4 || $eq5 || $eq6 || $eq7 || $eq8 > "82") { // echo exec("echo rgb ".$eq0Color." 111111 > /dev/input/ckb1/cmd"); echo exec("echo rgb ".$eqoColor." lctrl,lwin,lalt:".$eqbColor." x,c:".$eqbColor." v,b,g:".$eqbColor." n,m:".$eqbColor." comma,dot:".$eqbColor." rwin,rctrl:".$eqbColor." up,left,right,down:".$eqbColor." num0,numdot,numenter:".$eqbColor." > /dev/input/ckb1/cmd"); }; if ($eq1 || $eq2 || eq3 || $eq4 || $eq5 || $eq6 || $eq7 || $eq8 > "84") { // echo exec("echo rgb ".$eq0Color." 111111 > /dev/input/ckb1/cmd"); echo exec("echo rgb ".$eqoColor." lctrl,lwin,lalt:".$eqbColor." x,c:".$eqbColor." v,b,f,g:f:".$eqbColor." n,m:".$eqbColor." comma,dot,k,l:".$eqbColor." slash,rshift,bslash_iso,rbrace,semicolon:".$eqbColor." rwin,rctrl:".$eqbColor." up,left,right,down:".$eqbColor." num0,numdot,numenter:".$eqbColor." > /dev/input/ckb1/cmd"); }; if ($eq1 || $eq2 || eq3 || $eq4 || $eq5 || $eq6 || $eq7 || $eq8 > "88") { // echo exec("echo rgb ".$eq0Color." 111111 > /dev/input/ckb1/cmd"); echo exec("echo rgb ".$eqoColor." lctrl,lwin,lalt:".$eqbColor." x,c:".$eqbColor." v,b,f,g,f,r:".$eqbColor." n,m,h,j:".$eqbColor." comma,dot,k,l,i,o:".$eqbColor." slash,rshift,bslash_iso,rbrace,colon,0,p,rbrace:".$eqbColor." rwin,rctrl,rquote,hash:".$eqbColor." up,left,right,down:".$eqbColor." num0,numdot,numenter:".$eqbColor." > /dev/input/ckb1/cmd"); }; if ($eq1 || $eq2 || eq3 || $eq4 || $eq5 || $eq6 || $eq7 || $eq8 > "94") { // echo exec("echo rgb ".$eq0Color." 111111 > /dev/input/ckb1/cmd"); echo exec("echo rgb ".$eqoColor." lctrl,lwin,lalt:".$eqbColor." x,c,s:".$eqbColor." v,b,f,g,r,t:".$eqbColor." n,m,h,j:".$eqbColor." comma,dot,k,l,i,o:".$eqbColor." rwin,rctrl:".$eqbColor." up,left,right,down:".$eqbColor." num0,numdot,numenter:".$eqbColor." > /dev/input/ckb1/cmd"); }; if ($eq1 || $eq2 || eq3 || $eq4 || $eq5 || $eq6 || $eq7 || $eq8 > "100") { // echo exec("echo rgb ".$eq0Color." 111111 > /dev/input/ckb1/cmd"); echo exec("echo rgb ".$eqoColor." lctrl,lwin,lalt:".$eqbColor." x,c,s,d:".$eqbColor." v,b,f,g,r,t:".$eqbColor." n,m,h,j,y,u:".$eqbColor." comma,dot,k,l,i,o,8:".$eqbColor." up,left,right,down:".$eqbColor." num0,numdot,numenter:".$eqbColor." > /dev/input/ckb1/cmd"); }; if ($eq1 || $eq2 || eq3 || $eq4 || $eq5 || $eq6 || $eq7 || $eq8 > "127") { // echo exec("echo rgb ".$eq0Color." 111111 > /dev/input/ckb1/cmd"); echo exec("echo rgb ".$eqoColor." lctrl,lwin,lalt:".$eqbColor." x,c,s,d:".$eqbColor." v,b,f,g,r,t,4:".$eqbColor." n,m,h,j,y,u:".$eqbColor." comma,dot,k,l,i,o,8,9:".$eqbColor." up,left,right,down:".$eqbColor." up,left,right,down:".$eqbColor." num0,numdot,numenter,num1,num2,num3:".$eqbColor." > /dev/input/ckb1/cmd"); }; if ($eq1 || $eq2 || eq3 || $eq4 || $eq5 || $eq6 || $eq7 || $eq8 == "255") { // echo exec("echo rgb ".$eq0Color." 111111 > /dev/input/ckb1/cmd"); }; if ($eq1 || $eq2 || eq3 || $eq4 || $eq5 || $eq6 || $eq7 || $eq8 > "240") { // echo exec("echo rgb ".$eq0Color." 111111 > /dev/input/ckb1/cmd"); echo exec("echo rgb ".$eqoColor." lctrl,lwin,lalt:".$eqbColor." x,c,s,d:".$eqbColor." v,b,f,g,r,t,4,5:".$eqbColor." n,m,h,j,y,u:".$eqbColor." ralt,comma,dot,k,l,i,o,8,9:".$eqbColor." up,left,right,down:".$eqbColor." num0,numdot,numenter:".$eqbColor." num0,numdot,numenter,num1,num2,num3,num4,num5,num6:".$eqbColor." > /dev/input/ckb1/cmd"); }; if ($eq1 || $eq2 || eq3 || $eq4 || $eq5 || $eq6 || $eq7 || $eq8> "310") { // echo exec("echo rgb ".$eq0Color." 111111 > /dev/input/ckb1/cmd"); echo exec("echo rgb ".$eqoColor." lctrl,lwin,lalt,minus,z,bslash,lshift:".$eqbColor." x,c,s,d,e:".$eqbColor." v,b,f,g,r,t:".$eqbColor." n,m,h,j,y,u:".$eqbColor." enter:".$eqbColor." up,left,right,down,del:".$eqbColor." num0,numdot,numenter,num1,num2,num3:".$eqbColor." > /dev/input/ckb1/cmd"); }; if ($eq1 || $eq2 || eq3 || $eq4 || $eq5 || $eq6 || $eq7 || $eq8 > "320") { // echo exec("echo rgb ".$eq0Color." 111111 > /dev/input/ckb1/cmd"); echo exec("echo rgb ".$eqoColor." lctrl,lwin,lalt,z,bslash,lshift,caps:".$eqbColor." x,c,s,d,w,e,d,3,4:".$eqbColor." n,m,h,j,y,u,6,7:".$eqbColor." up,left,right,down,del,end,pgdn:".$eqbColor." > /dev/input/ckb1/cmd"); }; if ($eq1 || $eq2 || eq3 || $eq4 || $eq5 || $eq6 || $eq7 || $eq8 > "330") { // echo exec("echo rgb ".$eq0Color." 111111 > /dev/input/ckb1/cmd"); echo exec("echo rgb ".$eqoColor." lctrl,lwin,lalt,z,bslash,lshift,caps,tab,q:".$eqbColor." x,c,s,d,w,e,d,3,4,5:".$eqbColor." 2,3:".$eqbColor." up,left,right,down,del,end,pgdn:".$eqbColor." num0,numdot,numenter,num1,num2,num3,num4,num5,num6,num7,num8,num9,numplus:".$eqbColor." > /dev/input/ckb1/cmd"); }; if ($eq1 || $eq2 || eq3 || $eq4 || $eq5 || $eq6 || $eq7 || $eq8 > "340") { // echo exec("echo rgb ".$eq0Color." 111111 > /dev/input/ckb1/cmd"); echo exec("echo rgb ".$eqoColor." lctrl,lwin,lalt,z,bslash,lshift,caps,tab,a,q,1,grave:".$eqbColor." x,c,s,d,w,e,d,3:".$eqbColor." n,m,h,j,y,u:".$eqbColor." up,left,right,down,del,end,pgdn,ins,home,pgup:".$eqbColor." num0,numdot,numenter,num1,num2,num3,num4,num5,num6,num7,num8,num9,numplus,numlock,numstar,numslash,numminus:".$eqbColor." > /dev/input/ckb1/cmd"); }; if ($eq4 || $eq5 || $eq6 || $eq7 || $eq8 > "359") { //~ echo exec("echo rgb ".$eq0Color." 111111 > /dev/input/ckb1/cmd"); if ($eq1){ echo exec("echo rgb esc,f1,f2:".$eqhColor." > /dev/input/ckb1/cmd"); }; if ($eq2){ echo exec("echo rgb f3,f4:".$eqhColor." > /dev/input/ckb1/cmd"); }; if ($eq3){ echo exec("echo rgb f5,f6:".$eqhColor." > /dev/input/ckb1/cmd"); }; if ($eq4){ echo exec("echo rgb f7,f8:".$eqhColor." > /dev/input/ckb1/cmd"); }; if ($eq5){ echo exec("echo rgb f9,f10:".$eqhColor." > /dev/input/ckb1/cmd"); }; if ($eq6){ echo exec("echo rgb f11,f12:".$eqhColor." > /dev/input/ckb1/cmd"); }; if ($eq7){ echo exec("echo rgb prtscn,scroll,pause:".$eqhColor." > /dev/input/ckb1/cmd"); }; if ($eq8){ echo exec("echo rgb stop,prev,play,next:".$eqhColor." > /dev/input/ckb1/cmd"); }; }; } echo exec("echo rgb space:560000 > /dev/input/ckb1/cmd"); echo exec("echo rgb lock,mute,light:560000 > /dev/input/ckb1/cmd"); if ($_GET['mode'] == 'rainbow'){ echo shell_exec("php ./k70.php ".$eqbColor." ".$eqoColor); echo $return_var; } if ($_GET['mode'] == 'kill'){ $sys = 'pid'; $pid = file_get_contents($sys); echo $pid; echo shell_exec("sudo kill ".$pid); echo shell_exec("sudo kill ".$pid+1); echo shell_exec("sudo kill ".$pid+2); echo shell_exec("sudo kill ".$pid+3); } if ($pwn === "true") { if ($eqdata >= null){ $neo = str_repeat($keys[array_rand($keys, 1)].",",$pot); $neo = str_repeat($keys[array_rand($keys, 1)].",",$pot); echo exec("echo rgb ".$keys[array_rand($keys, 1)].$neo.":".$whiteRabbit[array_rand($whiteRabbit, 1)]." > /dev/input/ckb1/cmd"); //~ echo exec("echo rgb ".$keys[array_rand($keys, 1)].",".$keys[array_rand($keys, 1)].",".$keys[array_rand($keys, 1)].",".$keys[array_rand($keys, 1)].":".$whiteRabbit[array_rand($whiteRabbit, 1)]." > /dev/input/ckb1/cmd"); } }; if ($randpwn === "true") { if ($eqdata >= null){ $neo = str_repeat($keys[array_rand($keys, 1)].",",$pot); $neo = str_repeat($keys[array_rand($keys, 1)].",",$pot); echo exec("echo rgb ".$keys[array_rand($keys, 1)].$neo.":".$world[array_rand($world, 1)]." > /dev/input/ckb1/cmd"); //~ echo exec("echo rgb ".$keys[array_rand($keys, 1)].",".$keys[array_rand($keys, 1)].",".$keys[array_rand($keys, 1)].",".$keys[array_rand($keys, 1)].":".$world[array_rand($world, 1)]." > /dev/input/ckb1/cmd"); } }; <file_sep>/README.md # phpCorsair!<br>Spectral audio based events for corsair RGB devices. #### Controls Corsair devices running under the ckb-daemon with php <img src="http://i.imgur.com/1TjI3cx.gif"></img> <img src="http://i.imgur.com/f7JEuLl.png"></img> * Rainbow effect for Corsair devices running trought the ckb-daemon. * https://github.com/ccMSC/ckb * Should works with any device running the ckb-daemon. * The cue software can stay well closed. * But it can also works on top of the ckb software to add trippy effects. * It can run many times in parallel to add extra trippy effects. * Make sure the ckb-daemon is running with: <b>sudo ckb-daemon</b> * If the driver fail: <b>sudo killall ckb-daemon && sudo ckb-daemon</b> * Add a keyboard shortcut to call, or run in terminal: * Kill anytime to keep the colors as a color roulette. ##### Deploy and run: <h5><code> git init && git pull https://github.com/webdev23/phpCorsair.git && chromium-browser --app=http://localhost:9040/phpcorsair! | php -S localhost:9040 </code></h5> ###### Dependencies: <a href="apt://php7.0">php7.0</a> <a href="apt://curl">curl</a> <code>sudo apt install php7.0 && sudo apt install curl</code> ###### To serve daemon.php from the folder: <code>php -S localhost:9040</code> ###### Or as a daemon: <code>nohup chromium-browser --app=http://localhost:9040/phpcorsair! | nohup php -S localhost:9040 &</code> ###### You may want to close the terminal and keep the program running, with screen: <code>sudo apt install screen</code> <code>screen chromium-browser --app=http://localhost:9040/phpcorsair!</code> ###### To run from the folder if the daemon is listening open the file with chromium browser, or with this command line:. <code>chromium-browser --app=http://localhost:9040/phpcorsair!</code> ###### Rainbow only via the terminal: <code> php <(curl -s https://raw.githubusercontent.com/webdev23/phpCorsair/master/rainbow) </code> or just: <code>./rainbow </code> All files should stays on the same folder, as they are going to talk to each others. This should be all. Here is a youtube video of the beginning of this project, showing some features: https://www.youtube.com/watch?v=H7mKN2PASGM Enjoy! <file_sep>/k70.php <?php echo "phpCorsair v0.1!\n"; /* Rainbow effect for Corsair devices running trought the ckb-daemon. * Tested only on ubuntu with the k70rgb, but should works with any device. * This program only need the ckb-daemon to run, beside php. * It can also works in adjonction of the ckb software to add cools effects. * Make sure the ckb-daemon is running with: sudo ckb-daemon * If the driver fail: sudo killall ckb-daemon && sudo ckb-daemon * Add a keyboard shortcut to call, or run like this in terminal: * * php k70.php rainbow * * To kill gksudo killall php * * * Enjoy the powerful wtf licence. * * * <NAME> | nov2016 * ponyhacks.com * */ stream_set_blocking(STDIN, 0); error_reporting(0); echo exec("echo hwsave > /dev/input/ckb1/cmd"); echo exec("echo idle > /dev/input/ckb1/cmd"); usleep(140000); echo exec("echo hwload > /dev/input/ckb1/cmd"); echo exec("echo active > /dev/input/ckb1/cmd"); echo exec("echo fps 60 > /dev/input/ckb1/cmd"); usleep(10000); $GLOBALS['cmd'] = $argv[1]; $GLOBALS['ratio'] = $argv[2]; $GLOBALS['maxloops'] = '38'; function rain() { if ($GLOBALS['cmd'] == 'rainbow') { for ($i = 1; $i <= $GLOBALS['maxloops']; $i++) { if ($i < $GLOBALS['maxloops']) { usleep(80000); $rainbow=array('ff0000','ff3300','ff6600','ff9900','ccff00', '66ff00','33ff00','00ff00','00ff33','99ff00','ffcc00','ffff00', '00ff66','00ff99','00ffcc','00ffff','00ccff','0099ff','0066ff', '0033ff','0000ff','3300ff','6600ff','9900ff','cc00ff','ff00ff', 'ff00cc','ff0099','ff0066','ff0033','ff0000','ff3300','ff6600', 'ffff00','ccff00','99ff00','66ff00','33ff00','00ff00','00ff33', '00ff66','00ff99','00ffcc','00ffff','00ccff','0099ff','0066ff', '0033ff','0000ff','3300ff','6600ff','ff0000','ff3300','ff6600', 'ffff00','ccff00','99ff00','66ff00','33ff00','00ff00','00ff33', '00ff66','00ff99','00ffcc','00ffff','00ccff','0099ff','0066ff', '0033ff','0000ff','3300ff','6600ff','9900ff','cc00ff','ff00ff', 'ff00cc','ff0099','ff0066','ff0033','ff0000','ff3300','ff6600'); echo $rainbow[$i]; echo exec("echo rgb ".$rainbow[$i]." esc,f1,f2,f3,f4,f5,f6,f7,f7,f8,f9,f10,f11,f12:". $rainbow[$i+3]." 1,2,3,4,5,6,7,8,9,0:". $rainbow[$i-3]." bslash_iso,lctrl,lwin,lalt,caps,tab,lshift,rctrl,rwin,ralt,rshift,enter,ins:". $rainbow[$i-8]." m,prtscn,comma,dot,slash:". $rainbow[$i-6]." bslash,bspace,quote,grave,rbrace,lbrace,equal,minus:". $rainbow[$i+5]." up,left,down,right:". $rainbow[$i+14]." > /dev/input/ckb1/cmd"); } else { rain(); } }}} rain();
15a662195381f5c772e9b0cbbd312bb3d542a842
[ "Markdown", "PHP" ]
3
PHP
webdev23/phpCorsair
0473b074619845745620af778139cc3faac2a21f
39b483abd76b4401871f0594589546dd74a7b968
refs/heads/master
<file_sep>// // OnboardingHome.swift // SwiftLearning // // Created by <NAME> on 06/02/20. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct OnboardingHome: View { @State var selection: Int? = nil var body: some View { NavigationView { VStack { NavigationLink(destination: Login()) { Text("Login") } NavigationLink(destination: Register()) { Text("Register") } } } } } struct OnboardingHome_Previews: PreviewProvider { static var previews: some View { OnboardingHome() } } <file_sep>// // Home.swift // SwiftLearning // // Created by <NAME> on 15/02/20. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import CoreLocation struct Home: View { @ObservedObject var locationManager = LocationManager() var loader = true; var userLatitude: String { return "\(locationManager.lastLocation?.coordinate.latitude ?? 0)" } var userLongitude: String { return "\(locationManager.lastLocation?.coordinate.longitude ?? 0)" } var body: some View { VStack { Button(action: { deleteData() }) { Text("logout") } }.onAppear { self.callWeatherData() } } func callWeatherData() { var loader1 = true; Weather.getWeatherData(lattitude: userLatitude, longitude: userLongitude, completionHandler: { results, error in loader1 = false; //loader = loader1 }) } } func deleteData() { Auth.deleteCurrentUser(); } struct Home_Previews: PreviewProvider { static var previews: some View { Home() } } <file_sep>// // Weather.swift // SwiftLearning // // Created by <NAME> on 02/03/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import Alamofire import SwiftyJSON class Weather { static func getWeatherData(lattitude : String, longitude: String, completionHandler: @escaping (JSON?, String) -> ()) { var url = "http://api.openweathermap.org/data/2.5/weather?lat=\(lattitude)&lon=\(longitude)&appid=a8aaa0ae0cffa88a32a9ecfbb188a0fe"; var resultData: JSON? = nil APIRequestFetcher.api(url: url, completionHandler: { results, error in if case .failure = error { completionHandler(nil, "error") } guard let results = results, !results.isEmpty else { return } completionHandler(results, "success") }) } } <file_sep>// // Auth.swift // SwiftLearning // // Created by <NAME> on 14/02/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import RealmSwift class Auth { static func register( currentUser: CurrentUser ) { let realm = try! Realm() try! realm.write { realm.add(currentUser) } print(currentUser.name); } static func deleteCurrentUser() { let realm = try! Realm() let data = realm.objects(CurrentUser.self)[0]; try! realm.write { realm.delete(data); } } } <file_sep>// // Login.swift // SwiftLearning // // Created by <NAME> on 06/02/20. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct Login: View { var body: some View { Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/) } } struct Login_Previews: PreviewProvider { static var previews: some View { Login() } } <file_sep>// // APIRequestFetcher.swift // SwiftLearning // // Created by <NAME> on 03/03/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import Alamofire import SwiftyJSON enum NetworkError: Error { case failure case success } class APIRequestFetcher { static func api(url: String, completionHandler: @escaping (JSON?, NetworkError) -> ()) { AF.request(url).response { response in guard let data = response.data else { completionHandler(nil, .failure) return } let decoder = JSONDecoder() guard let results = response.data else { return } print("hello"); let json = try? JSON(data:results) completionHandler(json, .success) } } } <file_sep>// // Auth.swift // SwiftLearning // // Created by <NAME> on 14/02/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import RealmSwift class CurrentUser: Object { @objc dynamic var name = "" @objc dynamic var emailId = "" @objc dynamic var username = "" } <file_sep>// // Register.swift // SwiftLearning // // Created by <NAME> on 07/02/20. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import RealmSwift struct Register: View { @State private var name: String = "" @State private var email: String = "" @State private var username: String = "" @State private var password: String = "" var body: some View { VStack { TextField("Enter your name", text: $name).textFieldStyle(RoundedBorderTextFieldStyle()).padding(.bottom, 10) TextField("Enter your emailId", text: $email).textFieldStyle(RoundedBorderTextFieldStyle()).padding(.bottom, 10) TextField("Username", text: $username).textFieldStyle(RoundedBorderTextFieldStyle()).padding(.bottom, 10) SecureField("Password", text: $password).textFieldStyle(RoundedBorderTextFieldStyle()) Spacer() Button(action: { onSubmitForm(name: self.name, email: self.email, username: self.username , password: self.password) }) { Text("Register") } }.padding(.horizontal, 15) .onAppear{ let realm = try! Realm() let data = realm.objects(CurrentUser.self); } } } func onSubmitForm(name: String, email: String, username: String, password: String) { let currentUser = CurrentUser() currentUser.name = name currentUser.emailId = email currentUser.username = username Auth.register(currentUser: currentUser); if let window = UIApplication.shared.windows.first { window.rootViewController = UIHostingController(rootView: Home()) window.makeKeyAndVisible() } } struct Register_Previews: PreviewProvider { static var previews: some View { Register() } }
ff486adf1009601c34394eda4305f71f072f6ba1
[ "Swift" ]
8
Swift
DiksonSamuel/SwiftLearning
e7c1eb7ca93d57720108257cb09d77f0d01b6351
e762eeb6d62c2443e46116737eda81bf62221629
refs/heads/master
<repo_name>NesaByte/First-Of-Cornelius-Reign<file_sep>/cpp/w3lab/Book.h /**************************************************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * *****************************************************************************************/ #ifndef Book_H //header safeguards #define Book_H namespace sict { const int max_title_size = 33; //const char* max_title_size[33]; const int max_name_size = 17; //const char* max_name_size[17]; const long long min_isbn_value = 1000000000000; const long long max_isbn_value = 9999999999999; class Book { char family_name[max_name_size]; char given_name[max_name_size]; long long isbn; char title[max_title_size]; public: void set(const char*, const char*, const char*, long long); bool isEmpty() const; //strncpy void display() const; }; } #endif <file_sep>/milestones/ms3/Utilities.h /******************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop MILESTONE 2 * * DATE: 3/25/19 * ********************************************************/ #ifndef AMA_UTILITIES_H #define AMA_UTILITIES_H #include <iostream> #include "Product.h" using namespace std; namespace ama { double& operator+=(double& total, const Product& prod); ostream& operator<<(ostream& out, const Product& prod); istream& operator>>(istream& in, Product& prod); //std::ostream& operator<<(double value); } #endif <file_sep>/milestones/ms5/AmaApp.h /******************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop MILESTONE 5 * * Date: 04/06/2019 * *********************************************/ #ifndef AMAAPP_H #define AMAAPP_H #include <iostream> #include "iProduct.h" #include "Utilities.h" #include "Product.h" #include "Sort.h" namespace ama { class AmaApp { char m_filename[256]; iProduct* m_products[100]; int m_noOfProducts; AmaApp(const AmaApp& object) = delete; AmaApp& operator = (const AmaApp& object) = delete; void pause() const; int menu() const; void loadProductRecords(); void saveProductRecords() const; void listProducts() const; void deleteProductRecord(iProduct* product); void sort(); iProduct* find(const char* sku) const; void addQty(iProduct* product); void addProduct(char tag); public: AmaApp(const char* filename); ~AmaApp(); int run(); }; } #endif // !AMA_AMAAPP_H <file_sep>/milestones/ms4/Utilities.cpp /******************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop MILESTONE 2 * * DATE: 3/27/19 * ********************************************************/ #include <iostream> #include "Utilities.h" #include <iomanip> using namespace std; namespace ama { double& operator+=(double& total, const iProduct& prod) { //if (prod.taxStatus) return (total += prod.total_cost()); } ostream& operator<<(ostream& out, const iProduct& prod) { prod.write(out, write_human); return out; } istream& operator>>(istream& in, iProduct& prod) { prod.read(in, true); return in; } iProduct* createInstance(char tag) // dynamically create instances in the Product hierarchy { if (tag == 'N' || tag == 'n') return new Product();//create an object of type product else return nullptr; } } <file_sep>/milestones/ms4/ErrorState.cpp /******************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop MILESTONE 2 * * DATE: 3/12/19 * ********************************************************/ #include <iostream> #include <cstring> #include "ErrorState.h" using namespace std; namespace ama { //constructors: ErrorState::ErrorState(const char* errorMessage)// = nullptr) { if (errorMessage == nullptr || *errorMessage == '\0')// || errorMessage == "") { m_errMsg = nullptr; } else { message(errorMessage); } } //deconstructor: ErrorState::~ErrorState() { delete[] m_errMsg; m_errMsg = nullptr; } ErrorState& ErrorState::operator=(const char* pText) { if (pText == nullptr || !*pText) //|| pText[0] == '\0' || pText == NULL) { m_errMsg = nullptr; } else { //m_errMsg = nullptr; message(pText); } return *this; } //bool ErrorState::operator bool() const // isGood? { if (m_errMsg != nullptr) { // cout << endl << " bool true" << endl; return true; } else { // cout << endl << " bool false" << endl; return false; } } //message void ErrorState::message(const char* pText) { //int strLength = strlen(pText); //m_errMsg = new char[strLength + 1]; //strncpy(m_errMsg, pText, strLength); //m_errMsg[0] = '\0'; if (pText == nullptr || *pText == 0)// || pText == '\0' || pText == NULL) { m_errMsg = nullptr; } else { m_errMsg = nullptr; m_errMsg = new char[strlen(pText) + 1]; strcpy(m_errMsg, pText);//strcpy_s(m_errMsg, pText); } } const char* ErrorState::message() const { if (m_errMsg)//(m_errMsg != nullptr) { return m_errMsg; } else { return nullptr; } } //<< std::ostream& operator<<(std::ostream& os, const ErrorState& erState) { if (erState.message() != nullptr) { os << erState.message(); } return os; } } <file_sep>/milestones/ms3/Utilities.cpp /******************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop MILESTONE 2 * * DATE: 3/25/19 * ********************************************************/ #include <iostream> #include "Utilities.h" #include <iomanip> using namespace std; namespace ama { double& operator+=(double& total, const Product& prod) { //if (prod.taxStatus) return (total += prod.total_cost()); } ostream& operator<<(ostream& out, const Product& prod) { prod.write(out, write_human); return out; } istream& operator>>(istream& in, Product& prod) { prod.read(in, true); return in; } } <file_sep>/milestones/ms4/Product.cpp /******************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop MILESTONE 2 * * DATE: 3/27/19 * ********************************************************/ #include <iostream> #include <cstring> #include <string> #include <iomanip> #include <cstdlib> //#include <stdio.h> #include "Product.h" #include "ErrorState.h" using namespace std; namespace ama { void Product::message(const char* pText) { errorState.message(pText); } bool Product::isClear() const { // return errorState.(m_errMsg); //return (errorState.message()); // return (errorState.message() ? "true" : "false"); //if (errorState.message() != nullptr) // return true; //else // return false; } Product::Product(char type) : m_type(type) { strncpy(m_sku, "", max_length_sku); m_name = nullptr; //strncpy(*m_name, "x", max_length_name); strncpy(m_unit, "", max_length_unit); m_qtyOnhand = 0; m_qtyNeeded = 0; m_price = 0; taxStatus = false; } //A Custom Constructor with 7 arguments Product::Product(const char* sku, const char* name, const char* unit, double price, int qtyNeeded, int qtyOnhand, bool tax) : m_type('N') { if (name == nullptr && name[0] == '\0' && price == 0 && sku == nullptr) { strncpy(m_sku, "", max_length_sku); //strncpy(m_name, "", sizeof(m_name)); //max_length_name); strncpy(m_unit, "", max_length_unit); //strcpy_s(m_sku, ""); m_name = nullptr; //strcpy_s(m_unit, ""); m_price = 0; m_qtyNeeded = 0; m_qtyOnhand = 0; taxStatus = false; } else { strncpy(m_sku, sku, max_length_sku); int nameLength = strlen(name); m_name = new char[nameLength + 1]; strcpy(m_name, name); //strncpy(m_name, name, sizeof(m_name)); strncpy(m_unit, unit, max_length_unit); m_price = price; m_qtyNeeded = qtyNeeded; m_qtyOnhand = qtyOnhand; taxStatus = tax; } } // //The Copy Constructor. Product::Product(const Product& object) : m_type('N') { strncpy(m_sku, object.m_sku, max_length_sku); int nameLength = strlen(object.m_name); m_name = new char[nameLength + 1]; strcpy(m_name, object.m_name); strncpy(m_unit, object.m_unit, max_length_unit); m_qtyOnhand = object.m_qtyOnhand; m_qtyNeeded = object.m_qtyNeeded; m_price = object.m_price; taxStatus = object.taxStatus; } // //The Destructor Product::~Product() { delete[] m_name; // m_name = nullptr; } //The Copy Assignment Operator Product& Product::operator=(const Product& object) { strcpy(m_sku, object.m_sku); int nameLength = strlen(object.m_name); m_name = new char[nameLength + 1]; strcpy(m_name, object.m_name); strcpy(m_unit, object.m_unit); m_qtyOnhand = object.m_qtyOnhand; m_qtyNeeded = object.m_qtyNeeded; m_price = object.m_price; taxStatus = object.taxStatus; return *this; } int Product::operator+=(int cnt) { if (cnt > 0) { m_qtyOnhand += cnt; return m_qtyOnhand; } else { return m_qtyOnhand; } } bool Product::operator==(const char* sku) const { if (strcmp(m_sku, sku) == 0) return true; else return false; } bool Product::operator>(const char* sku) const { //cout << endl <<" " << m_sku << " > " << sku << endl; return (strcmp(m_sku, sku) > 0) ? true : false; //if (m_sku > sku) //1234>1233 //{ // return true; //} //else //{ // return false; //} } //needed for the ms4 operator> const char Product::type() const { return m_type; } //needed for the ms4 operator> const char* Product::name() const { return m_name; } bool Product::operator>(const iProduct& object) const//bool Product::operator>(const Product& object) const { //cout << endl<<" " << m_name << " > " << object.m_name << endl; return (strcmp(m_name, object.name()) > 0) ? true : false; //if (m_name > object.m_name) // return true; //else // return false; } int Product::qtyAvailable() const { return m_qtyOnhand; } int Product::qtyNeeded() const { return m_qtyNeeded; } double Product::oneTax() const { if (taxStatus == true) return m_price * (1 + tax_rate); else return m_price; } double Product::total_cost() const { return (oneTax() * (m_qtyOnhand)); } bool Product::isEmpty() const { return m_sku[0] == 0 && m_name == nullptr && m_price == 0 && m_qtyOnhand == 0 && m_qtyNeeded == 0; // if (m_name == nullptr && m_sku[0] == '\0' && m_price == 0)//(*this == nullptr) // { // return true; // } // else{ // return false; //} } std::istream& Product::read(std::istream& in, bool interractive) { if (interractive == false) { //char taxYN; //bool valid; //char* tag = new char[max_length_sku + 1]; char* sku = new char[max_length_sku + 1]; char* name = new char[max_length_name + 1]; char* unit = new char[max_length_unit + 1]; char* price = new char[max_length_sku + 1]; char* tax = new char[5]; char* qtyA = new char[max_length_unit + 1]; char* qtyN = new char[max_length_unit + 1]; //in.getline(tag, ama::max_length_sku, ','); in.getline(sku, ama::max_length_sku, ','); //cout << sku; strcpy(m_sku, sku); //cout << m_type << "," << m_name << "," << m_unit << "," << m_price << ","; in.getline(name, ama::max_length_name, ','); //cout << name; //thats it? no need to make a function? this is the function for it? int nameLength = strlen(name); m_name = new char[nameLength + 1]; strcpy(m_name, name); //strcpy(m_name, name); in.getline(unit, ama::max_length_unit, ','); strcpy(m_unit, unit); //cout << unit; in.getline(price, 10, ','); //cout << price; m_price = stod(price); in.getline(tax, 5, ','); taxStatus = stod(tax); //cout << tax; //if (m_tax == 0) // taxStatus == false; //else // taxStatus == true; in.getline(qtyA, 5, ','); //cout << qtyA; m_qtyOnhand = std::atoi(qtyA); in.getline(qtyN, 5, '\n'); //cout << qtyN; m_qtyNeeded = std::atoi(qtyN); } else { char sku[max_length_sku + 1]; char *name = new char[max_length_name + 1]; char unit[max_length_unit + 1]; int qtyA; int qtyN; double price; //char tax; //bool taxable; char taxYN[2]; bool valid; //ErrorState error; cout << right << setw(max_length_label) << "Sku: "; in >> sku; //strcpy(m_sku, sku); cout << right << setw(max_length_label) << " Name (no spaces): "; in >> name; //int nameLength = strlen(name); //m_name = new char[nameLength + 1]; //strcpy(m_name, name); cout << right << setw(max_length_label) << " Unit: "; in >> unit; //strcpy(m_unit, unit); cout << right << setw(max_length_label) << " Taxed? (y/n): "; //Taxed? (y/n):␣<User Types Here – y, Y, n, or N are acceptable in >> taxYN; valid = !strcmp(taxYN, "Y") || !strcmp(taxYN, "y") || !strcmp(taxYN, "N") || !strcmp(taxYN, "n"); if (!valid) { //cout << "noy valid"; in.setstate(std::ios::failbit); message("Only (Y)es or (N)o are acceptable!"); } if (in.fail() == false) { cout << right << setw(max_length_label) << " Price: "; in >> price; //m_price = stod(price); if (in.fail() == true) { in.setstate(ios::failbit); //in.setstate(ios::failbit); message("Invalid Price Entry!"); } if (in.fail() == false) { cout << right << setw(max_length_label) << " Quantity on hand: "; in >> qtyA; //m_qtyOnhand = stod(qtyA); if (in.fail() == true) { in.setstate(ios::failbit); message("Invalid Quantity Available Entry!"); } if (in.fail() == false) { cout << right << setw(max_length_label) << " Quantity needed: "; in >> qtyN; if (in.fail() == true) { //cout << "in.fail() == true"; in.setstate(ios::failbit); message("Invalid Quantity Needed Entry!"); //cout << "nooooooooooooo" << endl; }//else //m_qtyNeeded = stod(qtyN); } } } if (!in.fail()) { Product temp; if (!strcmp(taxYN, "Y") || !strcmp(taxYN, "y")) temp = Product(sku, name, unit, price, qtyN, qtyA, 1); else temp = Product(sku, name, unit, price, qtyN, qtyA, 0); //Product temp = Product(sku, name, unit, price, qtyN, qtyA, taxaYN); *this = temp; } //delete[] name; //name = nullptr; return in;// .total_cost(); } return in; } std::ostream& Product::write(std::ostream& out, int writeMode) const { if (!isEmpty()) { if (writeMode == write_condensed) { out << m_type << "," << m_sku << "," << m_name << "," << m_unit << ","; out.setf(ios::fixed); out << setprecision(2); out << m_price << ","; int tax = 1; if (!taxStatus) { tax = 0; } out << tax << "," << m_qtyOnhand << "," << m_qtyNeeded; } if (writeMode == write_table) { out << right << setw(max_length_sku+1) << m_sku << " | "; /* char temp[17]; strncpy(temp, m_name, 17); if (strlen(m_name) > 16) { temp[13] = temp[14] = temp[15] = '.'; } temp[16] = '\0'; cout << "DEBUG: " << temp;*/ // you make it work too easy, i dont why is it so hard. if (m_name != nullptr && (strlen(m_name) > 16)) { string str = m_name; string th = str.substr(0, 13); string dot = "..."; string name = th + dot; out << left << setw(16) << name; //that should also work } else { out << m_name; } out << " | "; //<< left << setw(16) out << left << setw(10) << m_unit << right << " | "; out << right << setw(7); out.setf(ios::fixed); out << setprecision(2); out << m_price << " | "; string ts = "yes"; if (!taxStatus) { ts = "no"; } out << left << setw(3) << ts << right << " | "; out << right << setw(6) << m_qtyOnhand << right << " | "; out << right << setw(6) << m_qtyNeeded << right << " |"; } if (writeMode == write_human) { //out.setf(ios::right); //out << setw(24); out << right << setw(max_length_label) << "Sku: " << m_sku << endl; out << right << setw(max_length_label) << "Name: " << m_name << endl; out.setf(ios::fixed);// , ios::floatfield); out << right << setw(max_length_label); out << setprecision(2); out << "Price: " << m_price << endl; //out.unsetf(ios::fixed); out.setf(ios::fixed); out << right << setw(max_length_label); out << setprecision(2); out << "Price after Tax: " << oneTax() << endl; //out.unsetf(ios::fixed); out << right << setw(max_length_label) << "Quantity Available: " << m_qtyOnhand << " " << m_unit << endl; out << right << setw(max_length_label) << "Quantity Needed: " << m_qtyNeeded << " " << m_unit << endl; //out.unsetf(ios::floatfield); } else { return out; } } else if (errorState.message() != nullptr)// ? "null" : msg.message()) out << errorState.message(); return out; } } <file_sep>/cpp/w4lab/Traveler.h // TODO: add file header comments here /**************************************************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 4 Lab: TRAVELERS VALIDATION LOGIC * *****************************************************************************************/ // TODO: add header file guard here #ifndef SICT_TRAVELER_H #define SICT_TRAVELER_H // TODO: declare your namespace here namespace sict { // TODO: define the constants here const int max_desination_size = 32; const int name_size = 16; // TODO: define the Traveler class here class Traveler { char m_tFirstName[name_size];//The travelerís first name char m_tLastName[name_size];//The travelerís last name char m_destination[max_desination_size];//The destination public: Traveler(); //default constructor Traveler(const char*, const char*, const char*); bool isEmpty() const; void display() const; }; } #endif<file_sep>/cpp/w3home/Book.cpp /**************************************************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * *****************************************************************************************/ #include <iostream> #include <cstring> #include "Book.h" using namespace std; namespace sict { void Book::set(const char* gName, const char* fName, const char* tit, long long number) { if (min_isbn_value <= number && number <= max_isbn_value) { long long tempNumber = number; //9780441172719 int tempStorage = 0; int sumOdd = 0; int sumEven = 0; int sumTotal = 0; int last; int difference; int multiple; last = tempNumber % 10; //stores the last number of isbn tempNumber = tempNumber / 10; for (int i = 12; i >= 0; i--) { tempStorage = tempNumber % 10; //9 7 8 0 4 4 1 1 7 2 7 1 9 tempNumber = tempNumber / 10; if (i % 2 == 0) { sumOdd = sumOdd + tempStorage; //add all odd-positioned numbers } else { sumEven = sumEven + tempStorage; //add all even-positioned numbers } } sumTotal = sumEven + (sumOdd * 3); // summation of sumOdd and of sumEven which is multiplied by 3 multiple = ((sumTotal / 10) * 10) + 10; //formula to take the highest integer multiple of 10 of the sumTotal difference = multiple - sumTotal; //difference between multiple and sumTotal if (last == difference) //if last digit is equals to the difference, accept the input. { strncpy(this->title, tit, max_title_size); strncpy(this->family_name, fName, max_name_size); strncpy(this->given_name, gName, max_name_size); isbn = number; } else { isbn = 0; } } else { isbn = 0; } } void Book::set(int year, double price) { if (isbn != 0) { m_year = year; m_price = price; } else { isbn = 0; } } bool Book::isEmpty() const { if (isbn == 0) { return true; }else return false; } void Book::display(bool empty) const { if (empty == false) { if (Book::isEmpty() == true) { cout << "The book object is empty!" << endl; } else { cout << "Author: " << family_name << ", " << given_name << endl << "Title: " << title << endl << "ISBN-13: " << isbn << endl << "Publication Year: " << m_year << endl << "Price: " << m_price << endl; } } else { if (Book::isEmpty() == true) { cout.setf(ios::left); cout << "|"; cout.width(92); cout << "The book object is empty! " << "|" << endl; } else { cout.setf(ios::right); cout << "|"; cout.width(max_name_size); cout << family_name; cout << "|"; cout.width(max_name_size); cout << given_name; cout << "|"; cout.unsetf(ios::right); cout.setf(ios::left); cout.width(max_title_size); cout << title; cout << "|"; cout.width(13); cout << isbn; cout << "|"; cout.width(4); cout << m_year; cout.setf(ios::fixed); cout.precision(2); cout.setf(ios::right); cout << "|"; cout.width(6); cout << m_price; cout << "|" << endl; cout.unsetf(ios::fixed); cout.unsetf(ios::right); } } } } <file_sep>/milestones/ms5/Sort.h #ifndef SICT_SORT_H #define SICT_SORT_H #include <iostream> #include <cstring> namespace sict { template<typename T> void sort(T* data, int n) { int i, j; T temp; for (i = n - 1; i > 0; i--) { for (j = 0; j < i; j++) { if (*data[j] > *data[j + 1]) { temp = data[j]; data[j] = data[j + 1]; data[j + 1] = temp; } } } } } #endif // !SICT_SORT_H <file_sep>/milestones/ms5/Product.h /******************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop MILESTONE 2 * * DATE: 3/27/19 * ********************************************************/ #ifndef AMA_PRODUCT_H #define AMA_PRODUCT_H #include <iostream> #include "ErrorState.h" #include "iProduct.h" #include "Utilities.h" namespace ama { class Product : public iProduct { const char m_type; char m_sku[max_length_sku]; char m_unit[max_length_unit]; char* m_name; int m_qtyOnhand; int m_qtyNeeded; double m_price; int m_tax; bool taxStatus; ErrorState errorState; protected: void message(const char* pText); bool isClear() const; public: Product(char type = 'N'); Product(const char* sku, const char* name, const char* unit, double price = 0, int qtyNeeded = 0, int qtyOnhand = 0, bool tax = true); Product(const Product& object); ~Product(); Product& operator=(const Product& obj); void sku(char sku[max_length_sku+1]); void unit(char unit[max_length_unit+1]); void name(const char* name); const char type() const; const char* name() const; double oneTax() const; int operator+=(int cnt); bool operator==(const char* sku) const; bool operator>(const char* sku) const; bool operator>(const iProduct& other) const; int qtyAvailable() const; int qtyNeeded() const; double total_cost() const; bool isEmpty() const; std::istream& read(std::istream& in, bool interractive); std::ostream& write(std::ostream& out, int writeMode) const; }; } #endif <file_sep>/cpp/w8lab/Allocator.cpp /************************************************ * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 8 Lab: Account * * Dated March 20 2019 * ************************************************/ #include "SavingsAccount.h" namespace sict { const double m_interest = 0.05; //from iAccount? iAccount* CreateAccount(const char* type, double balance) { iAccount *temp = nullptr; if (type[0] == 'S'){ temp = new SavingsAccount(balance, m_interest); } return temp; } }<file_sep>/cpp/w4home/Traveler.h // TODO: add file header comments here /**************************************************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 4 Home: TRAVELERS VALIDATION LOGIC * *****************************************************************************************/ // TODO: add header file guard here #ifndef SICT_TRAVELER_H #define SICT_TRAVELER_H // TODO: declare your namespace here namespace sict { // TODO: define the constants here const int max_desination_size = 32; const int name_size = 16; // TODO: define the Traveler class here class Traveler { char m_tFirstName[name_size];//The travelerís first name char m_tLastName[name_size];//The travelerís last name char m_destination[max_desination_size];//The destination int m_dYear; int m_dMonth; int m_dDay; public: Traveler(); //default constructor Traveler(const char*, const char*, const char*); bool isEmpty() const; void display() const; Traveler(const char*, const char*, const char*, const int, const int, const int); const char* name() const; bool canTravelWith(const Traveler&) const; }; } #endif<file_sep>/cpp/w6lab/Contact.cpp /**************************************************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 6: Class with a Resource * *****************************************************************************************/ #include <iostream> #include <cstring> #include <iomanip> #include "Contact.h" using namespace std; namespace sict { bool Contact::check(long long phoneNumber) const { if (phoneNumber > 0) { return true; } else { return false; } if ( (10000000000 <= phoneNumber) && (phoneNumber <= 999999999999) && ((phoneNumber % 10000000000 / 1000000000) >= 1) && ((phoneNumber % 10000000 / 1000000) >= 1) ) { return true; } else { return false; } } Contact::Contact() { m_nameOfContact[0] = '\0'; m_phoneNumbers = nullptr; m_numberOfPhoneNumbers = 0; } Contact::Contact(const char *name, const long long *phone, const int number) { if (name == '\0') { *this->m_nameOfContact = '\0'; } else { strncpy(this->m_nameOfContact, name, max_name_size - 1); m_nameOfContact[max_name_size] = '\0'; m_numberOfPhoneNumbers = number; } if (phone) { m_phoneNumbers = new long long[m_numberOfPhoneNumbers]; for (int i = 0; i < m_numberOfPhoneNumbers; i++) { if (check(phone[i])) { m_phoneNumbers[i] = phone[i]; } } } } Contact::~Contact() { delete[] m_phoneNumbers; } bool Contact::isEmpty() const { if (m_nameOfContact[0] == '\0' || m_nameOfContact == nullptr) { return true; } else { return false; } } void Contact::display() const { if (isEmpty() == true) { cout << "Empty contact!" << endl; } else { cout << m_nameOfContact << endl; for (int i = 0; i < m_numberOfPhoneNumbers; i++) { if ( (10000000000 <= m_phoneNumbers[i]) && (m_phoneNumbers[i] <= 999999999999) && ((m_phoneNumbers[i] % 10000000000 / 1000000000) >= 1) && ((m_phoneNumbers[i] % 10000000 / 1000000) >= 1) ) { int countryCode = m_phoneNumbers[i] / 10000000000; int areaCode = m_phoneNumbers[i] % 10000000000 / 10000000; int first = m_phoneNumbers[i] % 10000000 / 10000; int second = m_phoneNumbers[i] % 10000000 % 10000; cout << "(+" << countryCode << ") " << areaCode << " "; cout << setfill('0') << setw(3); cout << first << "-"; cout << setfill('0') << setw(4); cout << second << endl; } } } } } <file_sep>/cpp/w8lab/SavingsAccount.h /************************************************ * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 8 Lab: Account * * Dated March 20 2019 * ************************************************/ #ifndef SICT_SAVINGSACCOUNT_H #define SICT_SAVINGSACCOUNT_H #include "Account.h" namespace sict{ class SavingsAccount : public Account { double m_intRate; public: SavingsAccount(double balance, double interestRate); void monthEnd(); void display(ostream& out) const; }; } #endif <file_sep>/cpp/w5lab/Fraction.h /******************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 5 Lab: FRACTIONS * *********************************************************/ // TODO: header file guard #ifndef SICT_FRACTION_H #define SICT_FRACTION_H // TODO: create namespace namespace sict{ // TODO: define the Fraction class class Fraction { // TODO: declare instance variables int m_numerator; int m_denominator; // TODO: declare private member functions int max() const; int min() const; void reduce(); int gcd() const; public: // TODO: declare public member functions Fraction(); // default constructor Fraction(int numerator, int denominator); bool isEmpty() const; void display() const; // TODO: declare the + operator overload Fraction operator+(const Fraction& rhs) const; //Fraction (const Fraction& other); //~Fraction(); }; } #endif <file_sep>/cpp/w8lab/iAccount.h /************************************************ * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 8 Lab: Account * * Dated March 20 2019 * ************************************************/ #ifndef SICT_IACCOUNT_H #define SICT_IACCOUNT_H #include <iostream> using namespace std; namespace sict { class iAccount { public: //includes a destructor: //https://stackoverflow.com/questions/13576055/how-is-default-different-from-for-default-constructor-and-destructor virtual ~iAccount() = default; //pure virtual public member functions: //https://www.geeksforgeeks.org/pure-virtual-functions-and-abstract-classes/ virtual bool credit(double amount) = 0; virtual bool debit(double amount) = 0; virtual void monthEnd() = 0; virtual void display(ostream& out) const = 0; }; //helper for allocator iAccount* CreateAccount(const char* type, double balance); } #endif // !SICT_IACCOUNT_H_ <file_sep>/cpp/w8home/Account.h /************************************************ * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 8 Lab: Account * * Dated March 20 2019 * ************************************************/ #ifndef SICT_ACCOUNT_H #define SICT_ACCOUNT_H #include "iAccount.h" namespace sict { //deriving from iAccount //https://www.geeksforgeeks.org/pure-virtual-functions-and-abstract-classes/ class Account : public virtual iAccount { double m_iniBal; public: Account(double balance = 0.0); bool credit(double amount); bool debit(double amount); protected: double balance() const; }; } #endif // !SICT_ACCOUNT_H <file_sep>/cpp/w5home/Fraction.cpp // TODO: insert header files /******************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 5 Lab: FRACTIONS * *********************************************************/ // TODO: continue the namespace #include <iostream> #include <cstring> #include "Fraction.h" using namespace std; namespace sict { // TODO: implement the default constructor Fraction::Fraction() // default constructor { m_denominator = 0; m_numerator = 0; // cout << endl << " creation: numerator= " << m_numerator << " denomerator= " << m_denominator << endl << endl; } // TODO: implement the two-argument constructor Fraction::Fraction(int numerator, int denominator) { if (numerator > 0 && denominator > 0 ) { this->m_numerator = numerator; this->m_denominator = denominator; reduce(); // cout << endl << " successfully copied: numerator= " << m_numerator << " denomerator= " <<m_denominator << endl << endl; } else { *this = Fraction(); // cout << endl << " Set objects to safe empty state. numerator= " << m_numerator << " denomerator= " << m_denominator << endl << endl; } } // TODO: implement the max int Fraction::max() const// a private query that returns the greater of the numerator and denominator { if (m_numerator > m_denominator) { return m_numerator; } else return m_denominator; } // TODO: implement the min query int Fraction::min() const // – a private query that returns the lesser of the numerator and denominator { if (m_numerator > m_denominator) { return m_denominator; } else return m_numerator; } // gcd returns the greatest common divisor of num and denom // int Fraction::gcd() const { int mn = min(); // min of numerator and denominator int mx = max(); // max of numerator and denominator int g_c_d = 1; bool found = false; for (int x = mn; !found && x > 0; --x) { // from mn decrement until divisor found if (mx % x == 0 && mn % x == 0) { found = true; g_c_d = x; } } return g_c_d; } // TODO: implement the reduce modifier void Fraction::reduce() { if (isEmpty() == false) { int divisor = gcd(); m_numerator = m_numerator / divisor; m_denominator = m_denominator / divisor; } } // TODO: implement the display query void Fraction::display() const// – sends the fraction to standard output in the following form if the object holds a valid fraction and its denominator is not unit - valued(1) { if (isEmpty() == true) { cout << "no fraction stored"; } else { if (m_denominator == 1) { cout << m_numerator; } else { cout << m_numerator << "/" << m_denominator; } } } // TODO: implement the isEmpty query bool Fraction::isEmpty() const { if (m_denominator == 0) return true; else return false; } // TODO: implement the + operator Fraction Fraction::operator+(const Fraction& rhs) const { Fraction rhsTemp(0, 0); if ((isEmpty() == false) && (rhs.isEmpty() == false)) { rhsTemp.m_numerator = ((m_numerator * rhs.m_denominator) + (rhs.m_numerator * m_denominator)); rhsTemp.m_denominator = ((m_denominator * rhs.m_denominator)); } return rhsTemp; } Fraction Fraction::operator*(const Fraction& rhs) const { Fraction rhsTemp(0, 0); if ((isEmpty() == false) && (rhs.isEmpty() == false)) { rhsTemp.m_numerator = this->m_numerator * rhs.m_numerator; rhsTemp.m_denominator = this->m_denominator * rhs.m_denominator; } return rhsTemp; } bool Fraction::operator==(const Fraction& rhs) const { bool valid = (isEmpty() == false) && (rhs.isEmpty() == false); bool same = (m_denominator == rhs.m_denominator) && (m_numerator == rhs.m_numerator); return same && valid; } bool Fraction::operator!=(const Fraction& rhs) const { bool valid = (isEmpty() == false) && (rhs.isEmpty() == false); bool same = (m_denominator != rhs.m_denominator) && (m_numerator != rhs.m_numerator); return valid && same; } Fraction& Fraction::operator+=(const Fraction& rhs) { if ((isEmpty() == false) && (rhs.isEmpty() == false)) //if not empty { m_numerator = ((m_numerator * rhs.m_denominator) + (rhs.m_numerator * m_denominator)); m_denominator = (m_denominator * rhs.m_denominator); } return *this; } } <file_sep>/cpp/w6lab/Contact.h /**************************************************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 6: Class with a Resource * *****************************************************************************************/ #ifndef SICT_CONTACT_H #define SICT_CONTACT_H #include <iostream> namespace sict { const int max_name_size = 16; class Contact { char m_nameOfContact[max_name_size]; long long* m_phoneNumbers; int m_numberOfPhoneNumbers; bool check(long long) const; public: Contact(); Contact(const char* name, const long long* phone, const int number); ~Contact(); bool isEmpty() const; void display() const; }; } #endif // !CONTACT_H <file_sep>/milestones/ms5/ErrorState.h /******************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop MILESTONE 2 * * DATE: 3/12/19 * ********************************************************/ #ifndef AMA_ERRORSTATE_H #define AMA_ERRORSTATE_H #include <iostream> #include <string> namespace ama { class ErrorState { char* m_errMsg; public: ~ErrorState(); explicit ErrorState(const char* errorMessage = nullptr); ErrorState(const ErrorState& other) = delete; ErrorState& operator=(const ErrorState& other) = delete; operator bool() const; ErrorState& operator=(const char* pText); void message(const char* pText); const char* message() const; }; std::ostream& operator<<(std::ostream& os, const ErrorState& date); } #endif // !ERRORSTATE_H <file_sep>/milestones/ms5/Perishable.h /******************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop MILESTONE 5 * * Date: 04/06/2019 * *********************************************/ #ifndef AMA_PERISHABLE_H #define AMA_PERISHABLE_H #include <iostream> #include "Product.h" #include "Date.h" #include "ErrorState.h" #include "iProduct.h" #include "Utilities.h" namespace ama { class Perishable : public Product { Date expiryDate; public: Perishable(); std::ostream& write(std::ostream& out, int writeMode) const; std::istream& read(std::istream& in, bool interractive); }; } #endif // !AMA_PERISHABLE_H <file_sep>/cpp/w1lab/tools.h /**************************************************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * *****************************************************************************************/ // Displays the user interface menu int menu(); // Performs a fool-proof integer entry int getInt(int min, int max);<file_sep>/milestones/ms5/Perishable.cpp /******************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop MILESTONE 5 * * Date: 04/06/2019 * *********************************************/ #include <iostream> #include <iomanip> #include <sstream> #include "Perishable.h" using namespace std; namespace ama { Perishable::Perishable() :Product ('P') {} ostream& Perishable::write(ostream& out, int writeMode) const { Product::write(out, writeMode); if (this->isEmpty() == false && this->isClear()) { if (writeMode == write_condensed) { out << ","; expiryDate.write(out); } else if (writeMode == write_human) { out.setf(ios::right); out.width(max_length_label); out << "Expiry Date: "; expiryDate.write(out); out << endl; } else if (writeMode == write_table) { out.setf(ios::right); out << " "; out.width(10); expiryDate.write(out); out << " |"; } } return out; } istream& Perishable::read(istream& in, bool interractive) { Product::read(in, interractive); Date dt; if (interractive == true) { if (this->isClear()) { cout.setf(ios::right); cout.width(max_length_label); cout << "Expiry date (YYYY/MM/DD): "; in >> dt; } if (this->isClear() && dt.status() != no_error) { if (dt.status() == ama::error_day) { this->message("Invalid Day in Date Entry"); in.setstate(ios::failbit); } else if (dt.status() == ama::error_mon) { this->message("Invalid Month in Date Entry "); in.setstate(ios::failbit); } else if (dt.status() == ama::error_year) { this->message("Invalid Year in Date Entry"); in.setstate(ios::failbit); } else if (dt.status() == ama::error_input) { this->message("Invalid Date Entry"); in.setstate(ios::failbit); } } if(isClear()) { expiryDate = dt; } } else { expiryDate.read(in); in.ignore(); } return in; } } <file_sep>/milestones/ms5/Utilities.h /******************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop MILESTONE 2 * * DATE: 3/25/19 * ********************************************************/ #ifndef AMA_UTILITIES_H #define AMA_UTILITIES_H #include <iostream> #include "Product.h" using namespace std; namespace ama { double& operator+=(double& total, const iProduct& prod); ostream& operator<<(ostream& out, const iProduct& prod); istream& operator>>(istream& in, iProduct& prod); //ms5 : responsible to dynamically create instances in the Product hierarchy. iProduct* createInstance(char tag); // dynamically create instances in the Product hierarchy } #endif <file_sep>/cpp/w8home/ChequingAccount.h /************************************************ * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 8 Home: Account * * Dated March 24 2019 * ************************************************/ #ifndef SICT_CHEQUINGACCOUNT_H #define SICT_CHEQUINGACCOUNT_H #include "Account.h" namespace sict { class ChequingAccount : public Account { double m_transFee; double m_monthlyFee; public: ChequingAccount(double balance, double transFee, double monthlyFee); bool credit(double amount); bool debit(double amount); void monthEnd(); void display(ostream& out) const; ///ChequingAccount(); //~ChequingAccount(); }; } #endif // !SICT_CHEQUINGACCOUNT_H <file_sep>/milestones/ms5/AmaApp.cpp /******************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop MILESTONE 5 * * Date: 04/06/2019 * *********************************************/ #include <iostream> #include <string> #include <iomanip> #include <fstream> #include <string> #include "AmaApp.h" using namespace std; namespace ama { AmaApp::AmaApp(const char* filename) { if (filename != 0) strncpy(m_filename, filename, 256); else strncpy(m_filename, "", 256); for (int i = 0; i < 100; i++) { m_products[i] = nullptr; } m_noOfProducts = 0; loadProductRecords(); } //destructor AmaApp::~AmaApp() { for (int j = 0; j < m_noOfProducts; j++) { delete m_products[j]; m_products[j] = nullptr; } } void AmaApp::pause() const { cout << "Press Enter to continue..." << endl; cin.ignore(); } int AmaApp::menu() const { int option = 0; cout << "Disaster Aid Supply Management Program" << endl << "--------------------------------------" << endl << "1- List products" << endl << "2- Search product" << endl << "3- Add non-perishable product" << endl << "4- Add perishable product" << endl << "5- Add to product quantity" << endl << "6- Delete product" << endl << "7- Sort products" << endl << "0- Exit program" << endl << "> "; cin >> option; if (option >= 0 && option <= 7) { cin.clear(); cin.ignore(); return option; } else { cin.clear(); cin.ignore(); return -1; } } void AmaApp::loadProductRecords() { for (int j = 0; j < m_noOfProducts; j++) { delete m_products[j]; m_products[j] = nullptr; } fstream file; char oneChar; int i = 0; file.open(m_filename, ios::in | ios::out); if (file.is_open()) { do { file >> oneChar; if (file.fail()) { break; } file.ignore(); m_products[i] = ama::createInstance(oneChar); if (m_products[i] != nullptr) { m_products[i]->read(file, false); i++; } } while (!file.eof()); m_noOfProducts = i; } file.close(); } void AmaApp::saveProductRecords() const { fstream file; file.open("inventory.txt", ios::out); for (int i = 0; i < m_noOfProducts; i++) { m_products[i]->write(file, write_condensed); file << endl; } file.clear(); file.close(); } void AmaApp::listProducts() const { fstream file("inventory.txt", ios::in | ios::out); double total = 0; cout << "------------------------------------------------------------------------------------------------" << endl; cout << "| Row | SKU | Product Name | Unit | Price | Tax | QtyA | QtyN | Expiry |" << endl; cout << "|-----|---------|------------------|------------|---------|-----|--------|--------|------------|" << endl; for (int i = 0; i < m_noOfProducts; i++) { cout << "|"; cout << right << setw(4) << i + 1 << " |"; m_products[i]->write(cout, ama::write_table); cout << endl; total += *this->m_products[i]; } cout << "------------------------------------------------------------------------------------------------" << endl; cout << "| Total cost of support ($): | "; cout << setw(10) << setprecision(2) << total; cout << " |" << endl; cout << "------------------------------------------------------------------------------------------------" << endl << endl; pause(); } void AmaApp::deleteProductRecord(iProduct* product) { fstream file; file.open(m_filename, ios::out); for (int i = 0; i < m_noOfProducts; i++) { if (m_products[i] != product) { m_products[i]->write(file, write_condensed); file << endl; } } } void AmaApp::sort() { sict::sort(m_products, m_noOfProducts);//T sort(const T* data, int n) } iProduct* AmaApp::find(const char* sku) const { for (int i = 0; i < m_noOfProducts; i++) { if (*m_products[i] == sku) { return m_products[i]; } } return nullptr; } void AmaApp::addQty(iProduct* product) { int value = 0; int qty = 0; product->write(cout, ama::write_human); cout << endl << endl; cout << "Please enter the number of purchased items: "; cin >> value; if (cin.fail()) { cin.clear(); cin.ignore(123, '\n'); cout << "Invalid quantity value!" << endl << endl; } else { qty = product->qtyNeeded() - product->qtyAvailable(); if (qty <= value) { int extra = value - qty; cout << "Too many items; only " << qty << " is needed. Please return the extra " << extra << " items." << endl; *product += qty; } else { *product += value; } cout << endl << "Updated!" << endl << endl; cin.clear(); cin.ignore(1000, '\n'); } saveProductRecords(); } void AmaApp::addProduct(char tag) { iProduct* prod = ama::createInstance(tag); if (prod != nullptr) { cin >> *prod; if (cin.fail()) { cout << endl << *prod << endl << endl; cin.clear(); cin.ignore(1024, '\n'); delete prod; } else { m_products[m_noOfProducts] = prod; m_noOfProducts++; saveProductRecords(); cout << endl << "Success!" << endl << endl; } cin.clear(); } } int AmaApp::run() { int menuOption = 0; int flag = 0; iProduct* theProd = nullptr; Product oneprod; do { menuOption = menu(); switch (menuOption) { case 1://List the products AmaApp::listProducts(); break; case 2: //Display product char mm_sku[123]; cout << "Please enter the product SKU: "; cin >> mm_sku; cout << endl; cin.ignore(123, '\n'); theProd = find(mm_sku); if (theProd != nullptr) { theProd->write(cout, write_human); cout << endl; } else { cout << "No such product!" << endl; } pause(); break; case 3: //Add non-perishable product addProduct('n'); loadProductRecords(); break; case 4:// Add perishable product addProduct('p'); loadProductRecords(); break; case 5: // Add to quantity of purchased products char add_sku[123]; cout << "Please enter the product SKU: "; cin >> add_sku; theProd = find(add_sku); if (theProd != nullptr) { cout << endl; AmaApp::addQty(theProd); } else { cout << endl << "No such product!" << endl << endl; } break; case 6: //Delete product char del_sku[123]; cout << "Please enter the product SKU: "; cin >> del_sku; theProd = find(del_sku); if (theProd != nullptr) { deleteProductRecord(theProd); loadProductRecords(); cout << endl << "Deleted!" << endl; } else { cout << endl << "No such product!" << endl; } break; case 7:// Sort products AmaApp::sort(); AmaApp::saveProductRecords(); cout << "Sorted!" << endl << endl; break; case 0: //Exit program cout << "Goodbye!" << endl; return 0; break; default: cout << "~~~Invalid selection, try again!~~~" << endl; pause(); break; } } while (flag == 0); return 0; } } <file_sep>/milestones/ms5/Product.cpp /******************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop MILESTONE 2 * * DATE: 3/27/19 * ********************************************************/ #include <iostream> #include <cstring> #include <string> #include <iomanip> #include "Product.h" #include "ErrorState.h" #include "Utilities.h" using namespace std; namespace ama { void Product::message(const char* pText) { errorState.message(pText); } bool Product::isClear() const { return (errorState.message() ? false : true); } Product::Product(char type) : m_type(type) { m_sku[0] = '\0'; m_name = nullptr; m_unit[0] = '\0'; m_price = 0; m_qtyOnhand = 0; m_qtyNeeded = 0; taxStatus = false; } //A Custom Constructor with 7 arguments Product::Product(const char* sku, const char* name, const char* unit, double price, int qtyNeeded, int qtyOnhand, bool tax) : Product('N') { if (name == nullptr && name[0] == '\0' && price == 0 && sku == nullptr) { strncpy(m_sku, "", max_length_sku); strncpy(m_unit, "", max_length_unit); m_name = nullptr; m_price = 0; m_qtyNeeded = 0; m_qtyOnhand = 0; taxStatus = false; } else { strncpy(m_sku, sku, max_length_sku); int nameLength = strlen(name); m_name = new char[nameLength + 1]; strcpy(m_name, name); strncpy(m_unit, unit, max_length_unit); m_price = price; m_qtyNeeded = qtyNeeded; m_qtyOnhand = qtyOnhand; taxStatus = tax; } } Product::Product(const Product& object) : m_type('N') { strncpy(m_sku, object.m_sku, max_length_sku); int nameLength = strlen(object.m_name); m_name = new char[nameLength + 1]; strcpy(m_name, object.m_name); strncpy(m_unit, object.m_unit, max_length_unit); m_qtyOnhand = object.m_qtyOnhand; m_qtyNeeded = object.m_qtyNeeded; m_price = object.m_price; taxStatus = object.taxStatus; } Product::~Product() { delete[] m_name; } Product& Product::operator=(const Product& object) { strcpy(m_sku, object.m_sku); int nameLength = strlen(object.m_name); m_name = new char[nameLength + 1]; strcpy(m_name, object.m_name); strcpy(m_unit, object.m_unit); m_qtyOnhand = object.m_qtyOnhand; m_qtyNeeded = object.m_qtyNeeded; m_price = object.m_price; taxStatus = object.taxStatus; return *this; } int Product::operator+=(int cnt) { if (cnt > 0) { m_qtyOnhand += cnt; return m_qtyOnhand; } else return m_qtyOnhand; } bool Product::operator==(const char* sku) const { if (strcmp(m_sku, sku) == 0) return true; else return false; } bool Product::operator>(const char* sku) const { return (strcmp(m_sku, sku) > 0) ? true : false; } const char Product::type() const { return m_type; } const char* Product::name() const { return m_name; } bool Product::operator>(const iProduct& object) const { return (strcmp(m_name, object.name()) > 0) ? true : false; } int Product::qtyAvailable() const { return m_qtyOnhand; } int Product::qtyNeeded() const { return m_qtyNeeded; } double Product::oneTax() const { if (taxStatus == true) return m_price * (1 + tax_rate); else return m_price; } double Product::total_cost() const { return (oneTax() * (m_qtyOnhand)); } bool Product::isEmpty() const { if (m_name == nullptr) { return true; } else { return false; } } void Product::sku(char sku[max_length_sku+1]) { strcpy(m_sku, sku); } void Product::unit(char unit[max_length_unit+1]) { strncpy(m_unit, unit, max_length_unit); } void Product::name(const char* name) { m_name = new char[strlen(name) + 1]; strncpy(m_name, name, max_length_sku); } std::istream& Product::read(std::istream& in, bool interractive) { if (interractive == false) { in.getline(this->m_sku, max_length_sku, ','); m_name = new char[max_length_name + 1]; in.getline(m_name, max_length_name, ','); in.getline(m_unit, max_length_unit, ','); in >> m_price; in.ignore(); in >> taxStatus; in.ignore(); in >> m_qtyOnhand; in.ignore(); in >> m_qtyNeeded; in.ignore(); } else { char taxYN; cout << right << setw(max_length_label) << "Sku: "; in >> m_sku; m_name = new char[max_length_name]; cout << right << setw(max_length_label) << " Name (no spaces): "; in >> m_name; cout << right << setw(max_length_label) << " Unit: "; in >> m_unit; cout << right << setw(max_length_label) << " Taxed? (y/n): "; in >> taxYN; if (taxYN == 'Y' || taxYN == 'y') taxStatus = true; else if (taxYN == 'N' || taxYN == 'n') taxStatus = false; else { in.setstate(ios::failbit); message("Only (Y)es or (N)o are acceptable!"); } if (in.fail() == false) { cout << right << setw(max_length_label) << " Price: "; in >> m_price; if (in.fail() == true) { in.setstate(ios::failbit); message("Invalid Price Entry!"); } if (in.fail() == false) { cout << right << setw(max_length_label) << " Quantity on hand: "; in >> m_qtyOnhand; if (in.fail() == true) { in.setstate(ios::failbit); message("Invalid Quantity Available Entry!"); } if (in.fail() == false) { cout << right << setw(max_length_label) << " Quantity needed: "; in >> m_qtyNeeded; if (in.fail() == true) { in.setstate(ios::failbit); message("Invalid Quantity Needed Entry!"); } } } } } if (!in.fail()) { Product theProd(m_sku, m_name, m_unit, m_price, m_qtyNeeded, m_qtyOnhand, taxStatus); *this = theProd; } return in; } std::ostream& Product::write(std::ostream& out, int writeMode) const { if (errorState) { out << errorState; } else if (!isEmpty()) { if (writeMode == write_condensed) { out << m_type << "," << m_sku << "," << m_name << "," << m_unit << ","; out.setf(ios::fixed); out << setprecision(2); out << m_price << ","; int tax = 1; if (!taxStatus) { tax = 0; } out << tax << "," << m_qtyOnhand << "," << m_qtyNeeded; } else if (writeMode == write_table) { out << right << setw(max_length_sku+1) << m_sku << " | "; if (m_name != nullptr && (strlen(m_name) > 16)) { string str = m_name; string th = str.substr(0, 13); string dot = "..."; string name = th + dot; out << left << setw(16) << name; } else { out << left << setw(16) << m_name; } out << " | "; out << left << setw(10) << m_unit << right << " | "; out << right << setw(7); out.setf(ios::fixed); out << setprecision(2); out << m_price << " | "; string ts = "yes"; if (!taxStatus) { ts = "no"; } out << right<< setw(3) << ts << " | "; out << right << setw(6) << m_qtyOnhand << " | "; out << right << setw(6) << m_qtyNeeded << " |"; } else if (writeMode == write_human) { out << right << setw(max_length_label) << "Sku: " << m_sku << endl; out << right << setw(max_length_label) << "Name: " << m_name << endl; out.setf(ios::fixed); out << right << setw(max_length_label); out << setprecision(2); out << "Price: " << m_price << endl; out.setf(ios::fixed); out << right << setw(max_length_label); out << setprecision(2); out << "Price after Tax: " << oneTax() << endl; out << right << setw(max_length_label) << "Quantity Available: " << m_qtyOnhand << " " << m_unit << endl; out << right << setw(max_length_label) << "Quantity Needed: " << m_qtyNeeded << " " << m_unit << endl; } } return out; } } <file_sep>/cpp/w2home/CellPhone.cpp /**************************************************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * *****************************************************************************************/ // TODO: include the necessary headers #include <iostream> #include "CellPhone.h" using namespace std; // TODO: the sict namespace namespace sict { // TODO: definition for display(...) //stores the input from client and displays it void display(const CellPhone& phone) { cout << "Phone " << phone.m_model << " costs $" << phone.m_price << "!" << endl; } void display(const CellPhone Phones[], int count) { double small; //cheapest cout << "------------------------------" << endl << "Phones available at the mall:" << endl << "------------------------------" << endl; for (int i = 0; i < count; i++) { small = Phones[0].m_price; if (Phones[i].m_price < small) { small = Phones[i].m_price; } cout << i+1 << ". Phone " << Phones[i].m_model<< " costs $" << Phones[i].m_price << "!" << endl; } cout << "------------------------------" << endl << "The cheapest phone costs $" << small <<"."<< endl << "------------------------------" << endl; } } <file_sep>/cpp/w2lab/CellPhone.cpp /**************************************************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * *****************************************************************************************/ // TODO: include the necessary headers // TODO: the sict namespace // TODO: definition for display(...) #include <iostream> #include "CellPhone.h" using namespace std; namespace sict { //stores the input from client and displays it void display(const CellPhone& phone) { cout << "Phone " << phone.m_model << " costs $" << phone.m_price << "!" << endl; } } <file_sep>/cpp/w8home/Allocator.cpp /************************************************ * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 8 Lab: Account * * Dated March 20 2019 * ************************************************/ #include "SavingsAccount.h" #include "ChequingAccount.h" namespace sict { const double m_interest = 0.05; const double m_tFee = 0.50; const double m_mFee = 2.00; iAccount* CreateAccount(const char* type, double balance) { if (type[0] == 'S'){ iAccount* Stemp = new SavingsAccount(balance, m_interest); return Stemp; }else if (type[0] == 'C') { iAccount* Ctemp = new ChequingAccount(balance, m_tFee, m_mFee); return Ctemp; } else { return nullptr; } }; }<file_sep>/milestones/ms5/Date.h /******************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop MILESTONE 1 * ********************************************************/ #ifndef AMA_DATE_H #define AMA_DATE_H #include <iostream> namespace ama { const int min_year = 2019; const int max_year = 2028; const int no_error = 0; const int error_year = 1; const int error_mon = 2; const int error_day = 3; const int error_invalid_operation = 4; const int error_input = 5; class Date { //class attributes int m_year; // from min_year to max_year only int m_month; // from 1 - 12 int m_dayOfMonth; // from 1-31 int m_status; // error code //private functions void status(int newStatus); // sets status of date object int mdays(int year, int month) const; // returns number of days in a given month for a given year. public: // public functions Date(); Date(int year, int month, int day); int status() const;// A query void clearError(); //clearError(...): A modifier that resets the status of an object to no_error. bool isGood() const; // query Date& operator+=(int days); Date& operator++(); Date operator++(int); Date operator+(int days) const; bool operator==(const Date& rhs) const; bool operator!=(const Date& rhs) const; bool operator<(const Date& rhs) const; bool operator>(const Date& rhs) const; bool operator<=(const Date& rhs) const; bool operator>=(const Date& rhs) const; std::istream& read(std::istream& is); std::ostream& write(std::ostream& ostr) const; }; std::ostream& operator<<(std::ostream&, const Date&); std::istream& operator>>(std::istream&, Date&); } #endif <file_sep>/cpp/w8lab/SavingsAccount.cpp /************************************************ * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 8 Lab: Account * * Dated March 20 2019 * ************************************************/ #include "SavingsAccount.h" using namespace std; namespace sict { SavingsAccount::SavingsAccount(double balance, double interestRate): Account(balance) { if (interestRate > 0) { m_intRate = interestRate; } else m_intRate = 0.0; } /////////////////////////////////////////////// void SavingsAccount::monthEnd() { double temp = balance() * m_intRate; credit(temp); //int endBal = 0; //int endCrd = 0; //endBal = balance(); //endCrd = credit(endBal); //endCrd * m_intRate; } void SavingsAccount::display(ostream& out) const { //http://www.cplusplus.com/reference/ios/ios_base/precision/ out << "Account type: Savings" << endl; out.setf(ios::fixed, ios::floatfield); out.precision(2); out << "Balance: $" << balance() << endl; out << "Interest Rate (%): " << m_intRate * 100 << endl; out.unsetf(ios::floatfield); } //Account(double balance = 0.0); //bool credit(double amount); //bool debit(double amount); //double balance() const; }<file_sep>/milestones/ms5/Sort.cpp //https://en.cppreference.com/w/cpp/language/template_parameters //Add to the project a header file named Sort.h. In this file, #include <iostream> #include <cstring> namespace sict { } //This function should sort the elements of the array in ascending order <file_sep>/cpp/w7home/Hero.cpp /**************************************************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 7: Derived Classes (Hero) * * Date: 3.13.2019 * *****************************************************************************************/ #include <cstring> #include "Hero.h" using namespace std; namespace sict { Hero::Hero() { m_name[0] = '\0'; m_health = 0; m_attack = 0; } Hero::Hero(const char *name, int health, int attack) { if ((name[0] != '\0') && (health > 0) && (attack > 0)) { strncpy(m_name, name, 40); m_health = health; m_attack = attack; } else { *this = Hero(); } } void Hero::operator-=(int attack) { if (attack > 0) { if (isAlive()) m_health -= attack; if (m_health < 0) { m_health = 0; } } } bool Hero::isAlive() const { if (m_health > 0) return true; else return false; } int Hero::attackStrength() const { if (m_name[0] == '\0' && m_health == 0 && m_attack == 0) { return 0; } else { return m_attack; } } std::ostream& operator<<(std::ostream& os, const Hero& hero) { if (hero.attackStrength() != 0) { os << hero.m_name; return os; } else { os << "No hero"; return os; } } const Hero& operator*(const Hero& first, const Hero& second) { Hero one = first; Hero two = second; Hero winner; for (int i = 0; i < max_rounds && one.isAlive() != 0 && two.isAlive() != 0; i++) { one -= two.attackStrength(); two -= one.attackStrength(); if (one.isAlive() == false || two.isAlive() == false) { cout << "Ancient Battle! " << one << " vs " << two << " : Winner is "; if (one.isAlive() == false) cout << two; else cout << one; cout << " in " << i + 1 << " rounds." << endl; } } if (one.isAlive() && two.isAlive() == false) return first; else return second; } }<file_sep>/cpp/w3lab/Book.cpp /**************************************************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * *****************************************************************************************/ #include <iostream> #include <cstring> #include <cmath> #include "Book.h" using namespace std; namespace sict { void Book::set(const char* gName, const char* fName, const char* tit, long long number) { /*delete[] family_name; delete[] given_name; delete[] isbn; family_name = new char; given_name = new char; isbn = new char;*/ if (min_isbn_value <= number && number <= max_isbn_value) { strncpy(this->title, tit, max_title_size); strncpy(this->family_name, fName, max_name_size); strncpy(this->given_name, gName, max_name_size); isbn = number; } else { isbn = 0; } } bool Book::isEmpty() const { if (isbn == 0) { return true; }else return false; } void Book::display() const { if (Book::isEmpty() == false) { cout << "Author: " << family_name << ", " << given_name << endl << "Title: " << title << endl << "ISBN-13: " << isbn << endl; } else cout << "The book object is empty!" << endl; } } <file_sep>/cpp/w2lab/CellPhone.h /**************************************************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * *****************************************************************************************/ // TODO: header safeguards #ifndef SICT_CAKE_H #define SICT_CAKE_H // TODO: sict namespace namespace sict { // TODO: define the structure CellPhone in the sict namespace struct CellPhone { //cellphone model name that contains 32 characters, including null //holes the description of the cellphone model char m_model[32]; //floating point number in double precision //stores the price of cellphone double m_price; }; // TODO: declare the function display(...), // also in the sict namespace //display function to displa the phone model and the phone price void display(const CellPhone&); //a query } #endif <file_sep>/cpp/w6home/Contact.cpp /**************************************************************************************** * Name: <NAME> and <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 6: Class with a Resource * * Date: 3.8.2019 * *****************************************************************************************/ #include <iostream> #include <cstring> #include <iomanip> #include "Contact.h" using namespace std; namespace sict { bool Contact::check(long long phoneNumber) const { if (phoneNumber > 0) { return true; } if ( (10000000000 <= phoneNumber) && (phoneNumber <= 999999999999) && ((phoneNumber % 10000000000 / 1000000000) >= 1) && ((phoneNumber % 10000000 / 1000000) >= 1) ) { return true; } else { return false; } } void Contact::emptyThis() { m_nameOfContact[0] = '\0'; m_phoneNumbers = nullptr; m_numberOfPhoneNumbers = 0; } Contact::Contact() { emptyThis(); } Contact::Contact(const char *name, const long long *phone, const int number) { emptyThis(); int valid = 0; if (name == '\0') { *this->m_nameOfContact = '\0'; } else { strncpy(this->m_nameOfContact, name, max_name_size - 1); } m_numberOfPhoneNumbers = number; for(int a = 0; a < number; a++) { if (check(phone[a])) { valid++; } } if (phone) { m_phoneNumbers = new long long[valid]; for (int i = 0; i < number; i++) { if (check(phone[i])) { m_phoneNumbers[i] = phone[i]; } } } } Contact::~Contact() { delete[] m_phoneNumbers; } bool Contact::isEmpty() const { if (m_nameOfContact[0] == '\0' || m_nameOfContact == nullptr) { return true; } else { return false; } } void Contact::display() const { if (isEmpty() == true) { cout << "Empty contact!" << endl; } else { cout << m_nameOfContact << endl; for (int i = 0; i < m_numberOfPhoneNumbers; i++) { if ( (10000000000 <= m_phoneNumbers[i]) && (m_phoneNumbers[i] <= 999999999999) && ((m_phoneNumbers[i] % 10000000000 / 1000000000) >= 1) && ((m_phoneNumbers[i] % 10000000 / 1000000) >= 1) ) { int countryCode = m_phoneNumbers[i] / 10000000000; int areaCode = m_phoneNumbers[i] % 10000000000 / 10000000; int first = m_phoneNumbers[i] % 10000000 / 10000; int second = m_phoneNumbers[i] % 10000000 % 10000; cout << "(+" << countryCode << ") " << areaCode << " "; cout << setfill('0') << setw(3); cout << first << "-"; cout << setfill('0') << setw(4); cout << second << endl; } } } } Contact::Contact(const Contact& duplicate) { m_phoneNumbers = nullptr; *this = duplicate; } Contact& Contact::operator=(const Contact& copy) { if (this != &copy) { strncpy(this->m_nameOfContact, copy.m_nameOfContact, max_name_size - 1); //name m_numberOfPhoneNumbers = copy.m_numberOfPhoneNumbers; //size delete[] m_phoneNumbers; //clear if (copy.m_phoneNumbers != nullptr) //phone { m_phoneNumbers = new long long[m_numberOfPhoneNumbers]; for (int i = 0; i < m_numberOfPhoneNumbers; i++) { m_phoneNumbers[i] = copy.m_phoneNumbers[i]; } } else m_phoneNumbers = nullptr; //0 } // cout << "operator ="; return *this; //reference } Contact& Contact::operator+=(long long phoneNumber) { bool valid = check(phoneNumber); if (valid == true) //validates the number received { m_numberOfPhoneNumbers++; long long* new_PhoneNumbers = new long long[m_numberOfPhoneNumbers]; // resizes the phone number array to hold all of the existing number for (int i = 0; i < m_numberOfPhoneNumbers - 1; ++i) //reload { new_PhoneNumbers[i] = m_phoneNumbers[i]; } new_PhoneNumbers[m_numberOfPhoneNumbers - 1] = phoneNumber; //hold new delete[] m_phoneNumbers; //garbage bin m_phoneNumbers = new_PhoneNumbers; //new } return *this; //ref } } <file_sep>/milestones/ms5/Date.cpp /******************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop MILESTONE 1 * ********************************************************/ #include <iostream> #include "Date.h" using namespace std; namespace ama { void Date::status(int newStatus) { m_status = newStatus; } int Date::mdays(int year, int mon) const { int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, -1 }; int month = mon >= 1 && mon <= 12 ? mon : 13; month--; return days[month] + int((month == 1)*((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)); } Date::Date() { m_year = 0; m_month = 0; m_dayOfMonth = 0; clearError(); } Date::Date(int year, int month, int day) { if (year >= min_year && year <= max_year) { if (month >= 1 && month <= 12) { if (day > 0 && day <= mdays(year, month)) { m_year = year; m_month = month; m_dayOfMonth = day; status(no_error); } else { status(error_day); } } else { status(error_mon); } } else { status(error_year); } if (!isGood()) { m_year = 0; m_month = 0; m_dayOfMonth = 0; } } int Date::status() const { return m_status; } void Date::clearError() { this->m_status = no_error; } bool Date::isGood() const { bool test = false; if ( (m_status == no_error) && (m_year >= min_year && m_year <= max_year) && (m_month >= 1 && m_month <= 12) && (m_dayOfMonth <= mdays(m_year, m_month)) ) { test = true; } return test; } Date& Date::operator+=(int days) { if (isGood() == false) { m_status = error_invalid_operation; } else { int number = m_dayOfMonth + days; if (number <= mdays(m_year, m_month) && number > 0) { m_dayOfMonth += days; m_status = no_error; } else { m_status = error_invalid_operation; } } return *this; } Date& Date::operator++() //prefix++ { if (isGood() == false) { m_status = error_invalid_operation; } else { int number = m_dayOfMonth + 1; if (number <= mdays(m_year, m_month)) { m_dayOfMonth += 1; m_status = no_error; } else { m_status = error_invalid_operation; } } return *this; } Date Date::operator++(int) //postfix { Date temp = *this; if (isGood() == false) { m_status = error_invalid_operation; } else { int number = m_dayOfMonth + 1; if (number <= mdays(m_year, m_month)) { m_dayOfMonth += 1; m_status = no_error; } else { m_status = error_invalid_operation; } } return temp; } Date Date::operator+(int days) const { Date plus = *this; plus += days; return plus; } bool Date::operator==(const Date& rhs) const { bool dayEqual = this->m_dayOfMonth == rhs.m_dayOfMonth; bool monthEqual = this->m_month == rhs.m_month; bool yearEqual = this->m_year == rhs.m_year; return (dayEqual && monthEqual && yearEqual); } bool Date::operator!=(const Date& rhs) const { return !(*this == rhs); } bool Date::operator<(const Date& rhs) const { bool yearLess = this->m_year < rhs.m_year; bool monthLess = this->m_month < rhs.m_month; bool dayLess = this->m_dayOfMonth < rhs.m_dayOfMonth; if (yearLess) { return true; } else if (monthLess) { return true; } else if (dayLess) { return true; } else { return false; } } bool Date::operator>(const Date& rhs) const { bool dayGreat = this->m_dayOfMonth > rhs.m_dayOfMonth; bool monthGreat = this->m_month > rhs.m_month; bool yearGreat = this->m_year > rhs.m_year; if (yearGreat) { return true; } else if (monthGreat) { return true; } else if (dayGreat) { return true; } else { return false; } } bool Date::operator<=(const Date& rhs) const { return (*this < rhs || *this == rhs); } bool Date::operator>=(const Date& rhs) const { return (*this > rhs || *this == rhs); } std::istream& Date::read(std::istream& is) { int year = 0, month = 0, day = 0; is >> year; is.ignore(); is >> month; is.ignore(); is >> day; if (is.fail()) { this->status(error_input); } else *this = Date(year, month, day); return is; } std::ostream& Date::write(std::ostream& os) const { os.fill('0'); os.width(4); os << m_year; os << "/"; os.fill('0'); os.width(2); os.unsetf(ios::left); os << m_month; os << "/"; os.fill('0'); os.width(2); os << m_dayOfMonth; os.fill(' '); return os; } std::ostream& operator<<(std::ostream& os, const Date& date) { date.write(os); return os; } std::istream& operator>>(std::istream& is, Date& date) { date.read(is); return is; } } <file_sep>/cpp/w7home/Hero.h /**************************************************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 7: Derived Classes (Hero) * * Date: 3.13.2019 * *****************************************************************************************/ #ifndef SICT_HERO_H #define SICT_HERO_H #include <iostream> namespace sict { const int max_rounds = 100; class Hero { char m_name[40]; int m_health; int m_attack; public: Hero(); Hero(const char *name, int health, int attack); void operator-=(int attack); bool isAlive() const; int attackStrength() const; friend std::ostream& operator<<(std::ostream& os, const Hero& hero); }; const Hero& operator*(const Hero& first, const Hero& second); } #endif // !SICT_HERO_H <file_sep>/milestones/ms5/iProduct.h /******************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop MILESTONE 2 * * DATE: 3/27/19 * ********************************************************/ #ifndef AMA_IPRODUCT_H #define AMA_IPRODUCT_H #include <iostream> namespace ama { const int max_length_label = 30; const int max_length_sku = 7; const int max_length_name = 75; const int max_length_unit = 10; const int write_condensed = 0; const int write_table = 1; const int write_human = 2; const double tax_rate = 0.13; class iProduct { public: //pure virtual virtual std::ostream& write(std::ostream& os, int writeMode) const = 0; virtual std::istream& read(std::istream& is, bool interractive) = 0; virtual bool operator==(const char* sku) const = 0; virtual double total_cost() const = 0; virtual int qtyNeeded() const = 0; virtual int qtyAvailable() const = 0; virtual const char* name() const = 0; virtual int operator+=(int qty) = 0; virtual bool operator>(const iProduct& other) const = 0; virtual ~iProduct() = default; }; } #endif //AMA_IPRODUCT_H<file_sep>/cpp/w3home/Book.h /**************************************************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * *****************************************************************************************/ #ifndef Book_H //header safeguards #define Book_H namespace sict { const int max_title_size = 32; const int max_name_size = 16; const long long min_isbn_value = 1000000000000; const long long max_isbn_value = 9999999999999; class Book { char family_name[max_name_size]; char given_name[max_name_size]; long long isbn; char title[max_title_size]; int m_year; float m_price; public: void set(const char*, const char*, const char*, long long); void set(int, double); bool isEmpty() const; void display(bool = false) const; }; } #endif <file_sep>/cpp/w4home/Traveler.cpp // TODO: add file header comments here /**************************************************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 4 Home: TRAVELERS VALIDATION LOGIC * *****************************************************************************************/ // TODO: add your headers here #include <iostream> #include <cstring> #include "Traveler.h" using namespace std; // TODO: continue your namespace here namespace sict { // TODO: implement the default constructor here Traveler::Traveler() //my custom made constructor { *this->m_tFirstName = '\0'; *this->m_tLastName = '\0'; *this->m_destination = '\0'; } // TODO: implement the constructor with 3 parameters here Traveler::Traveler(const char* firstName, const char* lastName, const char* destination) { if ((firstName == '\0' || nullptr) || (lastName == '\0' || nullptr) || (destination == '\0' || nullptr)) { *this = Traveler(); //instead of: //*this->m_tFirstName = '\0'; //*this->m_tLastName = '\0'; //*this->m_destination = '\0'; } else { strncpy(this->m_tFirstName, firstName, name_size); strncpy(this->m_tLastName, lastName, name_size); strncpy(this->m_destination, destination, max_desination_size); m_dYear = 2019; m_dMonth = 7; m_dDay = 1; } } // TODO: implement isEmpty query here bool Traveler::isEmpty() const { if ((*this->m_tFirstName == '\0' || m_tFirstName == nullptr) || (*this->m_tLastName == '\0' || m_tLastName == nullptr) || (*this->m_destination == '\0' || m_destination == nullptr)) return true; else return false; } // TODO: implement display query here void Traveler::display() const { if (Traveler::isEmpty() == false) { cout << m_tLastName << ", " << m_tFirstName << " goes to " << m_destination << " on " << this->m_dYear << "/"; cout.fill('0'); cout.width(2); cout << m_dMonth << "/"; cout.fill('0'); cout.width(2); cout << m_dDay << endl; } else { cout << "--> Not a valid traveler! <--" << endl; } } Traveler::Traveler(const char* fName, const char* lName, const char* dest, const int year, const int month, const int day) { if ( (fName == '\0' || nullptr) || (lName == '\0' || nullptr) || (dest == '\0' || nullptr) || (year < 2019) || (year > 2022) || (year == 0) || (month < 1) || (month > 12) || (month == 0) || (day < 1) || (day > 31) || (day == 0) ) { *this = Traveler(); m_dYear = 0; m_dMonth = 0; m_dDay = 0; } else { strncpy(this->m_tFirstName, fName, name_size); strncpy(this->m_tLastName, lName, name_size); strncpy(this->m_destination, dest, max_desination_size); this->m_dYear = year; this->m_dMonth = month; this->m_dDay = day; } } const char* Traveler::name() const { return m_tFirstName; } //bool canTravelWith(const Traveler&) const; bool Traveler::canTravelWith(const Traveler& friends) const { if ((strcmp(friends.m_destination, m_destination) == 0) && (friends.m_dYear == m_dYear) && (friends.m_dMonth == m_dMonth) && (friends.m_dDay == m_dDay)) return 1; return 0; } } <file_sep>/cpp/w7home/SuperHero.h /**************************************************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 7: Derived Classes (Hero) * * Date: 3.17.2019 * *****************************************************************************************/ #ifndef SICT_SUPERHERO_H #define SICT_SUPERHERO_H #include "Hero.h" namespace sict { class SuperHero : public Hero { int m_bonus; int m_defend; public: SuperHero(); SuperHero(const char *name, int health, int attack, int bonus, int defend); int attackStrength() const; int defend() const; }; const SuperHero& operator*(const SuperHero& first, const SuperHero& second); } #endif <file_sep>/cpp/w8home/Account.cpp /************************************************ * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 8 Lab: Account * * Dated March 20 2019 * ************************************************/ #include "Account.h" namespace sict { Account::Account(double balance) { if (balance > 0) { m_iniBal = balance; } else m_iniBal = 0.0; } bool Account::credit(double amount) { if (amount > 0) { m_iniBal = m_iniBal + amount; return true; } else return false; } bool Account::debit(double amount) { if (amount > 0) { m_iniBal = m_iniBal - amount; return true; } else return false; } double Account::balance() const { return m_iniBal; } //virtual ~iAccount() = default; //virtual bool credit(double amount) = 0; //virtual bool debit(double amount) = 0; //virtual void monthEnd() = 0; //virtual void display(ostream& out) const = 0; } <file_sep>/cpp/w1home/tools.h /**************************************************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * *****************************************************************************************/ #ifndef SICT_TOOLS_H #define SICT_TOOLS_H namespace sict{ // Displays the user interface menu int menu(); // Performs a fool-proof integer entry int getInt(int min, int max); } #endif <file_sep>/cpp/w8home/ChequingAccount.cpp /************************************************ * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 8 Home: Account * * Dated March 24 2019 * ************************************************/ #include "ChequingAccount.h" using namespace std; namespace sict { ChequingAccount::ChequingAccount(double balance, double transFee, double monthlyFee): Account(balance) { if (transFee > 0) m_transFee = transFee; else m_transFee = 0.0; if (monthlyFee > 0) m_monthlyFee = monthlyFee; else m_monthlyFee = 0.0; } bool ChequingAccount::credit(double amount) { if (amount > 0) { Account::credit(amount); Account::debit(m_transFee); return true; } else return false; } bool ChequingAccount::debit(double amount) { if (amount > 0) { Account::debit(amount); Account::debit(m_transFee); return true; } else return false; } void ChequingAccount::monthEnd() { debit(m_monthlyFee-m_transFee); } void ChequingAccount::display(ostream& out) const { out << "Account type: Chequing" << endl; out.setf(std::ios::fixed); out.precision(2); out << "Balance: $" << balance() << endl; out << "Per Transaction Fee: " << m_transFee << endl; out << "Monthly Fee: " << m_monthlyFee << endl; out.unsetf(std::ios::fixed); } } <file_sep>/cpp/w4lab/Traveler.cpp // TODO: add file header comments here /**************************************************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 4 Lab: TRAVELERS VALIDATION LOGIC * *****************************************************************************************/ // TODO: add your headers here #include <iostream> #include <cstring> #include "Traveler.h" using namespace std; // TODO: continue your namespace here namespace sict { // TODO: implement the default constructor here Traveler::Traveler() //default constructor { *this->m_tFirstName = '\0'; *this->m_tLastName = '\0'; *this->m_destination = '\0'; } // TODO: implement the constructor with 3 parameters here Traveler::Traveler(const char* firstName, const char* lastName, const char* destination) { if ((firstName == '\0' || nullptr) || (lastName == '\0' || nullptr) || (destination == '\0' || nullptr)) { *this->m_tFirstName = '\0'; *this->m_tLastName = '\0'; *this->m_destination = '\0'; } else { strncpy(this->m_tFirstName, firstName, name_size); strncpy(this->m_tLastName, lastName, name_size); strncpy(this->m_destination, destination, max_desination_size); } } // TODO: implement isEmpty query here bool Traveler::isEmpty() const { if ((*this->m_tFirstName == '\0' || m_tFirstName == nullptr) || (*this->m_tLastName == '\0' || m_tLastName == nullptr) || (*this->m_destination == '\0' || m_destination == nullptr)) return true; else return false; } // TODO: implement display query here void Traveler::display() const { if (Traveler::isEmpty() == false) { cout << m_tFirstName << " " << m_tLastName << " goes to " << m_destination << endl; } else { cout << "--> Not a valid traveler! <--" << endl; } } } <file_sep>/cpp/w7home/SuperHero.cpp /**************************************************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 7: Derived Classes (Hero) * * Date: 3.17.2019 * *****************************************************************************************/ #include <cstring> #include "Hero.h" #include "SuperHero.h" using namespace std; namespace sict { SuperHero::SuperHero() { Hero("", 0, 0); m_bonus = 0; m_defend = 0; } SuperHero::SuperHero(const char *name, int health, int attack, int bonus, int defend) : Hero(name, health, attack) { if ((name[0] != '\0') && (health > 0) && (attack > 0)) { Hero(name, health, attack); m_bonus = bonus; m_defend = defend; } else { *this = SuperHero(); m_bonus = 0; m_defend = 0; } } int SuperHero::attackStrength()const { if (m_bonus == 0 && m_bonus == 0) return 0; else return (Hero::attackStrength() + m_bonus); } int SuperHero::defend() const { if (m_bonus == 0 && m_defend == 0) return 0; else return m_defend; } const SuperHero& operator*(const SuperHero& first, const SuperHero& second) { SuperHero one = first; SuperHero two = second; SuperHero winner; for (int i = 0; i < max_rounds && one.isAlive() != 0 && two.isAlive() != 0; i++) { one -= (two.attackStrength() - one.defend()); two -= (one.attackStrength() - two.defend()); if (one.isAlive() == false || two.isAlive() == false) { cout << "Super Fight! " << one << " vs " << two << " : Winner is "; if (one.isAlive() == false) cout << two; else cout << one; cout << " in " << i + 1 << " rounds." << endl; } } if (one.isAlive() && two.isAlive() == false) return first; else return second; } } <file_sep>/milestones/ms3/Product.h /******************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop MILESTONE 2 * * DATE: 3/25/19 * ********************************************************/ #ifndef AMA_PRODUCT_H #define AMA_PRODUCT_H #include <iostream> #include "ErrorState.h" namespace ama { const int max_length_label = 30; const int max_length_sku = 7; const int max_length_name = 75; const int max_length_unit = 10; const int write_condensed = 0; const int write_table = 1; const int write_human = 2; const double tax_rate = 0.13; class Product { const char m_type; char m_sku[max_length_sku]; char m_unit[max_length_unit]; char* m_name;//[max_length_name]; int m_qtyOnhand; int m_qtyNeeded; double m_price; bool taxStatus; ErrorState errorState; protected: void message(const char* pText); bool isClear() const; public: Product(char type = 'N'); //Zero/One Argument Constructor Product(const char* sku, const char* name, const char* unit, double price = 0, int qtyNeeded = 0, int qtyOnhand = 0, bool tax = true);//A Custom Constructor with 7 arguments Product(const Product& object);//The Copy Constructor. ~Product();//The Destructor Product& operator=(const Product& obj);//The Copy Assignment Operator double oneTax() const; int operator+=(int cnt); bool operator==(const char* sku) const; bool operator>(const char* sku) const; bool operator>(const Product&) const; int qtyAvailable() const; int qtyNeeded() const; double total_cost() const; bool isEmpty() const; std::istream& read(std::istream& in, bool interractive); std::ostream& write(std::ostream& out, int writeMode) const; //std::ostream& operator<<(double value); }; } #endif <file_sep>/cpp/w7lab/Hero.cpp /**************************************************************************************** * Name: <NAME> * * Seneca Email: <EMAIL> * * Student Number: 104497185 * * Workshop 7: Derived Classes (Hero) * * Date: 3.13.2019 * *****************************************************************************************/ #include <cstring> #include "Hero.h" using namespace std; namespace sict { Hero::Hero() { m_name[0] = '\0'; m_health = 0; m_attack = 0; } Hero::Hero(const char *name, int health, int attack) { if ((name[0] != '\0') && (health > 0) && (attack > 0)) { strncpy(m_name, name, 40); m_health = health; m_attack = attack; } else { *this = Hero(); } } void Hero::operator-=(int attack) { if (attack > 0) { if (isAlive()) m_health -= attack; if (m_health < 0) { m_health = 0; } } } bool Hero::isAlive() const { if (m_health > 0) return true; else return false; } int Hero::attackStrength() const { if (m_name[0] == '\0' && m_health == 0 && m_attack == 0) { return 0; } else { return m_attack; } } std::ostream& operator<<(std::ostream& os, const Hero& hero) { if (hero.attackStrength() != 0) { os << hero.m_name; return os; } else { os << "No hero"; return os; } } const Hero& operator*(const Hero& first, const Hero& second) { Hero left = first, right = second, winner; int round = 0; for (int i = 0; i < max_rounds && (left.isAlive() && right.isAlive()); ++i) { left -= right.attackStrength(); right -= left.attackStrength(); round = i; } round++; if (!left.isAlive() && !right.isAlive()) { winner = left; cout << "Ancient Battle! " << first << " vs " << second << " : Winner is " << winner << " in " << round << " rounds." << endl; return first; } else if (!left.isAlive()) { winner = right; cout << "Ancient Battle! " << first << " vs " << second << " : Winner is " << winner << " in " << round << " rounds." << endl; return second; } else if (!right.isAlive()) { winner = left; cout << "Ancient Battle! " << first << " vs " << second << " : Winner is " << winner << " in " << round << " rounds." << endl; return first; } else { return first; } } }
4b44c6bf38e09ac217f0b7fcd6af88c788a43a3e
[ "C", "C++" ]
51
C++
NesaByte/First-Of-Cornelius-Reign
79b938f7017260b1d9235ffc9b32b62f699d01c5
31329cec1caccb3aaadb0133d07e230bee4d2fcd
refs/heads/master
<repo_name>hyperioware/Game-Board-Generator<file_sep>/js/index.js class Board{ height = 0; width = 0; name = ""; tiles = {}; constructor(settings){ this.height = settings.height; this.width = settings.width; this.name = settings.name; this.tiles = settings.tiles; } updateTile(){ //TODO } addTile(){ //TODO } removeTile(){ //TODO } } <file_sep>/README.md Welcome to the Game Board Generator! The idea is to be able to design a game board that can be played on via the web or printed and placed on a table. Users could create anything from a chess board to a D&D board by setting the board tiles, defining the pieces, and setting the rules.
3d4bb60d170b84bd5b2e38a6c246e4a9e82bde1e
[ "JavaScript", "Markdown" ]
2
JavaScript
hyperioware/Game-Board-Generator
c1c472f43e638f31cf5c91862b3e3947d22d1906
d068617359019ac0b514511b77b8948062a484b1
refs/heads/master
<file_sep>package actions; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Action; import org.openqa.selenium.interactions.Actions; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; public class DragAndDrop { WebDriver driver; String URL_14 = "http://nouri-tawfik.com/formations/selenium/demo-v1/views/droppable.php"; @BeforeTest public void setUp() { System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); driver.manage().window().maximize(); } @Test public void demoSwitchAlerte() throws Exception { long startTime; long endTime; long duration; double seconds; //open URL startTime=System.nanoTime(); driver.get(URL_14); endTime=System.nanoTime(); duration=endTime-startTime; seconds=duration/1000000000.0; System.out.println("logging page time:" +seconds); //from WebElement MyFrame = driver.findElement(By.className("demo-frame")); driver.switchTo().frame(MyFrame); WebElement draggable =driver.findElement(By.id("draggable")); //to WebElement droppable =driver.findElement(By.id("droppable")); //message WebElement message =driver.findElement(By.xpath("//div[@id='droppable']/p")); // Actions myAction =new Actions(driver) ; myAction.clickAndHold(draggable).moveToElement(droppable).release().build().perform(); // action enchainé par une autre action String newMessage =message.getText(); System.out.println(newMessage); Assert.assertEquals(newMessage,"Dropped!"); } @AfterTest public void cleanUp() throws Exception { Thread.sleep(3000); // driver.quit(); } } <file_sep>package advanced; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.io.FileHandler; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import org.openqa.selenium.io.FileHandler; import java.util.concurrent.TimeUnit; import java.io.File; public class ScreenShot { WebDriver driver; JavascriptExecutor js; String URL_14 = "http://nouri-tawfik.com/formations/selenium/demo-v1/views/droppable.php"; @BeforeTest public void setUp() { System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); driver.manage().window().maximize(); } @Test public void demoSwitchAlerte() throws Exception { //open URL driver.get(URL_14); File ramFile=((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);//TakesScreenshot is an interface that implements chromedriver FileHandler.copy(ramFile, new File("C:\\IMAGE\\Testt.png")); } @AfterTest public void cleanUp() throws Exception { Thread.sleep(3000); // driver.quit(); } } <file_sep>package dbtest; import org.openqa.selenium.WebDriver; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.sql.*; import java.util.Properties; public class PostgresqlDBTesting { // Connection object static Connection conn = null; // Statement object private static Statement st; // Result set private static ResultSet results = null; // Contant for Database URL public static String DB_URL = "jdbc:postgresql://localhost:5432/user"; // Contant for Database Username public static String DB_USER = "postgres"; // Contant for Database Password public static String DB_PASSWORD = "<PASSWORD>"; // Driver public static String driver = "org.postgresql.Driver"; // WebDriver public static WebDriver wd; @BeforeClass public void beforeClass() { // Initialize WebDriver //wd = new ChromeDriver(); // Properties for creating connection to database Properties props = new Properties(); props.setProperty("user", "postgres"); props.setProperty("password", "<PASSWORD>"); try { // STEP 1: Register JDBC driver Class.forName(driver).newInstance(); // STEP 2: Get connection to DB System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); // conn = DriverManager.getConnection(DB_URL, props); System.out.println("Connected database successfully..."); // STEP 3: Statement object to send the SQL statement to the Database System.out.println("Creating statement..."); st = conn.createStatement(); } catch (Exception e) { e.printStackTrace(); } } @Test public void test() { String query = "select * from user_info"; try { // STEP 4: Extract data from result set results = st.executeQuery(query); while(results.next()) { int id = results.getInt("user_id"); String first = results.getString("first_name"); String last = results.getString("last_name"); String city = results.getString("city"); // Display value System.out.println("ID: "+id); System.out.println("First Name: "+first); System.out.println("Last Name: "+last); System.out.println("City: "+city); // From GUI //WebElement element = wd.findElement(By.id("uname")); //String actualUsername = element.getText(); //Assert.assertEquals(actualUsername, first); } results.close(); } catch (SQLException se) { se.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } } @AfterClass public void afterClass() { try { if(results != null) results.close(); if(st != null) conn.close(); if(conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } } } <file_sep>package selftraining; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import java.io.File; import org.openqa.selenium.io.FileHandler; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.concurrent.TimeUnit; public class Screenshots { WebDriver driver; // URL05 String baseUrl = "https://www.expedia.com/"; @Before public void setUp() throws Exception{ System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); //driver.manage().window().maximize(); driver.get(baseUrl); Thread.sleep(1000); } @Test public void demoScreenshots() throws Exception { driver.findElement(By.id("tab-flight-tab-hp")).click(); //Find elements WebElement flight_origin = driver.findElement(By.id("flight-origin-hp-flight")); WebElement flight_destination = driver.findElement(By.id("flight-destination-hp-flight")); WebElement departure_date = driver.findElement(By.id("flight-departing-hp-flight")); WebElement return_date = driver.findElement(By.id("flight-returning-hp-flight")); // WebElement search = driver.findElement(By.xpath("//*[@id='gcw-flights-form-hp-flight']/div[8]/label/button")); WebElement search =driver.findElement(By.id("search-button-hp-package")); //Send data to the elements flight_origin.sendKeys("New York"); departure_date.sendKeys("05/22/2018"); return_date.clear(); return_date.sendKeys("05/23/2018"); flight_destination.sendKeys("Chicago"); search.click(); } @After public void tearDown() throws Exception { /*String fileName = ".//Screenshots//ScreenShot"+"_"+getDate()+".png"; File screenFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileHandler.copy(screenFile, new File(fileName)); */ File myFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileHandler.copy(myFile, new File("c:/test.png")); System.out.println("screenshot finished"); Thread.sleep(2000); driver.quit(); } public static String getDate() { Date today = Calendar.getInstance().getTime(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss"); return formatter.format(today); } } <file_sep>package driver; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.sql.Driver; import java.util.List; import java.util.Set; public class ChromeDriverDemo { WebDriver driver; String URL = "https://www.google.com/"; @BeforeTest public void setup() { // iNIT System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); driver = new ChromeDriver(); } @Test public void demochrome() { // LOADING PAGE driver.get(URL); //GETTING ID // /html//form[@id='tsf']//div[@class='a4bIc']/input[@role='combobox'] //Driver.findElement(By.xpath(""//form[@id='tsf']//div[@class='a4bIc']/input[@role='combobox'])ath("").sendkeys(); driver.findElement(By.id("lst-ib")).sendKeys("marwa\n"); // String title = driver.getTitle(); Assert.assertEquals(title, "marwa - Recherche Google"); } @AfterTest public void clr() { driver.quit(); } } <file_sep>package basics; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; public class SwitchFrame { WebDriver driver; // URL 02 String baseUrl = "http://nouri-tawfik.com/formations/selenium/demo-v1/practice-page.html"; @BeforeTest public void setUp() throws Exception{ System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); //driver.manage().window().maximize(); driver.get(baseUrl); Thread.sleep(1000); } @Test public void demoSwitchFrame() throws Exception { Thread.sleep(3000); // Switch to frame by Id driver.switchTo().frame("courses-iframe"); // Switch to frame by name //driver.switchTo().frame("iframe-name"); // Switch to frame by numbers //driver.switchTo().frame(0); // Open a new link driver.findElement(By.linkText("Les fondamentaux du Raspberry Pi")).click(); Thread.sleep(4000); driver.switchTo().defaultContent(); Thread.sleep(6000); driver.findElement(By.id("name")).sendKeys("Test Successful"); } @AfterTest public void tearDown() throws Exception { Thread.sleep(5000); driver.quit(); } } <file_sep>package selftraining; import net.bytebuddy.utility.JavaModule; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Action; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.Select; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.Set; import java.util.concurrent.TimeUnit; public class SeWebDriver { WebDriver driver; String URL="http://nouri-tawfik.com/formations/selenium/demo-v1/practice-page.html"; String URL2="http://nouri-tawfik.com/formations/selenium/demo-v1/views/droppable.php"; @BeforeTest public void Setup(){ System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait( 15, TimeUnit.SECONDS) ; driver.manage().window().maximize(); } @Test(enabled = false) public void test(){ driver.get(URL); String title =driver.findElement(By.className("navbar-brand")).getText(); Assert.assertEquals(title,"SELENIUM WEBDRIVER"); } @Test(enabled = false) public void testRadioButton() { driver.get(URL); WebElement radio1 = driver.findElement(By.id("bmwradio")); Boolean IsSelected =radio1.isSelected(); Assert.assertEquals(IsSelected,Boolean.FALSE); radio1.click(); IsSelected =radio1.isSelected(); Assert.assertEquals(IsSelected,Boolean.TRUE); WebElement radio2 =driver.findElement(By.id("benzradio")); radio2.click(); } @Test(enabled = false) public void multiSelect(){ driver.get(URL); WebElement select =driver.findElement(By.id("multiple-select-example")); Select mySelection=new Select(select); mySelection.selectByIndex(0); mySelection.selectByVisibleText("Orange"); mySelection.selectByValue("peach"); System.out.println("all items are selected"); // mySelection.deselectAll(); //System.out.println("all items are deselected"); } @Test(enabled =false) public void selectClass(){ driver.get(URL); WebElement carSelect =driver.findElement(By.id("carselect")); Select car=new Select(carSelect); car.selectByValue("benz"); } @Test(enabled = false) public void demoSwitchAlerte() throws Exception{ String input="marwa"; driver.get(URL); WebElement name=driver.findElement(By.id("name")); name.sendKeys(input); WebElement AlerteButton=driver.findElement(By.id("alertbtn")); AlerteButton.click(); //Switching Alert myAlerte=driver.switchTo().alert(); //getting ALerte message String AlerteMessage=myAlerte.getText(); Assert.assertEquals(AlerteMessage,"Hello " +input+ ", share this practice page and share your knowledge"); myAlerte.accept(); } @Test(enabled = false) public void switchWindow()throws Exception{ driver.get(URL); String mainPage = driver.getWindowHandle(); System.out.println(mainPage); // Get the handle String parentHandle = driver.getWindowHandle(); System.out.println("Parent Handle: " + parentHandle); // Find Open Window button WebElement OpenTab =driver.findElement(By.id("opentab")); OpenTab.click(); // Get all handles Set<String> allPageshandles = driver.getWindowHandles(); System.out.println("ALLpages= " + allPageshandles); // Switching between handles for (String currentPage : allPageshandles) { System.out.println("Current Page " + currentPage); if (!currentPage.equals(parentHandle)) { // Switch to new opened window ==> 'http://nouri-tawfik.com/se-former.html' driver.switchTo().window(currentPage); Thread.sleep(2000); // Open a new link driver.findElement(By.linkText("Les fondamentaux du Raspberry Pi")).click(); Thread.sleep(4000); driver.close(); break; } } // Switch back to the parent window driver.switchTo().window(parentHandle); driver.findElement(By.id("name")).sendKeys("Test Successful"); } @Test(enabled = false) public void switchFrame() throws Exception{ driver.get(URL); driver.switchTo().frame("courses-iframe"); Thread.sleep(3000); driver.findElement(By.linkText("Développement d'objets connectés")).click(); Thread.sleep(4000); driver.switchTo().defaultContent(); Thread.sleep(6000); driver.findElement(By.id("name")).sendKeys("Test Successful"); } @Test(enabled = false) public void dragAndDrop(){ driver.get(URL2); WebElement MyFrame =driver.findElement(By.className("demo-frame")); driver.switchTo().frame(MyFrame); WebElement Draggable =driver.findElement(By.id("draggable")); WebElement Droppable =driver.findElement(By.id("droppable")); Actions myAction =new Actions(driver); myAction.clickAndHold(Draggable).moveToElement(Droppable).perform(); } @AfterTest public void clr() throws Exception{ Thread.sleep(6000); driver.quit(); } } <file_sep>package Hello; import org.testng.annotations.*; public class Taxi { @Test (priority = 3) public void StratCar(){ System.out.println("StratCar"); } @Test (priority = 2) public void DriveCar(){ System.out.println("DriveCar"); } @Test (priority = 1) public void StopCar(){ System.out.println("StopCar"); } } <file_sep>package advanced; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Action; import org.openqa.selenium.interactions.Actions; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; public class WindowSize { WebDriver driver; JavascriptExecutor js; String URL_14 = "http://nouri-tawfik.com/formations/selenium/demo-v1/views/droppable.php"; @BeforeTest public void setUp() { System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); driver.manage().window().maximize(); js = (JavascriptExecutor) driver; } @Test public void demoSwitchAlerte() throws Exception { //open URL driver.get(URL_14); long height; long width; //size of the window // js.executeScript(alert("Bonjour MARWA")); js.executeScript("alert('marwa')"); height = (long) js.executeScript("return window.innerHeight;"); width = (long) js.executeScript("return window.innerWidth;"); System.out.println(height); System.out.println(width); } @AfterTest public void cleanUp() throws Exception { Thread.sleep(3000); // driver.quit(); } }
b4351e28b4710e2eccfef99c0f315c4b8f97ddb5
[ "Java" ]
9
Java
Marwahmandi/SeleniumWebDriverTrainingByTawfik
6bd3ef7fa047872641b7718b7ab273196e2a9ea6
24987c7d97afc10ef110bff2538138be2cc0b0f7
refs/heads/master
<repo_name>macedonga/bot.dashboard<file_sep>/assets/js/main.js function getUrlParameter(name) { name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]'); var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'); var results = regex.exec(location.search); return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' ')); }; function shake() { document.body.classList.add("shake"); setTimeout(() => { document.body.classList.remove("shake"); }, 820); }<file_sep>/assets/js/dash.js $(document).ready(function() { $.get("https://dash.macedon.ga/api/discord.php?end=users/@me", function(data) { if (data === "Not logged in") return location.href = "https://dash.macedon.ga/api/oauth.php"; const ud = JSON.parse(data); $(".u-a").attr('src', "https://cdn.discordapp.com/avatars/" + ud.id + "/" + ud.avatar + ".png") $("#u-n").text("Hello " + ud.username + "!"); var counter = 0; $.get("https://dash.macedon.ga/api/discord.php?end=users/@me/guilds", function(data) { const servers = JSON.parse(data); servers.forEach(server => { if (server.owner) { var serverBTN = $("<button></button>").text(server.name).addClass("server").attr('id', server.id); serverBTN.on("click", function() { var serverPost = { sid: server.id.toString() }; $.ajax({ url: "https://api.macedon.ga/mdbu/server/check", type: "POST", data: serverPost, async: false, success: function(response, textStatus, jqXHR) { if (!response.connected) alert("The bot isn't in the server you selected.\nInvite it first and then you can select this server.") else $(".content").fadeOut(500, function() { $(".header").fadeOut(500, function() { $(".loader").fadeIn(500, function() { location.href = "https://dash.macedon.ga/dash/manage.html?sid=" + server.id; }); }); }); }, error: function(jqXHR, textStatus, errorThrown) { return location.href = "https://dash.macedon.ga/error.html"; } }); }); $('.content').append(serverBTN); counter = counter + 1; } }); setTimeout(function() { $(".loader").fadeOut(500, function() { $(".header").fadeIn(500); $(".content").fadeIn(500); }); }, 500) }); }); });<file_sep>/api/discord.php <?php if(isset($_COOKIE["at"])) { $access_token = $_COOKIE["at"]; if (isset($_GET["end"])) $info_request = "https://discordapp.com/api/" . $_GET["end"]; else $info_request = "https://discordapp.com/api/"; $info = curl_init(); curl_setopt_array($info, array( CURLOPT_URL => $info_request, CURLOPT_HTTPHEADER => array( "Authorization: Bearer {$access_token}" ), CURLOPT_RETURNTRANSFER => true )); $out = curl_exec($info); curl_close($info); echo $out; } else { echo "Not logged in"; }<file_sep>/api/logout.php <?php if(isset($_COOKIE["at"])){ setcookie("at","", time() - 3600); Header("Location: https://dash.macedon.ga/"); } else { Header("Location: https://dash.macedon.ga/"); } ?><file_sep>/api/oauth.php <?php if (isset($_GET["error"])) { Header("Location: https://dash.macedon.ga/error.html"); } elseif (isset($_GET["code"])) { Header("Location: login.php?code={$_GET["code"]}"); } else { Header("Location: https://discord.com/api/oauth2/authorize?client_id=747489983601836042&response_type=code&scope=guilds%20identify"); } ?><file_sep>/api/login.php <?php define('OAUTH2_CLIENT_ID', '747489983601836042'); define('OAUTH2_CLIENT_SECRET', $_ENV["CS"]); if (isset($_GET["error"])) { Header("Location: https://dash.macedon.ga/error.html"); } elseif (isset($_GET["code"])) { $redirect_uri = "https://dash.macedon.ga/dash/index.html"; $token_request = "https://discordapp.com/api/oauth2/token"; $token = curl_init(); curl_setopt_array($token, array( CURLOPT_URL => $token_request, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => array( "grant_type" => "authorization_code", "client_id" => OAUTH2_CLIENT_ID, "client_secret" => OAUTH2_CLIENT_SECRET, "redirect_uri" => $redirect_uri, "code" => $_GET["code"], ), )); curl_setopt($token, CURLOPT_RETURNTRANSFER, true); $resp = json_decode(curl_exec($token)); curl_close($token); if (isset($resp->access_token)) { $access_token = $resp->access_token; setcookie("at", $access_token); Header("Location: https://dash.macedon.ga/dash"); } else { Header("Location: https://dash.macedon.ga/error.html"); } } else { Header("Location: https://dash.macedon.ga/error.html"); } <file_sep>/api/get_token.php <?php if(isset($_COOKIE["at"])){ echo $_COOKIE["at"]; } else { echo "Not logged in"; } ?>
fddf7dd6397c24985306c52cad80c8f90da98fca
[ "JavaScript", "PHP" ]
7
JavaScript
macedonga/bot.dashboard
ca6eefaed65f3510ab7f2f87f5853dd748c0ced7
5a3c12def7af5c211f791d2d09ef4528d9738f18
refs/heads/master
<file_sep>#!/bin/bash is_num() { [ $# -eq 1 ] || exit 1 echo $1 | grep -q '^[0-9]*$' if [ $? -eq 0 ]; then return 0 fi return 1 } main_name() { mainname=$(echo $1 | awk -F'.' '{print $1}') echo $mainname } print_line() { echo -e "========================================================" #echo -e "\033[01;33m------------------------------------------------------------- \033[00;37m " } print_warn_prefix() { echo -ne "\033[01;31m!!! Warning: \033[0m " } is_valid_input_file() { valid_suffix="inp xmi com gjf" for suf in ${valid_suffix} do if [ -f $1.${suf} ]; then print_line echo -e "Input file: " $1.${suf} "\t" return 0 fi done print_warn_prefix echo "could not find input file for job: " $1 return 1 } print_usage() { echo "Usage: $(basename $0) <jobnames>" } check_variables() { if [ -z ${XQSUB_PBS_SCRIPT} ]; then echo "Please set XQSUB_PBS_SCRIPT in your .bashrc" exit 1 fi if [ ! -f $XQSUB_PBS_SCRIPT ]; then echo "${XQSUB_PBS_SCRIPT} not found" echo "Please check XQSUB_PBS_SCRIPT in your .bashrc" exit 1 fi if [ -z $XQSUB_DEFAULT_PPN ]; then echo "Please set XQSUB_DEFAULT_PPN in your .bashrc" exit 1 fi is_num $XQSUB_DEFAULT_PPN if [[ $? -ne 0 ]]; then echo "XQSUB_DEFAULT_PPN should be a number" echo "Please check XQSUB_PBS_SCRIPT in your .bashrc" exit 1 fi if [[ $XQSUB_DEFAULT_PPN -gt ${MAX_PPN} ]]; then echo "XQSUB_DEFAULT_PPN should be smaller than ${MAX_PPN}" echo "Please check XQSUB_DEFAULT_PPN in your .bashrc" exit 1 fi } MAX_PPN=12 check_variables if [ $# -lt 1 ]; then print_usage exit 1 fi PPN=${XQSUB_DEFAULT_PPN} declare jobnames for file in $@ do is_num ${file} if [[ $? -eq 0 ]]; then #echo "ppn is set to " ${file} PPN=${file} else jobname=$(main_name ${file}) echo " ${jobnames} " | grep -q " ${jobname} " if [ $? -eq 0 ]; then print_warn_prefix echo ${jobname} "have been submitted already" continue fi is_valid_input_file ${jobname} || continue jobnames="${jobnames} ${jobname}" echo -e "JobName: " ${jobname} if [ ${PPN} -gt ${MAX_PPN} ]; then print_warn_prefix echo "We can not use so many CPU: ${PPN}, decrease to ${MAX_PPN} instead" PPN=${MAX_PPN} fi echo -e "CPU: " ${PPN} qsubcmd="qsub -N $jobname -l nodes=1:ppn=${PPN} ${XQSUB_PBS_SCRIPT}" echo "qsub command: " $qsubcmd ${qsubcmd} && echo -e "\033[01;32mSubmitted successfully\033[0m" print_line fi done exit 0
40f7a8977b6bf1575c1e063311a1b140ca1103e9
[ "Shell" ]
1
Shell
linxuhuizj/myqsub
354cd7587c825e2020d83237aa0cec45bc7f1f6a
597b7affe4676aa818af0f0f6264bff53f2e164f
refs/heads/master
<file_sep>package com.example.vmac.chatbot; import android.content.Intent; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import com.example.vmac.WatBot.R; public class confirm_query_received extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_confirm_query_received); } //avoid user going back into game when it is finished. Back to home screen. @Override public void onBackPressed() { Intent backToHome = new Intent(this, home_screen.class); startActivity(backToHome); } } <file_sep># The Turing Game: Client <file_sep># Class worked on by: <NAME>, <NAME> import unittest from data_pre_processor import DataPreProcessor class TestDataPreProcessor(unittest.TestCase):#pip3 install -U -r requirements.txt # Test convert accented chars function - Diego def test_ConvertChar(self): testInput = 'æ' preProcessor = DataPreProcessor(testInput) preProcessor.convertAccentedCharsToAscii() testInput = preProcessor.input self.assertEqual(testInput, 'a') testInput = 'je ètais' preProcessor = DataPreProcessor(testInput) preProcessor.convertAccentedCharsToAscii() testInput = preProcessor.input self.assertEqual(testInput, 'je etais') testInput = 'í' preProcessor = DataPreProcessor(testInput) preProcessor.convertAccentedCharsToAscii() testInput = preProcessor.input self.assertEqual(testInput, 'i') testInput = 'Ø' preProcessor = DataPreProcessor(testInput) preProcessor.convertAccentedCharsToAscii() testInput = preProcessor.input self.assertEqual(testInput,'o') testInput = 'Ùaemd' preProcessor = DataPreProcessor(testInput) preProcessor.convertAccentedCharsToAscii() testInput = preProcessor.input self.assertEqual(testInput, 'uaemd') testInput = 'ůűų or ŷÝŸ' preProcessor = DataPreProcessor(testInput) preProcessor.convertAccentedCharsToAscii() testInput = preProcessor.input self.assertEqual(testInput,'uuu or yyy') # Test convert number word to digit - Luiz Fellipe def test_NumWordToDigit(self): testInput = 'fsd' preProcessor = DataPreProcessor(testInput) preProcessor.convertNumberWordToDigit() testInput = preProcessor.input self.assertEqual(testInput, 'fsd') # FAILS THIS TEST testInput = 'one.two' preProcessor = DataPreProcessor(testInput) preProcessor.convertNumberWordToDigit() testInput = preProcessor.input print (f"{testInput} : testing input") self.assertEqual(testInput, '1.2') testInput = 'one' preProcessor = DataPreProcessor(testInput) preProcessor.convertNumberWordToDigit() testInput = preProcessor.input self.assertEqual(testInput, '1') # FAILS THIS TEST testInput = 'one two' preProcessor = DataPreProcessor(testInput) preProcessor.convertNumberWordToDigit() testInput = preProcessor.input self.assertEqual(testInput,'1 2') testInput = 'twelve' preProcessor = DataPreProcessor(testInput) preProcessor.convertNumberWordToDigit() testInput = preProcessor.input self.assertEqual(testInput, '12') testInput = 'one or three' preProcessor = DataPreProcessor(testInput) preProcessor.convertNumberWordToDigit() testInput = preProcessor.input self.assertEqual(testInput,'1 or 3') if __name__ == '__main__': unittest.main()<file_sep>package com.example.vmac.WatBot; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Typeface; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.os.CountDownTimer; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.example.vmac.chatbot.results; import com.example.vmac.chatbot.results_2; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.FirebaseApp; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.ibm.watson.developer_cloud.android.library.audio.MicrophoneHelper; import com.ibm.watson.developer_cloud.android.library.audio.MicrophoneInputStream; import com.ibm.watson.developer_cloud.android.library.audio.StreamPlayer; import com.ibm.watson.developer_cloud.android.library.audio.utils.ContentType; import com.ibm.watson.developer_cloud.assistant.v2.Assistant; import com.ibm.watson.developer_cloud.assistant.v2.model.CreateSessionOptions; import com.ibm.watson.developer_cloud.assistant.v2.model.MessageInput; import com.ibm.watson.developer_cloud.assistant.v2.model.MessageOptions; import com.ibm.watson.developer_cloud.assistant.v2.model.MessageResponse; import com.ibm.watson.developer_cloud.assistant.v2.model.SessionResponse; import com.ibm.watson.developer_cloud.http.ServiceCall; import com.ibm.watson.developer_cloud.service.security.IamOptions; import com.ibm.watson.developer_cloud.speech_to_text.v1.SpeechToText; import com.ibm.watson.developer_cloud.speech_to_text.v1.model.RecognizeOptions; import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechRecognitionResults; import com.ibm.watson.developer_cloud.speech_to_text.v1.websocket.BaseRecognizeCallback; import com.ibm.watson.developer_cloud.text_to_speech.v1.TextToSpeech; import com.ibm.watson.developer_cloud.text_to_speech.v1.model.SynthesizeOptions; import java.io.InputStream; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private ChatAdapter mAdapter; private ArrayList messageArrayList; private ArrayList completeGames; private EditText inputMessage; private ImageButton btnSend; private ImageButton btnRecord; StreamPlayer streamPlayer = new StreamPlayer(); private boolean initialRequest; private boolean permissionToRecordAccepted = false; private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200; private static String TAG = "MainActivity"; private static final int RECORD_REQUEST_CODE = 101; private boolean listening = false; private MicrophoneInputStream capture; private Context mContext; private MicrophoneHelper microphoneHelper; private Assistant watsonAssistant; private SessionResponse watsonAssistantSession; private SpeechToText speechService; private TextToSpeech textToSpeech; //Firebase atributes private FirebaseAuth mAuth; private FirebaseUser mCurrentUser; private FirebaseAuth.AuthStateListener mAuthListener; //Firebase listeners ValueEventListener mCurrentGameStatusListener; ValueEventListener mAvailableGameListener; ChildEventListener mChatRoomMessageListener; //firebase realtime database private FirebaseDatabase mDatabase; private DatabaseReference mDatabaseRef; //reference to a game obect //private TuringGame currentGame; private boolean isHumanGame; private boolean gameJoined; private String gameState; private int messageNum; private String myId; private String chatRoomId; private int mGameStatus; private int mPrevGameStatus; private static final int GAME_NOT_ACTIVE = 1; private static final int GAME_ACTIVE = 5; private static final int GAME_STOPPED = 15; private static final int GAME_STARTING = 25; private static final int GAME_PAUSED = 35; private static final int GAME_NULL = 0; //UI elements private ProgressBar mProgressBar; private Button mTimerStopButton; private TextView mTimerTime; //Timer private CountDownTimer mCountDownTimer; private final long gameLength = 5 * 60000; // fix game length at 5 minutes private long mTimeLeft; private boolean mTimerRunning; private boolean guessedRight; private String userId; /** * Method to be called when activity is created * created: * last modified : 14/03/2019 by J.Cistiakovas - added functionality for the timer. * modified : 07/03/2019 by J.Cistiakovas - added a progress bar that initially appears on * the screen. Added a thread that performs matchmaking and at the end hides the progress bar. * Added checks to ensure that send/record buttons can only be used when game has started. * modified : 07/03/2019 by J.Cistiakovas - added a function call to matchmaking * modified : 22/02/2019 by J.Cistiakovas - added database listener * modified: 21/02/2019 by J.Cistiakovas - added anonymous sign in functionality * modified: 11/03/2019 - 24/03/2019 by C.Coady - added matchmaking functionality along with some * tweaks to the database structure. * - added funcitonality so all messages are pushed * to firebase for both human and bot games. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //inflate the layout setContentView(R.layout.activity_main); //buttons used to guess if human or bot Button guessButton1 = findViewById(R.id.human); Button guessButton2 = findViewById(R.id.bot); mContext = getApplicationContext(); inputMessage = findViewById(R.id.message); btnSend = findViewById(R.id.btn_send); btnRecord = findViewById(R.id.btn_record); String customFont = "Montserrat-Regular.ttf"; Typeface typeface = Typeface.createFromAsset(getAssets(), customFont); inputMessage.setTypeface(typeface); recyclerView = findViewById(R.id.recycler_view); mTimerTime = findViewById(R.id.timerTime); messageArrayList = new ArrayList<>(); completeGames = new ArrayList<String>(); //mAdapter = new ChatAdapter(messageArrayList,myId); microphoneHelper = new MicrophoneHelper(this); LinearLayoutManager layoutManager = new LinearLayoutManager(this); layoutManager.setStackFromEnd(true); recyclerView.setLayoutManager(layoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); //recyclerView.setAdapter(mAdapter); this.inputMessage.setText(""); mProgressBar = findViewById(R.id.progressBar); recyclerView.setVisibility(View.GONE); mProgressBar.setVisibility(View.VISIBLE); mGameStatus = GAME_NOT_ACTIVE; mPrevGameStatus = GAME_NULL; //initiate game parameters mTimerRunning = false; messageNum = 0; new Thread(new Runnable() { @Override public void run() { matchmaking(); //find an opponent initialRequest = true; createWatsonServices(); //create text-to-speech and voice-to-text services if (isHumanGame) { createFirebaseServices(); } else { initialRequest = false; // set it randomly, it determines who starts the conversation createWatsonAssistant(); } runOnUiThread(new Runnable() { @Override public void run() { if(MainActivity.this == null) return; mProgressBar.setVisibility(View.GONE); recyclerView.setVisibility(View.VISIBLE); mAdapter = new ChatAdapter(messageArrayList, myId); recyclerView.setAdapter(mAdapter); mAdapter.notifyDataSetChanged(); //TODO: see this //mGameStatus = GAME_ACTIVE; } }); //start the timer //TODO: synchronise time //startTimer(); } }).start(); int permission = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO); if (permission != PackageManager.PERMISSION_GRANTED) { Log.i(TAG, "Permission to record denied"); makeRequest(); } else { Log.i(TAG, "Permission to record was already granted"); } recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new ClickListener() { @Override public void onClick(View view, final int position) { Message audioMessage = (Message) messageArrayList.get(position); if (audioMessage != null && !audioMessage.getMessage().isEmpty()) { new SayTask().execute(audioMessage.getMessage()); } } @Override public void onLongClick(View view, int position) { recordMessage(); } })); btnSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //only send the message if game is active if (checkInternetConnection() && mGameStatus == GAME_ACTIVE) { sendMessage(); } } }); btnRecord.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mGameStatus == GAME_ACTIVE) { recordMessage(); } } }); //sendMessage(); //timer listener - DETECTING WHEN USER GUESSES HUMAN guessButton1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(isHumanGame){ guessedRight = true; }else{ guessedRight = false; } timerStartStop(); } }); //timer listener - DETECTING WHEN USER GUESSES BOT guessButton2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(!isHumanGame){ guessedRight = true; }else{ guessedRight = false; } timerStartStop(); } }); } ; /** * Method to be called when activity is started * created: 15:00 22/03/2019 by J.Cistiakovas * last modified: - */ @Override public void onStart() { super.onStart(); //initiate sign in check //mAuthListener.onAuthStateChanged(mAuth); } @Override public void onPause() { super.onPause(); detachListeners(); // mPrevGameStatus = mGameStatus; // mGameStatus = GAME_PAUSED; } @Override public void onResume() { super.onResume(); attachListeners(); // if(mPrevGameStatus != GAME_NULL) { // mGameStatus = mPrevGameStatus; // } } @Override public void onDestroy() { super.onDestroy(); if(mCountDownTimer != null) { mCountDownTimer.cancel(); } } // Speech-to-Text Record Audio permission @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case REQUEST_RECORD_AUDIO_PERMISSION: permissionToRecordAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED; break; case RECORD_REQUEST_CODE: { if (grantResults.length == 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) { Log.i(TAG, "Permission has been denied by user"); } else { Log.i(TAG, "Permission has been granted by user"); } return; } case MicrophoneHelper.REQUEST_PERMISSION: { if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) { showToast("Permission to record audio denied", Toast.LENGTH_SHORT); } } } // if (!permissionToRecordAccepted ) finish(); } protected void makeRequest() { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, MicrophoneHelper.REQUEST_PERMISSION); } /** * Method to be called to send a message * created: 23/02/2019 by J.Cistiakovas * last modified: 23/02/2019 by J.Cistiakovas */ private void sendMessage() { if (isHumanGame) { sendMessageHuman(); } else { sendMessageBot(); } } /** * Method that sends a message to a human play via Firebase realtime databse * created: 22:00 23/03/2019 by J.Cistiakovas * last modified: 19:00 24/03/2019 by C.Coady - updated messages to include new type * attribute. This denotes if the message was sent by a human or a bot. */ private void sendMessageHuman() { //create a new TuringMessage object using values from the editText box String id = mAuth.getUid() + (new Integer(messageNum++).toString()); Message message = new Message(); message.setMessage(this.inputMessage.getText().toString().trim()); message.setId(id); message.setSender(myId); message.setType("human"); //return if message is empty if (message.getMessage().equals("")) { return; } //publish the message in an chatRooms mDatabaseRef.child("chatRooms").child(chatRoomId).child(message.getId()).setValue(message); // add a message object to the list messageArrayList.add(message); this.inputMessage.setText(""); // make adapter to update its view and add a new message to the screen //mAdapter.notifyDataSetChanged(); new SayTask().execute(message.getMessage()); scrollToMostRecentMessage(); } // Sending a message to Watson Assistant Service private void sendMessageBot() { final String inputmessage = this.inputMessage.getText().toString().trim(); if (!this.initialRequest) { Message inputMessage = new Message(); inputMessage.setMessage(inputmessage); inputMessage.setId("1"); inputMessage.setSender(myId); inputMessage.setType("human"); messageArrayList.add(inputMessage); } else { Message inputMessage = new Message(); inputMessage.setMessage(inputmessage); inputMessage.setId("100"); inputMessage.setSender(myId); inputMessage.setType("human"); this.initialRequest = false; showToast("Tap on the message for Voice", Toast.LENGTH_LONG); } this.inputMessage.setText(""); mAdapter.notifyDataSetChanged(); scrollToMostRecentMessage(); Thread thread = new Thread(new Runnable() { public void run() { try { if (watsonAssistantSession == null) { ServiceCall<SessionResponse> call = watsonAssistant.createSession( new CreateSessionOptions.Builder().assistantId(mContext.getString(R.string.assistant_id)).build()); watsonAssistantSession = call.execute(); } MessageInput input = new MessageInput.Builder() .text(inputmessage) .build(); MessageOptions options = new MessageOptions.Builder() .assistantId(mContext.getString(R.string.assistant_id)) .input(input) .sessionId(watsonAssistantSession.getSessionId()) .build(); //blocking statement MessageResponse response = watsonAssistant.message(options).execute(); Log.i(TAG, "run: " + response); final Message outMessage = new Message(); if (response != null && response.getOutput() != null && !response.getOutput().getGeneric().isEmpty() && "text".equals(response.getOutput().getGeneric().get(0).getResponseType())) { outMessage.setMessage(response.getOutput().getGeneric().get(0).getText()); outMessage.setId("2"); outMessage.setType("bot"); //add random delay to make it seem more like a human responding double delay = Math.random() * (1000000000 * outMessage.getMessage().length()) + 1000000000; for(int i = 0; i < delay; i++){} messageArrayList.add(outMessage); // speak the message new SayTask().execute(outMessage.getMessage()); scrollToMostRecentMessage(); } } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); } private class SayTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { streamPlayer.playStream(textToSpeech.synthesize(new SynthesizeOptions.Builder() .text(params[0]) .voice(SynthesizeOptions.Voice.EN_US_LISAVOICE) .accept(SynthesizeOptions.Accept.AUDIO_WAV) .build()).execute()); return "Did synthesize"; } } //Record a message via Watson Speech to Text private void recordMessage() { if (listening != true) { capture = microphoneHelper.getInputStream(true); new Thread(new Runnable() { @Override public void run() { try { speechService.recognizeUsingWebSocket(getRecognizeOptions(capture), new MicrophoneRecognizeDelegate()); } catch (Exception e) { showError(e); } } }).start(); listening = true; showToast("Listening....Click to Stop", Toast.LENGTH_LONG); } else { try { microphoneHelper.closeInputStream(); listening = false; showToast("Stopped Listening....Click to Start", Toast.LENGTH_LONG); } catch (Exception e) { e.printStackTrace(); } } } /** * Check Internet Connection * * @return */ private boolean checkInternetConnection() { // get Connectivity Manager object to check connection ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); // Check for network connections if (isConnected) { return true; } else { showToast(" No Internet Connection available ", Toast.LENGTH_LONG); return false; } } //Private Methods - Speech to Text private RecognizeOptions getRecognizeOptions(InputStream audio) { return new RecognizeOptions.Builder() .audio(audio) .contentType(ContentType.OPUS.toString()) .model("en-US_BroadbandModel") .interimResults(true) .inactivityTimeout(2000) .build(); } //Watson Speech to Text Methods. private class MicrophoneRecognizeDelegate extends BaseRecognizeCallback { @Override public void onTranscription(SpeechRecognitionResults speechResults) { if (speechResults.getResults() != null && !speechResults.getResults().isEmpty()) { String text = speechResults.getResults().get(0).getAlternatives().get(0).getTranscript(); showMicText(text); } } @Override public void onError(Exception e) { showError(e); enableMicButton(); } @Override public void onDisconnected() { enableMicButton(); } } private void showMicText(final String text) { runOnUiThread(new Runnable() { @Override public void run() { inputMessage.setText(text); } }); } private void enableMicButton() { runOnUiThread(new Runnable() { @Override public void run() { btnRecord.setEnabled(true); } }); } private void showError(final Exception e) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); e.printStackTrace(); } }); } /** * Method that scrolls the recycler view to the most recent message * created: 26/02/2019 by J.Cistiakovas * last modified: 20/03/2019 by J.Cistiakovas - fixed NullPointerException */ private void scrollToMostRecentMessage() { runOnUiThread(new Runnable() { public void run() { if(MainActivity.this == null || mAdapter == null) return; mAdapter.notifyDataSetChanged(); if (mAdapter.getItemCount() > 1) { recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, null, mAdapter.getItemCount() - 1); Log.d(TAG, "Scrolled to the most recent message!"); } } }); } /* public void onPause() { super.onPause(); }*/ /** * Method to initialise all the objects required for Watson Services to work, * but assistant s not initialised * created: - * last modified: 07/03/2019 by J.Cistiakovas */ private void createWatsonServices() { textToSpeech = new TextToSpeech(); textToSpeech.setIamCredentials(new IamOptions.Builder() .apiKey(mContext.getString(R.string.TTS_apikey)) .build()); textToSpeech.setEndPoint(mContext.getString(R.string.TTS_url)); speechService = new SpeechToText(); speechService.setIamCredentials(new IamOptions.Builder() .apiKey(mContext.getString(R.string.STT_apikey)) .build()); speechService.setEndPoint(mContext.getString(R.string.STT_url)); } /** * Method to initialise Watson assistant * created: - * last modified: 07/03/2019 by J.Cistiakovas */ private void createWatsonAssistant() { watsonAssistant = new Assistant("2018-11-08", new IamOptions.Builder() .apiKey(mContext.getString(R.string.assistant_apikey)) .build()); watsonAssistant.setEndPoint(mContext.getString(R.string.assistant_url)); myId = "100"; } /** * Method to initialise Firebase services, such as Auth and Realtime Database * created: 04/03/2019 by J.Cistiakovas * last modified: 24/03/2019 by C.Coady - removed message listener as this is handled in the * loadMessages method */ private void createFirebaseServices() { //Firebase anonymous Auth FirebaseApp.initializeApp(this); mAuth = FirebaseAuth.getInstance(); mCurrentUser = mAuth.getCurrentUser(); //listener that listens for change in the Auth state mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull final FirebaseAuth firebaseAuth) { FirebaseUser currentUser = firebaseAuth.getCurrentUser(); //check if user is already signed in //TODO: retrieve/reset local information from the memory, e.g. score if (currentUser == null) { mAuth.signInAnonymously().addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { mCurrentUser = firebaseAuth.getCurrentUser(); showToast("Hello, " + mCurrentUser.getUid(), Toast.LENGTH_LONG); } else { showToast("Authentication failed!", Toast.LENGTH_LONG); //TODO: fail the program or do something here } } }); } else { //user is signed in - happy days mCurrentUser = currentUser; showToast("Hello, " + currentUser.getUid(), Toast.LENGTH_LONG); Log.d(TAG, "User already signed in. User id : " + mCurrentUser.getUid()); } } }; mAuth.addAuthStateListener(mAuthListener); myId = mAuth.getUid(); //Firebase realtime database initialisation mDatabase = FirebaseDatabase.getInstance(); mDatabaseRef = mDatabase.getReference(); } /** * This method starts a listener on the game state, if the game * is complete it will update the local gameState variable which * allows us to change to a guessing screen etc. * created: 11/03/2019 by C.Coady * last modified: 24/03/2019 by C.Coady */ private void gameState(){ //Get a reference to the availableGames section of the database final DatabaseReference currentGameRef = mDatabaseRef.child("availableGames"); //Create a new listener to listen for changes in the game state mCurrentGameStatusListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { //if we are currently in a game if(gameJoined && chatRoomId != null){ //Take a snapshot of the current game state from the database gameState = dataSnapshot.child(chatRoomId).getValue().toString(); if(gameState.equals("complete")){ //make the user guess now showToast("the game is now over", Toast.LENGTH_LONG); stopTimer(); } else if (gameState.equals("full") && mGameStatus == GAME_NOT_ACTIVE){ mGameStatus = GAME_ACTIVE; startTimer(); } } } @Override public void onCancelled(DatabaseError databaseError) { // Getting Post failed, log a message Log.w(TAG, "loadPost:onCancelled", databaseError.toException()); } }; //Attach the listener to the database reference currentGameRef.addValueEventListener(mCurrentGameStatusListener); } /** * This method handles all of the matchmaking for the game. * When a game starts, the user will check to see if there are any 'empty' * chatrooms. If there are, the user will join (this is a human to human game) and * a listener will be started on that chatroom to check for new messages. * If no chatrooms are available the user will create one and wait to see if someone * joins. If no one joins the user will be matched with a bot and the game will start. * created: 11/03/2019 by C.Coady * last modified: 24/03/2019 by C.Coady - added a naive way of ensuring old games are removed * from the database */ private void matchmaking() { //initialse the firebase database createFirebaseServices(); //create text-to-speech and voice-to-text services createWatsonServices(); isHumanGame = true; //mDatabaseRef = mDatabase.getReference(); final DatabaseReference availableGameRef = mDatabaseRef.child("availableGames"); mAvailableGameListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot availableGame) { int completeGameCount = 0; for (DataSnapshot game: availableGame.getChildren()) { String key = game.getKey(); String status = game.getValue().toString(); if(status.equals("empty") && !gameJoined){ gameJoined = true; chatRoomId = key; showToast("Joined game " + chatRoomId, Toast.LENGTH_LONG); } else if(status.equals("complete")) { completeGames.add(key); completeGameCount++; } } if(completeGameCount > 0){ deleteFinishedGames(); } } @Override public void onCancelled(DatabaseError databaseError) { //error loading from the database } }; availableGameRef.addListenerForSingleValueEvent(mAvailableGameListener); //start a listener to see if the game has ended gameState(); //wait for a bit to read from the database double currentWaitTime = 0; double delay = 1000000000.0; while(!gameJoined && currentWaitTime < delay){ currentWaitTime++; } //we have not found a game if(!gameJoined){ //create a game createGame(); showToast("Created game " + chatRoomId, Toast.LENGTH_LONG); //update game status gameJoined = true; //wait for a bit to see if anyone joins the game for(double playerWait = 0; playerWait < delay*2; playerWait++){} if(gameState.equals("empty")){ //make this a bot game isHumanGame = false; createWatsonAssistant(); showToast("This is a game against a bot!", Toast.LENGTH_LONG); Log.d(TAG, "This is a game against a bot!"); availableGameRef.child(chatRoomId).setValue("full"); if (Math.random() < 0.5) { initialRequest = false; } else{ initialRequest = true; } } } else{ //join the game and set it to full showToast("This is a game against a human!", Toast.LENGTH_LONG); Log.d(TAG, "This is a game against a human!"); //make the game session full availableGameRef.child(chatRoomId).setValue("full"); } //load message listener loadMessages(); } /** * This method starts a listener on the chatRoom in the database. * When ever a message is added to the chatRoom the listener will * add the new message to the arrayList of messages so it can be * displayed on screen * created: 11/03/2019 by C.Coady * last modified: 23/03/2019 by C.Coady */ private void loadMessages(){ if(isHumanGame){ DatabaseReference messageRef = mDatabaseRef.child("chatRooms"); mChatRoomMessageListener = new ChildEventListener() { // TODO: not load previous conversation, possibly use timestamps @Override public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { //retrieve the message from the datasnapshot Message newMessage = dataSnapshot.getValue(Message.class); //TODO: deal with double messages, sould not be much of a problem if we start a new chat each time if (TextUtils.equals(newMessage.getSender(), mAuth.getUid())) { //don't add own message return; } messageArrayList.add(newMessage); //mAdapter.notifyDataSetChanged(); scrollToMostRecentMessage(); } @Override public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { } @Override public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) { } @Override public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }; messageRef.child(chatRoomId).addChildEventListener(mChatRoomMessageListener); } } /** * This method loops through the arrayList of messages and uploads each one * to the chat room corresponding to 'chatRoomId' on the database. * created: 23/03/2019 by C.Coady * last modified: 24/03/2019 by C.Coady */ private void uploadMessages(){ //get a reference to the chat rooms section of the database DatabaseReference chatRef = mDatabaseRef.child("chatRooms").child(chatRoomId); //loop through messages and upload them to the chat for(int i = 0; i < messageArrayList.size(); i++){ chatRef = chatRef.push(); Message message = (Message) messageArrayList.get(i); message.setId(chatRef.getKey()); //publish the message in an chatRooms chatRef.setValue(message); chatRef = mDatabaseRef.child("chatRooms").child(chatRoomId); } } /** * This method loops through the completeGames arrayList and deletes * the chat room id corresponding to the deleted game from the * database. This will prevent the list of elements in available games * from getting too big. May have potential problems if a game has just * ended and new player searching for a game deletes the chatroom before * both players of that game have guessed. A possible solution would be * to introduce timestamps to each chatroom, then if the chatroom is more * than a certain age, it can be assumed that the game is over and then * deleted. * created: 01/04/2019 by C.Coady * last modified: 01/04/2019 by C.Coady */ private void deleteFinishedGames(){ if(completeGames != null) { //get a reference to the chat rooms section of the database DatabaseReference chatRef = mDatabaseRef.child("availableGames"); for(int i = 0; i < completeGames.size(); i++){ //remove the chatroom from availableGames chatRef.child((String)completeGames.get(i)).removeValue(); } } } /** * This method takes creates an availableGame which players can join. * A random game key is generated by firebase which is used to identify * the game 'chatRoomId'. * The status of the new chatroom is set to empty while we wait for * other players to join the game. * created: 21/03/2019 by C.Coady * last modified: 24/03/2019 by C.Coady */ private boolean createGame(){ //get a reference to the chat rooms section of the database DatabaseReference chatRef = mDatabaseRef.child("availableGames"); //create a new chatroom with a unique reference chatRef = chatRef.push(); //update the chatroom id to the newly generated one chatRoomId = chatRef.getKey(); //make this chatroom empty chatRef.setValue("empty"); //TODO add some error checking if we fail to connect to the database return true; } /** * This method sets the gameState to 'complete' on the availableGames section * of the database and then uploads the messages to the database if the game * was against a bot those messages are only stored locally. * created: 21/03/2019 by C.Coady * last modified: 24/03/2019 by C.Coady */ private boolean endGame(){ //get a reference to the chat rooms section of the database DatabaseReference chatRef = mDatabaseRef.child("availableGames"); //make this chatroom complete chatRef.child(chatRoomId).setValue("complete"); //if the game is against a bot, push messages to the database if(!isHumanGame){ uploadMessages(); } //TODO add some error checking if we fail to connect to the database return true; } /** * Method that makes a Toast via a UI thread * created: 11/03/2019 by J.Cistiakovas * last modified: 20/03/2019 by J.Cistiakovas - fixed NullPointerException */ private void showToast(final String string, final int duration) { runOnUiThread(new Runnable() { public void run() { if(MainActivity.this == null) return; Toast.makeText(mContext, string, duration).show(); } }); } /** * Logic for the timer * created: 14/03/2019 by J.Cistiakovas * last modified: 14/03/2019 by J.Cistiakovas */ //TODO: save the score private void timerStartStop(){ if(mTimerRunning && mGameStatus==GAME_ACTIVE){ //stop timer stopTimer(); } else { //not running, start the timer //set up the timer startTimer(); } } /** * Method creates and starts a new timer * created: 14/03/2019 by J.Cistiakovas * last modified: 20/03/2019 by J.Cistiakovas - fixed NullPointerException */ private void startTimer(){ //set up the timer runOnUiThread(new Runnable() { @Override public void run() { if(MainActivity.this == null) return; mCountDownTimer = new CountDownTimer(gameLength,1000) { @Override public void onTick(long l) { mTimeLeft = l; updateTime(); } @Override public void onFinish() { stopTimer(); } }; mCountDownTimer.start(); } }); mTimerRunning = true; Log.d(TAG,"New timer started!"); } /** * Updates the textField showing the time left * created: 14/03/2019 by J.Cistiakovas * last modified: 14/03/2019 by J.Cistiakovas */ private void updateTime(){ if(mGameStatus != GAME_ACTIVE){ return; } //change the string int minutes = (int) mTimeLeft / 60000; int seconds = (int) (mTimeLeft % 60000) / 1000; String timeLeftText; timeLeftText = String.format("%02d:%02d",minutes, seconds); mTimerTime.setText(timeLeftText); } /** * Stops the timer and updates the game state * created: 14/03/2019 by J.Cistiakovas * last modified: 20/03/2019 by L.Brennan * modified: 14/03/2019 by J.Cistiakovas */ //TODO: add actions to be done as the game is stopped/ended private void stopTimer() { //stop the game and move to other activity - results being displayed //change the states mCountDownTimer.cancel(); mTimerRunning = false; //return if game was not active. This will prevent from unexpected effect in case // listener fires when activity is not in foreground // if(mGameStatus != GAME_ACTIVE){ // return; // } mGameStatus = GAME_STOPPED; //showToast("Timer stop pressed", Toast.LENGTH_SHORT); Log.d(TAG,"Timer stop pressed."); //Takes to results screen saying if it was a bot or human if(isHumanGame) //if human { Intent human_results_intent = new Intent(this, results_2.class); //pass the time it took the user to complete the game into results int minutes = (int) (mTimeLeft / 60000); int seconds = (int) (mTimeLeft % 60000) / 1000; minutes = 4 - minutes; //get time taken by subtracting // time left from time elapsed seconds = 60 - seconds; String timeLeftText; timeLeftText = String.format("%02d mins : %02d seconds",minutes, seconds); human_results_intent.putExtra("timeTaken",timeLeftText); human_results_intent.putExtra("guessedRight", guessedRight); endGame(); detachListeners(); startActivity(human_results_intent); } else //if bot { Intent bot_results_intent = new Intent(this, results.class); //pass the time it took the user to complete the game into results int minutes = (int) (mTimeLeft / 60000); int seconds = (int) (mTimeLeft % 60000) / 1000; minutes = 4 - minutes; //get time taken by subtracting // time left from time elapsed seconds = 60 - seconds; String timeLeftText; timeLeftText = String.format("%02d mins : %02d seconds",minutes, seconds); bot_results_intent.putExtra("timeTaken",timeLeftText); bot_results_intent.putExtra("guessedRight", guessedRight); endGame(); detachListeners(); startActivity(bot_results_intent); } } private void detachListeners(){ if(mCurrentGameStatusListener != null) { mDatabaseRef.child("availableGames").removeEventListener(mCurrentGameStatusListener); } if(mAvailableGameListener != null) { mDatabaseRef.child("availableGames").removeEventListener(mAvailableGameListener); } if(mChatRoomMessageListener != null) { mDatabaseRef.child("chatRooms").removeEventListener(mChatRoomMessageListener); } } private void attachListeners(){ if(mCurrentGameStatusListener != null) { mDatabaseRef.child("availableGames").addValueEventListener(mCurrentGameStatusListener); } if(mAvailableGameListener != null) { mDatabaseRef.child("availableGames").addListenerForSingleValueEvent(mAvailableGameListener); } if(mChatRoomMessageListener != null) { mDatabaseRef.child("chatRooms").addChildEventListener(mChatRoomMessageListener); } } } <file_sep>package com.example.vmac.chatbot; import android.content.Intent; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.example.vmac.WatBot.R; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class contact extends AppCompatActivity { private EditText mContactEmail; private EditText mMessage; private static final String TAG = "ContactActivity"; private static final int EMAIL_CODE = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_contact); //button enabling user to send us a message/query Button send_button = findViewById(R.id.send_button); mContactEmail = findViewById(R.id.contactEmail); mMessage = findViewById(R.id.contactMessage); send_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { uploadContactMessage(); // switch to the new activity is disabled as stops the user from successfully sending an email openConfirmQueryScreen(); } }); } //function that takes user to a page confirming their query has been received after they send it public void openConfirmQueryScreen() { Intent confirm_query_received_intent = new Intent(this, confirm_query_received.class); startActivity(confirm_query_received_intent); } /** * Method that uploads the feedback into the database. * created: 30/03/2019 by J.Cistiakovas * last modified: 30/03/2019 by J.Cistiakovas */ private void uploadContactMessage(){ String message = mMessage.getText().toString().trim(); String email = mContactEmail.getText().toString().trim(); FirebaseAuth Auth = FirebaseAuth.getInstance(); FirebaseDatabase Database = FirebaseDatabase.getInstance(); DatabaseReference DatabaseRefFeedback = Database.getReference("feedback"); DatabaseReference newFeedback = DatabaseRefFeedback.push(); newFeedback.child("message").setValue(message); newFeedback.child("reply-email").setValue(email); } } <file_sep># The Turing Game: Dummy Server The code for the dummy server is now located [here](https://github.com/conormccauley1999/SWENG-2020-Dummy-Server). You can make a sample request like so: `curl localhost:1234/api/conversation/start` <file_sep>/* Reference: https://github.com/ScaleDrone/android-chat-tutorial */ package com.sweng.theturinggamedemo; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONObject; import java.io.IOException; import java.util.Objects; import java.util.Timer; import java.util.TimerTask; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class PlayActivity extends AppCompatActivity { private MessageAdapter messageAdapter; private ListView messageView; private int messageNum = 1; private int countdown = 30; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_play); Objects.requireNonNull(getSupportActionBar()).hide(); messageAdapter = new MessageAdapter(this); messageView = findViewById(R.id.play_list_messages); messageView.setAdapter(messageAdapter); EditText textInput = findViewById(R.id.play_input_text); ImageButton sendButton = findViewById(R.id.play_input_send); sendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String messageText = textInput.getText().toString().trim(); if (messageText.length() != 0) { addMessage(true, messageText); textInput.getText().clear(); getMessages(messageNum); messageNum++; } } }); TextView timerText = findViewById(R.id.play_text_timer); Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (countdown < 0) { timer.cancel(); try { Thread.sleep(1000); } catch (Exception ignored) { } startActivity(new Intent(PlayActivity.this, GuessActivity.class)); } else { String padding = (countdown < 10) ? "0" : ""; timerText.setText(String.format("00:%s%d", padding, countdown)); countdown--; } } }, 1000, 1000); } private void addMessage(boolean ourMessage, String text) { Message message = new Message(ourMessage, text); runOnUiThread(() -> { messageAdapter.add(message); messageView.setSelection(messageView.getCount() - 1); }); } private void getMessages(int messageNum) { String route = Constants.BASE_URL + String.format("message%d.json", messageNum); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(route).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { call.cancel(); } @Override public void onResponse(Call call, Response response) throws IOException { try { JSONObject json = new JSONObject(response.body().string()); JSONArray messages = json.getJSONArray("messages"); for (int i = 0; i < messages.length(); i++) { Thread.sleep(1000); String messageText = messages.getJSONObject(i).getString("text"); addMessage(false, messageText); } } catch (Exception e) { finish(); } } }); } } <file_sep>package com.sweng.theturinggamedemo; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import org.jetbrains.annotations.NotNull; import org.json.JSONObject; import java.io.IOException; import java.util.Objects; import java.util.concurrent.ExecutionException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class SearchingActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_searching); Objects.requireNonNull(getSupportActionBar()).hide(); String route = Constants.BASE_URL + "start.json"; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(route).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { call.cancel(); } @Override public void onResponse(Call call, Response response) throws IOException { try { JSONObject json = new JSONObject(response.body().string()); int conversationId = json.getInt("cid"); startActivity(new Intent(SearchingActivity.this, PlayActivity.class)); } catch (Exception e) { finish(); } } }); } } <file_sep># Class worked on by: Claire import random from personality import Personality class YoungAdult(Personality): def __init__(self, name): Personality.__init__(self, name) self.age = random.randint(22, 28) self.probSpellingMistake = random.randint(2,5) def addPersonality(self, input): output = self.shortenWords(input) return output # You -> u for instance, more likely to be commonly appropriate. Needs to return a string. - Kishore def shortenWords(self, input): return input # Add appropriate emjois - <NAME> def addEmojis(self, input): if input.find('sad')!= -1: index = input.find('sad') length = len('sad') output_line = input[:index+length] + ' \U0001F625' + input[index+length:] print(output_line) return output_line elif input.find('happy')!= -1: index = input.find('happy') length = len('happy') output_line = input[:index+length] + ' \U0001F603' + input[index+length:] print(output_line) return output_line elif input.find('funny')!= -1: index = input.find('funny') length = len('funny') output_line = input[:index+length] + ' \U0001F602' + input[index+length:] print(output_line) return output_line elif input.find('love')!= -1: index = input.find('love') length = len('love') output_line = input[:index+length] + ' \U0001F60D' + input[index+length:] print(output_line) return output_line elif input.find('star')!= -1: index = input.find('star') length = len('star') output_line = input[:index+length] + ' \U0001F929' + input[index+length:] print(output_line) return output_line elif input.find('good night')!= -1: index = input.find('good night') length = len('good night') output_line = input[:index+length] + ' \U0001F634' + input[index+length:] print(output_line) return output_line elif input.find('angry')!= -1: index = input.find('angry') length = len('angry') output_line = input[:index+length] + ' \U0001F621' + input[index+length:] print(output_line) return output_line return input<file_sep>package com.sweng.theturinggame; public class Personality { public static String apply(int conversationId, String message) { return ""; } } <file_sep>package com.sweng.theturinggamedemo; class Constants { static final String TAG = "DEMO_DEBUG"; static final String BASE_URL = "https://raw.githubusercontent.com/conormccauley1999/SWENG-2020-Dummy-Server/master/json/"; } <file_sep># Class worked on by: Claire, <NAME> from data_pre_processor import DataPreProcessor from teenager import Teenager from young_adult import YoungAdult from adult import Adult from data_post_processor import DataPostProcessor from ai_brain import AI from apscheduler.schedulers.background import BackgroundScheduler import random end = False # Takes input from commandline, processes it, displays processed output via commandline. def main(): # This will be an environment variable later terminalMode = True # Simple bit of beautifying for our command-line output. c_background = "" c_blue = "" c_green = "" c_red = "" c_close = "" # Certain aspects of this program will only exist on the commandline. if terminalMode: # Set up our timer timer = BackgroundScheduler({"apscheduler.timezone": "Europe/Dublin"}) timer.add_job(endProgram, "interval", minutes=1) c_background = "\033[44m" c_blue = "\033[94m" c_green = "\033[92m" c_red = "\033[91m" c_close = "\033[0m" # Small bit of starting text to introduce the user. startingText = ["Ask a question, and see how our AI responds.", "Please ensure queries have more than three words.", "You will have 60 seconds upon entering your first query to make further queries.", "The program will wait for your last query before exiting."] print(c_green + "\n".join(startingText) + c_close) # Where input is user input from commandline. print(c_background + "Enter the input, or enter 'exit' to end:" + c_close) personality = None # Random name generator with open("data/names.txt") as word_file: names = word_file.read().split() name = random.choice(names) # Personality is randomly assigned between teenager, young adult and adult with a random name each time. perNum = random.randint(1, 3) if perNum == 1: personality = Teenager(name) elif perNum == 2: personality = YoungAdult(name) else: personality = Adult(name) # Our input/feedback loop, starting our timer on its initial run. initial = True global end while(not end): if terminalMode: userInput = input() # Start the timer after the first user input. if initial: timer.start() initial = False # Exit on 'exit'. if(userInput == "exit"): break # Determine our input, whether an error or a valid query. output = arrangeResp(userInput, personality) # Handle queries that are too short. if output == False: print(c_red + "The input string must have a minimum of three words!" + c_close) else: print(c_blue + output + c_close) print(c_background + "Enter another input:" + c_close) if terminalMode: print(c_green + "Program exited." + c_close) def arrangeResp(userInput, personality): # Creating our AI. ai = AI(personality.name) # Where output is the processed output. preProcessor = DataPreProcessor(userInput) # Was the query too short for the AI, if so, exit. if preProcessor.processInput() == False: return False # This is passed to the model. processedInput = preProcessor.input # Receive response from the model. response = ai.respond(processedInput, 1) response = preProcessor.array2String(response) postProcessor = DataPostProcessor(response, personality) postProcessor.postProcess() return response def endProgram(): global end end = True return if __name__ == '__main__': main() <file_sep># The Turing Game: AI
d27933ecbd2d7a1b12a99d76e025f31940d82551
[ "Markdown", "Java", "Python" ]
13
Java
BrendanJobus/SWENG-2020-The-Turing-Game
0a4a14772a022851cb11dc10014a2252c61fa3e6
21e8473783d4fda2dab342d10c295b0ef14431e7
refs/heads/master
<repo_name>adamtyoung/aRmy403k<file_sep>/README.md # What it is Nothing to see here <file_sep>/gitpush.sh #!/usr/bin/env bash # read projects current directory with $PWD cd /Users/adamtyoung/calendars git add --all git commit -m "Commit from shell" git push origin --all echo 'Committed'
011e7235d44850942a05149657abb604b00ceb00
[ "Markdown", "Shell" ]
2
Markdown
adamtyoung/aRmy403k
874aa9f1440da7c518031a4d52c4241e7526f55d
f5e868d42a85cef0f127c36561f9bda54614f57f
refs/heads/main
<repo_name>sebastianseeds/SBS_Event_Display<file_sep>/bbcal_eventdisplay.C #include "Riostream.h" #include <TMath.h> #include <TFile.h> #include <TF1.h> #include <TH1.h> #include <TH2.h> #include <TGraphErrors.h> #include <TTree.h> #include <TGaxis.h> #include <TLine.h> #include <TROOT.h> #include <TLegend.h> #include <string> #include <TCanvas.h> #include <TStyle.h> //Display an array, set a minimum value to display. void Draw(Double_t data[], vector<Double_t>* means, Double_t min, const char* title, Int_t rows = 27, Int_t cols = 7){ //Create a 2D histogram to store the data. TH2I* display = new TH2I(Form("display_%d", rows),title,cols,0,cols,rows,0,rows); //Fill the bins with data. for(int i = 0; i < cols; i++){ for(int j = 0; j < rows; j++){ //int k = (j*cols)+i; //if(cols==2) int k = (i*rows)+j; //Only display if value(channel) > min. if(data[k] - means->at(k) > min){ //Fill the bins display->SetBinContent(i+1,j+1,(Int_t)(data[k] - means->at(k))); } else { //Else display 0. display->SetBinContent(i+1,j+1,0); } } } display->GetYaxis()->SetNdivisions(rows); display->GetXaxis()->SetNdivisions(cols); //Have to completely replace axes to position axis labels where they are display->GetYaxis()->SetLabelSize(0); display->GetXaxis()->SetLabelSize(0); //Let's make a function to set the axis values TF1 *xfunc = new TF1("xfunc","x",1,cols+1); TF1 *yfunc = new TF1("yfunc","x",1,rows+1); //Set colour, box text size and remove the stats box. display->SetFillColor(kRed-9); display->SetStats(0); //display->SetMarkerSize(1.2+((7-cols)/1.7)); display->SetMarkerSize(2.5); //Have to make the old axis labels invisible (unable to edit some axis properties directly). display->GetYaxis()->SetLabelSize(0); display->GetXaxis()->SetLabelSize(0); display->SetTitleSize(10.5); //Display the event. display->Draw("box,text"); //Create completely new axes to get label in the middle of the divisions) TGaxis *x = new TGaxis(0,0,cols,0,"xfunc",cols+1,"M"); //x->SetLabelSize(0.25/cols); x->SetLabelSize(0.05); //x->SetLabelOffset(0.015*(cols-7)); x->SetLabelOffset(0.001); x->Draw(); TGaxis *y = new TGaxis(0,0,0,rows,"yfunc",rows+1,"M"); //y->SetLabelSize(0.25/cols); y->SetLabelSize(0.05); y->Draw(); //Vertical lines. for (int i = 1; i < cols; i++){ TLine *line = new TLine(i,0,i,rows); line->SetLineStyle(kDotted); line->Draw(); } //Horizontal lines. //Vertical lines. for (int i = 1; i < rows; i++){ TLine *line = new TLine(0,i,cols,i); line->SetLineStyle(kDotted); line->Draw(); } //Memory clean up. //delete gROOT->FindObject("display"); } void eventDisplay(const char* filename, Int_t evt = -1){ vector<Double_t>* meanValuesSH = new vector<double>; meanValuesSH->resize(189); vector<Double_t>* meanValuesPS = new vector<double>; meanValuesPS->resize(52); /* //Get the mean and RMS values. vector<Double_t>* rmsValues; vector<Double_t>* rmsValuesPS; TFile *calibration = TFile::Open("pedestalcalibrated.root"); meanValues = (vector<Double_t>*)calibration->Get("Mean"); rmsValues = (vector<Double_t>*)calibration->Get("RMS"); meanValuesPS = (vector<Double_t>*)calibration->Get("MeanPS"); rmsValuesPS = (vector<Double_t>*)calibration->Get("RMSPS"); calibration->Close(); */ //Create a Canvas TCanvas* c1 = new TCanvas("c1","Event Display (ADC integral in pC)",600,800); TPad *shower = new TPad("shower","Shower",0.01,0.01,0.49,0.99); shower->Draw(); TPad *preshower = new TPad("preshower","Pre-Shower",.51,.01,.99,.99); preshower->SetLeftMargin(0.15); preshower->Draw(); TCanvas* c2 = new TCanvas("c2","Event Display (ADC time in ns)",600,800); TPad *tshower = new TPad("tshower","Shower",0.01,0.01,0.49,0.99); tshower->Draw(); TPad *tpreshower = new TPad("tpreshower","Pre-Shower",.51,.01,.99,.99); tpreshower->SetLeftMargin(0.15); tpreshower->Draw(); //Open the file. TFile *events = TFile::Open(filename); //Get the Tree. TTree* tree = 0; events->GetObject("T",tree); //Set the variable to hold the values. Double_t dataSH[189]; Double_t dataPS[52]; Double_t tdataSH[189]; Double_t tdataPS[52]; tree->SetBranchAddress("bb.sh.a_p",&dataSH); tree->SetBranchAddress("bb.ps.a_p",&dataPS); tree->SetBranchAddress("bb.sh.a_time",&tdataSH); tree->SetBranchAddress("bb.ps.a_time",&tdataPS); //Get the number of events. Int_t nEvents = TMath::Min((UInt_t) tree->GetEntries(), (UInt_t)evt+1); Int_t event = 0; Int_t cell = 0; if(evt>=0 && evt<nEvents){ tree->GetEntry(evt); //Create the histogram to draw this event. std::string title = "Event "; title += std::to_string(evt); //Display the event shower->cd(); Draw(dataSH,meanValuesSH, 10, title.c_str(),27,7); preshower->cd(); Draw(dataPS,meanValuesPS, 10, "" ,26,2); tshower->cd(); Draw(tdataSH,meanValuesSH, 10, title.c_str(),27,7); tpreshower->cd(); Draw(tdataPS,meanValuesPS, 10, "" ,26,2); }else{ for(Int_t event = 0; event < nEvents; event++){ //Read in that data. tree->GetEntry(event); //Get the total calibrated ADC value Double_t sum = 0; for(int i = 0; i < 189; i++){ sum += dataSH[i];//-meanValues->at(i); meanValuesSH->at(i) = 0.; } for(int i = 0; i < 52; i++){ sum += dataPS[i];//-meanValues->at(i); meanValuesPS->at(i) = 0.; } //Don't display events with a total ADC value < 50 if(sum < 2){ continue; } //Create the histogram to draw this event. std::string title = "Event "; title += std::to_string(event); //Display the event //c1->cd(1); shower->cd(); Draw(dataSH,meanValuesSH, 10, title.c_str(),27,7); //c1->cd(2); preshower->cd(); Draw(dataPS,meanValuesPS, 10, "" ,26,2); gPad -> WaitPrimitive(); //Memory clean up delete gROOT->FindObject("display"); } } }
25719c1914f49a896dbe96c4fad8bda99946e958
[ "C" ]
1
C
sebastianseeds/SBS_Event_Display
9741a6aad7d263f4a1f7f963b7f2b7cdefadf5f5
49281974464c0763071ee0164fdf5a7c209a471d
refs/heads/master
<file_sep>def convert(s): s = s.replace("[","") s = s.replace("]","") #print("str = " + s) s = s.split(",") res = [] for i in s: aux = float(i) res.append(aux) #print("resultat = " + str(res)) return res<file_sep>####### SERVER ######## import socket import strToArray import movimentServos def Main(): print("IP Adress: ") s = socket.socket() print(str(socket.gethostbyname(socket.gethostname()))) host = '192.168.43.73' #socket.gethostbyname(socket.gethostname()) port = 12345 #s = socket.socket() s.bind((host,port)) s.listen(5) c, addr = s.accept() print("Connection from: " + str(addr)) while True: data = c.recv(1024).decode('utf-8') if not data: break print( data + " recived") c.send(data.encode('utf-8')) mimoPose = strToArray.convert(data) print(mimoPose) movimentServos.colocarAngles(mimoPose) c.close() if __name__ == '__main__': Main()<file_sep>import math import numpy as np def calcAngles(mimoB): """[y][x]""" ls = mimoB[0] le = mimoB[2] lw = mimoB[4] rs = mimoB[1] re = mimoB[3] rw = mimoB[5] ls = np.array(ls) le = np.array(le) lw = np.array(lw) rs = np.array(rs) re = np.array(re) rw = np.array(rw) mimoPos = [] #------Costat esquerra----- #print("----costat esquerra---") #-------colze------- b = np.linalg.norm(ls-le) #print("costat b: " + str(b)) a = np.linalg.norm(le-lw) #print("costat a: " + str(a)) c = np.linalg.norm(lw-ls) #print("costat c: " + str(c)) alpha = ((b**2) + (c**2) - (a**2))/(2*b*c) alpha = math.acos(alpha) alpha = math.degrees(alpha) #convertim de radiants a graus #print("alpha : " + str(alpha) + " servo 6 ombro 2") beta = ((a**2) + (c**2) - (b**2))/(2*a*c) beta = math.acos(beta) beta = math.degrees(beta) #convertim de radiants a graus #print("beta : " + str(beta) ) gamma = 180-alpha-beta #print("gamma : " + str(gamma) + " servo 4 colze") colze = gamma #--------ombro------- b = np.linalg.norm(rs-ls) #print("costat b: " + str(b)) a = np.linalg.norm(ls-le) #print("costat a: " + str(a)) c = np.linalg.norm(le-rs) #print("costat c: " + str(c)) alpha = ((b**2) + (c**2) - (a**2))/(2*b*c) alpha = math.acos(alpha) alpha = math.degrees(alpha) #convertim de radiants a graus #print("alpha : " + str(alpha) + " servo 6 ombro 2") beta = ((a**2) + (c**2) - (b**2))/(2*a*c) beta = math.acos(beta) beta = math.degrees(beta) #convertim de radiants a graus #print("beta : " + str(beta) ) gamma = 180-alpha-beta #print("gamma : " + str(gamma) + " servo 4 colze") if le[0] < ls[0]: ombro = gamma - 90 ombro = 180 - ombro cas0 = False else: ombro = gamma - 90 cas0 = True #ombro, colze mimoPos.append(ombro) mimoPos.append(colze) #-------Costat dret------- #print("\n----costat dret---") #-------colze------- b = np.linalg.norm(re-rs) #print("costat b: " + str(b)) a = np.linalg.norm(rs-rw) #print("costat a: " + str(a)) c = np.linalg.norm(rw-re) #print("costat c: " + str(c)) alpha = ((b**2) + (c**2) - (a**2))/(2*b*c) alpha = math.acos(alpha) alpha = math.degrees(alpha) #convertim de radiants a graus #print("alpha : " + str(alpha) + " servo 3 colze") beta = ((a**2) + (c**2) - (b**2))/(2*a*c) beta = math.acos(beta) beta = math.degrees(beta) #convertim de radiants a graus #print("beta : " + str(beta) ) gamma = 180-alpha-beta #print("gamma : " + str(gamma) + " servo 5 hombro 2") colze = alpha #-------ombro------- b = np.linalg.norm(rs-ls) #print("costat b: " + str(b)) a = np.linalg.norm(ls-re) #print("costat a: " + str(a)) c = np.linalg.norm(re-rs) #print("costat c: " + str(c)) alpha = ((b**2) + (c**2) - (a**2))/(2*b*c) alpha = math.acos(alpha) alpha = math.degrees(alpha) #convertim de radiants a graus #print("alpha : " + str(alpha) + " servo 3 colze") beta = ((a**2) + (c**2) - (b**2))/(2*a*c) beta = math.acos(beta) beta = math.degrees(beta) #convertim de radiants a graus #print("beta : " + str(beta) ) gamma = 180-alpha-beta #print("gamma : " + str(gamma) + " servo 5 hombro 2") if re[0] < rs[0]: ombro = alpha - 90 ombro = 180 - ombro cas1 = False else: ombro = alpha - 90 cas1 = True #ombro, colze mimoPos.append(ombro) mimoPos.append(colze) #------calcul estat------- if cas0 == False and cas1 == False: estat = 0 if cas0 == True and cas1 == True: estat = 1 if cas0 == True and cas1 == False: estat = 2 if cas0 == False and cas1 == True: estat = 3 #print("cas0 = " + str(cas0) + "cas1 = " + str(cas1)) mimoPos.append(estat) #-------print result------- print("ombro esquerra: " + str(mimoPos[0]) + "\n") print("colze esquerra: " + str(mimoPos[1]) + "\n") print("ombro dret: " + str(mimoPos[2]) + "\n") print("colze dret: " + str(mimoPos[3]) + "\n") print("estat: " + str(mimoPos[4]) + "\n") return mimoPos """ if __name__ == "__main__": mimoPos = [] print ("--pose bracos adalt--") ls = [199, 186] rs = [193, 121] le = [176, 223] re = [164, 89] lw = [138, 226] rw = [125, 95] mimoPos.append(ls) mimoPos.append(rs) mimoPos.append(le) mimoPos.append(re) mimoPos.append(lw) mimoPos.append(rw) print("mimoPos: " + str(mimoPos)) calcAngles(mimoPos) print ("\n--pose bracos abaix--") mimoPos = [] ls = [45, 216] rs = [45, 111] le = [118, 251] re = [130, 72] lw = [191, 264] rw = [217, 66] mimoPos.append(ls) mimoPos.append(rs) mimoPos.append(le) mimoPos.append(re) mimoPos.append(lw) mimoPos.append(rw) print("mimoPos: " + str(mimoPos)) calcAngles(mimoPos) print ("\n--pose dret adalt esquerra abaix--") mimoPos = [] ls = [45, 216] rs = [193, 121] le = [118, 251] re = [164, 89] lw = [191, 264] rw = [125, 95] mimoPos.append(ls) mimoPos.append(rs) mimoPos.append(le) mimoPos.append(re) mimoPos.append(lw) mimoPos.append(rw) print("mimoPos: " + str(mimoPos)) calcAngles(mimoPos) print ("\n--pose dret abaix esquerra adalt--") mimoPos = [] rs = [45, 111] re = [130, 72] rw = [217, 66] ls = [199, 186] le = [176, 223] lw = [138, 226] mimoPos.append(ls) mimoPos.append(rs) mimoPos.append(le) mimoPos.append(re) mimoPos.append(lw) mimoPos.append(rw) print("mimoPos: " + str(mimoPos)) calcAngles(mimoPos)"""<file_sep>from adafruit_servokit import ServoKit from time import sleep import random kit = ServoKit(channels = 16) minAngle = 580 maxAngle = 2480 migAngle = 1530 migAngleL = 1350 def initMimobot(): kit.servo[1].set_pulse_width_range(migAngle, maxAngle) kit.servo[1].angle = 0 kit.servo[0].set_pulse_width_range(migAngle, maxAngle) kit.servo[0].angle = 0 kit.servo[2].set_pulse_width_range(minAngle, maxAngle) kit.servo[2].angle = 0 kit.servo[3].set_pulse_width_range(minAngle, maxAngle) kit.servo[3].angle = 0 kit.servo[4].set_pulse_width_range(minAngle, maxAngle) kit.servo[4].angle = 0 kit.servo[5].set_pulse_width_range(maxAngle, maxAngle) kit.servo[5].angle = 0 sleep(1) def colocarAngles(mimoB): c = mimoB[4] #cas elevat if c == 0: #kit.servo[4].set_pulse_width_range(maxAngle, maxAngle) #kit.servo[4].angle = 0 #kit.servo[5].angle = 0 s6 = (mimoB[0]*10) + (minAngle+50) s4 = (mimoB[1]*10) + minAngle + 50 if s4 > 1530: s4 = maxAngle - s4 s4 = 1530 + s4 else: s4 = 2480 s5 = (mimoB[2]*10) + (minAngle+50) s3 = (mimoB[3]*10) + minAngle + 50 if s3 > 1530: s3 = maxAngle - s3 s3 = 1530 + s3 else: s3 = 2480 kit.servo[0].set_pulse_width_range(s3, maxAngle) #re kit.servo[0].angle = 0 #s4 = (mimoB[1]*10) + (950) kit.servo[1].set_pulse_width_range(s4, maxAngle) #le kit.servo[1].angle = 0 kit.servo[2].set_pulse_width_range(s5, maxAngle) #rs kit.servo[2].angle = 0 kit.servo[3].set_pulse_width_range(s6, maxAngle) #ls kit.servo[3].angle = 0 if c == 1: #croissant s6 = (mimoB[0]*10) + (minAngle+50) s4 = (mimoB[1]*10) + minAngle + 50 if s4 > 1530: s4 = maxAngle - s4 s4 = 1530 - s4 else: s4 = 630 s5 = (mimoB[2]*10) + (minAngle+50) s3 = (mimoB[3]*10) + minAngle + 50 if s3 > 1530: s3 = maxAngle - s3 s3 = 1530 - s3 else: s3 = 630 #kit.servo[4].angle = 0 #kit.servo[5].angle = 180 kit.servo[0].set_pulse_width_range(s3, maxAngle) #re kit.servo[0].angle = 0 kit.servo[1].set_pulse_width_range(s4, maxAngle) #le kit.servo[1].angle = 0 kit.servo[2].set_pulse_width_range(s5, maxAngle) #rs kit.servo[2].angle = 0 kit.servo[3].set_pulse_width_range(s6, maxAngle) #ls kit.servo[3].angle = 0 if c == 2: #l down & r up #banda dreta amunt s5 = (mimoB[2]*10) + (minAngle+50) s3 = (mimoB[3]*10) + minAngle + 50 if s3 > 1530: s3 = maxAngle - s3 s3 = 1530 + s3 else: s3 = 2480 #banda esquerra avall s6 = (mimoB[0]*10) + (minAngle+50) s4 = (mimoB[1]*10) + minAngle + 50 if s4 > 1530: s4 = maxAngle - s4 s4 = 1530 - s4 else: s4 = 630 kit.servo[0].set_pulse_width_range(s3, maxAngle) #re kit.servo[0].angle = 0 kit.servo[1].set_pulse_width_range(s4, maxAngle) #le kit.servo[1].angle = 0 kit.servo[2].set_pulse_width_range(s5, maxAngle) #rs kit.servo[2].angle = 0 kit.servo[3].set_pulse_width_range(s6, maxAngle) #ls kit.servo[3].angle = 0 if c == 3: #r down & l up #banda esquerra amunt s6 = (mimoB[0]*10) + (minAngle+50) s4 = (mimoB[1]*10) + minAngle + 50 if s4 > 1530: s4 = maxAngle - s4 s4 = 1530 + s4 else: s4 = 2480 #banda dreta avall s5 = (mimoB[2]*10) + (minAngle+50) s3 = (mimoB[3]*10) + minAngle + 50 if s3 > 1530: s3 = maxAngle - s3 s3 = 1530 - s3 else: s3 = 630 kit.servo[0].set_pulse_width_range(s3, maxAngle) #re kit.servo[0].angle = 0 kit.servo[1].set_pulse_width_range(s4, maxAngle) #le kit.servo[1].angle = 0 kit.servo[2].set_pulse_width_range(s5, maxAngle) #rs kit.servo[2].angle = 0 kit.servo[3].set_pulse_width_range(s6, maxAngle) #ls kit.servo[3].angle = 0 <file_sep># This example moves a servo its full range (180 degrees by default) and then back. from board import SCL, SDA import busio import time from tkinter import * import sys # Import the PCA9685 module. from adafruit_pca9685 import PCA9685 # This example also relies on the Adafruit motor library available here: # https://github.com/adafruit/Adafruit_CircuitPython_Motor from adafruit_motor import servo i2c = busio.I2C(SCL, SDA) # Create a simple PCA9685 class instance. pca = PCA9685(i2c) pca.frequency = 50 # To get the full range of the servo you will likely need to adjust the min_pulse and max_pulse to # match the stall points of the servo. # This is an example for the Sub-micro servo: https://www.adafruit.com/product/2201 # servo7 = servo.Servo(pca.channels[7], min_pulse=580, max_pulse=2480) # This is an example for the Micro Servo - High Powered, High Torque Metal Gear: # https://www.adafruit.com/product/2307 # servo7 = servo.Servo(pca.channels[7], min_pulse=600, max_pulse=2400) # This is an example for the Standard servo - TowerPro SG-5010 - 5010: # https://www.adafruit.com/product/155 # servo7 = servo.Servo(pca.channels[7], min_pulse=600, max_pulse=2500) # This is an example for the Analog Feedback Servo: https://www.adafruit.com/product/1404 # servo7 = servo.Servo(pca.channels[7], min_pulse=600, max_pulse=2600) # The pulse range is 1000 - 2000 by default. abs_min = 580 #580 abs_max = 2480 #2480 servo = servo.Servo(pca.channels[0]) current_val = 1530 servo.angle = 0 def show_values(self): current_val = w1.get() servo.set_pulse_width_range(current_val, abs_max) servo.angle = 0 master = Tk() w1 = Scale(master, from_=abs_min, to=abs_max,command=show_values) #slider 1 w1.pack() print (w1.get()) Button(master, text='Show', command=show_values).pack() #call function #to get slider mainloop() pca.deinit()
8f60dc7061cd45659749268bd96a963732ae0d9a
[ "Python" ]
5
Python
EdgarSalanova/MIMOBOT2019
3948e34a1e7ad892a86f32c848a67323b66633f8
24d91e68bc0fa45e7aad194d4a660acd9d981fc0
refs/heads/master
<repo_name>LordOfDav11/TMP102-SCD30-sensors-for-I2C-STM32<file_sep>/main.c /* USER CODE BEGIN INIT */ static const uint8_t TMP102_ADDR = 0x48 << 1; // Use 8-bit address static const uint8_t REG_TEMP = 0x00; /* USER CODE END INIT */ int main(void) { /* USER CODE BEGIN 1 */ HAL_StatusTypeDef ret; uint8_t buf[12]; int16_t val; float temp_c; /* USER CODE END 1 */ /* USER CODE BEGIN WHILE */ while (1) { // Tell TMP102 that we want to read from the temperature register buf[0] = REG_TEMP; ret = HAL_I2C_Master_Transmit(&hi2c1, TMP102_ADDR, buf, 1, HAL_MAX_DELAY); if ( ret != HAL_OK ) { strcpy((char*)buf, "Error Tx\r\n"); } else { // Read 2 bytes from the temperature register ret = HAL_I2C_Master_Receive(&hi2c1, TMP102_ADDR, buf, 2, HAL_MAX_DELAY); if ( ret != HAL_OK ) { strcpy((char*)buf, "Error Rx\r\n"); } else { //Combine the bytes val = ((int16_t)buf[0] << 4) | (buf[1] >> 4); // Convert to 2's complement, since temperature can be negative if ( val > 0x7FF ) { val |= 0xF000; } // Convert to float temperature value (Celsius) temp_c = val * 0.0625; // Convert temperature to decimal format temp_c *= 100; sprintf((char*)buf, "%u.%u C\r\n", ((unsigned int)temp_c / 100), ((unsigned int)temp_c % 100)); } } // Send out buffer (temperature or error message) HAL_UART_Transmit(&huart2, buf, strlen((char*)buf), HAL_MAX_DELAY); // Wait HAL_Delay(500); /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } <file_sep>/README.md # TMP102 Sensor adress 0x48 Temperature register at 0x00 ``` 3V3 ---> V+ PB8 ---> SCL PB9 ---> SDA GND ---> GND GND ---> ADD0 ALERT (NC) ``` SCL and SDA pull-up resistor (5k) to 3.3V # SCD30 Sensor adress 0x61 Get data ready 0x0202 Read measure 0x0300 Self recalibration 0x5306 ``` 3V3 ---> V+ PB8 ---> SCL PB9 ---> SDA GND ---> GND ```
14ba88bd77274ccb4534eccc7df590e92bd5b5c2
[ "Markdown", "C" ]
2
C
LordOfDav11/TMP102-SCD30-sensors-for-I2C-STM32
3dce12d1435dbc52ab91706af9a0e3e8fba1ab3c
46a15e26ec6ab438f13e6506562cc4468e72ccef
refs/heads/master
<repo_name>uniqueginun/react-js-crud<file_sep>/src/App.js import React, { Component } from "react"; import { Button, Modal, ModalHeader, ModalBody, Form, FormGroup, Label, Input } from "reactstrap"; import SpinnerComponent from "./components/Spinner"; import Persons from "./components/Persons"; import axios from "axios"; class App extends Component { state = { loading: true, customers: [], modal: false, name: "", email: "", phone: "", id: null }; toggle = () => { this.setState({ modal: !this.state.modal }); }; style = { padding: ".5rem" }; componentDidMount() { this.fetchCustomers(); } async fetchCustomers() { const response = await axios.get("http://customers.test/api/customers"); this.setState({ loading: !this.state.loading, customers: response.data }); } handleUpdate = (id, name, email, phone) => { this.setState({ id, name, phone, email }); this.toggle(); }; renderContent = () => { if (this.state.loading) { return <SpinnerComponent />; } return ( <Persons customers={this.state.customers} handleDelete={this.handleDelete} handleUpdate={this.handleUpdate} /> ); }; syncFormData = event => { this.setState({ [event.target.name]: event.target.value }); }; handleDelete = id => { axios.delete(`http://customers.test/api/customers/${id}`).then(response => { this.setState({ customers: [...this.state.customers].filter(customer => { return customer.id !== id; }) }); }); }; async handleSubmit(event) { event.preventDefault(); if (this.state.id) { this.updateCustomer(); } else { this.createCustomer(); } } async updateCustomer() { const editedCustomer = { name: this.state.name, email: this.state.email, phone: this.state.phone, website: "http://test.net" }; const response = await axios.put( "http://customers.test/api/customers/" + this.state.id, editedCustomer ); this.setState({ id: null, name: "", email: "", phone: "", customers: [...this.state.customers].map(customer => { if (customer.id === response.data.id) { customer = response.data; } return customer; }) }); this.toggle(); } async createCustomer() { const newCustomer = { name: this.state.name, email: this.state.email, phone: this.state.phone, website: "http://test.net" }; const response = await axios.post( "http://customers.test/api/customers", newCustomer ); this.setState({ customers: [...this.state.customers, response.data], name: "", email: "", phone: "" }); this.toggle(); } render() { const { name, email, phone } = this.state; return ( <div className="container mt-4"> <div className="bg-info clearfix" style={this.style}> <Button className="btn btn-info float-left"> React Js Student Menagement System </Button> <Button onClick={this.toggle} className="btn btn-success float-right"> <i className="fa fa-plus" aria-hidden="true"></i> </Button> <div> <Modal isOpen={this.state.modal} toggle={this.toggle} className="customerModal" > <ModalHeader toggle={this.toggle}>Create Customers</ModalHeader> <ModalBody> <Form onSubmit={this.handleSubmit.bind(this)}> <FormGroup> <Label for="Name">Name</Label> <Input type="text" name="name" id="Name" onChange={this.syncFormData} value={name} /> </FormGroup> <FormGroup> <Label for="Email">Email</Label> <Input type="email" name="email" id="Email" onChange={this.syncFormData} value={email} /> </FormGroup> <FormGroup> <Label for="Phone">Phone</Label> <Input type="text" name="phone" id="Phone" onChange={this.syncFormData} value={phone} /> </FormGroup> <Button color="primary" type="submit"> Sunmit </Button>{" "} <Button color="secondary" onClick={this.toggle}> Cancel </Button> </Form> </ModalBody> </Modal> </div> </div> <div className="row mt-4 justify-content-start" style={this.style}> {this.renderContent()} </div> </div> ); } } export default App; <file_sep>/src/components/Person.jsx import React from "react"; import { Button } from "reactstrap"; const Person = props => { let { id, name, email, phone } = props.customer; return ( <tr className="bg-light"> <th scope="row">{id}</th> <td>{name}</td> <td>{email}</td> <td>{phone}</td> <td> <Button onClick={() => props.handleUpdate(id, name, email, phone)} color="warning" > <i className="fa fa-pencil" aria-hidden="true"></i> </Button>{" "} <Button onClick={() => props.handleDelete(id)} color="danger"> <i className="fa fa-trash-o" aria-hidden="true"></i> </Button>{" "} </td> </tr> ); }; export default Person;
4f26e996fab67864930e50183cd1a2f1b5201f2d
[ "JavaScript" ]
2
JavaScript
uniqueginun/react-js-crud
cd38cd9500daa0490492b9011ddd738320af019a
afc8bf6a942fb058275e72334790c9e18e68600c
refs/heads/master
<repo_name>ataitler/AirHockeyServer<file_sep>/Assets/Scripts/HumanController.cs using UnityEngine; using System.Collections; using AssemblyCSharp; public class HumanController : MonoBehaviour { private GameController gameController = null; public float Speed; public Camera cam; private Vector2 initPosition; private Vector2 initVelocity; //private Vector3 X_hat; //private Vector3 Y_hat; // Use this for initialization void Start () { GameObject gameControllerObject = GameObject.FindWithTag ("GameController"); if (gameControllerObject != null) { gameController = gameControllerObject.GetComponent<GameController>(); } if (gameController == null) { Debug.Log("Cannot find 'GameController' script"); } initPosition = new Vector2(1000, 0); initVelocity = new Vector2(0, 0); } // Update is called once per frame void Update () { } void FixedUpdate() { if (gameController.State == GameState.Playing) { float moveHorizontal = Input.GetAxis("Mouse X"); float moveVertical = Input.GetAxis("Mouse Y"); Vector2 move; if (cam.transform.rotation.z == 0) move = new Vector2(moveHorizontal, moveVertical) * Speed; else move = new Vector2(-moveVertical, moveHorizontal) * Speed; rigidbody2D.velocity = move; float posX,posY; posX = Mathf.Clamp(rigidbody2D.position.x, 0, 1180); posY = Mathf.Clamp(rigidbody2D.position.y, -590, 590); rigidbody2D.position = new Vector2(posX,posY); /* Vector2 posNext = rigidbody2D.position + 0.02f * move; float clampedX = Mathf.Clamp(posNext.x, 0, 1180); float clampedY = Mathf.Clamp(posNext.y, -590, 590); rigidbody2D.velocity = move; if (clampedX != posNext.x) { pos.x = clampedX; move.x = 0; rigidbody2D.position = pos; rigidbody2D.velocity = move; } if (clampedY != posNext.y) { pos.y = clampedY; move.y = 0; rigidbody2D.position = pos; rigidbody2D.velocity = move; } */ } else { this.rigidbody2D.position = initPosition; this.rigidbody2D.velocity = initVelocity; } } Vector2 Accelerate(Rigidbody2D body,Vector2 move) { Vector2 acc = new Vector2(); acc.x = move.x*body.mass; acc.y = move.y*body.mass; return acc; } } <file_sep>/Assets/Scripts/CommunicationController.cs using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using AssemblyCSharp; public class CommunicationController : MonoBehaviour { public PuckController Puck; public HumanController Human; public ComputerController Computer; public GameController gameController; public double visionTimeStep; //new private int counter, stepsCounter; //new //The collection of all clients logged into the game (an array of type ClientInfo) //ArrayList clientList; List<ClientInfo> clientList; private int numOfPlayers; //The main socket on which the server listens to the clients Socket serverSocket; byte[] byteData = new byte[1024]; // Use this for initialization void Start () { stepsCounter = (int)Math.Round(visionTimeStep / Time.fixedDeltaTime); //new counter = 1; //new numOfPlayers = gameController.PlayersNum; //clientList = new ArrayList(); clientList = new List<ClientInfo>(); // recieve connection object for articifial player and send camera data. try { //We are using UDP sockets serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //Assign the any IP of the machine and listen on port number 1234 IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 1234); //Bind this address to the server serverSocket.Bind(ipEndPoint); IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0); //The epSender identifies the incoming clients EndPoint epSender = (EndPoint)ipeSender; //Start receiving data serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender); } catch (Exception ex) { print ("Start: " + ex.Message); } } // Update is called once per frame void FixedUpdate () { if (gameController.State == GameState.Playing) { if (counter == stepsCounter) { // agentX, agentY, agentVx, agentVy, puckX, puckY, puckVx, puckVy, puckR, oppX, oppY, oppVx, oppVy string puckData = Puck.rigidbody2D.position.x.ToString()+","+Puck.rigidbody2D.position.y.ToString()+","+ Puck.rigidbody2D.velocity.x.ToString()+","+Puck.rigidbody2D.velocity.y.ToString()+","+ Puck.rigidbody2D.angularVelocity.ToString(); string player1Data = Computer.rigidbody2D.position.x.ToString()+","+Computer.rigidbody2D.position.y.ToString()+","+ Computer.rigidbody2D.velocity.x.ToString()+","+Computer.rigidbody2D.velocity.y.ToString(); string player2Data = Human.rigidbody2D.position.x.ToString()+","+Human.rigidbody2D.position.y.ToString()+","+ Human.rigidbody2D.velocity.x.ToString()+","+Human.rigidbody2D.velocity.y.ToString(); SendSignal(Command.Message, player1Data+","+puckData+","+player2Data, Players.Player1); if (gameController.PlayersNum == 2) SendSignal(Command.Message, player2Data+","+puckData+","+player1Data, Players.Player2); counter = 1; } else { counter++; } } } public void SendSignal(Command cmd, string msg, Players P) { Data msgToSend = new Data(); msgToSend.sID = 0; msgToSend.cmdCommand = cmd; msgToSend.strMessage = msg; print(cmd.ToString()); byte[] message = msgToSend.ToByte (); try { switch (P) { case Players.All: foreach (ClientInfo client in clientList) { serverSocket.BeginSendTo (message, 0, message.Length, SocketFlags.None, client.endpoint, new AsyncCallback (OnSend), client.endpoint); } break; case Players.Player1: ClientInfo client1 = clientList[0]; serverSocket.BeginSendTo (message, 0, message.Length, SocketFlags.None, client1.endpoint, new AsyncCallback (OnSend), client1.endpoint); break; case Players.Player2: if (clientList.Count > 1) { ClientInfo client2 = clientList[1]; serverSocket.BeginSendTo (message, 0, message.Length, SocketFlags.None, client2.endpoint, new AsyncCallback (OnSend), client2.endpoint); } break; } } catch (Exception ex) { print("SendSigal: " + ex.Message); } } private void OnReceive(IAsyncResult ar) { try { IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0); EndPoint epSender = (EndPoint)ipeSender; serverSocket.EndReceiveFrom(ar, ref epSender); Data msgReceived = new Data(byteData); print("Received: " + msgReceived.cmdCommand.ToString()); // message handling (switch) switch (msgReceived.cmdCommand) { case Command.Login: if (clientList.Count< numOfPlayers) { ClientInfo clientInfo = new ClientInfo(); clientInfo.endpoint = epSender; if (clientList.Count == 1) { clientInfo.ID = 1; //Add the first player - always the left player clientList.Add(clientInfo); SendSignal(Command.Login,clientInfo.ID.ToString(),Players.Player1); } else { clientInfo.ID = 2; // Add the second player - always the right player clientList.Add(clientInfo); SendSignal(Command.Login,clientInfo.ID.ToString(),Players.Player2); } } if (clientList.Count == numOfPlayers) { gameController.UpdateAsyncState(GameState.Idle); } break; case Command.Logout: int nIndex = 0; foreach (ClientInfo client in clientList) { if (client.endpoint.Equals(epSender)) { print ("removing player " + (nIndex+1).ToString()); clientList.RemoveAt(nIndex); break; } ++nIndex; } gameController.UpdateAsyncState(GameState.Disconnected); break; case Command.Message: string[] values = msgReceived.strMessage.Split(','); /*computerXvelocity = float.Parse(values[0])*2; computerYvelocity = float.Parse(values[1])*2;*/ if (msgReceived.sID == 1) { Computer.UpdateSpeed(float.Parse(values[0]), float.Parse(values[1])); } break; default: break; } ipeSender = new IPEndPoint(IPAddress.Any, 0); epSender = (EndPoint)ipeSender; //Start listening to the messages send by the players serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender); } catch (Exception ex) { print("OnReceive Error: " + ex.Message); } } private void OnSend(IAsyncResult ar) { try { serverSocket.EndSend(ar); } catch (Exception ex) { print("OnSend Error: " + ex.Message); } } } <file_sep>/Assets/Scripts/PuckController.cs using UnityEngine; using System.Collections; using AssemblyCSharp; public class PuckController : MonoBehaviour { public float MaxSpeed; private GameController gameController; // Use this for initialization void Start () { GameObject gameControllerObject = GameObject.FindWithTag ("GameController"); if (gameControllerObject != null) { gameController = gameControllerObject.GetComponent<GameController>(); } if (gameController == null) { Debug.Log("Cannot find 'GameController' script"); } } // Update is called once per frame void Update () { } void FixedUpdate() { if (gameController.State == GameState.Playing) { float ratio = rigidbody2D.velocity.magnitude / MaxSpeed; if (ratio > 1) { rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x / ratio, rigidbody2D.velocity.y / ratio); } } else { rigidbody2D.position = new Vector2(0,0); rigidbody2D.velocity = new Vector2(0,0); } //CheckPuckOnBoard(); } void CheckPuckOnBoard() { if (gameController.State == GameState.Playing) { if (rigidbody2D.position.x < -1300) gameController.UpdateScore(Players.Player2); //human else if (rigidbody2D.position.x > 1300) gameController.UpdateScore(Players.Player1); //agent else return; Players win = gameController.IsWin(); if (win == Players.All) { gameController.UpdateAsyncState(GameState.Starting); } else { gameController.UpdateAsyncState(GameState.Idle); gameController.LastWinner = win; } } } } <file_sep>/Assets/Scripts/Command.cs using System; namespace AssemblyCSharp { public enum Command { //Log into the server Login, //Logout of the server - irrelevent Logout, //Send a text message to all the chat clients Message, //reset game - irrelevent Reset, //No command Null, //Start playing Start, //Pause the game Pause, //Score update Score, //Start new game NewGame, //Game has ended EndGame } } <file_sep>/Assets/Scripts/GameController.cs using UnityEngine; using System; using System.Collections; using AssemblyCSharp; public class GameController : MonoBehaviour { private Logger mLogger = null; private FileLogger mFileLogger = null; private GameState state; public int MaxScore; private Vector3 countDown; private GameState flagState; private int[] scoreList; private int[] lastScoreList; private int timeToStart; private Players lastWinner; public int numOfPlayers; // text boards public GUIText GameInfoText; public GUIText ScoreBoardText; public GUIText winnerBoardText; public PuckController Puck; public ComputerController Player1; public HumanController Player2; public CommunicationController com; private int logCounter; private int logCycle; public GameState State { get { return state;} } public Players LastWinner { set { lastWinner = value; } } public int PlayersNum { get { return numOfPlayers;} } // Use this for initialization void Start () { UpdateState(GameState.Disconnected); logCycle = 10; scoreList = new int[2]; lastScoreList = new int[2]; lastWinner = Players.All; if (mLogger == null) { mLogger = Logger.Instance; mFileLogger = new FileLogger(@"c:\temp\trajectories.txt"); mFileLogger.Init(); mLogger.RegisterObserver(mFileLogger); mLogger.AddLogMessage("***** New run of the server!! *****"); mFileLogger.Terminate(); } } // Update is called once per frame void Update () { if (flagState != GameState.None) UpdateState(flagState); //print(state.ToString()); if (State == GameState.Idle) { if (Input.GetKeyDown(KeyCode.R)) { // start new game UpdateState(GameState.Starting); //StartCoroutine("GetReady"); } } if (state == GameState.Starting) { timeToStart = (int)countDown.sqrMagnitude; //print ("starting, " + timeToStart.ToString()); if (timeToStart > 0) { GameInfoText.text = timeToStart.ToString(); } else { UpdateState(GameState.Playing); mFileLogger.Init(); mLogger.AddLogMessage("Starting new chapter"); mLogger.AddLogMessage("Puck \t\t Agent \t\t Human"); mFileLogger.Terminate(); } } } void FixedUpdate() { /*if (state == GameState.Playing) { if (logCounter < logCycle) { logCounter++; } else { mFileLogger.Init(); mLogger.AddLogMessage(Puck.rigidbody2D.position.ToString() + "\t" + Player1.rigidbody2D.position.ToString() + "\t" + Player2.rigidbody2D.position.ToString()); mFileLogger.Terminate(); logCounter = 1; } }*/ } public void UpdateState(GameState st) { GameState currentState = this.state; // send signals switch (st) { case GameState.Disconnected: GameInfoText.text = "Welcome!"; ScoreBoardText.text = ""; winnerBoardText.text = ""; break; case GameState.Idle: UpdateScore(Players.All); if (lastWinner != Players.All) { if (lastWinner == Players.Player1) winnerBoardText.text = "Player 1 has won the game!"; else winnerBoardText.text = "Player 2 has won the game!"; ScoreBoardText.text = lastScoreList[0].ToString() + ":" + lastScoreList[1].ToString(); com.SendSignal(Command.EndGame, null, Players.All); } GameInfoText.text = "Press 'R' To Start a New Game"; countDown = new Vector3(1, 1, 1); break; case GameState.Starting: if (currentState == GameState.Idle) com.SendSignal(Command.NewGame, MaxScore.ToString(), Players.All); else if (currentState == GameState.Playing) com.SendSignal(Command.Pause, null, Players.All); winnerBoardText.text = ""; ScoreBoardText.text = scoreList[0].ToString() + ":" + scoreList[1].ToString(); ResetObjects(); StartCoroutine("GetReady"); break; case GameState.Playing: com.SendSignal(Command.Start, null, Players.All); GameInfoText.text = ""; countDown = new Vector3(1, 1, 1); break; } flagState = GameState.None; state = st; print (state.ToString()); } public void UpdateAsyncState(GameState st) { flagState = st; } IEnumerator GetReady() { int i; for (i=0; i<3; i++) { yield return new WaitForSeconds(1f); int norm = (int)countDown.sqrMagnitude; countDown [norm - 1] = 0; print(norm.ToString()); } } public void UpdateScore(Players P) { switch (P) { case Players.Player1: scoreList [0] += 1; break; case Players.Player2: scoreList [1] += 1; break; case Players.All: for (int i=0; i<2; i++) scoreList[i]=0; break; } if (P != Players.All) { if ((scoreList [0] == MaxScore) || (scoreList [1] == MaxScore)) { lastScoreList [0] = scoreList [0]; lastScoreList [1] = scoreList [1]; } com.SendSignal(Command.Score, scoreList [0].ToString() + ":" + scoreList [1].ToString(), Players.Player1); com.SendSignal(Command.Score, scoreList [1].ToString() + ":" + scoreList [0].ToString(), Players.Player2); } } public Players IsWin() { if (scoreList[0] == MaxScore) return Players.Player1; else if (scoreList[1] == MaxScore) return Players.Player2; else return Players.All; } private void ResetObjects() { Puck.rigidbody2D.rotation = 0; Puck.rigidbody2D.angularVelocity = 0; Puck.rigidbody2D.position = new Vector2(0, 0); Puck.rigidbody2D.velocity = new Vector2(0, 0); Player1.rigidbody2D.position = new Vector2(-1000, 0); Player1.rigidbody2D.velocity = new Vector2(0, 0); Player2.rigidbody2D.position = new Vector2(1000, 0); Player2.rigidbody2D.velocity = new Vector2(0, 0); } } <file_sep>/Assets/Scripts/GameState.cs using System; namespace AssemblyCSharp { public enum GameState { // No player connected Disconnected, // Players connected, no game in progress Idle, // beginning an episode of a game Starting, // game in progress, players are playing Playing, // not in any game state None } } <file_sep>/Assets/Scripts/Goal.cs using UnityEngine; using System.Collections; using AssemblyCSharp; public class Goal : MonoBehaviour { private GameController gameController; private PuckController puckController; // Use this for initialization void Start () { GameObject gameControllerObject = GameObject.FindWithTag ("GameController"); if (gameControllerObject != null) { gameController = gameControllerObject.GetComponent<GameController>(); } if (gameController == null) { Debug.Log("Cannot find 'GameController' script"); } // find the puck GameObject puckControllerObject = GameObject.FindWithTag ("Puck"); if (puckControllerObject != null) { puckController = puckControllerObject.GetComponent<PuckController>(); } if (puckController == null) { Debug.Log("Cannot find 'PuckController' script"); } } void OnTriggerEnter2D(Collider2D other) { if (other.tag == "Puck") { if (other.rigidbody2D.position.x < 0) gameController.UpdateScore(Players.Player2); //human else gameController.UpdateScore(Players.Player1); //agent Players win = gameController.IsWin(); if (win == Players.All) { gameController.UpdateAsyncState(GameState.Starting); } else { gameController.UpdateAsyncState(GameState.Idle); gameController.LastWinner = win; } } } } <file_sep>/Assets/Scripts/ClientInfo.cs using System; using System.Net; using System.Net.Sockets; namespace AssemblyCSharp { //The ClientInfo structure holds the required information about every //client connected to the server struct ClientInfo { public EndPoint endpoint; //Socket of the client public int ID; //ID of the player } } <file_sep>/Assets/Scripts/ILogger.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; //using System.Threading.Tasks; using AssemblyCSharp; using UnityEngine; public interface ILogger{ void ProcessLogMessage(string logMessage); } <file_sep>/Assets/Scripts/ComputerController.cs using UnityEngine; using System.Collections; using AssemblyCSharp; public class ComputerController : MonoBehaviour { private GameController gameController = null; private float xSpeed; private float ySpeed; private Vector2 initPosition; private Vector2 initVeclocity; // Use this for initialization void Start () { GameObject gameControllerObject = GameObject.FindWithTag ("GameController"); if (gameControllerObject != null) { gameController = gameControllerObject.GetComponent<GameController>(); } if (gameController == null) { Debug.Log("Cannot find 'GameController' script"); } initPosition = new Vector2(-1000, 0); initVeclocity = new Vector2(0, 0); xSpeed = 0; ySpeed = 0; } // Update is called once per frame void Update () { } void FixedUpdate() { if (gameController.State == GameState.Playing) { // Velocity control - step motors this.rigidbody2D.velocity = new Vector2(xSpeed, ySpeed); this.rigidbody2D.position = new Vector2( Mathf.Clamp(rigidbody2D.position.x, -1180, 0), Mathf.Clamp(rigidbody2D.position.y, -590, 590) ); } else { xSpeed = 0; ySpeed = 0; this.rigidbody2D.position = initPosition; this.rigidbody2D.velocity = initVeclocity; } } public void UpdateSpeed(float xVel, float yVel) { float acTh = 100; if (gameController.State == GameState.Playing) { // first order filter for the velocity //xSpeed = xSpeed + 0.01f * 50 * (xVel - xSpeed); //ySpeed = ySpeed + 0.01f * 50 * (yVel - ySpeed); // velocity saturation if (Mathf.Abs(xVel - xSpeed) > acTh) xSpeed = xSpeed + Mathf.Sign(xVel-xSpeed) * acTh; if (Mathf.Abs(yVel - ySpeed) > acTh) ySpeed = ySpeed + Mathf.Sign(yVel-ySpeed) * acTh; // infinite bandwidth plant //xSpeed = xVel; //ySpeed = yVel; } } public void Reset() { xSpeed = 0; ySpeed = 0; rigidbody2D.position = new Vector2 (-1000, 0); rigidbody2D.angularVelocity = 0; rigidbody2D.velocity = new Vector2 (0, 0); } } <file_sep>/Assets/Scripts/Players.cs using System; namespace AssemblyCSharp { public enum Players { Player1, Player2, All } } <file_sep>/README.md # AirHockeyServer Air hockey server for general agents
6ba02e2247b2af40781aa2c0e07af0c0ab1e36c8
[ "Markdown", "C#" ]
12
C#
ataitler/AirHockeyServer
b24d09ae5d709bac56281d3feeafeee21d4b076a
1176c47cec2d6ac1410a53974cdf51dc580bcfc0
refs/heads/master
<file_sep>import codecs from urllib.request import urlopen import math import pickle import json from html.parser import HTMLParser from itertools import zip_longest from snakemake.utils import min_version, R from Bio import SeqIO from Bio.KEGG.REST import * from Bio.KEGG.KGML import KGML_parser from Bio.Graphics.KGML_vis import KGMLCanvas from GoTools import parseGoOboDict from KeggTools import CachedKeggKoToPathwayMap from KeggTools import CachedKeggKoToEnzymeMap from KeggTools import CachedKeggPathwayIdToNameMap from KeggTools import KeggReactionIdToEcMap from MultiCachedDict import PersistantDict configfile: "config.json" rule all: input: expand("activation/ca_active_{geneset}_{comp}.tsv", geneset=["go", "cazy"], comp=["straw-malt", "alder-straw", "alder-malt", "stat-exp", "solid-liquidExp", "solid-liquidSta"]), expand("ca_{gSet}_activation.tsv", gSet=["go", "cazy", "kegg"]), expand("expr/{dir}_{comp}.tsv", dir=["up", "down", "diff"], comp=["straw-malt", "alder-straw", "alder-malt", "stat-exp", "solid-liquidExp", "solid-liquidSta"]), expand("expr/diffAnno_{comp}.tsv", comp=["straw-malt", "alder-straw", "alder-malt", "stat-exp", "solid-liquidExp", "solid-liquidSta"]), "expr/expr_strawSS-malt.tsv", "expr/expr_alder-strawSS.tsv", expand("keggPlots/{comp}.ca_active_kegg.expressionplots", comp=["straw-malt", "alder-straw", "alder-malt", "stat-exp", "solid-liquidExp", "solid-liquidSta"]), "overlap/genes.tsv", "overlap/geneSets.tsv" rule fastqc: input: "../ClaaquEProfiling/Raw Data/{sample}.fastq.gz" output: "QC/{sample}_fastqc.html" threads: 6 shell: "%(fastqc)s -o QC -t {threads} \"{input}\"" % config rule multiqc: input: expand("QC/{sample}_fastqc.html", sample=config["fileNames"].values()) output: "QC/multiqc_report.html", "QC/multiqc_data/multiqc_fastqc.txt" shell: "%(multiqc)s -f --interactive -o QC QC/*_fastqc.zip" % config rule combineIntoMatrix: input: expand("../rsem2/{sample}.genes.results", sample=config["sampleNames"].values()) output: fList="rsem.resultFiles.txt", mtx="genes.counts.matrix" shell: "ls {input} > {output.fList}; %(rsem2matrix)s --rsem_files {output.fList} --mode counts > {output.mtx}" % config rule deSeq2: input: counts="genes.counts.matrix", samples="samples.tsv" output: pcas="pcas.pdf", disp_medium="disp_medium.png", disp_phase="disp_phase.png", disp_cultureE="disp_cultureExp.png", disp_cultureS="disp_cultureSta.png", diff_medium="diff_medium.pdf", diff_phase="diff_phase.pdf", diff_cultureE="diff_cultureExp.pdf", diff_cultureS="diff_cultureSta.pdf", am_tab="expr/expr_alder-malt.tsv", sm_tab="expr/expr_straw-malt.tsv", as_tab="expr/expr_alder-straw.tsv", sm_tab_ss="expr/expr_strawSS-malt.tsv", as_tab_ss="expr/expr_alder-strawSS.tsv", se_tab="expr/expr_stat-exp.tsv", sle_tab="expr/expr_solid-liquidExp.tsv", sls_tab="expr/expr_solid-liquidSta.tsv" run: R(""" library(DESeq2, quietly=T) library(ggplot2, quietly=T) colData <- read.table("{input.samples}", row.names=1, header=T) colData$medium <- relevel(colData$medium, ref="malt") colData$culture <- relevel(colData$culture, ref="lq") colData$phase <- relevel(colData$phase, ref="exp") rawCountData <- read.table("{input.counts}", row.names=1, header=T) intCountData = sapply(rawCountData, as.integer) countData = intCountData[,rownames(colData)] row.names(countData) = row.names(rawCountData) dds <- DESeqDataSetFromMatrix(countData = countData, colData = colData, design = ~ culture+medium) dds_phase <- DESeqDataSetFromMatrix(countData = countData[,c(1,2,3,13,14)], colData = data.frame(phase=colData[c(1,2,3,13,14), 3]), design = ~ phase) dds_culture_exp <- DESeqDataSetFromMatrix(countData = countData[,c(10,11,12,13,14)], colData = data.frame(culture=colData[c(10,11,12,13,14), 1]), design = ~ culture) dds_culture_sta <- DESeqDataSetFromMatrix(countData = countData[,c(1,2,3,10,11,12)], colData = data.frame(culture=colData[c(1,2,3,10,11,12), 1]), design = ~ culture) dds_lq_exp <- DESeqDataSetFromMatrix(countData = countData[,c(4,5,6,7,8,9,13,14)], colData = data.frame(medium=colData[c(4,5,6,7,8,9,13,14), 2]), design = ~ medium) dds_lq_exp_ss <- DESeqDataSetFromMatrix(countData = countData[,c(4,5,6,7,8,9,15,16)], colData = data.frame(medium=colData[c(4,5,6,7,8,9,15,16), 2]), design = ~ medium) vsd <- varianceStabilizingTransformation(dds, blind=FALSE) d=plotPCA(vsd, intgroup=c("medium", "culture"), returnData=T) p1=ggplot(d, aes(x=PC1, y=PC2, shape=culture, color=medium)) + geom_point() vsd <- varianceStabilizingTransformation(dds_phase, blind=FALSE) p2=plotPCA(vsd, intgroup=c("phase")) vsd <- varianceStabilizingTransformation(dds_culture_exp, blind=FALSE) p3=plotPCA(vsd, intgroup=c("culture")) vsd <- varianceStabilizingTransformation(dds_culture_sta, blind=FALSE) p3=plotPCA(vsd, intgroup=c("culture")) vsd <- varianceStabilizingTransformation(dds_lq_exp, blind=FALSE) p4=plotPCA(vsd, intgroup=c("medium")) pdf("{output.pcas}") print(p1) print(p2) print(p3) print(p4) dev.off() #MEDIUM RESULT dds_lq_exp <- DESeq(dds_lq_exp, betaPrior=T) res_alder_malt = results(dds_lq_exp, alpha=0.05, contrast=c("medium","alder","malt")) res_straw_malt = results(dds_lq_exp, alpha=0.05, contrast=c("medium","straw","malt")) res_alder_straw = results(dds_lq_exp, alpha=0.05, contrast=c("medium","alder","straw")) png("{output.disp_medium}") plotDispEsts(dds_lq_exp) dev.off() pdf("{output.diff_medium}") plotMA(dds_lq_exp) dev.off() write.table(res_alder_malt, "{output.am_tab}", quote=F, sep="\t") write.table(res_straw_malt, "{output.sm_tab}", quote=F, sep="\t") write.table(res_alder_straw, "{output.as_tab}", quote=F, sep="\t") #SUB-SAMPLE MEDIUM RESULT dds_lq_exp_ss <- DESeq(dds_lq_exp_ss, betaPrior=T) res_straw_malt = results(dds_lq_exp_ss, alpha=0.05, contrast=c("medium","straw","malt")) res_alder_straw = results(dds_lq_exp_ss, alpha=0.05, contrast=c("medium","alder","straw")) write.table(res_straw_malt, "{output.sm_tab_ss}", quote=F, sep="\t") write.table(res_alder_straw, "{output.as_tab_ss}", quote=F, sep="\t") #PHASE RESULT dds_phase = DESeq(dds_phase, betaPrior=T) res_stat_exp = results(dds_phase, alpha=0.05) png("{output.disp_phase}") plotDispEsts(dds_phase) dev.off() pdf("{output.diff_phase}") plotMA(dds_phase) dev.off() write.table(res_stat_exp, "{output.se_tab}", quote=F, sep="\t") #CULTURE RESULT dds_culture_exp = DESeq(dds_culture_exp, betaPrior=T) res_solid_liquidExp = results(dds_culture_exp, alpha=0.05) png("{output.disp_cultureE}") plotDispEsts(dds_culture_exp) dev.off() pdf("{output.diff_cultureE}") plotMA(dds_culture_exp) dev.off() write.table(res_solid_liquidExp, "{output.sle_tab}", quote=F, sep="\t") dds_culture_sta = DESeq(dds_culture_sta, betaPrior=T) res_solid_liquidSta = results(dds_culture_sta, alpha=0.05) png("{output.disp_cultureS}") plotDispEsts(dds_culture_sta) dev.off() pdf("{output.diff_cultureS}") plotMA(dds_culture_sta) dev.off() write.table(res_solid_liquidSta, "{output.sls_tab}", quote=F, sep="\t") """) rule diffExpr: input: "expr/expr_{comp}.tsv" output: diff="expr/diff_{comp}.tsv", up="expr/up_{comp}.tsv", down="expr/down_{comp}.tsv" run: with open(output.diff, "w") as diff, open(output.up, "w") as up, open(output.down, "w") as down: with open(input[0]) as inStream: next(inStream) #header for line in inStream: gId, mean, change, lfc, start, p, padj = line.strip("\n").split("\t") if padj != "NA" and float(padj)<0.05 and abs(float(change))>1: diff.write(line) if float(change)>0: up.write(line) else: down.write(line) rule subsampleRes: input: all="expr/expr_straw-malt.tsv", subset="expr/expr_strawSS-malt.tsv" output: "subsampleChange.txt" run: allUp = set() allDown = set() allNC = set() with open(input.all) as inStream: header = next(inStream) for line in inStream: pId, mean, change, se, start, pvalue, padj = line.strip("\n").split("\t") if padj != "NA" and float(padj)<0.05: if float(change)>1: allUp.add(pId) elif float(change)<-1: allDown.add(pId) else: allNC.add(pId) else: allNC.add(pId) ssUp = set() ssDown = set() ssNC = set() with open(input.subset) as inStream: header = next(inStream) for line in inStream: pId, mean, change, se, start, pvalue, padj = line.strip("\n").split("\t") if padj != "NA" and float(padj)<0.05: if float(change)>1: ssUp.add(pId) elif float(change)<-1: ssDown.add(pId) else: ssNC.add(pId) else: ssNC.add(pId) assert len(allUp.union(allDown).union(allNC)) == len(ssUp.union(ssDown).union(ssNC)) with open(output[0], "w") as out: out.write("both up:\t%i\n" % len(allUp & ssUp)) out.write("both down:\t%i\n" % len(allDown & ssDown)) out.write("both no change:\t%i\n" % len(allNC & ssNC)) out.write("total:\t%i\n" % len(allUp.union(allDown).union(allNC))) out.write("percentage same:\t%f%%\n" % ((len(allUp & ssUp)+len(allDown & ssDown)+len(allNC & ssNC))/len(allUp.union(allDown).union(allNC))*100)) rule signalP: input: "../funannotate/caqua/predict_results/Clavariopsis_aquatica_WDA-00-1.proteins.fa" output: "signalp/Clavariopsis_aquatica_WDA-00-1.signalp.out" shell: "%(signalp)s -t euk -f short {input} > {output}" % config rule collectAnno: input: tsv="../Clavariopsis_aquatica_WDA-00-1.annotations.txt" output: go="ca_proteins_go.tsv", cog="ca_proteins_cog.tsv", cazy="ca_proteins_cazy.tsv" run: go = {} cazy = {} cog = {} with open(input.tsv) as inStream: header = next(inStream) arr = header.split("\t") assert arr[12] == "COG" assert arr[13] == "GO Terms" assert arr[17] == "CAZyme" for line in inStream: arr = line.split("\t") gId = arr[0] if arr[1] != "CDS": continue cogIds = arr[12].split(";") goIds = arr[13].split(";") cazyIds = arr[17].split(";") for gId in goIds: if len(gId) == 0: continue try: go[gId].append(arr[0]) except KeyError: go[gId] = [arr[0]] for cId in cazyIds: if len(cId) == 0: continue try: cazy[cId].append(arr[0]) except KeyError: cazy[cId] = [arr[0]] for cId in cogIds: if len(cId) == 0: continue try: cog[cId].append(arr[0]) except KeyError: cog[cId] = [arr[0]] with open(output.go, "w") as out: for gId, genes in go.items(): out.write("%s\t%s\n" % (gId, ",".join(genes))) with open(output.cog, "w") as out: for cId, genes in cog.items(): out.write("%s\t%s\n" % (cId, ",".join(genes))) with open(output.cazy, "w") as out: for cId, genes in cazy.items(): out.write("%s\t%s\n" % (cId, ",".join(genes))) rule getKeggKO: input: kegg="../kegg/user_ko.tsv" output: "ca_proteins_kegg.tsv" params: db="/home/heeger/data/dbs/keggKo2Pathway.db" run: ko2path = CachedKeggKoToPathwayMap(params.db) path = {} for line in open(input.kegg): arr = line.strip("\n").split("\t") if len(arr) == 1: continue gene, ko = arr try: pathSet = ko2path[ko] except KeyError: continue for p in pathSet: try: path[p].append(gene.split("-")[0]) except KeyError: path[p] = [gene.split("-")[0]] with open(output[0], "w") as out: for p, gset in path.items(): out.write("%s\t%s\n" % (p, ",".join(gset))) rule anno: input: fun="../Clavariopsis_aquatica_WDA-00-1.annotations.txt", kegg="ca_proteins_kegg.tsv", signalp="signalp/Clavariopsis_aquatica_WDA-00-1.signalp.out" output: json="anno.json", pickle="anno.pic" run: go = {} cazy = {} interpro = {} name = {} kegg = {} sigP = {} for line in open(input.fun): gene, feature, contig, start, stop, strand, tName, product, busco, pfam, interPro, eggNog, cog, goTerms, secreted, membrane, protease, cazyme, notes, translation = line.split("\t") if gene not in go: go[gene] = set() if len(goTerms) >0: go[gene] |= set(goTerms.split(";")) if gene not in cazy: cazy[gene] = set() if len(cazyme) > 0: cazy[gene] |= set(cazyme.split(";")) if gene not in interpro: interpro[gene] = set() if len(interPro) > 0: interpro[gene] |= set(interPro.split(";")) name[gene] = tName kegg[gene] = [] for line in open(input.kegg): path, genes = line.strip("\n").split("\t") for gene in genes.split(","): kegg[gene].append(path) for line in open(input.signalp): if line[0] == "#": continue arr = line.strip("\n").split() sigP[arr[0].split("-")[0]] = arr[9] anno = {"go": go, "cazy": cazy, "interpro": interpro, "name": name, "kegg": kegg, "signalp": sigP} pickle.dump(anno, open(output.pickle, "wb")) json.dump(anno, open(output.json, "wt"), indent=2) rule mgsa: input: anno="ca_proteins_{geneset}.tsv", exp="expr/expr_{comp}.tsv" output: tab="activation/ca_active_{geneset}_{comp}.tsv" run: R(""" library(mgsa, quietly=T) set.seed(42) tab=read.table("{input.anno}", sep="\t", stringsAsFactors=F, as.is=T) setNames = tab[,1] sets = strsplit(tab[,2], ',') names(sets) = setNames expTab=read.table("{input.exp}", sep="\t", row.names=NULL) observations = expTab$row.names[!is.na(expTab$padj) & expTab$padj<0.05 & abs(expTab$log2FoldChange)>1] print(length(observations)) result=mgsa(observations, sets) outTab=cbind(rownames(setsResults(result)), setsResults(result)) colnames(outTab) = c("setName", colnames(outTab)[2:5]) write.table(outTab, "{output.tab}", row.names=F, sep="\t", quote=F) """) rule getGoSummary: input: expand("activation/ca_active_{{goSet}}_{comp}.tsv", comp=["straw-malt", "alder-straw", "alder-malt", "stat-exp", "solid-liquidExp", "solid-liquidSta"]) output: "ca_{goSet,go.*}_activation.tsv" run: reader = codecs.getreader("utf-8") go = parseGoOboDict(reader(urlopen("http://purl.obolibrary.org/obo/go.obo"))) with open(output[0], "w") as out: out.write("condition\tGO ID\tGO name\tin Population\tin Study Set\tactivation\n") for inFile in input: comp = inFile.rsplit("_", 1)[-1].split(".")[0] with open(inFile) as inStream: headerLine = next(inStream) for line in inStream: goId, inPop, inSet, activation, _ = line.strip().split("\t") if float(activation) > 0.6: out.write("%s\t%s\t%s\t%s\t%s\t%s\n" % (comp, goId, go[goId].name, inPop, inSet, activation)) rule getCazySummary: input: expand("activation/ca_active_cazy_{comp}.tsv", comp=["straw-malt", "alder-straw", "alder-malt", "stat-exp", "solid-liquidExp", "solid-liquidSta"]) output: "ca_cazy_activation.tsv" run: # famName={} # reader = codecs.getreader("utf-8") # for line in reader(urlopen("http://csbl.bmb.uga.edu/dbCAN/download/FamInfo.txt")): # fam, ccd, cls, note, activ = line.strip("\n").split("\t") # famName[fam] = activ with open(output[0], "w") as out: out.write("condition\tCAZy Fam\tactivity\tin Population\tin Study Set\tactivation\n") for inFile in input: comp = inFile.rsplit("_", 1)[-1].split(".")[0] with open(inFile) as inStream: headerLine = next(inStream) for line in inStream: fam, inPop, inSet, activation, _ = line.strip().split("\t") if float(activation) > 0.6: out.write("%s\t%s\t%s\t%s\t%s\t%s\n" % (comp, fam, "--", inPop, inSet, activation)) rule getEcNum: input: "../kegg/user_ko.tsv" output: "ca_proteins_ec.tsv" params: db="/home/heeger/data/dbs/KeggKoToEcMap.db" run: ko2ec = CachedKeggKoToEnzymeMap(params.db) with open(output[0], "w") as out: for line in open(input[0]): arr = line.strip("\n").split("\t") if len(arr) == 1: continue gene, ko = arr try: ecSet = ko2ec[ko] except KeyError: continue out.write("%s\t%s\n" % (gene, ",".join(ecSet))) rule getKeggSummary: input: expand("activation/ca_active_kegg_{comp}.tsv", comp=["straw-malt", "alder-straw", "alder-malt", "stat-exp", "solid-liquidExp", "solid-liquidSta"]) output: "ca_kegg_activation.tsv" params: db="/home/heeger/data/dbs/KeggPathwayIdToNameMap.db" run: kegg = CachedKeggPathwayIdToNameMap(params.db) with open(output[0], "w") as out: out.write("condition\tKEGG ID\tKEGG pathway name\tin Population\tin Study Set\tactivation\n") for inFile in input: comp = inFile.rsplit("_", 1)[-1].split(".")[0] with open(inFile) as inStream: headerLine = next(inStream) for line in inStream: keggId, inPop, inSet, activation, _ = line.strip().split("\t") if float(activation) > 0.6: out.write("%s\t%s\t%s\t%s\t%s\t%s\n" % (comp, keggId, kegg[keggId], inPop, inSet, activation)) rule KeggUserData: input: ko="../kegg/user_ko.tsv", exp="expr/expr_{comp}.tsv", geneset="ca_proteins_kegg.tsv", act="activation/ca_active_kegg_{comp}.tsv" output: dynamic("keggUserData/{comp}_{path}.userData.tsv") run: gId2ko={} for line in open(input.ko): arr = line.strip("\n").split("\t") if len(arr) > 1: tId, ko = arr gId2ko[tId.split("-")[0]] = ko expr={} diff={} with open(input.exp) as diffIn: header = next(diffIn) for line in diffIn: gId, mean, change, lfc, start, p, adjp = line.strip("\n").split("\t") if adjp != "NA": expr[gId] = float(change) if float(adjp)<0.05 and abs(float(change))>1: diff[gId] = True else: diff[gId] = False active = set() with open(input.act) as inStream: header = next(inStream) for line in inStream: sId, _ = line.split("\t", 1) active.add(sId) gSet={} for line in open(input.geneset): path, geneList = line.strip().split("\t") #if path in active: gSet[path] = geneList.split(",") for path in gSet: if path in ["map01110", "map00958"]: print("skipping path: %s. Its too big." % path) continue koExpr = {} koDiff = {} for gId in gSet[path]: try: tKo = gId2ko[gId] tExpr = expr[gId] except KeyError: continue try: koExpr[tKo].append(tExpr) except KeyError: koExpr[tKo] = [tExpr] try: koDiff[tKo].append(diff[gId]) except KeyError: koDiff[tKo] = [diff[gId]] if len(koExpr) > 0: lim = math.ceil(max([abs(v) for vList in koExpr.values() for v in vList])) scale = 510.0/(lim*2) colors = {} border = {} for ko in koExpr: if len(koExpr[ko]) > 1: if all([e<0 for e in koExpr[ko]]) or all([e>0 for e in koExpr[ko]]): colors[ko] = dezToColor(((sum(koExpr[ko])/len(koExpr[ko]))+lim)*scale) if any(koDiff[ko]): border[ko] = "black" else: border[ko] = "grey" else: colors[ko] = "blue" border[ko] = "white" else: colors[ko] = dezToColor((koExpr[ko][0]+lim)*scale) border[ko] = "grey" if koDiff[ko][0]: border[ko] = "black" with open("keggUserData/%s_%s.userData.tsv" % (wildcards.comp, path), "w") as out: for ko, col in colors.items(): out.write("%s\t%s,%s\n" % (ko, col, border[ko])) rule keggPlot: input: act="activation/ca_active_kegg_{comp}.tsv", exp="expr/expr_{comp}.tsv", geneset="ca_proteins_kegg.tsv", ec="ca_proteins_ec.tsv", ko="../kegg/user_ko.tsv" output: "keggPlots/{comp}.ca_active_kegg.expressionplots" log: "logs/keggPlot_{comp}.log" params: minProp = 0.6, run: # reac2ec = KeggReactionIdToEcMap(cachePath="keggReacToEc.tsv") # # gId2ec={} # for line in open(input.ec): # arr = line.strip().split("\t") # if len(arr) == 1: # continue # gId, ecNum = arr # gId2ec[gId.split("-")[0]] = ecNum # gId2ko={} for line in open(input.ko): arr = line.strip("\n").split("\t") if len(arr) > 1: tId, ko = arr gId2ko[tId.split("-")[0]] = ko prop={} with open(input.act) as actIn: header = next(actIn) for line in actIn: path, pop, stud, act, err = line.strip().split("\t") if float(act) > params.minProp: prop[path] = float(act) gSet={} allGenes={} for line in open(input.geneset): path, geneList = line.strip().split("\t") gSet[path] = geneList.split(",") for gId in gSet[path]: allGenes[gId] = None expr={} diff={} with open(input.exp) as diffIn: header = next(diffIn) for line in diffIn: gId, mean, change, lfc, start, p, adjp = line.strip("\n").split("\t") if adjp != "NA": if gId in allGenes: expr[gId] = float(change) if float(adjp)<0.05 and abs(float(change))>1: diff[gId] = True else: diff[gId] = False with open(log[0], "w") as logStream: for path in gSet: if path in ["ko01110", "ko00958"]: print("skipping path: %s. Its too big." % path) continue if path not in prop and path not in ["ko00500", "ko04146"]: #skip non-significant pathes continue koExpr = {} koDiff = {} for gId in gSet[path]: try: tKo = gId2ko[gId] except KeyError: continue try: tExpr = expr[gId] except KeyError: logStream.write("No expressions for %s\n" % gId) continue if tKo not in koExpr: koExpr[tKo] = [] koDiff[tKo] = [] koExpr[tKo].append(tExpr) koDiff[tKo].append(diff[gId]) with open("keggPlots/%s.ca_active_kegg.%s.tsv" % (wildcards.comp, path), "w") as out: for gId in gSet[path]: out.write("%s\t%s\t%s\n" % (gId, gId2ko[gId], expr.get(gId, "-"))) if len(koExpr) == 0: continue #nothing we can do for this pathway pathway = KGML_parser.read(kegg_get(path.replace("map", "ko"), "kgml")) reacExpr={} reacDiff={} for reac in pathway.orthologs: for entry in reac.name.split(" "): rko = entry.split(":")[1] if rko in koExpr: try: reacExpr[reac.id].extend(koExpr[rko]) except KeyError: reacExpr[reac.id] = koExpr[rko] reacDiff[reac.id] = [] reacDiff[reac.id].extend(koDiff[rko]) colors = {} border = {} lim = math.ceil(max([abs(v) for vList in reacExpr.values() for v in vList])) scale = 510.0/(lim*2) for rId in reacExpr: if len(reacExpr[rId]) > 1: if all([e<0 for e in reacExpr[rId]]) or all([e>0 for e in reacExpr[rId]]): colors[rId] = dezToColor(((sum(reacExpr[rId])/len(reacExpr[rId]))+lim)*scale) if any(reacDiff[rId]): border[rId] = "#000000" else: border[rId] = "#878787" else: colors[rId] = "#0000ff" border[rId] = "#ffffff" else: colors[rId] = dezToColor((reacExpr[rId][0]+lim)*scale) border[rId] = "#878787" if reacDiff[rId][0]: border[rId] = "#000000" for reac in pathway.orthologs: if reac.id in colors: reac.graphics[0].bgcolor = colors[reac.id] reac.graphics[0].fgcolor = border[reac.id] #remove compound labels for compound in pathway.compounds: for graphic in compound.graphics: # print("remove label: "+graphic.name) graphic.name = "" canvas = KGMLCanvas(pathway, import_imagemap=True) canvas.fontsize=10 outPath="keggPlots/%s.ca_active_kegg.%s.pdf" % (wildcards.comp, path) canvas.draw(outPath) open(output[0], "w") rule collectExp: input: "singleGenePlots/{group}_geneList.tsv", expand("expr/expr_{comp}.tsv", comp=["straw-malt", "alder-malt"]) output: "singleGenePlots/{group}_expression.tsv" run: gene_list = set() g2n = {} for line in open(input[0]): name, gene = line.strip().split("\t") gene_list.add(gene) g2n[gene] = name with open(output[0], "w") as out: out.write("gene\tname\tcomp\tchange\tpvalue\n") for inFile in input[1:]: comp = inFile.rsplit(".", 1)[0].rsplit("_", 1)[-1] with open(inFile) as inStream: next(inStream) #header for line in inStream: gId, mean, change, lfc, start, p, padj = line.strip("\n").split("\t") if gId in gene_list: out.write("%s\t%s\t%s\t%s\t%s\n" % (gId, g2n[gId], comp, change, padj)) rule plotExp: input: "singleGenePlots/{group}_expression.tsv" output: "singleGenePlots/{group}_expression.pdf" run: R(""" library(ggplot2) d=read.table("{input}", sep="\t", header=T) sig=rep("", length(d$pvalue)) sig[d$pvalue<0.05] = "*" sig[d$pvalue<0.01] = "**" sig[d$pvalue<0.001] = "***" d$sig = sig ggplot(d, aes(gene, change, fill=comp, label=sig)) + geom_bar(position="dodge", stat="identity", width=.6) + coord_flip() + geom_text(aes(label=sig), position=position_dodge(.6)) + ggtitle("{wildcards.group}") + scale_x_discrete(breaks=d$gene, labels=paste(d$gene, d$name, sep="\n")) #number of comparisons: c=length(levels(d$comp)) #number of rows n=dim(d)[1] ggsave("{output}", width=7, height=max(7,n/c), limitsize = F) """) rule plotExpOverview_data: input: expand("singleGenePlots/{group}_expression.tsv", group=["cazy-AA1", "peroxi", "cyp450", "cazy-AA9", "cazy-CE1", "cazy-GH5", "cazy-GH7", "cazy-GH10", "cazy-GH11", "kegg-ko00052", "kegg-ko00040", "kegg-ko00500", "kegg-ko00640", "kegg-ko04146"]) output: "singleGenePlots/expOverview.tsv" run: num = {} order = [] for inFile in input: group = inFile.split("/", 1)[1].rsplit("_", 1)[0] num[group] = {} order.append(group) for comp in ["alder-malt", "straw-malt"]: num[group][comp] = {"up": 0, "down": 0} with open(inFile) as inStream: header = next(inStream) for line in inStream: gene, name, comp, change, pvalue = line.strip("\n").split("\t") if change!="NA" and pvalue != "NA" and abs(float(change)) > 1 and float(pvalue)<0.05: if float(change) > 0: num[group][comp]["up"] += 1 else: num[group][comp]["down"] -= 1 with open(output[0], "w") as out: out.write("group\tcomp\tdirection\tvalue\n") for group in order: for comp, cDat in num[group].items(): for direc in ["up", "down"]: out.write("%s\t%s\t%s\t%i\n" % (group, comp, direc, cDat[direc])) rule plotExpOverview_plot: input: "singleGenePlots/expOverview.tsv" output: "singleGenePlots/expOverview.svg" run: R(""" library(ggplot2) d = read.table("{input}", header=T) d$group = factor(d$group, levels=unique(d$group)) ggplot(d) + geom_bar(aes(x=group, y=value, fill=comp), stat="identity", position="dodge") + geom_hline(yintercept = 0) + coord_flip() + scale_fill_manual(values=c("#377a3e", "#c4b211")) ggsave("{output}") """) rule geneOverlap: input: stma="expr/expr_straw-malt.tsv", alma="expr/expr_alder-malt.tsv" output: "overlap/genes.tsv" run: gNr = 0 stma = set() with open(input.stma) as inStream: next(inStream) #header for line in inStream: gId, mean, change, lfc, start, p, padj = line.strip("\n").split("\t") if padj != "NA" and float(padj)<0.05 and abs(float(change))>1: stma.add(gId) gNr += 1 alma = set() with open(input.alma) as inStream: next(inStream) #header for line in inStream: gId, mean, change, lfc, start, p, padj = line.strip("\n").split("\t") if padj != "NA" and float(padj)<0.05 and abs(float(change))>1: alma.add(gId) AandB = len(stma & alma) AbutNotB = len(stma - alma) BbutNotA = len(alma - stma) norAnorB = gNr - len(alma | stma) R(""" d = c(%i, %i, %i, %i) cTab = matrix(d, nrow = 2) fRes=fisher.test(cTab, alternative = "greater") write.table(data.frame(A_and_B=d[1], A_but_not_B=d[2], B_but_not_A=d[3], not_A_not_B=d[4], pvalue=fRes$p.value), "{output}", row.names=F, sep="\t") """ % (AandB, AbutNotB, BbutNotA, norAnorB)) rule setOverlap: input: sm_go="activation/ca_active_go_straw-malt.tsv", sm_kegg="activation/ca_active_kegg_straw-malt.tsv", am_go="activation/ca_active_go_alder-malt.tsv", am_kegg="activation/ca_active_kegg_alder-malt.tsv" output: "overlap/geneSets.tsv" params: cutoff=0.6 run: totalGO = 0 totalKEGG = 0 inFiles = [input.sm_go, input.sm_kegg, input.am_go, input.am_kegg] sets = [set(), set(), set(), set()] for i, inFile in enumerate(inFiles): with open(inFile) as inStream: header = next(inStream) for line in inStream: if i==0: totalGO += 1 elif i==1: totalKEGG += 1 name, inP, inS, prop, se = line.split("\t") if float(prop) > params.cutoff: sets[i].add(name) sm_go, sm_kegg, am_go, am_kegg = sets go = (len(sm_go & am_go), #A and B len(sm_go - am_go), #A but not B len(am_go - sm_go), #B but not A totalGO - len(am_go| sm_go)#nor A nor B ) kegg = (len(sm_kegg & am_kegg), #A and B len(sm_kegg - am_kegg), #A but not B len(am_kegg - sm_kegg), #B but not A totalKEGG - len(am_kegg| sm_kegg)#nor A nor B ) arg = go+kegg R(""" go = c(%i, %i, %i, %i) kegg = c(%i, %i, %i, %i) gTab = matrix(go, nrow = 2) gRes=fisher.test(gTab, alternative = "greater") outTab = data.frame(set="GO", A_and_B=go[1], A_but_not_B=go[2], B_but_not_A=go[3], not_A_not_B=go[4], pvalue=gRes$p.value) kTab = matrix(kegg, nrow = 2) kRes=fisher.test(kTab, alternative = "greater") outTab = rbind(outTab, data.frame(set="KEGG", A_and_B=kegg[1], A_but_not_B=kegg[2], B_but_not_A=kegg[3], not_A_not_B=kegg[4], pvalue=kRes$p.value)) write.table(outTab, "{output}", row.names=F, sep="\t") """ % arg) rule diffAnno: input: exp="expr/expr_{comp}.tsv", anno="anno.pic" output: "expr/diffAnno_{comp}.tsv" params: cdb = "/home/heeger/data/dbs/cazyNames.db", kdb="/home/heeger/data/dbs/KeggPathwayIdToNameMap.db", gUrl="http://purl.obolibrary.org/obo/go.obo" run: cName = CazyNameDict(params.cdb) kName = CachedKeggPathwayIdToNameMap(params.kdb) reader = codecs.getreader("utf-8") gName = parseGoOboDict(reader(urlopen(params.gUrl))) anno = pickle.load(open(input.anno, "rb")) exp = [line.strip("\n").split("\t") for line in open(input.exp).readlines()[1:]] exp.sort(key=lambda x: saveFloat(x[6])) with open(output[0], "w") as out: for line in exp[:5000]: gene, mean, change, lfc, stat, pvalue, padj = line if saveFloat(padj)>0.05: break cIds = anno["cazy"][gene] cNames = ["%s:%s" % (cId, cName[cId]) for cId in cIds] kIds = anno["kegg"][gene] kNames = ["%s:%s" % (kId, kName[kId]) for kId in kIds] gIds = anno["go"][gene] gNames = ["%s:%s" % (gId, gName[gId].name) for gId in gIds] tAnno = list(zip_longest(gNames, kNames, cNames, fillvalue="")) if len(tAnno) == 0: out.write("%s\t%s\t%s\t\t\t\n" % (gene, change, padj)) else: out.write("%s\t%s\t%s\t%s\t%s\t%s\n" % (gene, change, padj, tAnno[0][0], tAnno[0][1], tAnno[0][2])) if len(tAnno) > 1: for g, k, c in tAnno[1:]: out.write("\t\t\t%s\t%s\t%s\n" % (g, k, c)) rule transMem: input: stma="expr/diff_straw-malt.tsv", alma="expr/diff_alder-malt.tsv", alst="expr/diff_alder-straw.tsv", anno="anno.pic" output: gl="singleGenePlots/transMem_geneList.tsv", stma="transMem/straw-malt.txt", alst="transMem/alder-straw.txt", alma="transMem/alder-malt.txt" run: anno=pickle.load(open(input.anno, "rb")) stma = [line.strip("\n").split("\t")[0] for line in open(input.stma).readlines()] alma = [line.strip("\n").split("\t")[0] for line in open(input.alma).readlines()] alst = [line.strip("\n").split("\t")[0] for line in open(input.alst).readlines()] tm_stma = set([g for g in stma if "GO:0055085" in anno["go"][g]]) tm_alma = set([g for g in alma if "GO:0055085" in anno["go"][g]]) tm_alst = set([g for g in alst if "GO:0055085" in anno["go"][g]]) with open(output.gl, "w") as out: for g in tm_stma.union(tm_alma).union(tm_alst): out.write("transMem\t%s\n" % g) open(output.stma, "w").write("\n".join(tm_stma)) open(output.alma, "w").write("\n".join(tm_alma)) open(output.alst, "w").write("\n".join(tm_alst)) rule gshTrans: input: anno="anno.pic", kegg="../kegg/user_ko.tsv" output: gl="singleGenePlots/gshTrans_geneList.tsv" run: iprs = ["IPR016639", "IPR014440", "IPR005442", "IPR003080", "IPR003081", "IPR003082", "IPR034339"] anno=pickle.load(open(input.anno, "rb")) gt = {} for g in anno["interpro"]: for a in anno["interpro"][g]: if a in iprs: try: gt[g].append(a) except KeyError: gt[g] = [a] for line in open(input.kegg): arr = line.strip("\n").split("\t") if len(arr) > 1 and arr[1] == "K00799": try: gt[arr[0].split("-")[0]].append(arr[1]) except KeyError: gt[arr[0].split("-")[0]] = [arr[1]] with open(output.gl, "w") as out: for g, annos in gt.items(): out.write("%s\t%s\n" % (",".join(annos + [anno["signalp"][g]]), g)) rule tyr: input: anno="anno.pic", kegg="../kegg/user_ko.tsv" output: gl="singleGenePlots/tyr_geneList.tsv" run: iprs = ["IPR002227", "IPR005203", "IPR005204", "IPR000896"] anno=pickle.load(open(input.anno, "rb")) gt = {} for g in anno["interpro"]: for a in anno["interpro"][g]: if a in iprs: try: gt[g].append(a) except KeyError: gt[g] = [a] for line in open(input.kegg): arr = line.strip("\n").split("\t") if len(arr) > 1 and arr[1] == "K00505": try: gt[arr[0].split("-")[0]].append(arr[1]) except KeyError: gt[arr[0].split("-")[0]] = [arr[1]] with open(output.gl, "w") as out: for g, annos in gt.items(): out.write("%s\t%s\n" % (",".join(annos + [anno["signalp"][g]]), g)) rule cyp450: input: anno="anno.pic" output: cl="singleGenePlots/cyp450_geneList.tsv" run: iprs = ["IPR001128"] anno=pickle.load(open(input.anno, "rb")) cl = {} for g in anno["interpro"]: for a in anno["interpro"][g]: if a in iprs: try: cl[g].append(a) except KeyError: cl[g] = [a] with open(output.cl, "w") as out: for g, iprs in cl.items(): out.write("%s\t%s\n" % (";".join(iprs + [anno["signalp"][g]]), g)) rule peroxi: input: anno="anno.pic", fullGO="ca_proteins_goFull.tsv", kegg="../kegg/user_ko.tsv" output: gl="singleGenePlots/peroxi_intGeneList.tsv" run: kos= {"K20205": "manganese peroxidase", "K15733": "dye decolorizing peroxidase", "K00430": "peroxidase" } gos = {"GO:0004601": "peroxidase activity" } iprs = {"IPR001621": "Fungal ligninase", "IPR010255": "Haem peroxidase", "IPR019793": "Peroxidases heam-ligand binding site" } fGo = {} for line in open(input.fullGO): go, gStr = line.strip("\n").split("\t") if go in gos: for g in gStr.split(","): try: fGo[g].append(go) except KeyError: fGo[g] = [go] kegg = {} for line in open(input.kegg): arr = line.strip("\n").split("\t") if len(arr) > 1 and arr[1] in kos: try: kegg[arr[0].split("-")[0]].append(arr[1]) except KeyError: kegg[arr[0].split("-")[0]] = [arr[1]] ipr = {} anno=pickle.load(open(input.anno, "rb")) with open(output.gl, "w") as out: for g in anno["interpro"]: tAnno = [] for a in anno["interpro"][g]: if a in iprs: tAnno.append("%s|%s" % (a, iprs[a])) if g in fGo: for a in fGo[g]: tAnno.append("%s|%s" % (a, gos[a])) if g in kegg: for a in kegg[g]: tAnno.append("%s|%s" % (a, kos[a])) if tAnno: out.write("%s\t%s\n" % (";".join(tAnno + [anno["signalp"][g]]), g)) rule extractPeroxiSeq: input: gl="singleGenePlots/peroxi_intGeneList.tsv", prot="../funannotate/caqua/predict_results/Clavariopsis_aquatica_WDA-00-1.proteins.fa" output: fasta="singleGenePlots/peroxi.fasta" run: gl = set() for line in open(input.gl): g = line.strip("\n").split("\t")[1] gl.add(g) with open(output.fasta, "w") as out: for rec in SeqIO.parse(input.prot, "fasta"): if rec.id.split("-")[0] in gl: out.write(rec.format("fasta")) rule extractCazySeq: input: anno="anno.pic", prot="../funannotate/caqua/predict_results/Clavariopsis_aquatica_WDA-00-1.proteins.fa" output: fasta="singleGenePlots/cazy-{fam}.fasta" run: anno=pickle.load(open(input.anno, "rb")) aa = {} for g in anno["cazy"]: for a in anno["cazy"][g]: if a.split("_")[0] == wildcards.fam: try: aa[g].append(a) except KeyError: aa[g] = [a] with open(output.fasta, "w") as out: for rec in SeqIO.parse(input.prot, "fasta"): if rec.id.split("-")[0] in aa: rec.id = rec.id.split("-")[0] rec.description = "" out.write(rec.format("fasta")) rule cazyFam: input: anno="anno.pic" output: aa="singleGenePlots/cazy-{fam}_geneList.tsv" run: anno=pickle.load(open(input.anno, "rb")) aa = {} for g in anno["cazy"]: for a in anno["cazy"][g]: if a.split("_")[0] == wildcards.fam: try: aa[g].append(a) except KeyError: aa[g] = [a] with open(output.aa, "w") as out: for g, annos in aa.items(): if len(annos) < 5: cString = ",".join(annos + [anno["signalp"][g]]) else: cString = ",".join(annos[:5] + ["...", anno["signalp"][g]]) out.write("%s\t%s\n" % (cString, g)) rule keggPath: input: anno="anno.pic", kegg="../kegg/user_ko.tsv" output: aa="singleGenePlots/kegg-{path}_geneList.tsv" run: anno=pickle.load(open(input.anno, "rb")) ko = {} for line in open(input.kegg): arr = line.strip("\n").split("\t") if len(arr) > 1: ko[arr[0].split("-")[0]] = arr[1] aa = {} for g in anno["kegg"]: for a in anno["kegg"][g]: if a == wildcards.path: try: aa[g].append(a) except KeyError: aa[g] = [a] with open(output.aa, "w") as out: for g, annos in aa.items(): out.write("%s,%s\t%s\n" % (ko[g], anno["signalp"][g], g)) ###### HELPER FUNCTIONS ########### def saveFloat(string): try: return float(string) except ValueError: if string == "NA": return 1 else: raise def dezToColor(value): if 0 < value < 255: return "#FF%02x%02x" % (int(value), int(value)) if value <= 510: return "#%02xFF%02x" % (510-int(value), 510-int(value)) raise ValueError("Can not convert to color. Value out of range: %i" % value) class CazyHTMLParser(HTMLParser): target = "before" result = [] def handle_starttag(self, tag, attrs): if tag=="td": for name, value in attrs: if name == "class" and value=="tdsum" and self.target == "before": self.target = "in" def handle_endtag(self, tag): if tag=="td" and self.target == "in": self.target = "after" def handle_data(self, data): if self.target == "in": self.result.append(data.strip()) class CazyNameDict(object): def __init__(self, dbpath): self.cache = PersistantDict(dbpath=dbpath) def __getitem__(self, key): try: return self.cache[key] except KeyError: value = self.htmlReq(key) self.cache[key] = value return self.cache[key] def htmlReq(self, key): reader = codecs.getreader("utf-8") a = reader(urlopen("http://www.cazy.org/%s.html" % key)) parser=CazyHTMLParser() parser.feed(a.read()) return "".join(parser.result) ########### alternative go from goViz import main as goViz from GoTools import createGoTree rule explicitGoParents: input: "ca_proteins_go.tsv" output: "ca_proteins_goFull.tsv" run: reader = codecs.getreader("utf-8") goDict=parseGoOboDict(reader(urlopen("http://purl.obolibrary.org/obo/go.obo"))) goTree=createGoTree(goDict) go2gene = {} for line in open(input[0]): goTerm, geneList = line.strip().split("\t") genes = geneList.split(",") for tGo in goTree[goTerm].ancestors(): for g in genes: try: go2gene[tGo].add(g) except KeyError: go2gene[tGo] = set([g]) with open(output[0], "w") as out: for gId, geneList in go2gene.items(): out.write("%s\t%s\n" % (gId, ",".join(geneList))) rule getGoFrame: input: "ca_proteins_goFull.tsv" output: "ca_proteins_goFrame.tsv" run: with open(output[0], "w") as out: for line in open(input[0]): goId, geneStr = line.strip().split("\t") for gene in geneStr.split(","): out.write("%s\tIEA\t%s\n" % (goId, gene)) rule goEnrichment: input: exprFile="expr/expr_{comp}.tsv", genesFile="../funannotate/caqua/predict_results/Clavariopsis_aquatica_WDA-00-1.proteins.fa", goFile="ca_proteins_goFrame.tsv" output: "gsea/enrich_{comp}.tsv", rscript="gsea/enrich_{comp}.R" run: genes = [rec.id.split("-")[0] for rec in SeqIO.parse(input.genesFile, "fasta")] diffGenes = set([]) with open(input.exprFile) as inFile: next(inFile) #skip header for line in inFile: gene, mean, change, ltfc, stat, pval, padj = line.strip("\n").split("\t") if padj != "NA" and float(padj)<0.05 and abs(float(change))>1: diffGenes.add(gene) rcmd = 'library("GSEABase")\n' \ 'library("GOstats")\n' \ 'library("GSEABase")\n' \ 'goFrameData = read.table("%s", sep="\\t", heade=F)\n' \ 'colnames(goFrameData) = c("frame.go_id", "frame.Evidence", "frame.gene_id")\n' \ 'goFrame = GOFrame(goFrameData, organism="Clavariopsis aquatica")\n' \ 'goAllFrame=GOAllFrame(goFrame)\n' % input.goFile rcmd += 'gsc = GeneSetCollection(goAllFrame, setType = GOCollection())\n' rcmd += 'universe=c(%s)\n' % (",".join(['"%s"' % g for g in genes])) rcmd += 'diffGenes=c(%s)\n' % (",".join(['"%s"' % g for g in diffGenes])) rcmd += 'params = GSEAGOHyperGParams(name="My Custom GSEA based annot Params",\n' \ ' geneSetCollection=gsc,\n' \ ' geneIds = diffGenes,\n' \ ' universeGeneIds = universe,\n' \ ' ontology = "MF",\n' \ ' pvalueCutoff = 0.05,\n' \ ' conditional = T,\n' \ ' testDirection = "over")\n' \ 'over = hyperGTest(params)\n' \ 'write.table(summary(over), "%s", sep="\\t", quote=F, row.names=F)\n' % output[0] with open(output.rscript, "w") as out: out.write(rcmd) shell("Rscript %s" % output.rscript) rule plotGoEnrichment: input: "gsea/enrich_{comp}.tsv" output: "gsea/enrich_{comp}.goGraph.svg" params: oboFile="/home/heeger/data/go/go.obo", sigLvl="0.05" run: with open(input[0]) as inStream, open(output[0], "w") as outStream: goViz(inStream, outStream, None, float(params.sigLvl))
8af571feac55b58f7051f3d448b248ac6379fbc3
[ "Python" ]
1
Python
f-heeger/caquatica_expression
6adc75aecba605413000002f25318da331928322
a1fe0cfc2a93af2f563e713fbff0f2b311383af1
refs/heads/master
<repo_name>diogoberton/Peppery_VW_plataforma_premios<file_sep>/Gruntfile.js module.exports = function( grunt ) { // Tasks que o Grunt deve executar grunt.initConfig({ uglify : { options : { mangle : false }, my_target : { files : { 'assets/js/master.js' : [ 'source/js/master.js' ] } } }, // uglify compass: { dist: { options: { sassDir: 'source/css', cssDir: 'assets/css', outputStyle: 'compressed' }, files: [{ expand: true, cwd: 'source/css', src: '**/*.scss', dest: 'assets/css', ext: '.css' }] } }, // compass htmlmin: { dist: { options: { removeComments: true, collapseWhitespace: true }, files: [{ expand: true, cwd: 'source', src: '**/*.html', dest: '' }] } }, // htmlmin watch : { dist : { files : [ 'source/js/**/*', 'source/css/**/*', 'source/**/*' ], tasks : [ 'uglify', 'compass', 'htmlmin' ], options: { livereload: true, } } }, // watch browserSync: { files: { // Aplicando o recurso de Live Reload nos seguintes arquivos src : [ 'assets/js/*.js', 'assets/css/*.css', '' ], }, options: { // Atribuindo um diretório base server: { baseDir: '' }, // Integrando com a tarefa "watch" watchTask: true, // Sincronizando os eventos entre os dispositívos ghostMode: { clicks: true, forms: true, scroll: true }, // Show me additional info about the process logLevel: "debug" } } }); // Plugins do Grunt grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-compass'); grunt.loadNpmTasks('grunt-contrib-htmlmin'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-browser-sync'); // Tarefas que serão executadas grunt.registerTask( 'default', [ 'browserSync', 'watch' ] ); };<file_sep>/source/js/master.js window.onload = function() { var isMobile = { Android: function() { return navigator.userAgent.match(/Android/i); }, BlackBerry: function() { return navigator.userAgent.match(/BlackBerry/i); }, iOS: function() { return navigator.userAgent.match(/iPhone|iPad|iPod/i); }, Opera: function() { return navigator.userAgent.match(/Opera Mini/i); }, Windows: function() { return navigator.userAgent.match(/IEMobile/i); }, any: function() { return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows()); } }; if ( isMobile.any() ) { $('body').addClass('mobile'); } else { $('body').addClass('desktop'); } // Swiper Carousel var swiperCarousel = new Swiper('.swiper-carousel', { pagination: '.swiper-pagination', paginationClickable: true, nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', touchRatio: 0.2, }); navigation(); }; function navigation() { $('#header .menu').on('click', function(){ if( $('#nav').hasClass('show') ) { $('#nav').removeClass('show'); } else{ $('#nav').addClass('show'); } }); document.querySelector("#nav-toggle").addEventListener("click", function() { this.classList.toggle("active"); }); };
aaca1f04a886cbc2548e64f7a3ab466f86336dbd
[ "JavaScript" ]
2
JavaScript
diogoberton/Peppery_VW_plataforma_premios
53915ff35742c3b0d0aa888c9bbf13098aaa8fd4
884384cc1dadd482444fdaa996c074e56453943c
refs/heads/master
<repo_name>ballavilley/register_app<file_sep>/app/models/teacher.rb class Teacher < ActiveRecord::Base attr_accessible :teacher_firstname, :teacher_surname has_many :sessions end <file_sep>/app/models/session.rb class Session < ActiveRecord::Base attr_accessible :session_level, :session_subject, :teacher_id belongs_to :teacher end <file_sep>/app/models/student.rb class Student < ActiveRecord::Base attr_accessible :date_of_birth, :firstname, :surname end
dc8cb7c0bcaf0a59ce28d01ac52b330763a898f7
[ "Ruby" ]
3
Ruby
ballavilley/register_app
d1d8649f1423654daaac942d36a09439267c80b4
ad261c7c357bdeb3e1cf0d37e6cba3c227129194
refs/heads/master
<repo_name>Ikera/ruby_coding_challenge<file_sep>/spec/question_spec.rb require 'spec_helper' require_relative '../question' describe Question do subject { Question.solution([2, 1, 3, 4]) } it '. solution' do expect(subject).to eq([12, 24, 8, 6]) end end <file_sep>/question.rb # Question -- Write a function that takes an array # as input and outputs an array of the same size containing # the multiplication of all elements excepts the one at current index. # Example -- [2, 1, 3, 4] #=> [12, 24, 8, 6] class Question class << self def solution(arr) arr.map.with_index { |_, idx| arr.reject.with_index { |el, i| i == idx }.inject(:*) } end end end
0cf578fd47a66bf88bfe77d034eed1ce57e6bb98
[ "Ruby" ]
2
Ruby
Ikera/ruby_coding_challenge
c28c9b12b1c025b7d13ffecfa66b1cbf6a103fa1
257ea11360b2e4a28fe04ed800c5f3be8130cf08
refs/heads/master
<file_sep>/** * Helpers */ var ingredients_api_url = 'https://aarse.cf/'; // Bypass CORS var cors_api_url = 'https://cors-anywhere.herokuapp.com/'; function doCORSRequest(options, printResult) { var x = new XMLHttpRequest(); x.open(options.method, cors_api_url + options.url); x.onload = x.onerror = function() { printResult(x.responseText); }; if (/^POST/i.test(options.method)) { x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); } x.send(options.data); } // Strip HTML function strip(html){ var doc = new DOMParser().parseFromString(html, 'text/html'); return doc.body.textContent || ""; } // Check if value is a number function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } // Fraction to number function fractionToNumber(x) { var y = x.split(' '); if(y.length > 1){ var z = y[1].split('/'); return(+y[0] + (z[0] / z[1])); } else{ var z = y[0].split('/'); if(z.length > 1){ return(z[0] / z[1]); } else{ return(z[0]); } } } // Get shopping list from API server function requestShoppingList(ingredients) { var ingredient_names = ingredients.map(function(ingredient){ return ingredient.Ingredient; }); var ingredient_names_text = ingredient_names.join("\n"); return $.post(ingredients_api_url + '?action=shopping_list', { ingredients: ingredient_names_text }); } /** * App ViewModel */ var MealPlanner = function() { var self = this; self.days = ko.observableArray(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']); self.meals = ko.observableArray(['Breakfast','Lunch','Dinner']); /** * Data Model */ //@todo: Each day+meal combination is its own observableArray - a computed would be better self.updateShoppingList = ko.observable(); // Nested observables are hard to track... self.recipes = {}; self.setup = function(meal_plan) { self.days().forEach(function(day){ self.recipes[day] = {}; self.meals().forEach(function(meal){ self.recipes[day][meal] = ko.observableArray(); }); }); } // Drag & Drop self.drop = function (data, model) { self.updateShoppingList(Math.random()); self.recipes[model.day][model.meal].push(data) } /** * Search */ self.searchText = ko.observable().extend({ throttle: 500 }); self.searchResults = ko.observableArray(); self.searching = ko.observable(false); self.showResults = ko.observable(false); self.search = function( text ) { self.searching(true); self.showResults(false); doCORSRequest({ method: 'GET', url: 'https://toh.test.rda.net/wp-json/wp/v2/recipe/?search=' + text // www is cached by varnish... }, function printResult(result) { recipes = JSON.parse(result); self.searchResults(recipes); self.searching(false); self.showResults(recipes.length>0) }); } self.searchText.subscribe(self.search); /** * Shopping List */ self.allIngredients = ko.computed(function(){ var that = this; this.updateShoppingList(); var all_ingredients = []; Object.keys(that.recipes).forEach(function (day) { Object.keys(that.recipes[day]).forEach(function (meal) { recipes_for_day_and_meal = that.recipes[day][meal](); recipes_for_day_and_meal.forEach(function(recipe){ recipe.rms_legacy_data.Ingredients.forEach(function(ingredient){ all_ingredients.push(ingredient); }); }); }); }); return all_ingredients; }, self); self.shoppingListLoading = ko.observable(false); self.shoppingList = ko.observableArray(); self.shoppingListEmpty = ko.computed(function(){ return this.shoppingList().length < 1; }, self); self.allIngredients.subscribe(function(ingredients){ self.shoppingListLoading(true); requestShoppingList(ingredients).then(function(response){ if (Array.isArray(response)) { // Small cleanup. @todo: move to API shopping_list = response.map(function(ingredient){ if ( ingredient.amount == 'NAN/NAN' ) return; return ingredient; }).filter(Boolean).sort(function(a,b) { if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; }) self.shoppingList(shopping_list); } else { self.shoppingList([]); } self.shoppingListLoading(false); }); }); /* self.shoppingList = ko.computed(function(){ self.updateShoppingList(); var all_ingredients = this.allIngredients(); var ingredients = {}; parseIngredients(all_ingredients); all_ingredients.forEach(function(ingredient){ // Some fractions are represented as "1-1/2" meaning 1 AND 1/2. Parser recognizes "1 1/2" ingredient_text = ingredient.Ingredient.replace(/([0-9]+)-([0-9]+\/[0-9]+)/gm, '$1 $2') // Parse ingredient info ingredient_info = IngredientsParser.parse(ingredient_text); ingredient_name = strip(ingredient_info.ingredient) // Some ingredients don't have units (e.g. "3 eggs") unit = ''; if ( ingredient_info && ingredient_info.unit) unit = ingredient_info.unit; // Some don't have amounts (e.g. "blueberries") amount = ''; if (ingredient_info && ingredient_info.amount) amount = ingredient_info.amount; // Some "Ingredients" in the database are actually titles... e.g. "<b>For the topping</b>" if ( unit || amount ) { if ( ! (ingredient_name + unit in ingredients) ) { ingredients[ingredient_name + unit] = ingredient_info; ingredients[ingredient_name + unit].ingredient = ingredient_name; ingredients[ingredient_name + unit].amount = 0; ingredients[ingredient_name + unit].unit = unit; } if ( isNumeric(amount) ) { ingredients[ingredient_name + unit].amount += parseFloat(amount); } else { // god help us // or maybe convert fractions to floats and then back to fractions ingredients[ingredient_name + unit].amount += fractionToNumber(amount); } } }); // @todo: convert back 0.3333333333 to 1/3 :) return Object.values(ingredients); }, self);*/ // UI self.toggleShoppingList = function() { document.getElementById('shopping-list').classList.toggle('collapsed'); } // Startup self.setup(); } ko.applyBindings(new MealPlanner());
15369b33486141fd2daa565f1e76ef22868f7a5d
[ "JavaScript" ]
1
JavaScript
aarse/mealmate
d442f7ceaf203ce6007b13f68569e0868c83bf80
25ce9e3c6698f012fb1cb0ee5a65ee3c0e3d2010
refs/heads/master
<file_sep><?php session_start(); if(isset($_POST['update'])) { include_once 'dbh.php'; $id = $_SESSION['edit']; $first = mysqli_real_escape_string($conn,$_POST['first']); $last = mysqli_real_escape_string($conn,$_POST['last']); $username = mysqli_real_escape_string($conn,$_POST['username']); $email = mysqli_real_escape_string($conn,$_POST['email']); $sql="UPDATE users SET user_first='$first' , user_last='$last' , user_uid='$username' , user_email='$email' WHERE user_id = '$id';"; mysqli_query($conn,$sql); $_SESSION['msg']="Information Updated "; header("Location: ../admin.php"); exit(); }<file_sep><?php $dbSevername = "localhost"; $dbUsername = "root"; $dbPassword = ""; $dbName = "loginsysteme"; $conn = mysqli_connect($dbSevername,$dbUsername,$dbPassword,$dbName); $sql = "SELECT * FROM users WHERE user_uid=@Rgh"; $result = mysqli_query($conn,$sql); $resultcheck = mysqli_num_rows($result); echo $resultcheck;<file_sep><?php include 'header.php'; if(isset($_SESSION['u_id'])) { $rgh='@Rgh'; $zah='@Zah'; $mah='@Mah'; echo ' <div id="navbar-collapse" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="home.php">Home</a></li> <li class="active"><a href="courses.php">Courses</a></li> <li><a href="teachers.php">Who are we ?</a></li>'; if($_SESSION['u_uid']==$rgh || $_SESSION['u_uid']==$zah || $_SESSION['u_uid']==$mah){ echo '<li><a href="admin.php">'.$_SESSION['u_first'].'</a></li>'; }else{ echo '<li><a href="user.php">'.$_SESSION['u_first'].'</a></li>'; } echo '<li><form action="includes/logout.inc.php" method="POST"> <div class="just "> <br> <input type="submit" class="btn btn-primary" id="submit" name="submit" value="Logout"> </div> </form></li> </ul> </div> </div> </nav> '; }else{ echo ' <div id="navbar-collapse" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="home.php" >Home</a></li> <li class="active"><a href="courses.php">Courses</a></li> <li><a href="teachers.php">Who are we ?</a></li> <li><a href="contact.php">Login</a></li> </ul> </div> </div> </nav> '; } ?> <section class="probootstrap-section probootstrap-section-colored probootstrap-bg probootstrap-custom-heading probootstrap-tab-section"> <div class="container"> <div class="row"> <div class="col-md-12 text-center section-heading probootstrap-animate"> <h2 class="mb0">Astronomy</h2> </div> </div> </div> <div class="probootstrap-tab-style-1"> <ul class="nav nav-tabs probootstrap-center probootstrap-tabs no-border"> <li class="active" ><a data-toggle="tab" href="#star">stellar astronomy</a></li> <li><a data-toggle="tab" href="#gala">Galactic astronomy</a></li> <li><a data-toggle="tab" href="#planet">Planetary science</a></li> <li><a data-toggle="tab" href="#cosmo">Cosmology</a></li> </ul> </div> </section> <section class="probootstrap-section probootstrap-section"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="tab-content"> <!--HADI 1--> <div id="star" class="tab-pane fade in active"> <div class="row"> <div class="col-md-12"> <?php if(isset($_SESSION['cname'])) { $sql="SELECT * FROM cours"; $result=mysqli_query($conn,$sql); foreach (mysqli_fetch_assoc($result) as $value) { if($_SESSION['category']=="Stellar astronomy") { echo ' <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img src="'.$value['c_img'].'" alt="Free Bootstrap Template by uicookies.com"> </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>'.$value['c_name'].'</h3> <p>'.$value['C_desc'].'</p> <p><a href='; if(isset($_SESSION['u_id'])){echo $value['c_vid'];}else{echo "img/gal_img_full_7.jpg";} echo ' class="btn btn-primary popup-vimeo">Watch It</a></p> </div> </div> '; } } } ?> </div> </div> </div> <!--HADI 2--> <div id="gala" class="tab-pane fade"> <div class="row"> <div class="col-md-12"> <?php if(isset($_SESSION['cname'])) { $sql="SELECT * FROM cours"; $result=mysqli_query($conn,$sql); foreach (mysqli_fetch_assoc($result) as $value) { if($_SESSION['category']=="Galactic astronomy") { echo ' <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img src="'.$value['c_img'].'" alt="Free Bootstrap Template by uicookies.com"> </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>'.$value['c_name'].'</h3> <p>'.$value['C_desc'].'</p> <p><a href='; if(isset($_SESSION['u_id'])){echo $value['c_vid'];}else{echo "img/gal_img_full_7.jpg";} echo ' class="btn btn-primary popup-vimeo">Watch It</a></p> </div> </div> '; } } } ?> </div> </div> </div> <!--HADI 3--> <div id="planet" class="tab-pane fade"> <div class="row"> <div class="col-md-12"> <?php if(isset($_SESSION['cname'])) { $sql="SELECT * FROM cours"; $result=mysqli_query($conn,$sql); foreach (mysqli_fetch_assoc($result) as $value) { if($_SESSION['category']=="Planetary science") { echo ' <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img src="'.$value['c_img'].'" alt="Free Bootstrap Template by uicookies.com"> </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>'.$value['c_name'].'</h3> <p>'.$value['C_desc'].'</p> <p><a href='; if(isset($_SESSION['u_id'])){echo $value['c_vid'];}else{echo "img/gal_img_full_7.jpg";} echo ' class="btn btn-primary popup-vimeo">Watch It</a></p> </div> </div> '; } } } ?> </div> </div> </div> </div> <!--HADI 4--> <div id="cosmo" class="tab-pane fade"> <div class="row"> <div class="col-md-12"> <?php if(isset($_SESSION['cname'])) { $sql="SELECT * FROM cours"; $result=mysqli_query($conn,$sql); foreach (mysqli_fetch_assoc($result) as $value) { if($_SESSION['category']=="Cosmology") { echo ' <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img src="'.$value['c_img'].'" alt="Free Bootstrap Template by uicookies.com"> </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>'.$value['c_name'].'</h3> <p>'.$value['C_desc'].'</p> <p><a href='; if(isset($_SESSION['u_id'])){echo $value['c_vid'];}else{echo "img/gal_img_full_7.jpg";} echo ' class="btn btn-primary popup-vimeo">Watch It</a></p> </div> </div> '; } } } ?> </div> </div> </div> </div> </section> <footer class="probootstrap-footer probootstrap-bg"> <div class="container"> <div class="row"> <div class="col-md-4"> <div class="probootstrap-footer-widget"> <h3>About Us</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Porro provident suscipit natus a cupiditate ab minus illum quaerat maxime inventore Ea consequatur consectetur hic provident dolor ab aliquam eveniet alias</p> <h3>Social</h3> <ul class="probootstrap-footer-social"> <li><a href="#"><i class="icon-twitter"></i></a></li> <li><a href="#"><i class="icon-facebook"></i></a></li> <li><a href="#"><i class="icon-github"></i></a></li> <li><a href="#"><i class="icon-dribbble"></i></a></li> <li><a href="#"><i class="icon-linkedin"></i></a></li> <li><a href="#"><i class="icon-youtube"></i></a></li> </ul> </div> </div> <div class="col-md-3 col-md-push-1"> <div class="probootstrap-footer-widget"> <h3>Links</h3> <ul> <li><a href="#">Home</a></li> <li><a href="#">Courses</a></li> <li><a href="#">Teachers</a></li> <li><a href="#">Contact</a></li> </ul> </div> </div> <div class="col-md-4"> <div class="probootstrap-footer-widget"> <h3>Contact Info</h3> <ul class="probootstrap-contact-info"> <li><i class="icon-location2"></i> <span>National Schools of Applied Sciences Of Al Hoceima </span></li> <li><i class="icon-mail"></i><span><EMAIL></span></li> <li><i class="icon-phone2"></i><span>+212-658206268</span></li> </ul> </div> </div> </div> <!-- END row --> </div> <div class="probootstrap-copyright"> <div class="container"> <div class="row"> <div class="col-md-8 text-left"> <p>L'Cours &copy; 2017</p> </div> <div class="col-md-4 probootstrap-back-to-top"> <p><a href="#" class="js-backtotop">Back to top <i class="icon-arrow-long-up"></i></a></p> </div> </div> </div> </div> </footer> </div> <!-- END wrapper --> <script src="js/scripts.min.js"></script> <script src="js/main.min.js"></script> <script src="js/custom.js"></script> </body> </html><file_sep>-- phpMyAdmin SQL Dump -- version 4.8.1 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Jun 30, 2018 at 01:17 AM -- Server version: 10.1.33-MariaDB -- PHP Version: 7.2.6 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `loginsysteme` -- -- -------------------------------------------------------- -- -- Table structure for table `categories` -- CREATE TABLE `categories` ( `id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `cours` -- CREATE TABLE `cours` ( `c_id` int(20) UNSIGNED NOT NULL, `c_categorie` varchar(30) NOT NULL, `c_name` varchar(30) NOT NULL, `c_desc` varchar(250) NOT NULL, `c_img` varchar(100) NOT NULL, `c_vid` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `user_id` int(20) UNSIGNED NOT NULL, `user_first` varchar(30) DEFAULT NULL, `user_last` varchar(30) DEFAULT NULL, `user_email` varchar(30) DEFAULT NULL, `user_uid` varchar(30) DEFAULT NULL, `user_pwd` varchar(100) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `users` -- INSERT INTO `users` (`user_id`, `user_first`, `user_last`, `user_email`, `user_uid`, `user_pwd`) VALUES (1, 'Ahmed', 'Zahlan', '<EMAIL>', '@Zah', '$2y$10$ppd8M/KSIkWLXa1zYeTGWeKZFCTdZ9ia0SML6EupI3VL6GkH6a9NW'), (2, 'Ahmed', 'Mahroug', '<EMAIL>', '@Mah', '$2y$10$4T5yXM.h9Pb5fi3QZh/O1O3tLhiGR4e17rYlW/k3sGFh.aXjZPNQm'), (3, 'oualid', 'rghioui', '<EMAIL>', '@Rgh', '$2y$10$GdIglbYkhaB7pY8wcdui5uNQlw1AayUtimuTgETdWUKkGemepJY4G'), (5, 'abdeslam', 'amrabbat', '<EMAIL>', '@Abdo', '$2y$10$QvDZWKZTQyMPO0Y1cQzepe8ST49ZqGV64H5Knzr5NlHN8bGaON00W'); -- -- Indexes for dumped tables -- -- -- Indexes for table `categories` -- ALTER TABLE `categories` ADD PRIMARY KEY (`id`); -- -- Indexes for table `cours` -- ALTER TABLE `cours` ADD PRIMARY KEY (`c_id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`user_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `categories` -- ALTER TABLE `categories` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `cours` -- ALTER TABLE `cours` MODIFY `c_id` int(20) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `user_id` int(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php include 'header.php'; include 'includes/dbh.php'; $smya = $_SESSION['u_first']; if(!isset($_SESSION['u_id'])) { header("Location: contact.php"); } $nameError = $descriptionError = $videoError = $categoryError = $imageError = $name = $description = $price = $category = $image = $video = ""; if(!empty($_POST)) { $name = checkInput($_POST['name']); $description = checkInput($_POST['description']); $category = checkInput($_POST['category']); $image = checkInput($_FILES["image"]["name"]); $imagePath = 'img/'. basename($image); $imageExtension = pathinfo($imagePath,PATHINFO_EXTENSION); $video = checkInput($_FILES["Video"]["name"]); $videoPath = 'vid/'. basename($video); $videoExtension = pathinfo($videoPath,PATHINFO_EXTENSION); $isSuccess = true; $isUploadSuccess = false; if(empty($name)) { $nameError = 'Ce champ ne peut pas être vide'; $isSuccess = false; } if(empty($description)) { $descriptionError = 'Ce champ ne peut pas être vide'; $isSuccess = false; } if(empty($category)) { $categoryError = 'Ce champ ne peut pas être vide'; $isSuccess = false; } if(empty($image)) { $imageError = 'Ce champ ne peut pas être vide'; $isSuccess = false; } if(empty($video)) { $videoError = 'Ce champ ne peut pas être vide'; $isSuccess = false; } else { $isUploadSuccess = true; if($imageExtension != "jpg" && $imageExtension != "jpeg" && $imageExtension != "png") { $imageError = "Les fichiers autorises sont: .jpg, .png..."; $isUploadSuccess = false; } #if(file_exists($imagePath)) # { # $imageError = "Le fichier existe deja"; # $isUploadSuccess = false; # } if($_FILES["image"]["size"] > 10000000000000) { $imageError = "Le fichier ne doit pas depasser les 500KB"; $isUploadSuccess = false; } if($isUploadSuccess) { if(!move_uploaded_file($_FILES["image"]["tmp_name"], $imagePath)) { $imageError = "Il y a eu une erreur lors de l'upload"; $isUploadSuccess = false; } } $isUploadSuccess = true; if($videoExtension != "mp4" && $videoExtension != "webm" && $videoExtension != "avi" && $videoExtension != "mpeg" ) { $videoError = "Les fichiers autorises sont: .mp4, .webm, .avi, .mpeg"; $isUploadSuccess = false; } # if(file_exists($videoPath)) #{ # $videoError = "Le fichier existe deja"; # $isUploadSuccess = false; #} if($_FILES["Video"]["size"] > 100000000000000000000) { $videoError = "Le fichier ne doit pas depasser les 500KB"; $isUploadSuccess = false; } if($isUploadSuccess) { if(!move_uploaded_file($_FILES["image"]["tmp_name"], $videoPath)) { $videoError = "Il y a eu une erreur lors de l'upload"; $isUploadSuccess = false; } } } if($isSuccess && $isUploadSuccess) { $db = "INSERT INTO cours(c_categorie,c_name,c_desc,c_img,c_vid) VALUES('$category','$name','$description','$imagePath','$videoPath');"; mysqli_query($conn,$db); $_SESSION['category']=$category; $_SESSION['cname']=$name; $_SESSION['desc']=$description; $_SESSION['img']=$imagePath; $_SESSION['vid']=$videoPath; } } function checkInput($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <div id="navbar-collapse" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="home.php">Home</a></li> <li><a href="courses.php">Courses</a></li> <li><a href="teachers.php">Who are we ?</a></li> <li class="active"><a href="user.php"><?php echo $_SESSION['u_first'];?></a></li> <li><form action="includes/logout.inc.php" method="POST"> <div class="just "> <br> <input type="submit" class="btn btn-primary" id="submit" name="submit" value="Logout"> </div> </form></li> </ul> </div> </div> </nav> <section class="probootstrap-section probootstrap-section-colored"> <div class="container"> <div class="row"> <div class="col-md-12 text-left section-heading probootstrap-animate"> <h1 class="mb0">Welcome <?php echo $_SESSION['u_first'];?></h1> </div> </div> </div> </section> <section class="probootstrap-section probootstrap-section-colored probootstrap-bg probootstrap-custom-heading probootstrap-tab-section" style="background-image: url(img/.jpg)"> <div class="container"> <div class="row"> <div class="col-md-12 text-center section-heading probootstrap-animate"> <h2 class="mb0">DO what you want</h2> </div> </div> </div> <div class="probootstrap-tab-style-1"> <ul class="nav nav-tabs probootstrap-center probootstrap-tabs no-border"> <li class="active" ><a data-toggle="tab" href="#getintouch">Get in Touch</a></li> <li><a data-toggle="tab" href="#uploadone">Upload One</a></li> </ul> </div> </section> <section class="probootstrap-section probootstrap-section"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="tab-content"> <div id="getintouch" class="container tab-pane fade in active"> <div class="row"> <div class="col-md-12"> <div class="row probootstrap-gutter0"> <div class="col-md-7 col-md-push-1 probootstrap-animate" id="probootstrap-content"> <h2>Get In Touch</h2> <p>Contact us.</p> <form action="#" method="post" class="probootstrap-form"> <div class="form-group"> <label for="subject">Subject</label> <input type="text" class="form-control" id="subject" name="subject"> </div> <div class="form-group"> <label for="message">Message</label> <textarea cols="30" rows="10" class="form-control" id="message" name="message"></textarea> </div> <div class="form-group"> <input type="submit" class="btn btn-primary btn-lg" id="submit" name="submit" value="Send Message"> </div> </form> </div> </div> </div> </div> </div> <div id="uploadone" class="tab-pane fade"> <div class="container admin" id="probootstrap-content"> <div class="row"> <h1 class="mb0">Upload One</h1> <br> <form class="form" action="user.php" role="form" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="name">Name:</label> <input type="text" class="form-control" id="name" name="name" placeholder="Name"> <span class="help-inline"><?php echo $nameError;?></span> </div> <div class="form-group"> <label for="description">Description:</label> <input type="text" class="form-control" id="description" name="description" placeholder="Description" value="<?php echo $description;?>"> <span class="help-inline"><?php echo $descriptionError;?></span> </div> <div class="form-group"> <label for="category">Catégorie:</label> <select class="form-control" id="category" name="category"> <optgroup label="Software"> <option value="Web">Web</option> <option value="Design">Design</option> <option value="Programming Languages">Programming Languages</option> </optgroup> <optgroup label="Major Math"> <option value="Algebra">Algebra</option> <option value="Probability">Probability</option> <option value="Analysis">Analysis</option> <option value="Geometry">Geometry</option> </optgroup> <optgroup label="Physics"> <option value="Mechanical">Mechanical</option> <option value="Electromgnetic">Electromgnetic</option> <option value="Nuclear Physics">Nuclear Physics</option> <option value="Quantum">Quantum</option> </optgroup> <optgroup label="Astronomy"> <option value="Stellar astronomy">Stellar astronomy</option> <option value="Galactic astronomy">Galactic astronomy</option> <option value="Planetary science">Planetary science</option> <option value="Cosmology">Cosmology</option> </optgroup> </select> <span class="help-inline"><?php echo $categoryError;?></span> </div> <div class="form-group"> <label for="image">Image For advertising:</label> <input type="file" id="image" name="image"> <span class="help-inline"><?php echo $imageError;?></span> </div> <div class="form-group"> <label for="video">Video:</label> <input type="file" id="Video" name="Video"> <span class="help-inline"><?php echo $videoError;?></span> </div> <br> <div class="form-group"> <input type="submit" class="btn btn-primary btn-lg" id="submit" name="submit" value="+ Upload"> </div> </form> </div> </div> </div> </div> </div> </div> </div> </section> <footer class="probootstrap-footer probootstrap-bg"> <div class="container"> <div class="row"> <div class="col-md-4"> <div class="probootstrap-footer-widget"> <h3>About Us</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Porro provident suscipit natus a cupiditate ab minus illum quaerat maxime inventore Ea consequatur consectetur hic provident dolor ab aliquam eveniet alias</p> <h3>Social</h3> <ul class="probootstrap-footer-social"> <li><a href="#"><i class="icon-twitter"></i></a></li> <li><a href="#"><i class="icon-facebook"></i></a></li> <li><a href="#"><i class="icon-github"></i></a></li> <li><a href="#"><i class="icon-dribbble"></i></a></li> <li><a href="#"><i class="icon-linkedin"></i></a></li> <li><a href="#"><i class="icon-youtube"></i></a></li> </ul> </div> </div> <div class="col-md-3 col-md-push-1"> <div class="probootstrap-footer-widget"> <h3>Links</h3> <ul> <li><a href="#">Home</a></li> <li><a href="#">Courses</a></li> <li><a href="#">Teachers</a></li> <li><a href="#">Contact</a></li> </ul> </div> </div> <div class="col-md-4"> <div class="probootstrap-footer-widget"> <h3>Contact Info</h3> <ul class="probootstrap-contact-info"> <li><i class="icon-location2"></i> <span>National Schools of Applied Sciences Of Al Hoceima </span></li> <li><i class="icon-mail"></i><span><EMAIL></span></li> <li><i class="icon-phone2"></i><span>+212-658206268</span></li> </ul> </div> </div> </div> <!-- END row --> </div> <div class="probootstrap-copyright"> <div class="container"> <div class="row"> <div class="col-md-8 text-left"> <p>L'Cours &copy; 2017</p> </div> <div class="col-md-4 probootstrap-back-to-top"> <p><a href="#" class="js-backtotop">Back to top <i class="icon-arrow-long-up"></i></a></p> </div> </div> </div> </div> </footer> </div> <!-- END wrapper --> <script src="js/scripts.min.js"></script> <script src="js/main.min.js"></script> <script src="js/custom.js"></script> </body> </html> <file_sep># MOOC Projet web MOOC : [Lien de la demo du site](https://youtu.be/hKccNUdn5sE) <file_sep><?php session_start(); if(isset($_GET['del'])) { include 'dbh.php'; $id=$_GET['del']; mysqli_query($conn,"DELETE FROM users WHERE user_id=$id"); $_SESSION['msg']="user deleted"; header('Location: ../admin.php'); exit(); }<file_sep> <?php include 'header.php'; ?> <div id="navbar-collapse" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="home.php">Home</a></li> <li><a href="courses.php">Courses</a></li> <li><a href="teachers.php">Who are we ?</a></li> <li class="active"><a href="contact.php">Login</a></li> </ul> </div> </div> </nav> <section class="probootstrap-section probootstrap-section-colored"> <div class="container"> <div class="row"> <div class="col-md-12 text-left section-heading probootstrap-animate"> <h1 class="mb0">Login</h1> </div> </div> </div> </section> <section class="probootstrap-section probootstrap-section-sm"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="row probootstrap-gutter0"> <div class="col-md-4" id="probootstrap-sidebar"> <div class="probootstrap-sidebar-inner probootstrap-overlap probootstrap-animate"> <h3 >Sign In</h3> <form action="includes/login.inc.php" method="post" class="probootstrap-form"> <div class="form-group"> <label for="username">UserName</label> <input type="text" class="form-control" id="username" name="username"> </div> <div class="form-group"> <label for="password">Password</label> <input type="<PASSWORD>" class="form-control" id="password" name="password"> </div> <div class="form-group"> <input type="submit" class="btn btn-primary btn-lg" id="submit" name="submit" value="Sign in"> </div> </form> </div> </div> <div class="col-md-7 col-md-push-1 probootstrap-animate" id="probootstrap-content"> <h2>Sign Up if you don't have account with us </h2> <p>Sign up using the form below.</p> <form action="includes/signup.inc.php" method="post" class="probootstrap-form needs-validation"> <div class="form-group"> <label for="name">First Name</label> <input type="name" class="form-control" id="first" name="first"> </div> <div class="form-group"> <label for="name">Last Name</label> <input type="name" class="form-control" id="last" name="last"> </div> <div class="form-group"> <label for="username">UserName</label> <input type="text" class="form-control" id="username" name="username" placeholder="@username"> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" class="form-control" id="email" name="email" placeholder="<EMAIL>"> </div> <div class="form-group"> <label for="password">Password</label> <input type="<PASSWORD>" class="form-control" id="password" name="password"> </div> <div class="form-group"> <label for="Copassword">Confirm Password</label> <input type="password" class="form-control" id="Copassword" name="Copassword"> </div> <div class="form-group"> <input type="submit" class="btn btn-primary btn-lg btn-block" id="submit" name="submit" value="Sign Up"> </div> </form> </div> </div> </div> </div> </div> </section> <footer class="probootstrap-footer probootstrap-bg"> <div class="container"> <div class="row"> <div class="col-md-4"> <div class="probootstrap-footer-widget"> <h3>About Us</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Porro provident suscipit natus a cupiditate ab minus illum quaerat maxime inventore Ea consequatur consectetur hic provident dolor ab aliquam eveniet alias</p> <h3>Social</h3> <ul class="probootstrap-footer-social"> <li><a href="#"><i class="icon-twitter"></i></a></li> <li><a href="#"><i class="icon-facebook"></i></a></li> <li><a href="#"><i class="icon-github"></i></a></li> <li><a href="#"><i class="icon-dribbble"></i></a></li> <li><a href="#"><i class="icon-linkedin"></i></a></li> <li><a href="#"><i class="icon-youtube"></i></a></li> </ul> </div> </div> <div class="col-md-3 col-md-push-1"> <div class="probootstrap-footer-widget"> <h3>Links</h3> <ul> <li><a href="#">Home</a></li> <li><a href="#">Courses</a></li> <li><a href="#">Teachers</a></li> <li><a href="#">Contact</a></li> </ul> </div> </div> <div class="col-md-4"> <div class="probootstrap-footer-widget"> <h3>Contact Info</h3> <ul class="probootstrap-contact-info"> <li><i class="icon-location2"></i> <span>National Schools of Applied Sciences Of Al Hoceima </span></li> <li><i class="icon-mail"></i><span><EMAIL></span></li> <li><i class="icon-phone2"></i><span>+212-658206268</span></li> </ul> </div> </div> </div> <!-- END row --> </div> <div class="probootstrap-copyright"> <div class="container"> <div class="row"> <div class="col-md-8 text-left"> <p>L'Cours &copy; 2017</p> </div> <div class="col-md-4 probootstrap-back-to-top"> <p><a href="#" class="js-backtotop">Back to top <i class="icon-arrow-long-up"></i></a></p> </div> </div> </div> </div> </footer> </div> <!-- END wrapper --> <script src="js/scripts.min.js"></script> <script src="js/main.min.js"></script> <script src="js/custom.js"></script> </body> </html><file_sep><?php include 'header.php'; if(isset($_SESSION['u_id'])) { $rgh='@Rgh'; $zah='@Zah'; $mah='@Mah'; echo ' <div id="navbar-collapse" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li class="active"><a href="home.php">Home</a></li> <li><a href="courses.php">Courses</a></li> <li><a href="teachers.php">Who are we ?</a></li>'; if($_SESSION['u_uid']==$rgh || $_SESSION['u_uid']==$zah || $_SESSION['u_uid']==$mah){ echo '<li><a href="admin.php">'.$_SESSION['u_first'].'</a></li>'; }else{ echo '<li><a href="user.php">'.$_SESSION['u_first'].'</a></li>'; } echo '<li><form action="includes/logout.inc.php" method="POST"> <div class="just "> <br> <input type="submit" class="btn btn-primary" id="submit" name="submit" value="Logout"> </div> </form></li> </ul> </div> </div> </nav> '; }else{ echo ' <div id="navbar-collapse" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li class="active"><a href="home.php" style="color: #20b2aa !important;">Home</a></li> <li><a href="courses.php">Courses</a></li> <li><a href="teachers.php">Who are we ?</a></li> <li><a href="contact.php">Login</a></li> </ul> </div> </div> </nav> '; } ?> <section class="flexslider"> <ul class="slides"> <li style="background-image: url(img/gal_img_full_1.jpg)" class="overlay"> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="probootstrap-slider-text text-center"> <h1 class="probootstrap-heading probootstrap-animate">Change Is The End Result Of All True Learning</h1> </div> </div> </div> </div> </li> <li style="background-image: url(img/gal_img_full_2.jpg)" class="overlay"> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="probootstrap-slider-text text-center"> <h1 class="probootstrap-heading probootstrap-animate">All Real Education Is The Architecture Of The Soul</h1> </div> </div> </div> </div> </li> <li style="background-image: url(img/gal_img_full_3.jpg)" class="overlay"> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="probootstrap-slider-text text-center"> <h1 class="probootstrap-heading probootstrap-animate">Knowledge Is The Movement From Darkness To Light </h1> </div> </div> </div> </div> </li> </ul> </section> <section class="probootstrap-section probootstrap-section-colored"> <div class="container"> <div class="row"> <div class="col-md-12 text-left section-heading probootstrap-animate"> <h1>Welcome to <span style="font-family: 'Lobster', cursive;">FEDNI</span> </h1> </div> </div> </div> </section> <section class="probootstrap-section"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="probootstrap-flex-block"> <div class="probootstrap-text probootstrap-animate"> <h3>About Us</h3> <p>At <span style="font-family: 'Lobster', cursive;">FEDNI</span>, we believe everyone deserves to have a website or online store. Innovation and simplicity makes us happy: our goal is to remove any technical or financial barriers that can prevent business owners from making their own website. We're excited to help you on your journey!</p> </div> <div class="probootstrap-image probootstrap-animate" style="background-image: url(img/gal_img_full_4.jpg)"> <a href="vid/avengers.mp4" class="btn-video popup-vimeo"><i class="icon-play3"></i></a> </div> </div> </div> </div> </div> </section> <section class="probootstrap-section" id="probootstrap-counter"> <div class="container "> <div class="row"> <div class="col-md-4 col-sm-6 col-xs-6 col-xxs-12 probootstrap-animate"> <div class="probootstrap-counter-wrap"> <div class="probootstrap-icon"> <i class="icon-users2" style="color: #20b2aa"></i> </div> <div class="probootstrap-text"> <span class="probootstrap-counter"> <span class="js-counter" data-from="0" data-to="20203" data-speed="55555555" data-refresh-interval="50">1</span> </span> <span class="probootstrap-counter-label">Visitors</span> </div> </div> </div> <div class="col-md-4 col-sm-6 col-xs-6 col-xxs-12 probootstrap-animate"> <div class="probootstrap-counter-wrap"> <div class="probootstrap-icon"> <i class="icon-user-tie" style="color: #20b2aa"></i> </div> <div class="probootstrap-text"> <span class="probootstrap-counter"> <span class="js-counter" data-from="0" data-to="139" data-speed="55555555" data-refresh-interval="50">1</span> </span> <span class="probootstrap-counter-label">Speakers</span> </div> </div> </div> <div class="col-md-4 col-sm-6 col-xs-6 col-xxs-12 probootstrap-animate"> <div class="probootstrap-counter-wrap"> <div class="probootstrap-icon"> <i class="icon-smile2" style="color: #20b2aa"></i> </div> <div class="probootstrap-text"> <span class="probootstrap-counter"> <span class="js-counter" data-from="0" data-to="100" data-speed="555555" data-refresh-interval="50">1</span>% </span> <span class="probootstrap-counter-label">Visitors Satisfaction</span> </div> </div> </div> </div> </div> </section> <section class="probootstrap-section probootstrap-section-colored probootstrap-bg probootstrap-custom-heading probootstrap-tab-section" style="background-image: url(img/gal_img_sm_1.jpg)"> <div class="container"> <div class="row"> <div class="col-md-12 text-center section-heading probootstrap-animate"> <h2 class="mb0">Highlights</h2> </div> </div> </div> <div class="probootstrap-tab-style-1"> <ul class="nav nav-tabs probootstrap-center probootstrap-tabs no-border"> <li class="active" ><a data-toggle="tab" href="#featured-news">Featured News</a></li> <li><a data-toggle="tab" href="#upcoming-events">Upcoming Events</a></li> </ul> </div> </section> <section class="probootstrap-section probootstrap-section"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="tab-content"> <div id="featured-news" class="tab-pane fade in active"> <div class="row"> <div class="col-md-12"> <div class="owl-carousel" id="owl1"> <div class="item"> <a href="#" class="probootstrap-featured-news-box"> <figure class="probootstrap-media"><img src="img/new1.jpg" class="img-responsive"></figure> <div class="probootstrap-text"> <h3>My Flatmate Experience in London</h3> <p>I was so looking forward to start my Erasmus in London. I always dreamed about moving to London and live there for a while, either as a student or at least do my internship there.</p> <span class="probootstrap-date"><i class="icon-calendar"></i>July 9, 2018</span> </div> </a> </div> <!-- END item --> <div class="item"> <a href="#" class="probootstrap-featured-news-box"> <figure class="probootstrap-media"><img src="img/new2.jpg" class="img-responsive"></figure> <div class="probootstrap-text"> <h3>187,138 Moroccan Students Pass Baccalaureate</h3> <p>The Ministry of Education, Vocational Training, Higher Education, and Scientific Research revealed on Friday that 187,138 students have passed the exam in the June session, representing a passing rate of 57.36 percent.</p> <span class="probootstrap-date"><i class="icon-calendar"></i>July 9, 2018</span> </div> </a> </div> <!-- END item --> <div class="item"> <a href="#" class="probootstrap-featured-news-box"> <figure class="probootstrap-media"><img src="img/new3.jpg" class="img-responsive"></figure> <div class="probootstrap-text"> <h3>French-Moroccan Actor Said Taghmaoui Joins Oscars’ Academy</h3> <p>He is the third Moroccan to join the prestigious academy. Following Moroccan filmmakers <NAME> and <NAME> in 2017, French-Moroccan actor <NAME> has accepted to be part of the Oscars’ Academy of Motion Pictures and Sciences.</p> <span class="probootstrap-date"><i class="icon-calendar"></i>July 9, 2018</span> </div> </a> </div> <!-- END item --> <div class="item"> <a href="#" class="probootstrap-featured-news-box"> <figure class="probootstrap-media"><img src="img/new4.jpg" class="img-responsive"></figure> <div class="probootstrap-text"> <h3>1st Workshop of Moroccan Experts in France to be Held in Morocco’s Skhirat</h3> <p>The Moroccan Delegate Ministry for Moroccans Residing Abroad has announced the organization of a two-day workshop that will convene Moroccan experts, entrepreneurs, and professionals living in France.</p> <span class="probootstrap-date"><i class="icon-calendar"></i> June 29, 2018</span> </div> </a> </div> <!-- END item --> </div> </div> </div> <!-- END row --> </div> <div id="upcoming-events" class="tab-pane fade"> <div class="row"> <div class="col-md-12"> <div class="owl-carousel" id="owl2"> <div class="item"> <a href="#" class="probootstrap-featured-news-box"> <figure class="probootstrap-media"><img src="img/tech.jpg" class="img-responsive"></figure> <div class="probootstrap-text"> <h3>Tech Experience 4.0</h3> <span class="probootstrap-date"><i class="icon-calendar"></i>Avrile 26,27,28 2019</span> <span class="probootstrap-location"><i class="icon-location2"></i>National Schools Of Applied Sciences Alhoceima</span> </div> </a> </div> <!-- END item --> <div class="item"> <a href="#" class="probootstrap-featured-news-box"> <figure class="probootstrap-media"><img src="img/img_sm_6.jpg" class="img-responsive"></figure> <div class="probootstrap-text"> <h3><NAME></h3> <span class="probootstrap-date"><i class="icon-calendar"></i>November 27,28,29, 2018</span> <span class="probootstrap-location"><i class="icon-location2"></i>White Palace, Brooklyn, NYC</span> </div> </a> </div> <!-- END item --> <div class="item"> <a href="#" class="probootstrap-featured-news-box"> <figure class="probootstrap-media"><img src="img/event1.jpg" class="img-responsive"></figure> <div class="probootstrap-text"> <h3>Social Media Day - Morocco</h3> <span class="probootstrap-date"><i class="icon-calendar"></i>July 14, 2018</span> <span class="probootstrap-location"><i class="icon-location2"></i>Casablanca, Casablanca-Settat</span> </div> </a> </div> <!-- END item --> <div class="item"> <a href="#" class="probootstrap-featured-news-box"> <figure class="probootstrap-media"><img src="img/event2.jpg" class="img-responsive"></figure> <div class="probootstrap-text"> <h3>PMP® Workshop</h3> <span class="probootstrap-date"><i class="icon-calendar"></i>September 9, 2018</span> <span class="probootstrap-location"><i class="icon-location2"></i>Casablanca Technopark Boulevard Dammam Casablanca, 20150</span> </div> </a> </div> <!-- END item --> </div> </div> </div> </div> </div> </div> </div> </div> </section> <section class="probootstrap-section probootstrap-bg-white probootstrap-border-top"> <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3 text-center section-heading probootstrap-animate"> <h2>Our Areas Of Learning</h2> </div> </div> <!-- END row --> <div class="row"> <div class="col-md-6"> <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img src="img/cours_2.jpg" > </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>Software</h3> <p>The application of engineering to the development of software in a systematic method.</p> <p><a href="software.php" class="btn btn-primary">Get In</a></p> </div> </div> <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img src="img/cours_3.jpg" > </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>Physics</h3> <p>Physics is really nothing more than a search for ultimate simplicity, but so far all we have is a kind of elegant messiness.</p> <p><a href="physic.php" class="btn btn-primary">Get In</a></p> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img src="img/cours_1.jpg" > </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>Math Major</h3> <p>Mathematics is a place where you can do things which you can't do in the real world.</p> <p><a href="math.php" class="btn btn-primary">Get In</a></p> </div> </div> <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img src="img/cours_4.jpg"> </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>Astronomy</h3> <p>Astronomy is, not without reason, regarded, by mankind, as the sublimest of the natural sciences. Its objects so frequently visible, and therefore familiar, being always remote and inaccessible, do not lose their dignity.</p> <p><a href="astro.php" class="btn btn-primary">Get In</a></p> </div> </div> </div> </div> </div> </div> </section> <section class="probootstrap-section probootstrap-bg probootstrap-section-colored probootstrap-testimonial" style="background-image: url(img/slider_4.jpg);"> <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3 text-center section-heading probootstrap-animate"> <h2 style="font-family: 'Lobster', cursive; font-size: 50px;">The Creators</h2> </div> </div> <!-- END row --> <div class="row"> <div class="col-md-12 probootstrap-animate"> <div class="owl-carousel owl-carousel-testimony owl-carousel-fullwidth"> <div class="item"> <div class="probootstrap-testimony-wrap text-center"> <figure> <img src="img/Ahmed.jpg" > </figure> <blockquote class="quote">&ldquo;Design must be functional and functionality must be translated into visual aesthetics, without any reliance on gimmicks that have to be explained.&rdquo; <cite class="author"> &mdash; <span><NAME></span></cite></blockquote> </div> </div> <div class="item"> <div class="probootstrap-testimony-wrap text-center"> <figure> <img src="img/person_2.jpg" > </figure> <blockquote class="quote">&ldquo;Creativity is just connecting things. When you ask creative people how they did something, they feel a little guilty because they didn’t really do it, they just saw something. It seemed obvious to them after a while.&rdquo; <cite class="author"> &mdash;<span><NAME></span></cite></blockquote> </div> </div> <div class="item"> <div class="probootstrap-testimony-wrap text-center"> <figure> <img src="img/person_3.jpg" > </figure> <blockquote class="quote">&ldquo;I think design would be better if designers were much more skeptical about its applications. If you believe in the potency of your craft, where you choose to dole it out is not something to take lightly.&rdquo; <cite class="author">&mdash; <span><NAME></span></cite></blockquote> </div> </div> </div> </div> </div> <!-- END row --> </div> </section> <footer class="probootstrap-footer probootstrap-bg"> <div class="container"> <div class="row"> <div class="col-md-4"> <div class="probootstrap-footer-widget"> <h3>About Us</h3> <p>At <span style="font-family: 'Lobster', cursive;">FEDNI</span>, we believe everyone deserves to have a website or online store. Innovation and simplicity makes us happy: our goal is to remove any technical or financial barriers that can prevent business owners from making their own website. We're excited to help you on your journey!</p> <h3>Social</h3> <ul class="probootstrap-footer-social"> <li><a href="#"><i class="icon-twitter"></i></a></li> <li><a href="#"><i class="icon-facebook"></i></a></li> <li><a href="#"><i class="icon-github"></i></a></li> <li><a href="#"><i class="icon-dribbble"></i></a></li> <li><a href="#"><i class="icon-linkedin"></i></a></li> <li><a href="#"><i class="icon-youtube"></i></a></li> </ul> </div> </div> <div class="col-md-3 col-md-push-1"> <div class="probootstrap-footer-widget"> <h3>Links</h3> <ul> <li><a href="home.php">Home</a></li> <li><a href="Courses.php">Courses</a></li> <li><a href="teachers.php">Who are we?</a></li> <li><a href="contact.php">Contact</a></li> </ul> </div> </div> <div class="col-md-4"> <div class="probootstrap-footer-widget"> <h3>Contact Info</h3> <ul class="probootstrap-contact-info"> <li><i class="icon-location2"></i> <span>National Schools of Applied Sciences Of Al Hoceima </span></li> <li><i class="icon-mail"></i><span><EMAIL></span></li> <li><i class="icon-phone2"></i><span>+212-658206268</span></li> </ul> </div> </div> </div> <!-- END row --> </div> <div class="probootstrap-copyright"> <div class="container"> <div class="row"> <div class="col-md-8 text-left"> <p>L'Cours &copy; 2018</p> </div> <div class="col-md-4 probootstrap-back-to-top"> <p><a href="#" class="js-backtotop">Back to top <i class="icon-arrow-long-up"></i></a></p> </div> </div> </div> </div> </footer> </div> <!-- END wrapper --> <script src="js/scripts.min.js"></script> <script src="js/main.min.js"></script> <script src="js/custom.js"></script> </body> </html><file_sep><?php include_once 'includes/dbh.php'; include_once 'header.php'; if(!$_SESSION['u_id']) { header('Location: contact.php'); exit(); } if(isset($_GET['edit'])) { $id = $_GET['edit']; $_SESSION['edit'] = $id; $res=mysqli_query($conn,"SELECT * FROM users WHERE user_id=$id"); $check = mysqli_num_rows($res); if($check==1){ $record = mysqli_fetch_array($res); $id = $record['user_id']; $first = $record['user_first']; $last = $record['user_last']; $username = $record['user_uid']; $email = $record['user_email']; }else{ header('Location: admin.php'); exit(); } } if(isset($_GET['mdf'])) { $id = $_GET['mdf']; $_SESSION['mdf'] = $id; $res=mysqli_query($conn,"SELECT * FROM cours WHERE c_id=$id"); $check = mysqli_num_rows($res); if($check==1){ $record = mysqli_fetch_array($res); $id = $record['c_id']; $name = $record['c_name']; $descreption = $record['c_desc']; $category = $record['c_categorie']; $img = $record['c_img']; $vid = $record['c_vid']; }else{ header('Location: admin.php'); exit(); } } ?> <div id="navbar-collapse" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="home.php">Home</a></li> <li><a href="courses.php">Courses</a></li> <li><a href="teachers.php">Who are we ?</a></li> <li class="active"><a href="amin.php"><?php echo $_SESSION['u_first']?></a></li> <li><form action="includes/logout.inc.php" method="POST"> <div class="just "> <br> <input type="submit" class="btn btn-primary" id="submit" name="submit" value="Logout"> </div> </form></li> </ul> </div> </div> </nav> <section class="probootstrap-section probootstrap-section-colored"> <div class="container"> <div class="row"> <div class="col-md-12 text-left section-heading probootstrap-animate"> <h1 class="mb0">Welcome <?php echo $_SESSION['u_first'] ?> .</h1> <p> THE ADMIN </p> </div> </div> </div> </section> <section class="probootstrap-section probootstrap-section-colored probootstrap-bg probootstrap-custom-heading probootstrap-tab-section" style="background-image: url()"> <div class="container"> <div class="row"> <div class="col-md-12 text-center section-heading probootstrap-animate"> <h2 class="mb0">MY control</h2> </div> </div> </div> <div class="probootstrap-tab-style-1"> <ul class="nav nav-tabs probootstrap-center probootstrap-tabs no-border"> <li class="active" ><a data-toggle="tab" href="#users">USERS</a></li> <li><a data-toggle="tab" href="#cours">COURSES</a></li> </ul> </div> </section> <section class="probootstrap-section probootstrap-section"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="tab-content"> <div id="users" class="container tab-pane fade in active"> <div class="col-md-7 col-md-push-1 probootstrap-animate" id="probootstrap-content"> <form action="includes/update.inc.php" method="POST" class="probootstrap-form needs-validation"> <input type="hidden" name="id" value="<?php echo $id; ?>"> <div class="form-group"> <label for="name">First Name</label> <input type="name" class="form-control" id="first" name="first" value="<?php if(!empty($first)){echo $first;} ?>"> </div> <div class="form-group"> <label for="name">Last Name</label> <input type="name" class="form-control" id="last" name="last" value="<?php if(!empty($last)){echo $last;}?>"> </div> <div class="form-group"> <label for="username">UserName</label> <input type="text" class="form-control" id="username" name="username" placeholder="@username" value="<?php if(!empty($username)){echo $username;} ?>"> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" class="form-control" id="email" name="email" placeholder="<EMAIL>" value="<?php if(!empty($email)){echo $email;} ?>"> </div> <div class="form-group"> <input type="submit" class="btn btn-primary btn-lg btn-block" id="submit" name="update" value="Update"> </div> </form> </div> <div class="row"> <div class="col-md-12 probootstrap-animate" id="probootstrap-content"> <!-- Website Overview --> <div class="panel panel-default"> <div class="panel-heading main-color-bg"> <h3>Users</h3> </div> <div class="panel-body"> <div class="row"> <div class="col-md-12"> <form action="includes/search.inc.php" method="POST"> <input class="form-control" type="email" name="email" placeholder="Enter Email"><br> <input class="btn btn-primary" type="submit" name="submit" value="Search"> </form> </div> <?php if(isset($_SESSION['msg'])){ echo '<div class="text-center" style="color: #3c763d; ">'; echo $_SESSION['msg']; unset($_SESSION['msg']); echo '</div>';} ?> </div> <br> <table class="table table-striped table-hover"> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> <th>Email</th> <th></th> <th></th> </tr> <?php $requete="SELECT user_id,user_first,user_last,user_uid,user_email FROM users"; $resultat= mysqli_query($conn,$requete); $nbart=mysqli_num_rows($resultat); if($nbart>0) { while($lign=mysqli_fetch_assoc($resultat)) { echo '<tr>'; foreach ($lign as $value) { echo "<td>".$value."</td>"; } echo '<td><a href="admin.php?edit='.$lign['user_id'].'" class="btn btn-success">Edit</a></td>'; echo '<td><a href="includes/delete.inc.php?del='.$lign['user_id'].'" class="btn btn-danger">Delete</a></td>'; echo '</tr>'; } } ?> </table> </div> </div> </div> </div> </div> <div id="cours" class="container tab-pane fade"> <div class="col-md-7 col-md-push-1 probootstrap-animate" id="probootstrap-content"> <form action="includes/update.inc.php" method="POST" class="probootstrap-form needs-validation"> <input type="hidden" name="id" value="<?php echo $id; ?>"> <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="first" name="first" value="<?php if(!empty($name)){echo $name;} ?>"> </div> <div class="form-group"> <label for="desc">Descreption</label> <input type="text" class="form-control" id="descreption" name="descreption" value="<?php if(!empty($descreption)){echo $descreption;}?>"> </div> <div class="form-group"> <label for="Category">Category</label> <input type="text" class="form-control" id="Category" name="Category" placeholder="Category" value="<?php if(!empty($category)){echo $category;} ?>"> </div> <div class="form-group"> <label for="image">image</label> <input type="text" class="form-control" id="image" name="image" placeholder="<EMAIL>" value="<?php if(!empty($img)){echo $img;} ?>"> </div> <div class="form-group"> <label for="video">video</label> <input type="text" class="form-control" id="video" name="video" placeholder="<EMAIL>" value="<?php if(!empty($vid)){echo $img;} ?>"> </div> <div class="form-group"> <input type="submit" class="btn btn-primary btn-lg btn-block" id="submit" name="update" value="Update"> </div> </form> </div> <div class="row"> <div class="col-md-12 probootstrap-animate" id="probootstrap-content"> <!-- Website Overview --> <div class="panel panel-default"> <div class="panel-heading main-color-bg"> <h3>Users</h3> </div> <div class="panel-body"> <div class="row"> <div class="col-md-12"> <form action="includes/search.inc.php" method="POST"> <input class="form-control" type="email" name="email" placeholder="Enter Email"><br> <input class="btn btn-primary" type="submit" name="submit" value="Search"> </form> </div> <?php if(isset($_SESSION['msg'])){ echo '<div class="text-center" style="color: #3c763d; ">'; echo $_SESSION['msg']; unset($_SESSION['msg']); echo '</div>';} ?> </div> <br> <table class="table table-striped table-hover"> <tr> <th>ID</th> <th>Category</th> <th>Name</th> <th>image</th> <th>video</th> <th></th> <th></th> </tr> <?php $requete="SELECT c_id,c_categorie,c_name,c_img,c_vid FROM cours"; $resultat= mysqli_query($conn,$requete); $nbart=mysqli_num_rows($resultat); if($nbart>0) { while($lign=mysqli_fetch_assoc($resultat)) { echo '<tr>'; foreach ($lign as $value) { echo "<td>".$value."</td>"; } echo '<td><a href="admin.php?mdf='.$lign['c_id'].'" class="btn btn-success">Edit</a></td>'; echo '<td><a href="includes/delete.inc.php?del='.$lign['c_id'].'" class="btn btn-danger">Delete</a></td>'; echo '</tr>'; } } ?> </table> </div> </div> </div> </div> </div> </div> </div> </div> </div> </section> <br><br><br> <footer class="probootstrap-footer probootstrap-bg"> <div class="probootstrap-copyright"> <div class="container"> <div class="row"> <div class="col-md-8 text-left"> <p>L\'Cours &copy; 2017</p> </div> <div class="col-md-4 probootstrap-back-to-top"> <p><a href="#" class="js-backtotop">Back to top <i class="icon-arrow-long-up"></i></a></p> </div> </div> </div> </div> </footer> </div> <!-- END wrapper --> <script src="js/scripts.min.js"></script> <script src="js/main.min.js"></script> <script src="js/custom.js"></script> </body> </html><file_sep><?php include 'header.php'; if(isset($_SESSION['u_id'])) { $rgh='@Rgh'; $zah='@Zah'; $mah='@Mah'; echo ' <div id="navbar-collapse" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="home.php">Home</a></li> <li class="active"><a href="courses.php">Courses</a></li> <li><a href="teachers.php">Who are we ?</a></li>'; if($_SESSION['u_uid']==$rgh || $_SESSION['u_uid']==$zah || $_SESSION['u_uid']==$mah){ echo '<li><a href="admin.php">'.$_SESSION['u_first'].'</a></li>'; }else{ echo '<li><a href="user.php">'.$_SESSION['u_first'].'</a></li>'; } echo '<li><form action="includes/logout.inc.php" method="POST"> <div class="just "> <br> <input type="submit" class="btn btn-primary" id="submit" name="submit" value="Logout"> </div> </form></li> </ul> </div> </div> </nav> '; }else{ echo ' <div id="navbar-collapse" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="home.php">Home</a></li> <li class="active"><a href="courses.php">Courses</a></li> <li><a href="teachers.php">Who are we ?</a></li> <li><a href="contact.php">Login</a></li> </ul> </div> </div> </nav> '; } ?> <section class="probootstrap-section probootstrap-section-colored probootstrap-bg probootstrap-custom-heading probootstrap-tab-section"> <div class="container"> <div class="row"> <div class="col-md-12 text-center section-heading probootstrap-animate"> <h2 class="mb0">Our areas of learning</h2> </div> </div> </div> <div class="probootstrap-tab-style-1"> <ul class="nav nav-tabs probootstrap-center probootstrap-tabs no-border"> <li class="active" ><a data-toggle="tab" href="#software">Software</a></li> <li><a data-toggle="tab" href="#math">Math MAjor</a></li> <li><a data-toggle="tab" href="#physic">Physics</a></li> <li><a data-toggle="tab" href="#astro">Astronomy</a></li> </ul> </div> </section> <section class="probootstrap-section probootstrap-section"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="tab-content"> <!--HADI 1--> <div id="software" class="tab-pane fade in active"> <div class="row"> <div class="col-md-6"> <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img style="width: 200px; height: 240px;" src="img/web_1.png" alt="Free Bootstrap Template by uicookies.com"> </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>Web</h3> <p>Web is chi haja tan9elbou 3liha.</p> <p><a href="software.php" class="btn btn-primary">Get In</a></p> </div> </div> <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img style="width: 200px; height: 240px;" src="img/adobe.jpg" alt="Free Bootstrap Template by uicookies.com"> </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>Design</h3> <p>Design is the creation of a plan or convention of an object, system or measurable human interaction.</p> <p><a href="design.php" class="btn btn-primary">Get In</a></p> </div> </div> </div> <div class="col-md-6"> <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img style="width: 360px; height: 360px;"src="img/prog.jpg" alt="Free Bootstrap Template by uicookies.com"> </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>Programming languages</h3> <p>Programming languages is a formal language that specifies a set of instructions that can be used to produce various kinds of output. Programming languages generally consist of instructions for a computer.</p> <p><a href="prog.php" class="btn btn-primary">Get In</a></p> </div> </div> </div> </div> </div> <!--HADI 2--> <div id="math" class="tab-pane fade"> <div class="row"> <div class="col-md-6"> <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img style="width: 200px; height: 260px;" src="img/algebra.jpg" alt="Free Bootstrap Template by uicookies.com"> </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>Algebra</h3> <p>Algebra is one of the broad parts of mathematics, together with number theory, geometry and analysis.</p> <p><a href="math.php" class="btn btn-primary">Get In</a></p> </div> </div> <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img style="width: 200px; height: 240px;" src="img/analysis.jpg" alt="Free Bootstrap Template by uicookies.com"> </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>Analysis</h3> <p>Analysis is one of the broad parts of mathematics, together with number theory, geometry and algebra.</p> <p><a href="analysis.php" class="btn btn-primary">Get In</a></p> </div> </div> </div> <div class="col-md-6"> <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img style="width: 200px; height: 240px;" src="img/probability.jpg" alt="Free Bootstrap Template by uicookies.com"> </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>Probability</h3> <p>Probability is the measure of the likelihood that an event will occur. See glossary of probability and statistics.</p> <p><a href="proba.php" class="btn btn-primary">Get In</a></p> </div> </div> <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img src="img/geometry.png" alt="Free Bootstrap Template by uicookies.com"> </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>Geometry</h3> <p>Geometry is one of the broad parts of mathematics, together with number theory, analysis and algebra. </p> <p><a href="geo.php" class="btn btn-primary">Get In</a></p> </div> </div> </div> </div> </div> <!--HADI 3--> <div id="physic" class="tab-pane fade"> <div class="row"> <div class="col-md-6"> <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img style="width: 200px; height: 240px;" src="img/meca.jpg" alt="Free Bootstrap Template by uicookies.com"> </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>Mechanical</h3> <p>Mechanical is scinece of the laws of mouvement and balance of bodies as well as driving forces.</p> <p><a href="physic.php" class="btn btn-primary">Get In</a></p> </div> </div> <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img style="width: 200px; height: 240px;" src="img/electro.jpg" alt="Free Bootstrap Template by uicookies.com"> </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>Electromagnetic</h3> <p>Electromagnetism is a branch of physics involving the study of the electromagnetic force, a type of physical interaction that occurs between electrically charged particles.</p> <p><a href="electro.php" class="btn btn-primary">Get In</a></p> </div> </div> </div> <div class="col-md-6"> <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img style="width: 200px; height: 240px;" src="img/nuclear.jpg" alt="Free Bootstrap Template by uicookies.com"> </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>Nuclear physics</h3> <p>Nuclear physics is the field of physics that studies atomic nuclei and their constituents and interactions.</p> <p><a href="nuclear.php" class="btn btn-primary">Get In</a></p> </div> </div> <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img style="width: 200px; height: 240px;" src="img/quantum.jpg" alt="Free Bootstrap Template by uicookies.com"> </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>Quantum</h3> <p>This means that the magnitude of the physical property can take on only discrete values consisting of integer multiples of one quantum.</p> <p><a href="quantum.php" class="btn btn-primary">Get In</a></p> </div> </div> </div> </div> </div> <!--HADI 4--> <div id="astro" class="tab-pane fade"> <div class="row"> <div class="col-md-6"> <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img style="width: 200px; height: 240px;" src="img/star.jpg" alt="Free Bootstrap Template by uicookies.com"> </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>Stellar astronomy</h3> <p>The study of stars and stellar evolution is fundamental to our understanding of the Universe.</p> <p><a href="astro.php" class="btn btn-primary">Get In</a></p> </div> </div> <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img src="img/gala.jpg" alt="Free Bootstrap Template by uicookies.com"> </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>Galactic astronomy</h3> <p>Our solar system orbits within the Milky Way, a barred spiral galaxy that is a prominent member of the Local Group of galaxies.</p> <p><a href="gala.php" class="btn btn-primary">Get In</a></p> </div> </div> </div> <div class="col-md-6"> <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img style="width: 200px; height: 330px;" src="img/planet.jpg" alt="Free Bootstrap Template by uicookies.com"> </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>Planetary science</h3> <p>Planetary science is the study of the assemblage of planets, moons, dwarf planets, comets, asteroids, and other bodies orbiting the Sun, as well as extrasolar planets.</p> <p><a href="planet.php" class="btn btn-primary">Get In</a></p> </div> </div> <div class="probootstrap-service-2 probootstrap-animate"> <div class="image"> <div class="image-bg"> <img style="width: 200px; height: 240px;" src="img/cosmo.jpg" alt="Free Bootstrap Template by uicookies.com"> </div> </div> <div class="text"> <span class="probootstrap-meta"><i class="icon-calendar2"></i> July 10, 2017</span> <h3>Cosmology</h3> <p>Cosmology is the study of the origin, evolution, and eventual fate of the universe.</p> <p><a href="cosmo.php" class="btn btn-primary">Get In</a></p> </div> </div> </div> </div> </div> </div> </div> </div> </div> </section> <footer class="probootstrap-footer probootstrap-bg"> <div class="container"> <div class="row"> <div class="col-md-4"> <div class="probootstrap-footer-widget"> <h3>About Us</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Porro provident suscipit natus a cupiditate ab minus illum quaerat maxime inventore Ea consequatur consectetur hic provident dolor ab aliquam eveniet alias</p> <h3>Social</h3> <ul class="probootstrap-footer-social"> <li><a href="#"><i class="icon-twitter"></i></a></li> <li><a href="#"><i class="icon-facebook"></i></a></li> <li><a href="#"><i class="icon-github"></i></a></li> <li><a href="#"><i class="icon-dribbble"></i></a></li> <li><a href="#"><i class="icon-linkedin"></i></a></li> <li><a href="#"><i class="icon-youtube"></i></a></li> </ul> </div> </div> <div class="col-md-3 col-md-push-1"> <div class="probootstrap-footer-widget"> <h3>Links</h3> <ul> <li><a href="#">Home</a></li> <li><a href="#">Courses</a></li> <li><a href="#">Teachers</a></li> <li><a href="#">Contact</a></li> </ul> </div> </div> <div class="col-md-4"> <div class="probootstrap-footer-widget"> <h3>Contact Info</h3> <ul class="probootstrap-contact-info"> <li><i class="icon-location2"></i> <span>National Schools of Applied Sciences Of Al Hoceima </span></li> <li><i class="icon-mail"></i><span><EMAIL></span></li> <li><i class="icon-phone2"></i><span>+212-658206268</span></li> </ul> </div> </div> </div> <!-- END row --> </div> <div class="probootstrap-copyright"> <div class="container"> <div class="row"> <div class="col-md-8 text-left"> <p>L'Cours &copy; 2017</p> </div> <div class="col-md-4 probootstrap-back-to-top"> <p><a href="#" class="js-backtotop">Back to top <i class="icon-arrow-long-up"></i></a></p> </div> </div> </div> </div> </footer> </div> <!-- END wrapper --> <script src="js/scripts.min.js"></script> <script src="js/main.min.js"></script> <script src="js/custom.js"></script> </body> </html><file_sep><?php session_start(); if(isset($_POST['submit'])) { include_once 'dbh.php'; $email = mysqli_real_escape_string($conn,$_POST['email']); if(!empty($email)){ $sql="SELECT user_id,user_email FROM users"; $resultat = mysqli_query($conn,$sql); $merrat = mysqli_num_rows($resultat); if($merrat>0) { while($lign=mysqli_fetch_assoc($resultat)) { if($email==$lign['user_email']) { $_SESSION['msg']="The user is in ID number ".$lign['user_id']." "; header('Location: ../admin.php'); exit(); } } }else{ header('Location : ../admin.php? NOT FOUND'); exit(); } }else{ header('Location: ../admin.php?plz enter some email '); exit(); } }else{ header('Location : ../admin.php'); exit(); }<file_sep><?php if(isset($_POST['submit'])) { include_once 'dbh.php'; $_first = mysqli_real_escape_string($conn,$_POST['first']); $_last = mysqli_real_escape_string($conn,$_POST['last']); $_username = mysqli_real_escape_string($conn,$_POST['username']); $_email = mysqli_real_escape_string($conn,$_POST['email']); $_password = mysqli_real_escape_string($conn,$_POST['password']); $_copassword = mysqli_real_escape_string($conn,$_POST['Copassword']); //Error //check for empty fields if(empty($_first) || empty($_last) || empty($_username) || empty($_email) || empty($_password) || empty($_copassword)){ header("Location: ../contact.php?contact=empty"); exit(); }else{ if(!preg_match("/^[a-zA-Z]*$/",$_first) || !preg_match("/^[a-zA-Z]*$/",$_last)) { header("Location: ../contact.php?contact=invalid"); exit(); }else{ //check for the email if(!filter_var($_email,FILTER_VALIDATE_EMAIL)) { header("Location: ../contact.php?sign=email"); }else{ $sql= "SELECT*FROM users WHERE username='$_username';"; $result = mysqli_query($conn,$sql); $resultcheck = mysqli_num_rows($result); if($resultcheck>0) { header("Location: ../contact.php?contact=usertaken"); exit(); }else{ //hashing the password if($_password!==$_copassword) { header("Location: ../contact.php?contact=passwordsnotequal"); exit(); }else{ $hashedPwd = password_hash($_password,PASSWORD_DEFAULT); //insert the user into the database $sql="INSERT INTO users (user_first,user_last,user_email,user_uid,user_pwd) VALUES ('$_first','$_last','$_email','$_username','$hashedPwd');"; mysqli_query($conn,$sql); header("Location: ../contact.php?contact=success"); exit(); } } } } } }else{ header("location: ../.php"); exit(); }<file_sep><?php session_start(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>FEDNI</title> <meta name="description" content="Free Bootstrap Theme by uicookies.com"> <meta name="keywords" content="free website templates, free bootstrap themes, free template, free bootstrap, free website template"> <link href="https://fonts.googleapis.com/css?family=Raleway:300,400,500,700|Open+Sans" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet"> <link rel="stylesheet" href="css/styles-merged.css"> <link rel="stylesheet" href="css/style.min.css"> <link rel="stylesheet" href="css/custom.css"> <!--<link rel="stylesheet" href="css/bootstrap.min.css">--> <!--<link rel="stylesheet" href="css/admin.css">--> <!--[if lt IE 9]> <script src="js/vendor/html5shiv.min.js"></script> <script src="js/vendor/respond.min.js"></script> <![endif]--> </head> <body> <div class="probootstrap-search" id="probootstrap-search"> <a href="#" class="probootstrap-close js-probootstrap-close"><i class="icon-cross"></i></a> <form action="#"> <input type="search" name="s" id="search" placeholder="Search a keyword and hit enter..."> </form> </div> <div class="probootstrap-page-wrapper"> <!-- Fixed navbar --> <div class="probootstrap-header-top"> <div class="container"> <div class="row"> <div class="col-lg-9 col-md-9 col-sm-9 probootstrap-top-quick-contact-info"> <span><i class="icon-location2" style="color: #333;"></i>National Schools of Applied Sciences Of Al Hoceima </span> <span><i class="icon-phone2" style="color: #333;"></i>+212-658206268</span> <span><i class="icon-mail" style="color: #333;"></i><EMAIL></span> </div> <div class="col-lg-3 col-md-3 col-sm-3 probootstrap-top-social"> <ul> <li><a href="#"><i class="icon-twitter" style="color: #00aced"></i></a></li> <li><a href="#"><i class="icon-facebook2" style="color: #3b5998"></i></a></li> <li><a href="#"><i class="icon-instagram2" style="color: #d62976"></i></a></li> <li><a href="#"><i class="icon-youtube" style="color: #FF0000"></i></a></li> <li><a href="#" class="probootstrap-search-icon js-probootstrap-search" style="color: #333"><i class="icon-search"></i></a></li> </ul> </div> </div> </div> </div> <nav class="navbar navbar-default probootstrap-navbar"> <div class="container"> <div class="navbar-header"> <div class="btn-more js-btn-more visible-xs"> <a href="#"><i class="icon-dots-three-vertical "></i></a> </div> <a class="navbar ll" href="home.php" style="font-family: 'Lobster', cursive; font-size: 50px;">FEDNI</a> </div><file_sep><?php include 'header.php'; if(isset($_SESSION['u_id'])) { $rgh='@Rgh'; $zah='@Zah'; $mah='@Mah'; echo ' <div id="navbar-collapse" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="home.php">Home</a></li> <li><a href="courses.php">Courses</a></li> <li><a href="teachers.php">Who are we ?</a></li>'; if($_SESSION['u_uid']==$rgh || $_SESSION['u_uid']==$zah || $_SESSION['u_uid']==$mah){ echo '<li><a href="admin.php">'.$_SESSION['u_first'].'</a></li>'; }else{ echo '<li><a href="user.php">'.$_SESSION['u_first'].'</a></li>'; } echo '<li><form action="includes/logout.inc.php" method="POST"> <div class="just "> <br> <input type="submit" class="btn btn-primary" id="submit" name="submit" value="Logout"> </div> </form></li> </ul> </div> </div> </nav> '; }else{ echo ' <div id="navbar-collapse" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="home.php">Home</a></li> <li><a href="courses.php">Courses</a></li> <li class="active"><a href="teachers.php">Who are we ?</a></li> <li><a href="contact.php">Login</a></li> </ul> </div> </div> </nav> '; } ?> <section class="probootstrap-section probootstrap-section-colored"> <div class="container"> <div class="row"> <div class="col-md-12 text-left section-heading probootstrap-animate"> <center><h1>Who are we ?</h1></center> </div> </div> </div> </section> <section class="probootstrap-section"> <div class="container"> <div class="row"> <div class="col-md-3 col-sm-6"> <div class="probootstrap-teacher text-center probootstrap-animate"> <figure class="media"> <img src="img/person_3.jpg" alt="Free Bootstrap Template by uicookies.com" class="img-responsive"> </figure> <div class="text"> <h3><NAME></h3> <p>Engineer student</p> <ul class="probootstrap-footer-social"> <li class="twitter"><a href="#"><i class="icon-twitter"></i></a></li> <li class="facebook"><a href="#"><i class="icon-facebook2"></i></a></li> <li class="instagram"><a href="#"><i class="icon-instagram2"></i></a></li> <li class="google-plus"><a href="#"><i class="icon-google-plus"></i></a></li> </ul> </div> </div> </div> <div class="col-md-3 col-sm-6"> <div class="probootstrap-teacher text-center probootstrap-animate"> <figure class="media"> <img src="img/person_2.jpg" alt="Free Bootstrap Template by uicookies.com" class="img-responsive"> </figure> <div class="text"> <h3><NAME></h3> <p>Engineer Student</p> <ul class="probootstrap-footer-social"> <li class="twitter"><a href="#"><i class="icon-twitter"></i></a></li> <li class="facebook"><a href="#"><i class="icon-facebook2"></i></a></li> <li class="instagram"><a href="#"><i class="icon-instagram2"></i></a></li> <li class="google-plus"><a href="#"><i class="icon-google-plus"></i></a></li> </ul> </div> </div> </div> <div class="clearfix visible-sm-block visible-xs-block"></div> <div class="col-md-3 col-sm-6"> <div class="probootstrap-teacher text-center probootstrap-animate"> <figure class="media"> <img src="img/Ahmed.jpg" alt="Free Bootstrap Template by uicookies.com" class="img-responsive"> </figure> <div class="text"> <h3><NAME></h3> <p>Engineer Student</p> <ul class="probootstrap-footer-social"> <li class="twitter"><a href="#"><i class="icon-twitter"></i></a></li> <li class="facebook"><a href="#"><i class="icon-facebook2"></i></a></li> <li class="instagram"><a href="#"><i class="icon-instagram2"></i></a></li> <li class="google-plus"><a href="#"><i class="icon-google-plus"></i></a></li> </ul> </div> </div> </div> <div class="col-md-3 col-sm-6"> <div class="probootstrap-teacher text-center probootstrap-animate"> <figure class="media"> <img src="img/person_7.jpg" alt="Free Bootstrap Template by uicookies.com" class="img-responsive"> </figure> <div class="text"> <h3><NAME></h3> <p>Engineer Student</p> <ul class="probootstrap-footer-social"> <li class="twitter"><a href="#"><i class="icon-twitter"></i></a></li> <li class="facebook"><a href="#"><i class="icon-facebook2"></i></a></li> <li class="instagram"><a href="#"><i class="icon-instagram2"></i></a></li> <li class="google-plus"><a href="#"><i class="icon-google-plus"></i></a></li> </ul> </div> </div> </div> </div> </div> </section> <footer class="probootstrap-footer probootstrap-bg"> <div class="container"> <div class="row"> <div class="col-md-4"> <div class="probootstrap-footer-widget"> <h3>About Us</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Porro provident suscipit natus a cupiditate ab minus illum quaerat maxime inventore Ea consequatur consectetur hic provident dolor ab aliquam eveniet alias</p> <h3>Social</h3> <ul class="probootstrap-footer-social"> <li><a href="#"><i class="icon-twitter"></i></a></li> <li><a href="#"><i class="icon-facebook"></i></a></li> <li><a href="#"><i class="icon-github"></i></a></li> <li><a href="#"><i class="icon-dribbble"></i></a></li> <li><a href="#"><i class="icon-linkedin"></i></a></li> <li><a href="#"><i class="icon-youtube"></i></a></li> </ul> </div> </div> <div class="col-md-3 col-md-push-1"> <div class="probootstrap-footer-widget"> <h3>Links</h3> <ul> <li><a href="#">Home</a></li> <li><a href="#">Courses</a></li> <li><a href="#">Teachers</a></li> <li><a href="#">Contact</a></li> </ul> </div> </div> <div class="col-md-4"> <div class="probootstrap-footer-widget"> <h3>Contact Info</h3> <ul class="probootstrap-contact-info"> <li><i class="icon-location2"></i> <span>National Schools of Applied Sciences Of Al Hoceima </span></li> <li><i class="icon-mail"></i><span><EMAIL></span></li> <li><i class="icon-phone2"></i><span>+212-658206268</span></li> </ul> </div> </div> </div> <!-- END row --> </div> <div class="probootstrap-copyright"> <div class="container"> <div class="row"> <div class="col-md-8 text-left"> <p>L'Cours &copy; 2017</p> </div> <div class="col-md-4 probootstrap-back-to-top"> <p><a href="#" class="js-backtotop">Back to top <i class="icon-arrow-long-up"></i></a></p> </div> </div> </div> </div> </footer> </div> <!-- END wrapper --> <script src="js/scripts.min.js"></script> <script src="js/main.min.js"></script> <script src="js/custom.js"></script> </body> </html>
ed45e3243b5494a662e7748646b9d56ffb388c15
[ "Markdown", "SQL", "PHP" ]
15
PHP
AhmedMah53/MOOC
decfdef504c64ae7ee6b2679e4eabdf7df5d5405
4e8dd6f17fce52aab8b0dad60e607c45cea99872
refs/heads/master
<file_sep>import _ from 'lodash'; import jsonPlaceholder from '../apis/jsonPlaceholder'; // Becomes the only action creator we will interact with // Will call fetchPosts and fetchUser for us export const fetchPostsAndUsers = () => async (dispatch, getState) => { await dispatch(fetchPosts()); //redux thunk will pick this up and update reducer _.chain(getState().posts) .map('userId') .uniq() .forEach((id) => dispatch(fetchUser(id))) .value(); }; export const fetchPosts = () => async (dispatch) => { const response = await jsonPlaceholder.get('/posts'); dispatch({ type: 'FETCH_POSTS', payload: response.data }); //returns an {} }; export const fetchUser = (id) => async (dispatch) => { const response = await jsonPlaceholder.get(`/users/${id}`); dispatch({ type: 'FETCH_USER', payload: response.data }); }; // Memoized version // export const fetchUser = (id) => (dispatch) => _fetchUser(id, dispatch); // const _fetchUser = _.memoize(async (id, dispatch) => { // const response = await jsonPlaceholder.get(`/users/${id}`); // dispatch({ type: 'FETCH_USER', payload: response.data }); // }); <file_sep># General Data Loading with Redux from outside API ## Components are generally responsible for fetching data they need by calling an action creator ### Component gets rendered onto the screen PostList components needs to get a list of posts from the API ### Component's 'componentDidMount' lifecycle method gets called Access to lifecycle methods ### We call action creator from 'componentDidMount' Any time PostList is rendered, action creator is automatically called ## Action creators are reponsible for making API requests (This is where Redux-Thunk is used) ### Action creator runs code to make an API request Axios is used to make the request ### API respondes with data Responds with list of blog posts ### Action creator returns an 'action' with the fetched data on the 'payload' property Action creator returns an action object, dispatch method sends info to all reducers ## We get fetched data into a component by generating new state in our redux store, then getting that into our component through mapStateToProps ### Some reducer sees the action, returns the data off the 'payload' Reducer watching for the type given to the action ### Because we generated some new state object, redux/react-redux cause our React app to be rerendered State changes so app rerenders ## Middleware in Redux Function that gets called with every action we dispatch Has the ability to STOP, MODIFY, or otherwise change actions Tons of open source middleware exist Most popular use of middleware is for dealing with async actions We using Redux-Thunk to solve our async issues ## Rules of Reducers Must return any value besides 'undefined' Produces 'state', or data to be used inside of your app using only previous state and the action (reducers are pure) Must not return reach 'out of itself' to decide what value to return Must not mutate its input 'state' argument
2cb1a56105fa631860e5ed46902860b2f5adfa53
[ "JavaScript", "Markdown" ]
2
JavaScript
ernie-ramos/blog
48e796af8ad2e341ff449f96f98c371fe9ee08b3
f8905317d8a6cfe2034a62e58abe11b02b49b3ec
refs/heads/master
<file_sep>// // ViewController.swift // JsonNoAPITest // // Created by <NAME> on 2015/12/08. // Copyright © 2015年 shitakemura. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class ViewController: UIViewController { @IBOutlet weak var textField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func ButtonClicked(sender: UIButton) { switch sender.tag { case 0: // JSON受信(APIなし) getJsonWithoutAPI() case 1: // JSON受信(APIあり) getJsonWithAPI() default: break } } func getJsonWithoutAPI() { let url = NSURL(string: "http://moonmile.net/ios9/persons.json") let req = NSURLRequest(URL: url!) let task = NSURLSession.sharedSession().dataTaskWithRequest(req, completionHandler: { ( data, res, err ) in if data != nil { dispatch_async(dispatch_get_main_queue(), { do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) print(json) for var i = 0; i < json.count; i++ { let item = (json as! NSArray)[i] let name = item["name"] as! String let age = item["age"] as! Int let addr = item["address"] as! String print("name: \(name) age: \(age) address: \(addr)") // self.textField.text = self.textField.text! + "\(name) \(age) \(addr)\n" } } catch { self.textField.text = "parse error" } }) } else { dispatch_async(dispatch_get_main_queue(), { self.textField.text = "error" }) } }) task.resume() } func getJsonWithAPI() { Alamofire.request(.GET, "http://moonmile.net/ios9/persons.json").responseJSON { response in print(response.result.value) guard let object = response.result.value else { return } let json = JSON(object) json.forEach { (_, json) in print(json["name"].string) print(json["age"].int) print(json["address"].string) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
dff70a26cc481cb4c57bae6606503974384242ef
[ "Swift" ]
1
Swift
shitakemura/JsonWithNoAPITest
e3a13f6df6b23b6c96ce3850bd527b24068126de
3bea9e6dee06ac13ab986150acfe0bd3b8fd698f
refs/heads/main
<file_sep>``` brew install ctags ln -s Code/shared/dotfiles/git/.git* ~ git init ``` <file_sep># This is how I do stuff This is a semi-complete collection of my configuration files and tools. ### First things first - [Install homebrew](https://brew.sh/) - `brew bundle install` - Run `install.sh` to symlink these configs to their various appropriate locations ### Setting up a new daily driver: - Firefox - Rectangle - Kitty - 1Password - Dropbox <file_sep>tap "homebrew/bundle" tap "homebrew/cask" tap "homebrew/cask-fonts" tap "homebrew/core" tap "homebrew/services" tap "mongodb/brew" tap "puma/puma" brew "python@3.9" brew "circleci" brew "cmake" brew "elasticsearch", restart_service: true brew "exif" brew "fish" brew "fzf" brew "geckodriver" brew "gh" brew "ghostscript" brew "gifsicle" brew "git" brew "git-lfs" brew "graphviz" brew "libheif" brew "imagemagick" brew "moreutils" brew "neovim" brew "node" brew "pipx" brew "r" brew "ruby-build" brew "rbenv" brew "redis", restart_service: true brew "ripgrep" brew "the_silver_searcher" brew "xsv" brew "zeromq" brew "mongodb/brew/mongodb-database-tools" brew "puma/puma/puma-dev" cask "chromedriver" cask "font-hack-nerd-font" cask "phantomjs" <file_sep>#!/bin/sh # Record the location of this repo. config_location=`pwd` echo $config_location # Links ln -sviw "$config_location/.profile" ~/.profile ln -sviw "$config_location/.profile" ~/.zprofile ln -sviwh "$config_location/vim/" ~/.vim ln -sviw "$config_location/.agignore" ~/.agignore ln -sviwh $config_location/git/.git{_template,config,ignore} ~ mkdir -p ~/.config ln -sviwh "$config_location/karabiner/" ~/.config/karabiner ln -sviwh "$config_location/fish/" ~/.config/fish ln -sviwh "$config_location/nvim/" ~/.config/nvim <file_sep>### To install ``` git clone <EMAIL>:vim/vim.git cd vim ./configure --with-features=huge \ --enable-multibyte \ --enable-rubyinterp \ --enable-python3interp \ --enable-perlinterp make make install git clone this repo ln -s dotfiles/vim ~/.vim git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim brew install fzf brew install ripgrep vim +PluginInstall +qall npm install -g typescript ~/.vim/bundle/YouCompleteMe/install.py ``` This should be turned into a proper script.
dde89ec7897305b4369223f047df8ecc1e00b0a6
[ "Markdown", "Ruby", "Shell" ]
5
Markdown
GabeIsman/dotfiles
db8be9b752af30ef16fb8eba66442d56dd0a76c4
e1252f4e5a6c429ad345753439d747cc892fe099
refs/heads/master
<file_sep><?php namespace Home\Controller; use Think\Controller; use Vendor\PHPExcel; class IndexController extends Controller { protected function checkRole($token) { $user = S($token); if ($user && isset($user['type_id'])) { return; } E(''); } public function index() { redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . C('WX_CROPID') . '&redirect_uri=' . urlencode('http://lmpx.staeco.cn:8080/StaecoTS/index.php?c=LoginRest&a=userLoginByWxCode') . '&response_type=code&scope=snsapi_userinfo&agentid=' . C('WX_AGENTID') . '&state=#wechat_redirect'); } public function exportUser($token) { $this->checkRole($token); $user = fillUserTags(M('user')->select()); Vendor('PHPExcel.PHPExcel'); $doc = new \PHPExcel(); $worksheet = $doc->getActiveSheet(); $worksheet->setCellValue('A1', '账户'); $worksheet->setCellValue('B1', '姓名'); $worksheet->setCellValue('C1', '性别'); $worksheet->setCellValue('D1', '手机'); $worksheet->setCellValue('E1', '邮箱'); $worksheet->setCellValue('F1', '日期'); $worksheet->setCellValue('G1', '标签'); for ($row = 2; $row < count($user) + 2; $row++) { $i = $row - 2; $userData = json_decode($user[$i]['data']); $worksheet->setCellValueByColumnAndRow(0, $row, $user[$i]['username']); $worksheet->setCellValueByColumnAndRow(1, $row, $userData->name); $worksheet->setCellValueByColumnAndRow(2, $row, $userData->gender == '0' ? '' : ($userData->gender == '1' ? '男' : '女')); $worksheet->setCellValueByColumnAndRow(3, $row, $userData->mobile); $worksheet->setCellValueByColumnAndRow(4, $row, $userData->email); $worksheet->setCellValueByColumnAndRow(5, $row, $user[$i]['create_date']); $worksheet->setCellValueByColumnAndRow(6, $row, implode(',', $user[$i]['usertags'])); } $writer = \PHPExcel_IOFactory::createWriter($doc, 'Excel5'); header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment; filename="用户-' . date('YmdHis') . '.xls"'); header('Cache-Control: max-age=0'); $writer->save('php://output'); } public function exportTaskDetailByArticleId($token, $articleId) { $this->checkRole($token); $db = M('task'); $task = $db->getTableName(); $data = M('article')->where(array('id' => $articleId))->select()[0]; $test = M('test'); $data['totalSize'] = $test->where(array('article_id' => $articleId))->count(); $data['totalMark'] = $test->where(array('article_id' => $articleId))->field(array('sum(mark)' => 'total_mark'))->select()[0]['total_mark']; $user = M('user')->getTableName(); $data['task'] = $db->join('LEFT JOIN ' . $user . ' ON ' . $task . '.user_id = ' . $user . '.id')->field(array( $task . '.status' => 'status', $task . '.data' => 'data', $user . '.username' => 'username', $user . '.data' => 'user' ))->where(array($task . '.article_id' => $articleId))->select(); Vendor('PHPExcel.PHPExcel'); $doc = new \PHPExcel(); $worksheet = $doc->getActiveSheet(); $worksheet->setCellValue('A1', '标题'); $worksheet->setCellValue('B1', $data['title']); if ($data['type_id'] == 2) { $worksheet->setCellValue('A2', '总分'); $worksheet->setCellValue('A3', '题目'); $worksheet->setCellValue('B2', $data['totalMark']); $worksheet->setCellValue('B3', $data['totalSize']); } $worksheet->setCellValue('A5', '账户'); $worksheet->setCellValue('B5', '姓名'); $worksheet->setCellValue('C5', '性别'); $worksheet->setCellValue('D5', '手机'); $worksheet->setCellValue('E5', '邮箱'); $worksheet->setCellValue('F5', '状态'); if ($data['type_id'] == 2) { $worksheet->setCellValue('G5', '得分'); } for ($row = 6; $row < count($data['task']) + 6; $row++) { $i = $row - 6; $user = json_decode($data['task'][$i]['user']); $taskData = json_decode($data['task'][$i]['data']); $worksheet->setCellValueByColumnAndRow(0, $row, $data['task'][$i]['username']); $worksheet->setCellValueByColumnAndRow(1, $row, $user->name); $worksheet->setCellValueByColumnAndRow(2, $row, $user->gender == '0' ? '' : ($user->gender == '1' ? '男' : '女')); $worksheet->setCellValueByColumnAndRow(3, $row, $user->mobile); $worksheet->setCellValueByColumnAndRow(4, $row, $user->email); $worksheet->setCellValueByColumnAndRow(5, $row, $data['task'][$i]['status'] == '1' ? '√' : '×'); if ($data['task'][$i]['status'] == '1' && $data['type_id'] == 2) { $worksheet->setCellValueByColumnAndRow(6, $row, $taskData->mark); } } $writer = \PHPExcel_IOFactory::createWriter($doc, 'Excel5'); header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment; filename="任务-' . date('YmdHis') . '.xls"'); header('Cache-Control: max-age=0'); $writer->save('php://output'); } public function startUpgradeFromGithub() { echo shell_exec("/usr/bin/git pull 2>&1"); } } <file_sep><?php namespace Api\Controller; use Think\Controller\RestController; use Think\Upload; use Vendor\PHPExcel; /** * 不删除题库文件 * * */ class TestRestController extends RestController { public function index($article_id, $title = '', $page = 0, $pageSize = 10) { $condition = array( 'article_id' => $article_id, 'title' => array('like', '%' . $title . '%') ); $test = M('test'); $this->response(O(true, 0, array( 'totalSize' => $test->where($condition)->count(), 'content' => $test->where($condition)->order('id')->limit($page * $pageSize, $pageSize)->select() )), 'json'); } public function add() { $upload = new Upload(); $upload->rootPath = './Uploads/'; $upload->exts = array('xls', 'xlsx'); $result = $upload->upload(); if ($result) { $file = $result['file']; $path = $upload->rootPath . $file['savepath'] . $file['savename']; Vendor('PHPExcel.PHPExcel'); $reader = \PHPExcel_IOFactory::load($path); $worksheet = $reader->getActiveSheet(); $articleId = M('article')->add(array( 'type_id' => 2, 'title' => $worksheet->getCell('B1')->getValue(), 'content' => $worksheet->getCell('B2')->getValue(), 'create_date' => date('Y-m-d H:i:s'), 'create_superuser_id' => S(I('param.token'))['id'] )); $highestRow = $worksheet->getHighestRow(); $test = M('test'); $test->startTrans(); for ($row = 5; $row <= $highestRow; $row++) { $data = array('article_id' => $articleId, 'type' => $worksheet->getCellByColumnAndRow(0, $row)->getValue(), 'no' => $row - 4, 'mark' => $worksheet->getCellByColumnAndRow(1, $row)->getValue(), 'title' => $worksheet->getCellByColumnAndRow(2, $row)->getValue(), 'content' => $worksheet->getCellByColumnAndRow(3, $row)->getValue(), 'image_url' => $worksheet->getCellByColumnAndRow(4, $row)->getValue(), 'right_answer' => $worksheet->getCellByColumnAndRow(5, $row)->getValue()); $data['type_id'] = array('单选题' => 0, '多选题' => 1, '判断题' => 2)[$data['type']]; $test->add($data); } $test->commit(); $this->response(O(), 'json'); } $this->response(O(false, -2), 'json'); } // public function deleteById($id) { // M('test')->delete($id); // $this->response(O(), 'json'); // } }<file_sep><?php namespace Api\Controller; use Think\Controller\RestController; use Think\Upload; class AttachmentRestController extends RestController { protected $_model; public function __construct() { $this->_model = M('attachment'); parent::__construct(); } protected function saveFile($exts = array()) { $upload = new Upload(); $upload->rootPath = './Uploads/'; if (!empty($exts)) { $upload->exts = $exts; } if ($result = $upload->upload()) { return $result['file']; } return false; } public function getPage($name = '', $page = 0, $pageSize = 10) { $condition = array( 'name' => array('like', '%'. $name . '%'), ); $this->response(O(true, 0, array( 'totalSize' => $this->_model->where($condition)->count(), 'content' => $this->_model->where($condition)->limit($page * $pageSize, $pageSize)->select() )), 'json'); } public function index($article_id) { $this->response(O(true, 0, array( 'content' => $this->_model->where(array('article_id' => $article_id))->select() )), 'json'); } public function add() { $file = $this->saveFile(array('jpg', 'gif', 'png', 'jpeg')); if ($file) { $this->response(O(true, 0, array( 'url' => __ROOT__ . '/Uploads/' . $file['savepath'] . $file['savename'] )), 'json'); } $this->response(O(false, -2), 'json'); } public function addByArticleId($article_id) { $file = $this->saveFile(); if ($file) { $this->_model->add(array( 'article_id' => $article_id, 'url' => __ROOT__ . '/Uploads/' . $file['savepath'] . $file['savename'], 'name' => $file['name'] )); $this->response(O(), 'json'); } $this->response(O(false, -2), 'json'); } public function deleteById($id) { $attachment = $this->_model; unlink('..' . $attachment->select($id)[0]['url']); $attachment->delete($id); $this->response(O(), 'json'); } }<file_sep><?php namespace Api\Model; use Think\Model; class UserTagModel extends Model { protected $_validate = array( array('name', 'require', '', self::MUST_VALIDATE, 'unique'), ); }<file_sep><?php namespace Api\Controller; use Think\Controller\RestController; use Api\Model\ArticleModel; /** * 需要验证 token * * */ class ArticleRestController extends RestController { protected $_model; public function __construct() { $this->_model = new ArticleModel(); parent::__construct(); } public function index($type_id, $title = '', $page = 0, $pageSize = 10) { $this->response(O(true, 0, array( 'totalSize' => $this->_model->where(array( 'type_id' => $type_id, 'title' => array('like', '%' . $title . '%') ))->count(), 'content' => $this->_model->getPageByCondition($type_id, $title, $page, $pageSize) )), 'json'); } /** * content 不使用 htmlspecialchars 过滤器 * * */ public function add() { $user = S(I('param.token')); if ($this->_model->create(array_merge(I('param.'), array( 'create_date' => date('Y-m-d H:i:s'), 'content' => I('param.content', '', ''), 'create_superuser_id' => $user['id'] )))) { $this->_model->add(); $this->response(O(), 'json'); } $this->response(O(false, -2), 'json'); } public function updateById($id) { if ($this->_model->create(array_merge(I('param.'), array( 'create_date' => date('Y-m-d H:i:s'), 'content' => I('param.content', '', '') )))) { $this->_model->save(); $this->response(O(), 'json'); } $this->response(O(false, -2), 'json'); } public function deleteById($id) { $this->_model->delete($id); $condition = array('article_id' => $id); M('task')->where($condition)->delete(); M('tasktimer')->where($condition)->delete(); M('test')->where($condition)->delete(); $this->response(O(), 'json'); } }<file_sep><?php namespace UserApi\Behavior; class UserAccessBehavior extends \Think\Behavior { public function run(&$param) { $user = S(I('post.token')); if ($user && !array_key_exists('type_id', $user)) { return ; } E(''); } }<file_sep>import { finish } from '@/api' const task = { state: { handle: undefined }, mutations: { SET_HANDLE: (state, handle) => { state.handle = handle } }, actions: { SetTiming({ commit, state }, start = true ) { return new Promise((resolve, reject) => { if (state.handle) { clearInterval(state.handle) } commit('SET_HANDLE', start ? setInterval(() => { finish().then(response => { const data = response.data.data if (data) { if (data.status == '1') { clearInterval(state.handle) commit('SET_HANDLE', undefined) } } }).catch(error => { commit('SET_HANDLE', undefined) }) }, 60000) : undefined) resolve() }) } } } export default task<file_sep><?php namespace Api\Controller; use Think\Controller\RestController; use Api\Model\UserTagModel; class UserTagRestController extends RestController { protected $_model; public function __construct() { $this->_model = new UserTagModel('usertag'); parent::__construct(); } public function index($name = '', $page = 0, $pageSize = PHP_INT_MAX) { $condition = array('name' => array('like', '%'. $name . '%')); $this->response(O(true, 0, array( 'totalSize' => $this->_model->where($condition)->count(), 'content' => $this->_model->where($condition)->limit($page * $pageSize, $pageSize)->select() )), 'json'); } public function add() { if ($this->_model->create()) { $this->_model->add(); $this->response(O(), 'json'); } $this->response(O(false, -2), 'json'); } public function updateById($id) { if ($this->_model->create()) { $this->_model->save(); $this->response(O(), 'json'); } $this->response(O(false, -2), 'json'); } public function deleteById($id) { $this->_model->delete($id); $this->response(O(), 'json'); } }<file_sep>import Vue from 'vue' import Vuex from 'vuex' import user from './modules/user' import userEditor from './modules/user-editor' import articleEditor from './modules/article-editor' Vue.use(Vuex) const getters = { token: state => state.user.token, username: state => state.user.username } const store = new Vuex.Store({ modules: { user, userEditor, articleEditor }, getters }) export default store<file_sep><?php return array( 'action_begin' => array('UserApi\\Behavior\\UserAccessBehavior') );<file_sep><?php namespace UserApi\Controller; use Think\Controller\RestController; class TaskDataProviderRestController extends RestController { protected function mergeTime($articleId, $userId, $lasts = NULL) { $taskTimer = M('tasktimer'); $condition = array( 'article_id' => $articleId, 'user_id' => $userId ); if ($lasts == NULL) { $lasts = $taskTimer->where($condition)->sum('lasts'); } $taskTimer->where($condition)->delete(); $taskTimer->add(array_merge(array( 'lasts' => $lasts, 'create_date' => date('Y-m-d H:i:s') ), $condition)); } protected function validate($articleId, $userId, $date) { $task = M('task')->where(array( 'article_id' => $articleId, 'user_id' => $userId ))->select()[0]; if (!$task['status']) { if (TaskDataProviderRestController::validateTime($task, $date)) { return $task; } } return false; } protected function updateAccessTime() { $token = I('post.token'); $user = S($token); $date = date('Y-m-d H:i:s'); $task = $this->validate($articleId = I('param.article_id', array_key_exists('reader_article_id', $user) ? $user['reader_article_id'] : ''), $user['id'], $date); if (is_array($task)) { $user['reader_article_id'] = $articleId; $user['create_date'] = $date; S($token, $user); return $task; } return false; } protected function saveAccessTime() { $user = S(I('post.token')); $userId = $user['id']; $articleId = $user['reader_article_id']; $createDate = $user['create_date']; $date = date('Y-m-d H:i:s'); if (isset($articleId) && isset($createDate)) { $task = $this->validate($articleId, $userId, $date); if (is_array($task)) { $taskTimer = M('tasktimer'); $taskTimer->add(array( 'article_id' => $articleId, 'user_id' => $userId, 'lasts' => strtotime($date) - strtotime($createDate), 'create_date' => $date )); $lasts = $taskTimer->where(array( 'article_id' => $articleId, 'user_id' => $userId ))->sum('lasts'); if (!$task['lasts'] || $lasts >= $task['lasts']) { $task['status'] = 1; $this->mergeTime($articleId, $userId, $lasts); M('task')->save($task); } return $task; } } return false; } protected function getContent($articleId, $task = false) { $article = M('article')->select($articleId)[0]; if (!$task) { $task = M('task')->where(array( 'article_id' => $articleId, 'user_id' => S(I('post.token'))['id'] ))->select()[0]; } $createSuperUser = M('superuser')->select($data['create_superuser_id'])[0]; return array_merge($article, array( 'createSuperUser' => $createSuperUser['username'], 'task' => array_merge($task, array('availability' => TaskDataProviderRestController::validateTime($task, date('Y-m-d H:i:s')))), 'lasts' => M('tasktimer')->where(array('article_id' => $articleId, 'user_id' => $task['user_id']))->sum('lasts'), 'attachment' => M('attachment')->where(array('article_id' => $articleId))->select() )); } public function getArticleById($article_id) { $this->response(O(true, 0, $this->getContent($article_id, $this->updateAccessTime())), 'json'); } public function finish() { $task = $this->saveAccessTime(); $this->updateAccessTime(); if (is_array($task)) { $this->response(O(true, 0, $task), 'json'); } $this->response(O(false, -2), 'json'); } public function getTestByArticleId($article_id) { $article = $this->getContent($article_id); $test = M('test'); $article['totalSize'] = $test->where(array('article_id' => $article_id))->count(); $article['totalMark'] = $test->where(array('article_id' => $article_id))->field(array('sum(mark)' => 'total_mark'))->select()[0]['total_mark']; $this->response(O(true, 0, $article), 'json'); } public function getQuestionByArticleIdAndNo($article_id, $no) { $this->updateAccessTime(); $test = M('test')->where(array('article_id' => $article_id, 'no' => $no))->select()[0]; unset($test['right_answer']); $this->response(O(true, 0, $test), 'json'); } public function getRightAnswer($article_id, $no, $finish) { $test = M('test')->where(array('article_id' => $article_id, 'no' => $no))->select()[0]; $task = $this->saveAccessTime(); if (is_array($task)) { $userId = $task['user_id']; $start = 1; $mark = 0; $data = json_decode($task['data']); if ($data) { $start = $data->start; $mark = $data->mark; } if ($start == $no) { $start++; if ($r = I('post.answer') == $test['right_answer']) { $mark += $test['mark']; } M('testmetadata')->add(array( 'article_id' => $article_id, 'user_id' => $userId, 'no' => $no, 'status' => $r, 'create_date' => date('Y-m-d H:i:s') )); $task['data'] = json_encode(array('start' => $start, 'mark' => $mark)); if ($finish != 'false') { $task['status'] = 1; $this->mergeTime($article_id, $userId); } M('task')->save($task); } else { $this->response(O(false, -2), 'json'); } } $this->response(O(true, 0, array('right_answer' => $test['right_answer'])), 'json'); } public static function validateTime($task, $date) { $now = strtotime($date); if (strtotime($task['from']) <= $now) { $to = $task['to']; if (!isset($to) || $now <= strtotime($to)) { return true; } } return false; } }<file_sep>import request from '@/utils/request' export function superUserLogin(username, password) { return request.post('/index.php?m=Home&c=LoginRest&a=superUserLogin', { username, password }) } export function logout() { return request.post('/index.php?m=Home&c=LoginRest&a=logout') } export function updateUser(username, password) { return request.post('/index.php?m=Api&c=SuperUserRest&a=update', { username, password }) } export function getArticlePage(typeId, title, page, pageSize) { return request.post('/index.php?m=Api&c=ArticleRest', { type_id: typeId, title, page, pageSize }) } export function addArticle(typeId, title, content) { return request.post('/index.php?m=Api&c=ArticleRest&a=add', { type_id: typeId, title, content }) } export function updateArticleById(id, title, content) { return request.post('/index.php?m=Api&c=ArticleRest&a=updateById', { id, title, content }) } export function deleteArticleById(id) { return request.post('/index.php?m=Api&c=ArticleRest&a=deleteById', { id }) } export function getUserGroupByParentId(parentId) { return request.post('/index.php?m=Api&c=UserGroupRest', { parent_id: parentId }) } export function addUserGroup(parentId, name) { return request.post('/index.php?m=Api&c=UserGroupRest&a=add', { parent_id: parentId, name }) } export function deleteUserGroupById(id) { return request.post('/index.php?m=Api&c=UserGroupRest&a=deleteById', { id }) } export function getUserPage(username/*, userGroupId*/, userTagIds, page, pageSize) { return request.post('/index.php?m=Api&c=UserRest', { username, // usergroup_id: userGroupId usertag_ids: userTagIds, page, pageSize }) } // export function addUser(username, password, userGroupId) { // return request.post('/index.php?m=Api&c=UserRest&a=add', { username, password, usergroup_id: userGroupId }) // } export function updateUserById(id, username, password/*, userGroupId*/, userTagIds) { return request.post('/index.php?m=Api&c=UserRest&a=updateById', { id, username, password, // usergroup_id: userGroupId usertag_ids: userTagIds }) } // export function deleteUserById(id) { // return request.post('/index.php?m=Api&c=UserRest&a=deleteById', { id }) // } export function getTaskPage(articleId, page, pageSize) { return request.post('/index.php?m=Api&c=TaskRest', { article_id: articleId, page, pageSize }) } export function addTaskByUserTagIdsAndUserIds(articleId, userTagIds, userIds, from, to, typeId, lasts) { return request.post('/index.php?m=Api&c=TaskRest&a=add', { article_id: articleId, usertag_ids: userTagIds, user_ids: userIds, from, to, type_id: typeId, lasts }) } export function updateTask(articleId, userId, from, to, typeId, lasts) { return request.post('/index.php?m=Api&c=TaskRest&a=updateByArticleIdAndUserId', { article_id: articleId, user_id: userId, from, to, type_id: typeId, lasts }) } export function deleteTaskByArticleIdAndUserId(articleId, userId) { return request.post('/index.php?m=Api&c=TaskRest&a=deleteByArticleIdAndUserId', { article_id: articleId, user_id: userId }) } export function getAttachmentPage(name, page, pageSize) { return request.post('/index.php?m=Api&c=AttachmentRest&a=getPage', { name, page, pageSize }) } export function getAttachmentByArticleId(articleId) { return request.post('/index.php?m=Api&c=AttachmentRest', { article_id: articleId }) } export function addAttachment(file) { var formData = new FormData() formData.append('file', file) return request.post('/index.php?m=Api&c=AttachmentRest&a=add', formData, { headers:{'Content-Type':'multipart/form-data'} }) } export function deleteAttachmentById(id) { return request.post('/index.php?m=Api&c=AttachmentRest&a=deleteById', { id }) } export function getTestPage(articleId, title, page, pageSize) { return request.post('/index.php?m=Api&c=TestRest', { article_id: articleId, title, page, pageSize }) } // export function deleteTestById(id) { // return request.post('/index.php?m=Api&c=TestRest&a=deleteById', { id }) // } export function getUserTagPage(name, page = '', pageSize = '') { return request.post('/index.php?m=Api&c=UserTagRest', { name, page, pageSize }) } export function addUserTag(name) { return request.post('/index.php?m=Api&c=UserTagRest&a=add', { name }) } export function updateUserTagById(id, name) { return request.post('/index.php?m=Api&c=UserTagRest&a=updateById', { id, name }) } export function deleteUserTagById(id) { return request.post('/index.php?m=Api&c=UserTagRest&a=deleteById', { id }) } export function getTestMetaData(articleId, userId, page, pageSize) { return request.post('/index.php?m=Api&c=TestMetaDataRest', { article_id: articleId, user_id: userId, page, pageSize }) } export function getData(page, pageSize) { return request.post('/index.php?m=Api&c=DataRest', { page, pageSize }) } export function addData() { return request.post('/index.php?m=Api&c=DataRest&a=add') } export function deleteDataByTime(time) { return request.post('/index.php?m=Api&c=DataRest&a=deleteByTime', { time }) }<file_sep>import Cookies from 'js-cookie' import { userLogin, getUserDetail, logout } from '@/api' let login = (commit, resolve) => response => { const data = response.data.data if (data) { let token = data.token Cookies.set('x-token', token) commit('SET_TOKEN', token) commit('SET_USERNAME', data.username) commit('SET_DATA', data.data) resolve() } } const user = { state: { token: '', username: '', data: '' }, mutations: { SET_TOKEN: (state, token) => { state.token = token }, SET_USERNAME: (state, username) => { state.username = username }, SET_DATA: (state, data) => { state.data = JSON.parse(data) }, }, actions: { LoginByToken({ commit }, token) { return new Promise((resolve, reject) => { getUserDetail(token).then(login(commit, resolve)).catch(error => { reject(error) }) }) }, LoginByUsernameAndPassword({ commit }, user) { const username = user.username.trim() return new Promise((resolve, reject) => { userLogin(username, user.password).then(login(commit, resolve)).catch(error => { reject(error) }) }) }, Logout({ commit, state }) { return new Promise((resolve, reject) => { logout(state.token).then(() => { commit('SET_TOKEN', '') Cookies.remove('x-token') resolve() }).catch(error => { reject(error) }) }) } } } export default user<file_sep><?php namespace Api\Controller; use Think\Controller\RestController; use Api\Model\TaskModel; /** * 没有考虑时间范围而直接发送通知 * * * */ class TaskRestController extends RestController { protected $_model; protected function notifyUser($userIdList) { list($headers, $body) = explode("\r\n\r\n", doRequest('https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' . C('WX_CROPID') . '&corpsecret=' . C('WX_CROPSECRET')), 2); if ($accessToken = json_decode($body)->access_token) { doRequest('https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' . $accessToken, '{"touser": "' . implode('|', M('user')->where(array('id' => array('in', $userIdList)))->getField('username', true)) . '", "msgtype": "text", "agentid": ' . C('WX_AGENTID') . ', "text": {"content": "有新任务。"}}'); } } public function __construct() { $this->_model = new TaskModel(); parent::__construct(); } public function index($article_id, $page = 0, $pageSize = 10) { $this->response(O(true, 0, array( 'totalSize' => $this->_model->where(array( 'article_id' => $article_id ))->count(), 'content' => $this->_model->getPageByCondition($article_id, $page, $pageSize) )), 'json'); } public function add($article_id, $usertag_ids = NULL, $user_ids = '') { if ($this->_model->create(array_merge(I('param.'), array( 'create_date' => date('Y-m-d H:i:s'), 'status' => 0 )))) { $userIds = array(); if ($user_ids) { $this->_model->addByArticleIdAndUserIds($article_id, $userIds = explode(',', $user_ids)); } $this->notifyUser(array_merge($userIds, $usertag_ids ? $this->_model->addByArticleIdAndUserTagIds($article_id, $usertag_ids) : array())); $this->response(O(), 'json'); } $this->response(O(false, -2), 'json'); } public function updateByArticleIdAndUserId($article_id, $user_id) { if ($this->_model->create(array_merge(I('param.'), array( 'create_date' => date('Y-m-d H:i:s'), 'status' => 0 )))) { $this->_model->deleteWithTaskTimer($article_id, $user_id); M('testmetadata')->where(array('article_id' => $article_id, 'user_id' => $user_id))->delete(); $this->_model->add(); $this->notifyUser(array($user_id)); $this->response(O(), 'json'); } $this->response(O(false, -2), 'json'); } public function deleteByArticleIdAndUserId($article_id, $user_id) { $this->_model->deleteWithTaskTimer($article_id, $user_id); $this->response(O(), 'json'); } }<file_sep># 想不到吧 ![](https://raw.githubusercontent.com/zyCwind/StaecoTS/master/Ref/screenshot.png)<file_sep>const userEditor = { state: { id: '', username: '', password: '', // userGroupId: '', userTagIds: '', showDialog: false } } export default userEditor<file_sep><?php return array( 'action_begin' => array('Api\\Behavior\\AccessBehavior') );<file_sep>import Vue from 'vue' import Router from 'vue-router' import NProgress from 'nprogress' import 'nprogress/nprogress.css' import store from './store' import routes from './router-routes' import Cookies from 'js-cookie' Vue.use(Router) const router = new Router({ routes }) NProgress.configure({ showSpinner: false }) const whiteList = ['/login'] router.beforeEach((to, from, next) => { NProgress.start() let token = store.getters.token || Cookies.get('x-token') if (token && !store.getters.username) { store.dispatch('LoginByToken', token).then(() => { if (to.path == '/login') { next('/') NProgress.done() } else { next() } }) } else if (token) { if (to.path == '/login') { next('/') NProgress.done() } else { if (store.getters.handle) { store.dispatch('SetTiming', false) } next() } } else { if (whiteList.indexOf(to.path) !== -1) { next() } else { next('/login') NProgress.done() } } }) router.afterEach(() => { NProgress.done() }) export default router<file_sep><?php namespace Api\Model; use Think\Model; class ArticleModel extends Model { protected $_validate = array( array('title', 'require'), array('type_id', array(0, 1, 2, 3), '', self::MUST_VALIDATE, 'in') ); public function getPageByCondition($typeId, $title, $page, $pageSize) { $article = $this->getTableName(); $superUser = M('superuser')->getTableName(); return $this->join('LEFT JOIN ' . $superUser . ' ON ' . $article . '.create_superuser_id = ' . $superUser . '.id')->field(array( $article . '.id' => 'id', $article . '.title' => 'title', $article . '.content' => 'content', $article . '.create_date' => 'create_date', $superUser . '.username' => 'create_superuser' ))->where(array( $article . '.type_id' => $typeId, $article . '.title' => array('like', '%' . $title . '%') ))->order($article . '.create_date desc')->limit($page * $pageSize, $pageSize)->select(); } }<file_sep><?php namespace UserApi\Controller; use Think\Controller\RestController; use UserApi\Model\TodoModel; class TodoRestController extends RestController { protected $_model; public function __construct() { $this->_model = new TodoModel('task'); parent::__construct(); } public function index($article_type_id, $page = 0, $pageSize = 10) { $userId = S(I('post.token'))['id']; $now = date('Y-m-d H:i:s'); $content = $this->_model->getPageByArticleTypeId($article_type_id, $userId, $now, $page, $pageSize); foreach ($content as $k => $v) { $content[$k]['availability'] = TaskDataProviderRestController::validateTime($v, $now); } $this->response(O(true, 0, array('totalSize' => $this->_model->countByArticleTypeId($article_type_id, $userId, $now), 'content' => $content)), 'json'); } public function count() { $this->response(O(true, 0, $this->_model->countGroupByArticleTypeId(S(I('post.token'))['id'], date('Y-m-d H:i:s'))), 'json'); } }<file_sep><?php function O($isSuccess = true, $code = 0, $data) { $responseBody = array( 'success' => $isSuccess, 'code' => $code ); if (!empty($data)) { $responseBody['data'] = $data; } return $responseBody; } function fillUserTags($userData) { $userTag = M('usertag')->select(); for ($i = 0; $i < count($userData); $i++) { $userData[$i]['usertags'] = array(); foreach(explode('|', $userData[$i]['usertag_ids']) as $v) { if ($v) { for ($j = 0; $j < count($userTag); $j++) { if ($v == $userTag[$j]['id']) { array_push($userData[$i]['usertags'], $userTag[$j]['name']); break; } } } } } return $userData; } function doRequest($url, $params = '') { $ch = curl_init($url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 1); if (!empty($params)) { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); } $result = curl_exec($ch); curl_close($ch); return $result; }<file_sep>/* Navicat MySQL Data Transfer Source Server : 172.16.58.3 Source Server Version : 50173 Source Host : 172.16.58.3:3306 Source Database : staeco_ts Target Server Type : MYSQL Target Server Version : 50173 File Encoding : 65001 Date: 2018-06-14 13:53:57 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for think_article -- ---------------------------- DROP TABLE IF EXISTS `think_article`; CREATE TABLE `think_article` ( `id` int(11) NOT NULL AUTO_INCREMENT, `type_id` int(11) NOT NULL, `title` varchar(255) COLLATE utf8_bin NOT NULL, `content` text COLLATE utf8_bin, `create_superuser_id` int(11) NOT NULL, `create_date` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=121 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- ---------------------------- -- Table structure for think_attachment -- ---------------------------- DROP TABLE IF EXISTS `think_attachment`; CREATE TABLE `think_attachment` ( `id` int(11) NOT NULL AUTO_INCREMENT, `article_id` int(11) NOT NULL, `url` varchar(255) COLLATE utf8_bin NOT NULL, `name` varchar(255) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=66 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- ---------------------------- -- Table structure for think_superuser -- ---------------------------- DROP TABLE IF EXISTS `think_superuser`; CREATE TABLE `think_superuser` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) COLLATE utf8_bin NOT NULL, `password` varchar(255) COLLATE utf8_bin NOT NULL, `data` varchar(255) COLLATE utf8_bin DEFAULT NULL, `create_date` datetime NOT NULL, `create_superuser_id` int(11) NOT NULL, `type_id` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- ---------------------------- -- Table structure for think_task -- ---------------------------- DROP TABLE IF EXISTS `think_task`; CREATE TABLE `think_task` ( `article_id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `from` datetime DEFAULT NULL, `to` datetime DEFAULT NULL, `type_id` int(11) NOT NULL, `lasts` int(11) DEFAULT NULL, `status` int(11) NOT NULL, `create_date` datetime NOT NULL, `data` varchar(255) COLLATE utf8_bin DEFAULT NULL, PRIMARY KEY (`article_id`,`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- ---------------------------- -- Table structure for think_tasktimer -- ---------------------------- DROP TABLE IF EXISTS `think_tasktimer`; CREATE TABLE `think_tasktimer` ( `id` int(11) NOT NULL AUTO_INCREMENT, `article_id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `lasts` int(11) NOT NULL, `create_date` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=9422 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- ---------------------------- -- Table structure for think_test -- ---------------------------- DROP TABLE IF EXISTS `think_test`; CREATE TABLE `think_test` ( `id` int(11) NOT NULL AUTO_INCREMENT, `article_id` int(11) NOT NULL, `no` int(11) NOT NULL, `type_id` int(11) NOT NULL, `title` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, `content` text CHARACTER SET utf8 COLLATE utf8_bin, `image_url` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL, `right_answer` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, `mark` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5938 DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for think_testmetadata -- ---------------------------- DROP TABLE IF EXISTS `think_testmetadata`; CREATE TABLE `think_testmetadata` ( `article_id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `no` int(11) NOT NULL, `status` int(255) NOT NULL, `create_date` datetime NOT NULL, PRIMARY KEY (`article_id`,`user_id`,`no`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for think_user -- ---------------------------- DROP TABLE IF EXISTS `think_user`; CREATE TABLE `think_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) COLLATE utf8_bin NOT NULL, `password` varchar(255) COLLATE utf8_bin DEFAULT NULL, `data` varchar(255) COLLATE utf8_bin DEFAULT NULL, `open_id` varchar(255) COLLATE utf8_bin DEFAULT NULL, `create_date` datetime NOT NULL, `usertag_ids` varchar(255) COLLATE utf8_bin DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=390 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- ---------------------------- -- Table structure for think_usertag -- ---------------------------- DROP TABLE IF EXISTS `think_usertag`; CREATE TABLE `think_usertag` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; <file_sep><?php namespace Common\Behavior; class ParamFilterBehavior extends \Think\Behavior { public function run(&$param) { foreach ($_POST as $k => $v) { if ($_POST[$k] == "") { unset($_POST[$k]); } } } }<file_sep><?php namespace Home\Controller; use Think\Controller\RestController; use Org\Util\String; use Org\Net\IpLocation; class LoginRestController extends RestController { protected function login($user) { $token = String::keyGen(); S($token, $user); return array_merge($user, array('token' => $token, 'password' => '')); } public function superUserLogin($username, $password) { $user = M('superuser')->where(array('username' => $username, 'password' => md5($<PASSWORD>)))->select(); if (!$user) { $this->response(O(false, -1), 'json'); } $this->response(O(true, 0, $this->login($user[0])), 'json'); } public function userLogin($username, $password) { $user = M('user')->where(array('username' => $username, 'password' => md5($<PASSWORD>)))->select(); if (!$user) { $this->response(O(false, -1), 'json'); } $this->response(O(true, 0, $this->login($user[0])), 'json'); } public function userLoginByWxCode($code) { list($headers, $body) = explode("\r\n\r\n", doRequest('https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' . C('WX_CROPID') . '&corpsecret=' . C('WX_CROPSECRET')), 2); if ($accessToken = json_decode($body)->access_token) { list($headers, $body) = explode("\r\n\r\n", doRequest('https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=' . $accessToken . '&code=' . $code), 2); if ($userTicket = json_decode($body)->user_ticket) { list($headers, $body) = explode("\r\n\r\n", doRequest('https://qyapi.weixin.qq.com/cgi-bin/user/getuserdetail?access_token=' . $accessToken, json_encode(array('user_ticket' => $userTicket))), 2); $userDetail = json_decode($body); $location = (new IpLocation('QQWry.dat'))->getlocation(); $date = date('Y-m-d H:i:s'); $data = array( 'username' => $userDetail->userid, 'password' => md5('<PASSWORD>'), 'data' => json_encode(array('name' => $userDetail->name, 'gender' => $userDetail->gender, 'avatar' => $userDetail->avatar, 'mobile' => $userDetail->mobile, 'email' => $userDetail->email, 'loginInfo' => $location['ip'] . '/' . String::autoCharset($location['country']) . ',' . String::autoCharset($location['area']) . '/' . $date)) ); $user = M('user'); $userData = $user->where(array('username' => $userDetail->userid))->select(); if (!$userData) { $data['create_date'] = $date; $user->add($data); } else { $user->save(array_merge($data, array('id' => $userData[0]['id']))); } redirect('./Public/m/#/login?token=' . $this->login($user->where(array('username' => $userDetail->userid))->select()[0])['token']); } } redirect('./Public/m/'); } public function logout($token) { S($token, NULL); $this->response(O(), 'json'); } }<file_sep><?php return array( 'DB_TYPE' => 'mysqli', // 数据库类型 'DB_HOST' => 'localhost', // 服务器地址 'DB_NAME' => 'staeco_ts', // 数据库名 'DB_USER' => 'root', // 用户名 'DB_PWD'=> '', // 密码 'DB_PORT' => '3306', // 端口 'DB_PREFIX' => 'think_', // 数据库表前缀 'WX_CROPID' => 'ww0000000000000000', // 微信企业号 'WX_AGENTID' => '0000000', // 应用 'WX_CROPSECRET' => '0000<PASSWORD>0000', // 密匙 'DATA_BACKUP_PATH' => './Backups' // 备份目录 );<file_sep><?php return array( 'DATA_CACHE_TIME' => 86400 //数据缓存有效期 );<file_sep>import Cookies from 'js-cookie' import { superUserLogin, logout } from '@/api' const user = { state: { token: Cookies.get('token'), username: Cookies.get('username') }, mutations: { SET_TOKEN: (state, token) => { state.token = token }, SET_USERNAME: (state, username) => { state.username = username } }, actions: { LoginByUsernameAndPassword({ commit }, user) { const username = user.username.trim() return new Promise((resolve, reject) => { superUserLogin(username, user.password).then(response => { const data = response.data.data if (data) { let token = data.token Cookies.set('token', token) commit('SET_TOKEN', token) /** * username 保存在 cookies 中, 并不重新拉取 * * */ let username = data.username Cookies.set('username', username) commit('SET_USERNAME', username) resolve() } }).catch(error => { reject(error) }) }) }, Logout({ commit, state }) { return new Promise((resolve, reject) => { logout(state.token).then(() => { commit('SET_TOKEN', '') Cookies.remove('token') resolve() }).catch(error => { reject(error) }) }) } } } export default user<file_sep><?php namespace Api\Behavior; class AccessBehavior extends \Think\Behavior { /** * 管理后台使用 token 登录 * * */ public function run(&$param) { $user = S(I('post.token')); if ($user && isset($user['type_id'])) { return ; } E(''); } }<file_sep><?php return array( 'app_init' => array('Common\\Behavior\\ParamFilterBehavior') );<file_sep><?php namespace Api\Model; use Think\Model; class UserModel extends Model { protected $_validate = array( array('username', 'require', '', self::MUST_VALIDATE, 'unique'), array('password', 'require'), // array('usergroup_id', 'require', '', self::MUST_VALIDATE, 'number') ); /** * 密码 md5 一下 * * */ protected $_auto = array( array('password', 'md5' , self::MODEL_BOTH, 'function') ); // public function getPageByCondition($condition, $page, $pageSize) { // $user = $this->getTableName(); // $userGroup = M('usergroup')->getTableName(); // $c = array($user . '.username' => $condition['username']); // if ($condition['usergroup_id']) { // $c[$user . '.usergroup_id'] = $condition['usergroup_id']; // } // return $this->join('LEFT JOIN ' . $userGroup . ' ON ' . $user . '.usergroup_id = ' . $userGroup . '.id')->field(array( // $user . '.id' => 'id', // $user . '.username' => 'username', // $user . '.data' => 'data', // $user . '.usergroup_id' => 'usergroup_id', // $user . '.create_date' => 'create_date', // $userGroup . '.name' => 'usergroup' // ))->where($c)->order($user . '.create_date desc')->limit($page * $pageSize, $pageSize)->select(); // } }<file_sep><?php namespace Api\Controller; use Think\Controller\RestController; use Api\Model\SuperUserModel; class SuperUserRestController extends RestController { protected $_model; public function __construct() { $this->_model = new SuperUserModel('superuser'); parent::__construct(); } public function update() { $user = S(I('post.token')); if ($this->_model->create(array_merge(I('param.'), array( 'id' => $user['id'] )))) { $this->_model->save(); $this->response(O(), 'json'); } $this->response(O(false, -2), 'json'); } }<file_sep><?php namespace UserApi\Model; use Think\Model; class TodoModel extends Model { public function countByArticleTypeId($articleTypeId, $userId, $now) { $task = $this->getTableName(); $article = M('article')->getTableName(); return $this->join('LEFT JOIN ' . $article . ' ON ' . $task . '.article_id = ' . $article . '.id')->where(array( $task . '.user_id' => $userId, $task . '.from' => array('elt', $now), $article . '.type_id' => $articleTypeId ))->count(); } public function getPageByArticleTypeId($articleTypeId, $userId, $now, $page, $pageSize) { $task = $this->getTableName(); $article = M('article')->getTableName(); return $this->join('LEFT JOIN ' . $article . ' ON ' . $task . '.article_id = ' . $article . '.id')->field(array( $task . '.article_id' => 'article_id', $task . '.user_id' => 'user_id', $task . '.from' => 'from', $task . '.to' => 'to', $task . '.type_id' => 'type_id', $task . '.lasts' => 'lasts', $task . '.status' => 'status', $task . '.create_date' => 'create_date', $task . '.data' => 'data', $article . '.title' => 'article_title' ))->where(array( $task . '.user_id' => $userId, $task . '.from' => array('elt', $now), $article . '.type_id' => $articleTypeId, ))->order($task . '.create_date desc')->limit($page * $pageSize, $pageSize)->select(); } public function countGroupByArticleTypeId($userId, $now) { $task = $this->getTableName(); $article = M('article')->getTableName(); return $this->join('LEFT JOIN ' . $article . ' ON ' . $task . '.article_id = ' . $article . '.id')->field(array( $article . '.type_id' => 'type_id', 'count('. $article . '.type_id)' => 'count' ))->where(array( $task . '.user_id' => $userId, $task . '.from' => array('elt', $now), $task . '.to' => array('gt', $now), $task . '.status' => 0 ))->group($article . '.type_id')->select(); } }<file_sep><?php namespace Api\Model; use Think\Model; class SuperUserModel extends Model { protected $_validate = array( array('username', 'require'), array('password', 'require') ); protected function _before_update(&$data, $options) { $data['password'] = md5($data['password']); } }<file_sep><?php namespace Api\Controller; use Think\Controller\RestController; class TestMetaDataRestController extends RestController { protected $_model; public function __construct() { $this->_model = M('testmetadata'); parent::__construct(); } public function index($article_id, $user_id = NULL, $page = 0, $pageSize = PHP_INT_MAX) { if ($user_id != NULL) { $testMetaData = $this->_model->getTableName(); $test = M('test')->getTableName(); $this->response(O(true, 0, array( 'totalSize' => $this->_model->where(array( 'article_id' => $article_id, 'user_id' => $user_id ))->count(), 'content' => $this->_model->join('LEFT JOIN ' . $test . ' ON ' . $testMetaData . '.no = ' . $test . '.no AND ' . $test . '.article_id = ' . $article_id)->field(array( $testMetaData . '.no' => 'no', $testMetaData . '.status' => 'status', $testMetaData . '.create_date' => 'create_date', $test . '.id' => 'id', $test . '.mark' => 'mark' ))->where(array( $testMetaData . '.article_id' => $article_id, $testMetaData . '.user_id' => $user_id ))->order($testMetaData . '.no')->limit($page * $pageSize, $pageSize)->select() )), 'json'); } $this->response(O(true, 0, array( 'totalSize' => M('test')->where(array('article_id' => $article_id))->count(), 'content' => $this->_model->field(array( 'article_id', 'no', 'count(status)' => 'total_count', 'sum(status)' => 'count', ))->where(array('article_id' => $article_id))->order('no')->group('no')->limit($page * $pageSize, $pageSize)->select() )), 'json'); } }<file_sep><?php namespace Api\Model; use Think\Model; class TaskModel extends Model { protected $_validate = array( array('type_id', array(0, 1), '', self::MUST_VALIDATE, 'in'), array('lasts', 'require', '', self::MUST_VALIDATE, 'number') ); public function addByArticleIdAndUserIds($articleId, $userIds) { $this->startTrans(); foreach ($userIds as $v) { $condition = array('article_id' => $articleId, 'user_id' => $v); $data = array_merge($condition, array('from' => $this->data['create_date']), $this->data); if ($this->where($condition)->count() == 0) $this->add($data); else { $this->save($data); } /** * 尝试删除测试元数据 * * * */ M('testmetadata')->where($condition)->delete(); } $this->commit(); } public function addByArticleIdAndUserTagIds($articleId, $userTagIds) { $user = M('user'); $condition = array(); $condition['usertag_ids'] = array(); foreach (explode('|', $userTagIds) as $v) { if ($v != '') { array_push($condition['usertag_ids'], array('like', '%|' . $v . '|%')); } } array_push($condition['usertag_ids'], 'OR'); $userIds = $user->where($condition)->getField('id', true); $this->addByArticleIdAndUserIds($articleId, $userIds); return $userIds; } public function getPageByCondition($articleId, $page, $pageSize) { $task = $this->getTableName(); $user = M('user')->getTableName(); return $this->join('LEFT JOIN ' . $user . ' ON ' . $task . '.user_id = ' . $user . '.id')->field(array( $task . '.article_id' => 'article_id', $task . '.user_id' => 'user_id', $task . '.from' => 'from', $task . '.to' => 'to', $task . '.type_id' => 'type_id', $task . '.lasts' => 'lasts', $task . '.status' => 'status', $task . '.create_date' => 'create_date', $task . '.data' => 'data', $user . '.username' => 'user', $user . '.data' => 'user_data' ))->where(array($task . '.article_id' => $articleId))->order($task . '.create_date desc')->limit($page * $pageSize, $pageSize)->select(); } public function deleteWithTaskTimer($articleId, $userId) { $condition = array('article_id' => $articleId, 'user_id' => $userId); M('tasktimer')->where($condition)->delete(); $this->delete(array($articleId, $userId)); } }<file_sep>import MainFramework from '@/views/main-framework' const _import = file => () => import('@/views/' + file + '.vue') const routes = [ { path: '/', component: MainFramework, redirect: '/dashboard', children: [ { meta: { title: '首页', icon: 'fa fa-home' }, path: '/dashboard', component: _import('dashboard') } ] }, { path: '/user', component: MainFramework, redirect: '/', children: [ { meta: { title: '我的', icon: 'fa fa-user' }, path: '/user/index', component: _import('user') } ] }, { meta: { title: '培训', icon: 'fa fa-book', parentPath: '/dashboard', showHome: true }, path: '/training', component: _import('training') }, { meta: { title: '党建', icon: 'fa fa-flag', parentPath: '/dashboard', showHome: true }, path: '/party-building', component: _import('party-building') }, { meta: { title: '通知', icon: 'fa fa-bell', parentPath: '/dashboard', showHome: true }, path: '/notification', component: _import('notification') }, { meta: { title: '考试', icon: 'fa fa-pencil', parentPath: '/dashboard', showHome: true }, path: '/test', component: _import('test') }, { meta: { title: '查找', icon: 'fa fa-search', parentPath: '/dashboard', showHome: true }, path: '/attachment-viewer', component: _import('attachment-viewer') }, { meta: { hidden: true }, path: '/login', component: _import('login') }, { meta: { hidden: true, showHome: true }, path: '/article', component: _import('article') }, { meta: { hidden: true, showHome: true }, path: '/answer-board', component: _import('answer-board') }, { meta: { hidden: true }, path: '/finished', component: _import('finished') } ] export default routes<file_sep><?php namespace Api\Controller; use Think\Controller\RestController; use Think\Db; use OT\Database; class DataRestController extends RestController { public function index($page = 0, $pageSize = 10) { $path = realpath(C('DATA_BACKUP_PATH')); $flag = \FilesystemIterator::KEY_AS_FILENAME; $glob = new \FilesystemIterator($path, $flag); $list = array(); foreach ($glob as $name => $file) { if (preg_match('/^\d{8,8}-\d{6,6}-\d+\.sql(?:\.gz)?$/', $name)) { $name = sscanf($name, '%4s%2s%2s-%2s%2s%2s-%d'); $date = "{$name[0]}-{$name[1]}-{$name[2]}"; $time = "{$name[3]}:{$name[4]}:{$name[5]}"; $part = $name[6]; if (isset($list["{$date} {$time}"])) { $info = $list["{$date} {$time}"]; $info['part'] = max($info['part'], $part); $info['size'] = $info['size'] + $file->getSize(); } else { $info['part'] = $part; $info['size'] = $file->getSize(); } $extension = strtoupper($file->getExtension()); $info['compress'] = ($extension === 'SQL') ? '-' : $extension; $info['time'] = array(strtotime("{$date} {$time}"), "{$date} {$time}"); array_push($list, $info); } } usort($list, "Api\Controller\DataRestController::sortByTime"); $this->response(O(true, 0, array( 'totalSize' => count($list), 'content' => array_slice($list, $page * $pageSize, $pageSize) )), 'json'); } public function deleteByTime($time){ // $name = date('Ymd-His', $time) . '-*.sql*'; // $path = realpath(C('DATA_BACKUP_PATH')) . DIRECTORY_SEPARATOR . $name; // array_map("unlink", glob($path)); // if (!count(glob($path))) { // $this->response(O(true, 0), 'json'); // } $this->response(O(false, -2), 'json'); } public function add() { $tables = array(); foreach (array_map('array_change_key_case', Db::getInstance()->query('SHOW TABLE STATUS')) as $table) { array_push($tables, $table['name']); } $config = array( 'path' => realpath(C('DATA_BACKUP_PATH')) . DIRECTORY_SEPARATOR, 'part' => 67108864, 'compress' => true, 'level' => 6, ); $l = "{$config['path']}backup.lock"; if (!is_file($l)) { file_put_contents($l, NOW_TIME); $name = date('Ymd-His', NOW_TIME); $database = new Database(array( 'name' => $name, 'part' => 1, ), $config); if (false !== $database->create()) { $i = 0; $start = 0; while (true) { $start = $database->backup($tables[$i], $start); if (false === $start) { break; } elseif (0 === $start) { if (!isset($tables[++$i])) { unlink($l); $this->response(O(), 'json'); } } else { $start = $start[0]; } } } } $this->response(O(false, -2), 'json'); } // 太卡了 // public function restore($time = 0) { // if (is_numeric($time)) { // $name = date('Ymd-His', $time) . '-*.sql*'; // $path = realpath(C('DATA_BACKUP_PATH')) . DIRECTORY_SEPARATOR . $name; // $files = glob($path); // $list = array(); // foreach ($files as $name) { // $basename = basename($name); // $match = sscanf($basename, '%4s%2s%2s-%2s%2s%2s-%d'); // $gz = preg_match('/^\d{8,8}-\d{6,6}-\d+\.sql.gz$/', $basename); // $list[$match[6]] = array($match[6], $name, $gz); // } // ksort($list); // $last = end($list); // if (count($list) === $last[0]) { // $part = 1; // $database = new Database($list[$part], array('path' => realpath(C('DATA_BACKUP_PATH')) . DIRECTORY_SEPARATOR, 'compress' => $list[$part][2])); // $start = 0; // $db = Db::getInstance(); // $db->startTrans(); // while (true) { // $start = $database->import($start); // if(false === $start){ // break; // } elseif (0 === $start) { // if(!isset($list[++$part])){ // $db->commit(); // $this->response(O(), 'json'); // } // } else { // $start = $start[0]; // } // } // } // } // $this->response(O(false, -2), 'json'); // } static function sortByTime($a, $b) { return $b['time'][0] - $a['time'][0]; } } <file_sep><?php namespace UserApi\Controller; use Think\Controller\RestController; use UserApi\Model\UserdetailModel; class UserDetailRestController extends RestController { public function index() { $token = I('post.token'); $this->response(O(true, 0, array_merge(S($token), array('token' => $token, 'password' => ''))), 'json'); } // public function updateUserPassword($password) { // $user = S(I('post.token')); // if (!empty($password)) { // M('user')->save(array( // 'id' => $user['id'], // 'password' => md5($<PASSWORD>) // )); // $this->response(O(), 'json'); // } // $this->response(O(false, -2), 'json'); // } }<file_sep>const articleEditor = { state: { id: '', title: '', content: '', showDialog: false } } export default articleEditor<file_sep>import axios from 'axios' import store from '@/utils/store' import qs from 'qs' const request = axios.create({ baseURL: process.env.BASE_API, timeout: 5000 }) request.interceptors.request.use(config => { if (store.getters.token) { config.data = qs.stringify({ token: store.getters.token, ...config.data }) } else { config.data = qs.stringify(config.data) } return config }, error => { Promise.reject(error) }) request.interceptors.response.use(response => { if (!response.data.success) { return Promise.reject(new Error(response.data.code)) } return response }, error => { return Promise.reject(error) }) export default request<file_sep><?php namespace Api\Controller; use Think\Controller\RestController; use Api\Model\UserModel; class UserRestController extends RestController { protected $_model; public function __construct() { $this->_model = new UserModel(); parent::__construct(); } public function index($username = '', $usertag_ids = NULL, $page = 0, $pageSize = 10) { $condition = array( 'username' => array('like', '%'. $username . '%'), ); if ($usertag_ids) { $condition['usertag_ids'] = array(); foreach (explode('|', $usertag_ids) as $v) { if ($v != '') { array_push($condition['usertag_ids'], array('like', '%|' . $v . '|%')); } } array_push($condition['usertag_ids'], 'OR'); } $this->response(O(true, 0, array( 'totalSize' => $this->_model->where($condition)->count(), 'content' => fillUserTags($this->_model->where($condition)->field(array( 'id', 'username', 'data', 'create_date', 'usertag_ids' ))->limit($page * $pageSize, $pageSize)->select()) )), 'json'); } // public function add() { // if ($this->_model->create(array_merge(I('param.'), array( // 'create_date' => date('Y-m-d H:i:s') // )))) { // $this->_model->add(); // $this->response(O(), 'json'); // } // $this->response(O(false, -2), 'json'); // } public function updateById($id, $usertag_ids = NULL) { unset($_POST['username']); if ($this->_model->create(array_merge(I('param.'), array( 'create_date' => date('Y-m-d H:i:s'), 'usertag_ids' => $usertag_ids != NULL ? $usertag_ids : array('exp', 'null') )))) { $this->_model->save(); $this->response(O(), 'json'); } $this->response(O(false, -2), 'json'); } // public function deleteById($id) { // $this->_model->delete($id); // $condition = array('user_id' => $id); // M('task')->where($condition)->delete(); // M('tasktimer')->where($condition)->delete(); // $this->response(O(), 'json'); // } }<file_sep><?php namespace UserApi\Controller; use Think\Controller\RestController; class UserArticleAttachmentRestController extends RestController { public function index($name = '', $page = 0, $pageSize = 10) { $user = S(I('post.token')); $cond = array( 'name' => array('like', '%'. $name . '%'), 'article_id' => array('in', M('task')->where(array('user_id' => $user['id']))->getField('article_id', true)) ); $attachment = M('attachment'); $this->response(O(true, 0, array('totalSize' => $attachment->where($cond)->count(), 'content' => $attachment->where($cond)->limit($page * $pageSize, $pageSize)->select())), 'json'); } }
fd3d8a960e7ac0d0b94a9c9f499c88f7ba21deb4
[ "JavaScript", "SQL", "Markdown", "PHP" ]
42
PHP
zyCwind/StaecoTS
d28e19fa4d453684638c55bf760469077b613048
12670922684b02d65dcc2d7769e472d3d2cd29bf
refs/heads/master
<repo_name>xinfeingxia85/note<file_sep>/shims.lua local Url = require "demo.url" local test = require "demo.test" test('Url.parse', function(t) -- 第一个测试 local url = Url.parse('http://user:pass@host.com:8080/p/a/t/h?query=string#hash') t.deepEqual(url, { protocol = 'http:', auth = 'user:pass', hostname = 'host.com', port = 8080, pathname = '/p/a/t/h', query = 'query=string', hash = '#hash' }) -- 第二个测试 local url2 = Url.parse('https://www.google.com/#q=search') t.deepEqual(url2, { protocol = 'https:', auth = nil, hostname = 'www.google.com', port = nil, pathname = '/', query = '', hash = '#q=search' }) end)<file_sep>/file.lua local imgFile = "/www/demo1/html/fangkm/1.jpg" -- 检查文件是否文目录 local function isDir(sPath) if type(sPath) ~= "string" then return false end local response = os.execute("cd " .. sPath) if response then return true else return false end end -- 文件是否存在 function fileExists(fileName) local f = io.open(fileName, "r") if f ~= nil then io.close(f) return true else return false end end -- 获取文件的路径 function getFileNameDir(fileName) return string.match(fileName, "(.*)/[^/]*%.%w+$") end -- 获取文件名 function stripPath(fileName) return string.match(fileName, ".*/([^/]*%.%w+)$") end -- 获取文件路径和文件名 function getFileInfo(fileName) local t = {} local _, _, fPath, fName = string.find(fileName, "(.*)/([^/]*%.%w+)$") table.insert(t, fPath) table.insert(t, fName) return t end -- 去除文件扩展名 function stripExtension(fileName) local idx = fileName:match(".+()%.%w+$") if idx then return fileName:sub(1, idx-1) else return fileName end end -- 获取扩展名 function getExtension(fileName) return string.match(fileName, ".+%.(%w+)$") end -- 开始执行 if not isDir(getFileNameDir(imgFile)) then os.execute("mkdir -p " .. getFileNameDir(imgFile)) end -- 获取宽或者高 local uri = ngx.var.img_size local width = string.sub(uri, 1, 1) local height = 0 if width == "-" then width = 0 height = string.sub(uri, 2, string.len(uri)) else width = string.sub(uri, 1, string.len(uri)-1) height = 0 end<file_sep>/string.lua -- string.gmatch(str, pattern) -- s = "hello world from lua" -- for w in string.gmatch(s, "%a+") do -- print(w, v) -- end -- string.gsub -- lookuptable = {hello = "hola", world = "mundo"} -- print(string.gsub("hello world", "(%w+)", lookuptable)) -- print(string.gsub("hello world", "(%w+)", function (s) -- return "" -- end)) -- print(string.match("abcdefg", "a")) -- print(string.reverse("abcde")) -- function aa() -- print("dd") -- end -- print(string.dump(aa)) --print(string.gsub("hello, up-down", "%A", ".")) -- test = "int x; /* x */ int y; /* y */" -- print(string.gsub(test, "/%*.*%*/", "<COMMENT -- print(string.gsub("a(enclosed (in) parenttheses) line", '%(.*%)', "")) -- pair = "name = Anna" -- _, _, m1, m2 = string.find(pair, "(%a+)%s*=%s*(%a+)") -- print(m1, m2) -- s = [[then he said: "it's all right"!]] -- a, b, c, quotedPart = string.find(s, "(\")(.-)%1") -- print(quotedPart) -- print(c) -- print(string.gsub("hello Lua!", "(%a)", "%1-%1")) -- s = [[the \quote{task} is to \em{change} that.]] -- s1 = string.gsub(s, "\\(%a+){(.-)}", "<%1>%2<%1>") -- print(s1) -- function handle -- name = "Lua" -- status = "great" -- eStr = [[$name is $status, isn't it?]] -- print((string.gsub(eStr, "$(%w+)", function (n) -- return _G[n] -- end))) -- s = "sin(3) = $[math.sin(3)]; 2^5 = $[2^5]" -- print((string.gsub(s, "$(%b[])", function (x) -- x = "return " .. string.sub(x, 2, -2) -- local f = loadstring(x) -- return f() -- end))) <file_sep>/url.lua local _ = require "demo.shim" local Url = { version = "1.0.1" } function splitTwo(str, sp) local arr = _.split(str, sp) local first = arr[1] local second = _.join(_.slice(arr, 2), sp) return first, second end function splicePattern(str, pattern) local matched if _.isString(str) then str = str:gsub(pattern, function(_matched) matched = _matched return '' end) end return matched, str end function Url.parse(str, shouldParseQuery) if not _.isString(str) then return str end local url = {} local rest = str --分析# rest, url.hash = splitTwo(str, '#') if url.hash then url.hash = '#' .. url.hash end --分析? rest, url.query = splitTwo(rest, '?') --分析协议 url.protocol, rest = splicePattern(rest, '^[a-zA-z][a-zA-z0-9.]*:') if _.startWith(rest, '//') then rest = _.slice(rest, 3) end --url.protocol = _.slice(url.protocol, 1, _.len(url.protocol)) --分析pathname rest, url.pathname = splitTwo(rest, '/') if not url.pathname then url.pathname = '' end url.pathname = '/' .. url.pathname --分析auth local auth, host = splitTwo(rest, '@') if _.empty(host) then host = auth auth = nil end url.auth = auth --分析host url.hostname, url.port = splitTwo(host, ':') if url.port then url.port = tonumber(url.port) end return url end return Url<file_sep>/oop.lua local function search(k, pParentList) for i=1, #pParentList do local v = pParentList[i][k] if v then return v end end end function createClass( ... ) local c = {} -- 新类 local parents = {...} setmetatable(c, {__index = function(t, k) return search(k, parents) end}) -- 将c作为其实例的元素 c.__index = c -- 为这个新类构造一个新的构造函数 function c:new(o) o = o or {} setmetatable(o, self) return o end return c end -- 第一个类CA local CA = {} function CA:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end function CA:setName(strName) self.name = strName end -- 第一个类CB local CB = {} function CB:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end function CB:getName() return self.name end local c = createClass(CA, CB) local objC = c:new{name="Jelly"} objC:setName("JellyThink") local newName = objC:getName() print(newName) <file_sep>/test.lua local _ = require "demo.shim" local queue = {} local function ok(val, msg) assert(true == val, msg) end local function equal(val, excepted, msg) if val ~= excepted then assert(false, msg or tostring(val) .. '=' .. tostring(excepted)) end end local function deepEqual(val, excepted, msg) local ok = _.isDeepEqual(val, excepted) if not ok then assert(false, msg or tostring(val) .. '=' .. tostring(excepted)) end end local function getT() return { ok = ok, equal = equal, deepEqual = deepEqual } end local function report(ok, title, msg) if ok then ngx.say('pass ' .. title) else ngx.say('fail ' .. title .. ' ' .. msg) end end local function execTest(title, func) local t = getT() local ok, ret = pcall(func, t) if ok then report(ok, title) else local info = debug.getinfo(1) report(ok, title, info.short_src .. ":" .. info.currentline) end end local function test(title, func) if _.isFunction(title) then return test('untitled', title) end if _.isFunction(func) then execTest(title, func) end end return test<file_sep>/oopa.lua function newObject(defaultName) local self = {name = defaultName} local getName = function () return self.name end local setName = function(v) self.name = v end return {setName = setName, getName = getName} end local objectA = newObject("fankm") objectA.setName("JellyThink") print(objectA.getName())<file_sep>/escape.lua s = [[name=al&query=a%2Bb+%3D+c&q=yes+or+no]] function unescape(s) s = string.gsub(s, "+", "") s = string.gsub(s, "%%(%x%x)", function(h) return string.char(tonumber(h, 16)) end) return s end function escape(s) s = string.gsub(s, "[%c=+&]", function (c) return string.format("%%%02x", string.byte(c)) end) s = string.gsub(s, " ", "+") return s end function encode(t) local s = "" for k,v in pairs(t) do s = s .. "&" .. escape(k) .. "=" .. escape(v) end return string.sub(s, 2) end function decode(s) local cgi = {} -- gfind在高版本中废弃,可以直接考虑用gmatch -- for name, value in string.gfind(s, "([^&=]+)=([^&=]+)") do -- name = unescape(name) -- value = unescape(value) -- cgi[name] = value for name, value in string.gmatch(s, "([^&=]+)=([^&=]+)") do name = unescape(name) value = unescape(value) cgi[name] = value end -- string.gsub(s, "([^&=]+)=([^&=]+)", function( ... ) -- local t = {...} -- name = unescape(t[1]) -- value = unescape(t[2]) -- cgi[name] = value -- end) return cgi end -- for k,v in pairs(decode(s)) do -- print(k,v) -- end -- print(escape("fang=\nkm")) t = {name = "al", query = "a+b = c", q="yes or no"} print(encode(t)) --测试提交1244444444
333a90fc4633df6a310a51fc58c1d0c8e5db8780
[ "Lua" ]
8
Lua
xinfeingxia85/note
b56d419d67788974bb3142869b0839eca8e1c631
16502f4ad1ed59a83f71df7ce79281b23d1af4d8
refs/heads/master
<repo_name>jharrilim/Chatroom<file_sep>/Client/src/environments/environment.prod.ts export const environment = { production: true, url: '/myHub' }; <file_sep>/Client/src/app/components/chat/chat.component.ts import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/core'; import { HubConnection, HubConnectionBuilder, LogLevel } from '@aspnet/signalr'; import { Message } from '../../models/message'; import { UserService } from '../../services/user.service'; import { environment } from '../../../environments/environment'; @Component({ selector: 'app-chat', templateUrl: './chat.component.html', styleUrls: ['./chat.component.css'] }) export class ChatComponent implements OnInit, OnDestroy { public messages: Message[] = []; public message: string = ''; private hubConnection: HubConnection | undefined; @ViewChild('msgBox') private messageBox: ElementRef; constructor(private userService: UserService) { } ngOnInit() { this.hubConnection = new HubConnectionBuilder() .withUrl(environment.url) .configureLogging(LogLevel.Information) .build(); this.hubConnection.on('GetChatHistory', (messages: Message[]) => { console.log(messages); this.messages = messages; }); this.hubConnection.on('SelfJoined', (id: string) => { console.log('Successfully joined the chat.'); this.userService.setUser(id); }); this.hubConnection.on('UserJoined', (id: string) => { console.log(`${id} has entered.`); }); this.hubConnection.on('ReceiveMessage', (message: Message) => { this.messages.push(message); }); this.hubConnection.start().catch(err => console.error(err.toString())); } ngOnDestroy() { if (this.hubConnection) this.hubConnection.stop().catch(err => console.error(err.toString())); } sendMessage() { if (!this.hubConnection) { console.error('Not connected.'); return; } this.hubConnection.invoke('SendMessage', this.userService.getUser(), this.message); this.message = ''; this.messageBox.nativeElement.focus(); } private getLocalTime(): string { const date: Date = new Date(); const ampm: string = date.getHours() >= 12 ? 'PM' : 'AM'; const hour = date.getHours() == 0 ? '12' : date.getHours() > 12 ? `${date.getHours() - 12}` : date.getHours().toString(); const dateFormat: string = `${hour}:${date.getMinutes()} ${ampm}`; return dateFormat; } } <file_sep>/README.md # WebSocket-Angular .NET Core 2.1 Signalr WebSocket and Angular 6 client. ## Dependencies - Node 10.8.0 - npm 6.2.0 - Global: @angular/cli@6.1.2 - dotnet 2.1.302 ## Setup ### Server > Run server as a console application with the port 8060. > If you choose to use a different port, > you must update the port on the client side as well which can be found [here](Client/src/app/components/chat/chat.component.ts#L20). ### Client > Install node packages and run on port 4200. If you want to run the client on a different port, > you must update the port found [here](Server/Startup.cs#L38). ## Build Steps ### Client ng cli is configured to output build to wwwroot on the Server. ```bash # Install packages cd Client/ npm i # Build prod ng build --prod ``` ### Server ```bash # Assuming you are still in Client cd ../Server dotnet build -c Release ``` #### Run Server ```bash # Use sudo for running on port 80 sudo dotnet bin/Release/netcoreapp2.1/WebSocket.Server.dll ``` If you are using windows, run PowerShell as admin and use the same command as above without sudo: ```powershell dotnet Server/bin/Release/netcoreapp2.1/WebSocket.Server.dll ``` <file_sep>/Server/Program.cs using System; using System.Net; using System.Security.Cryptography.X509Certificates; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace WebSocket.Server { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args) .Build() .Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) { var b = WebHost.CreateDefaultBuilder(args); #if RELEASE b.UseKestrel(options => { options.Listen(IPAddress.Any, 443, listenOpts => { listenOpts.UseHttps(Environment.GetEnvironmentVariable("certpath"), Environment.GetEnvironmentVariable("certpass")); }); }); #endif return b.UseStartup<Startup>(); } } } <file_sep>/Client/src/app/models/message.ts export class Message { constructor( public user: string, public content: string, public type: string = 'user', public unixTime?: number ) { } } <file_sep>/Client/src/app/components/nav/nav.component.ts import { Component, ViewChild, Renderer2, ElementRef, OnInit, Input } from '@angular/core'; import { BreakpointObserver, Breakpoints, BreakpointState } from '@angular/cdk/layout'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { UserService } from '../../services/user.service'; @Component({ selector: 'app-nav', templateUrl: './nav.component.html', styleUrls: ['./nav.component.css'] }) export class NavComponent implements OnInit { private name: string = ''; @ViewChild('mainContent') private main: ElementRef; @ViewChild('navTop') private navTop: ElementRef; @Input() public set nameField(name: string) { this.userService.setUser(name); this.name = name; } constructor ( private breakpointObserver: BreakpointObserver, private renderer: Renderer2, private userService: UserService ) { } public ngOnInit() { } isHandset$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset) .pipe( map(result => result.matches) ); public updateName() { console.log(name); this.userService.setUser(this.nameField); } } <file_sep>/Server/MyHub.cs using Microsoft.AspNetCore.SignalR; using System; using System.Linq; using System.Collections.Concurrent; using System.Security; using System.Threading.Tasks; namespace WebSocket.Server { public class MyHub : Hub { private static readonly int messageLimit = 100; private static readonly ConcurrentQueue<Message> messages; static MyHub() { messages = new ConcurrentQueue<Message>(); } public override async Task OnConnectedAsync() { await Clients.Caller.SendAsync("GetChatHistory", messages.ToList()); await Clients.Caller.SendAsync("SelfJoined", Context.ConnectionId); await Clients.Others.SendAsync("UserJoined", Context.ConnectionId); await SendMessage("System", $"{Context.ConnectionId} has joined the room.", "system"); await base.OnConnectedAsync(); } public override async Task OnDisconnectedAsync(Exception exception) { await SendMessage("System", $"{Context.ConnectionId} has left the room.", "system"); await base.OnDisconnectedAsync(exception); } public async Task SendMessage(string user, string message) { await SendMessage(user, message, "user"); } private async Task SendMessage(string user, string message, string type) { if(messages.Count >= messageLimit) { messages.TryDequeue(out _); } Message m = new Message() { User = user, Content = SecurityElement.Escape(message), UnixTime = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds, Type = type }; messages.Enqueue(m); await Clients.All.SendAsync("ReceiveMessage", m); } } } <file_sep>/Server/Message.cs using System; namespace WebSocket.Server { [Serializable] public class Message { public string User { get; set; } public string Content { get; set; } public string Type { get; set; } public double UnixTime { get; set; } public Message() { Type = "user"; } } }
6a28fdb83528c06671f7afc6dc8b86c320f731e8
[ "Markdown", "C#", "TypeScript" ]
8
TypeScript
jharrilim/Chatroom
e4f020507e049b7fe2da110d6c49d9fb8632731e
364b3eeea9754d0703e40444481de7eae0f67524
refs/heads/master
<repo_name>vStone/gir-eggdrop-urlwiz<file_sep>/README.md # Description This script grabs all urls (http only) on a irc channel (requires +urlwiz setting) and stores them in a database. # Features * support for tags (see below) * stores who pasted the link * stores for who the link was pasted (if the line is starting with <nick> ) * only enable for specific channels (+urlwiz) * supports logging if enabled for a channel (+logurlwiz) ## tags Optionally, you can add tags to a url you are pasting by appending \#tags. These should be split up by spaces. Also don't forget to add a space after the url or you would be adding to the url in stead of specifying a tag. # Prerequisites * Eggdrop * A mysql database * Some tcl packages: * http * uri * htmlparse * mysqltcl * tls (optional) # Instructions ## Database Create a mysql database and use the urlwiz.sql file to generate the required structure: mysql -u admin -p localhost > CREATE DATABASE urlwiz; > GRANT USAGE ON *.* to 'urlwiz_user'@'localhost' IDENTIFIED BY 'P4ssw0r!)'; > GRANT ALL PRIVILEGES ON 'urlwiz_db' TO 'urlwiz_user'@'localhost'; > FLUSH PRIVILEGES; > exit Bye mysql -u urlwiz_user -p urlwiz_db < urlwiz.sql ## Configuration Create a urlwiz.conf file with your settings the same dir as your eggdrop configuration file. Define following settings. set urlwiz(mysqldb) "db_schema" ;# name of mysql db set urlwiz(mysqluser) "db_user" ;# username for the mysql db set urlwiz(mysqlpass) {P4ssw0r!)} ;# password for the mysql db set urlwiz(mysqlhost) "hostname" ;# hostname for the mysql db ## Eggdrop Edit your eggdrop configuration file and add the following: source scripts/urlwiz/urlwiz.tcl <file_sep>/urlwiz.sql -- -- Table structure for table `tag` -- CREATE TABLE `tag` ( `tagid` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'TAG ID', `tag` varchar(100) NOT NULL COMMENT 'Tag', `count` int(10) unsigned NOT NULL DEFAULT '1', PRIMARY KEY (`tagid`), UNIQUE KEY `tag` (`tag`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 -- -------------------------------------------------------- -- -- Table structure for table `url` -- CREATE TABLE `url` ( `url_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'URL ID', `url` varchar(255) NOT NULL COMMENT 'Link (duh)', `title` varchar(255) NOT NULL, `tinyurl` varchar(50) NOT NULL COMMENT 'TinyURL for this link (if there was one generated)', `nick` varchar(32) NOT NULL COMMENT 'Who mentioned it?', `reffed` varchar(32) DEFAULT NULL, `channel` varchar(32) NOT NULL COMMENT 'Where was it mentioned?', `date` int(10) unsigned NOT NULL COMMENT 'When was it mentioned', PRIMARY KEY (`url_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 -- -------------------------------------------------------- -- -- Table structure for table `urltag` -- CREATE TABLE `urltag` ( `url_id` int(10) unsigned NOT NULL, `tag_id` int(10) unsigned NOT NULL, PRIMARY KEY (`url_id`,`tag_id`), KEY `tag_id` (`tag_id`), CONSTRAINT `urltag_ibfk_1` FOREIGN KEY (`url_id`) REFERENCES `url` (`url_id`) ON DELETE CASCADE, CONSTRAINT `urltag_ibfk_2` FOREIGN KEY (`tag_id`) REFERENCES `tag` (`tagid`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8
71ce54b043348a9062c0bc1fde8c97d6bc2116be
[ "Markdown", "SQL" ]
2
Markdown
vStone/gir-eggdrop-urlwiz
c51fdd979cc9476d9ccec884ed9b19cd78d3c742
3d834f363566d50e0fd7d728c8afb1f751cce602
refs/heads/main
<repo_name>Saisharan-24/Tourism-Superintendence<file_sep>/uview.php <?php include("dbconnect.php"); extract($_POST); session_start(); $uid=$_SESSION['uid']; $oname=$_REQUEST['oname']; $hid=$_REQUEST['hid']; $qr=mysql_query("select * from hregist where oname='$oname' && id='$hid'"); $rw=mysql_fetch_array($qr); $hid1=$rw['id']; $oname1=$rw['oname']; $amt=$rw['amnt']; if($_REQUEST["act"]==('add')) { $hhid=$_REQUEST['hid']; $qry=mysql_query("update hregist set status='1',uid='$uid' where id='$hhid'"); echo "<script>alert('House Booked')</script>"; } ?> <html> <title>House Rent</title> <head> <style type="text/css"> <!-- .style1 { font-size: 36px; font-weight: bold; color: #ffffff; } .style2 {font-size: 18px; font-weight: bold; color: #000000; } a { text-decoration:none; color:#000000; } .style3 {font-size: 18px} --> </style> </head> <body> <table width="95%" border="1" align="center" bordercolor="#001a33"> <tr> <td height="144" valign="top" bgcolor="#001a33" align="center"><p class="style1">House Rental Management System</p> <p align="center" class="style2">&nbsp;</p></td> </tr> </table> <table width="95%" border="0" align="center" bordercolor="#1a0000"> <tr> <td width="19%" height="34" bgcolor="#FF8C00"><div align="center"><strong><a href="userhome.php">User Home</a></strong></div></td> <td width="20%" bgcolor="#FF8C00"><div align="center"><strong><a href="view.php">View Details</a></strong></div></td> <td width="27%" bgcolor="#FF8C00"><div align="center"><strong><a href="index.php">LogOut</a></strong></div></td> </tr> </table> <p>&nbsp;</p> <table width="95%" border="0" align="center"> <tr> <td align="center"><p><strong>House Rental</strong>:</p> <table width="90%" border="0" align="center"> <tr> <td>&nbsp;&nbsp; <img src="images\1.jpg" width="1340" height="200"/> </tr> </table> <p>&nbsp; </p></td> </tr> </table> <table width="100%" border="0" align="center"> <tr> <td width="25%">&nbsp; </td> <td width="21%">&nbsp; </td> <td width="29%">&nbsp; </td> <td width="25%">&nbsp; </td> </tr> <?php $qr=mysql_query("select * from hregist where oname='$oname' && id='$hid'"); $rw=mysql_fetch_array($qr); $hid1=$rw['id']; $oname1=$rw['oname']; ?> <tr> <td>&nbsp;</td> <td align="center"><img src="images/<?php echo $rw['himg'];?>" width="200" height="200"></td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td align="justify"><strong>Owner Name</strong></td> <td align="left"><?php echo $rw['oname'];?></td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td align="justify"><strong>Location</strong></td> <td align="left"><?php echo $rw['loc'];?></td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td align="justify"><strong>Address</strong></td> <td align="left"><?php echo $rw['address'];?></td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td align="justify"><strong>Rent type<strong></td> <td align="left"><?php echo $rw['rtype'];?></td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td align="justify"><strong>Amount</strong></td> <td align="left"><?php echo $rw['amnt'];?></td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td align="justify"><strong>Number of rooms</strong></td> <td align="left"><?php echo $rw['rms'];?></td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td align="center"><a href="uview.php?act=add&oname=<?php echo $rw['oname'];?>&hid=<?php echo $rw['id'];?>">Book</a></td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td align="center">&nbsp;</td> <td align="center">&nbsp;</td> <td>&nbsp;</td> </tr> </table> <table width="95%" border="1" align="center" bordercolor="#001a33"> <tr> <td height="80" valign="center" bgcolor="#001a33" align="center"><p class="style1"></p></td> </tr> </table> </body> </html> <file_sep>/gregister.php <?php include("dbconnect.php"); extract($_POST); session_start(); if(isset($_POST['btn'])) { //checking name $qry=mysql_query("insert into gregister(name,gender,age,email,phone,address,zip,uname,psw) values('$name','$gender','$age','$email','$phone','$address','$zip','$uname','$psw')"); if($qry) { echo "<script>alert('inserted sucessfully')</script>"; } else { echo "failed"; } } ?> <html> <title>House Rent</title> <head> <style type="text/css"> <!-- .style1 { font-size: 36px; font-weight: bold; color: #ffffff; } .style2 {font-size: 18px; font-weight: bold; color: #ffffff; } a { text-decoration:none; color:#000000; } .style3 {font-size: 18px} --> </style> </head> <body> <table width="95%" border="1" align="center" bordercolor="#001a33"> <tr> <td height="144" valign="top" bgcolor="#001a33" align="center"><p class="style1">House Rental Management System</p> <p align="center" class="style2">&nbsp;</p></td> </tr> </table> <table width="95%" border="0" align="center" bordercolor="#1a0000"> <tr> <td width="19%" height="34" bgcolor="#FF8C00"><div align="center"><strong><a href="index.php">Home</a></strong></div></td> <td width="20%" bgcolor="#FF8C00"><div align="center"><strong><a href="admin.php">Admin</a></strong></div></td> <td width="19%" bgcolor="#FF8C00"><div align="center"><strong><a href="guest.php">House Owner</a></strong></div></td> <td width="15%" bgcolor="#FF8C00"><div align="center"><strong><a href="user.php">User</a></strong></div></td> <td width="27%" bgcolor="#FF8C00"><div align="center"><strong><a href="forgot.php">Forgot Password</a></strong></div></td> </tr> </table> <p>&nbsp;</p> <br /> <br /> <br /> <form id="f1" name="f1" method="post" action="#"> <table width="35%" border="0" align="center"> <tr> <td colspan="2" align="center" ><div class="style5"><h3>New House Owner Registation</h></div></td> </tr> <tr> <td width="30%">Name</td> <td width="70%"><input name="name" type="text" id="name"/> </td> </tr> <tr> <td>Gender</td> <td><input name="gender" type="radio" value="male" /> Male <input name="gender" type="radio" value="female" /> Female</td> </tr> <tr> <td>Age</td> <td> <input name="age" type="text" id="age" /> </td> </tr> <tr> <td>Email Id</td> <td><input name="email" type="text" id="email" /></td> </tr> <tr> <td>Phone Number </span></td> <td><input name="phone" type="text" id="phone" /></td> </tr> <tr> <td>Address</td> <td><textarea name="address" id="address"></textarea></td> </tr> <tr> <td>Zipcode</td> <td><input type="text" name="zip" id="zip"></td> </tr> <tr> <td>User Name</td> <td><input name="uname" type="text" id="uname" /></td> </tr> <tr> <td>Passwrod</td> <td><input name="psw" type="password" id="psw" /></td> </tr> <tr> <td>&nbsp;</td> <td><input name="btn" type="submit" id="btn" value="Submit" /> <input type="reset" name="Submit2" value="Reset" /></td> </tr> </table> </form> <table width="95%" border="1" align="center" bordercolor="#001a33"> <tr> <td height="80" valign="center" bgcolor="#001a33" align="center"><p class="style1"></p></td> </tr> </table> </body> </html> <file_sep>/payment.php <?php include("dbconnect.php"); extract($_POST); session_start(); $uid=$_SESSION['uid']; $amt=$_REQUEST['amt']; $hid=$_REQUEST['id']; if(isset($_POST['btn'])) { $qry=mysql_query("update hregist set status=3 where id='$hid'"); header("location:userhome.php"); } ?> <html> <title>House Rent</title> <head> <style type="text/css"> <!-- .style1 { font-size: 36px; font-weight: bold; color: #ffffff; } .style2 {font-size: 18px; font-weight: bold; color: #000000; } a { text-decoration:none; color:#000000; } .style3 {font-size: 18px} --> </style> </head> <body> <table width="95%" border="1" align="center" bordercolor="#001a33"> <tr> <td height="144" valign="top" bgcolor="#001a33" align="center"><p class="style1">House Rental Management System</p> <p align="center" class="style2">&nbsp;</p></td> </tr> </table> <table width="95%" border="0" align="center" bordercolor="#1a0000"> <tr> <td width="19%" height="34" bgcolor="#FF8C00"><div align="center"><strong><a href="userhome.php">User Home</a></strong></div></td> <td width="20%" bgcolor="#FF8C00"><div align="center"><strong><a href="view.php">View Details</a></strong></div></td> <td width="27%" bgcolor="#FF8C00"><div align="center"><strong><a href="index.php">LogOut</a></strong></div></td> </tr> </table> <p>&nbsp;</p> <table width="95%" border="0" align="center"> <tr> <td align="center"><p><strong>House Rental</strong>:</p> <table width="90%" border="0" align="center"> <tr> <td>&nbsp;&nbsp; <img src="images\1.jpg" width="1340" height="200"/> </tr> </table> <p>&nbsp; </p></td> </tr> </table> <form name="form1" method="post" action=""> <table width="50%" border="0" align="center"> <tr> <td colspan="2"><span class="style1">Payment Mode.... </span></td> </tr> <tr> <td>&nbsp;</td> <td><label> <input type="image" name="imageField" src="images/payment.png" /> </label></td> </tr> <tr> <td width="35%"><span class="style4">Amount</span> </td> <td><?php echo $amt;?></td> </tr> <tr> <td height="33"><span class="style4">Enter Card Number </span></td> <td><input name="cno" type="text" id="cno" /></td> </tr> <tr> <td height="36"><span class="style4">CVV Number </span></td> <td><input name="cvv" type="password" id="cvv" /></td> </tr> <tr> <td><span class="style4">Card Name </span></td> <td><input name="cname" type="text" id="cname" /></td> </tr> <tr> <td>&nbsp;</td> <td><label> <input name="btn" type="submit" id="btn" value="Pay Amount"> </label></td> </tr> </table> </form> <table width="95%" border="1" align="center" bordercolor="#001a33"> <tr> <td height="80" valign="center" bgcolor="#001a33" align="center"><p class="style1"></p></td> </tr> </table> </body> </html> <file_sep>/onwerhome.php <?php session_start(); include("dbconnect.php"); extract($_POST); $oid=$_SESSION['oid']; ?><file_sep>/reset1.php <?php include("dbconnect.php"); extract($_POST); session_start(); echo $email=$_REQUEST['email']; if(isset($_POST['btn'])) { if($psw==$psw1) { $qry=mysql_query("update register set psw='$psw' where email='$email'"); echo "<script>alert('Passwprd Update Sucess')</script>"; } else { echo "<script>alert('Pssword Not Match')</script>"; } } ?> <html> <title>House Rent</title> <head> <style type="text/css"> <!-- .style1 { font-size: 36px; font-weight: bold; color: #ffffff; } .style2 {font-size: 18px; font-weight: bold; color: #000000; } a { text-decoration:none; color:#000000; } .style3 {font-size: 18px} --> </style> </head> <body> <table width="95%" border="1" align="center" bordercolor="#001a33"> <tr> <td height="144" valign="top" bgcolor="#001a33" align="center"><p class="style1">House Rental Management System</p> <p align="center" class="style2">&nbsp;</p></td> </tr> </table> <table width="95%" border="0" align="center" bordercolor="#1a0000"> <tr> <td width="19%" height="34" bgcolor="#FF8C00"><div align="center"><strong><a href="index.php">Home</a></strong></div></td> <td width="20%" bgcolor="#FF8C00"><div align="center"><strong><a href="admin.php">Admin</a></strong></div></td> <td width="19%" bgcolor="#FF8C00"><div align="center"><strong><a href="guest.php">House Owner</a></strong></div></td> <td width="15%" bgcolor="#FF8C00"><div align="center"><strong><a href="user.php">User</a></strong></div></td> <td width="27%" bgcolor="#FF8C00"><div align="center"><strong><a href="forgot.php">Forgot Password</a></strong></div></td> </tr> </table> <p>&nbsp;</p> <table width="95%" border="0" align="center"> <tr> <td align="center"><p><span class="style3"><strong>House Rental</strong>:</span></p> <table width="90%" border="0" align="center"> <tr> <td>&nbsp;&nbsp; <img src="images\1.jpg" width="1340" height="200"/> </tr> </table> <p>&nbsp; </p></td> </tr> </table> <form id="form1" name="form1" method="post" action=""> <table width="46%" border="0" align="center"> <tr> <td colspan="2" rowspan="1"><div align="center" class="style2"><strong><font size="+1">Cahnge Psswords Login</font> </div></td> </tr> <tr> <td width="48%">&nbsp;</td> <td width="52%">&nbsp;</td> </tr> </tr> <tr> <td height="31"align="center"><span class="style2"><strong>Enter New Password </strong></span></td> <td><label> <input name="psw" type="password" id="psw" required/> </label></td> </tr> <tr> <td height="44" align="center"><span class="style2"><strong>Enter New Password Again</strong></span></td> <td><label> <input name="psw1" type="<PASSWORD>" id="<PASSWORD>" required/> </label></td> </tr> <tr> <td>&nbsp;</td> <td rowspan="2"><label> <input name="btn" type="submit" id="btn" /> <input type="reset" name="Submit2" value="Cancel" /> </label></td> </tr> </table> </form> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <table width="95%" border="1" align="center" bordercolor="#001a33"> <tr> <td height="80" valign="center" bgcolor="#001a33" align="center"><p class="style1"></p></td> </tr> </table> </body> </html> <file_sep>/view.php <?php session_start(); include("dbconnect.php"); extract($_POST); $uid=$_SESSION['uid']; ?> <html> <title>House Rent</title> <head> <style type="text/css"> <!-- .style1 { font-size: 36px; font-weight: bold; color: #ffffff; } .style2 {font-size: 18px; font-weight: bold; color: #000000; } a { text-decoration:none; color:#000000; } .style3 {font-size: 18px} --> </style> </head> <body> <table width="95%" border="1" align="center" bordercolor="#001a33"> <tr> <td height="144" valign="top" bgcolor="#001a33" align="center"><p class="style1">House Rental Management System</p> <p align="center" class="style2">&nbsp;</p></td> </tr> </table> <table width="95%" border="0" align="center" bordercolor="#1a0000"> <tr> <td width="19%" height="34" bgcolor="#FF8C00"><div align="center"><strong><a href="userhome.php">User Home</a></strong></div></td> <td width="20%" bgcolor="#FF8C00"><div align="center"><strong><a href="view.php">View Details</a></strong></div></td> <td width="27%" bgcolor="#FF8C00"><div align="center"><strong><a href="index.php">LogOut</a></strong></div></td> </tr> </table> <p>&nbsp;</p> <table width="95%" border="0" align="center"> <tr> <td align="center"><p><strong>House Rental</strong>:</p> <table width="90%" border="0" align="center"> <tr> <td>&nbsp;&nbsp; <img src="images\1.jpg" width="1340" height="200"/> </tr> </table> <p>&nbsp; </p></td> </tr> </table> <table width="100%" align="center"> <tr> <td colspan="10">&nbsp;</td> </tr> <tr> <td colspan="10" align="center">House Booking Details</td> </tr> <tr> <td colspan="10">&nbsp;</td> </tr> <tr> <td width="5%">&nbsp;</td> <td width="14%"><div align="center" class="style6"><strong>Id</strong> </div></td> <td width="10%"><div align="center" class="style6"><strong>Owner Name</strong> </div></td> <td width="12%"><div align="center" class="style6"><strong>House Location</strong> </div></td> <td width="13%"><div align="center" class="style6"><strong>Address</strong> </div></td> <td width="17%"><div align="center" class="style6"><strong>Rent Type</strong> </div></td> <td width="17%"><div align="center" class="style6"><strong>Status</strong> </div></td> </tr> <tr> <td colspan="10">&nbsp;</td> </tr> <?php $qry=mysql_query("select * from hregist where uid='$uid'"); $i=1; while($row=mysql_fetch_array($qry)) { $hid=$row['id']; $status=$row['status']; ?> <tr> <td width="5%">&nbsp;</td> <td><div align="center"><?php echo $row['id'];?></div></td> <td><div align="center"><?php echo $row['oname'];?></div></td> <td><div align="center"><?php echo $row['loc'];?></div></td> <td><div align="center"><?php echo $row['address'];?></div></td> <td><div align="center"><?php echo $row['rtype'];?></div></td> <td><div align="center"><?php if($status==1) { echo "Your Request Sent To the Owner"; } else if($status==2) { echo '<a href=payment.php?id='.$hid.'&amt='.$row['amnt'].'>Payment</a>'; } else { echo "Owner Accept Your Request"; } ?> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td width="17%">&nbsp;</td> </tr> <?php } ?> <tr> <td colspan="10" align="center">&nbsp;</td> </tr> </table> <br /> <br /> <br /> <table width="95%" border="1" align="center" bordercolor="#001a33"> <tr> <td height="80" valign="center" bgcolor="#001a33" align="center"><p class="style1"></p></td> </tr> </table> </body> </html> <file_sep>/admin.php <?php include("dbconnect.php"); extract($_POST); session_start(); if(isset($_POST['btn'])) { $qry=mysql_query("select * from admin where name='$uname' && psw='$password'"); $num=mysql_num_rows($qry); if($num==1) { echo "<script>alert('Login Successfull');</script>"; header("location:adminhome.php"); } else { echo "<script>alert('Login UnSuccessfull');</script>"; } } ?> <html> <title>House Rent</title> <head> <style type="text/css"> <!-- .style1 { font-size: 36px; font-weight: bold; color: #ffffff; } .style2 {font-size: 18px; font-weight: bold; color: #000000; } a { text-decoration:none; color:#000000; } .style3 {font-size: 18px} --> </style> </head> <body> <table width="95%" border="1" align="center" bordercolor="#001a33"> <tr> <td height="144" valign="top" bgcolor="#001a33" align="center"><p class="style1">House Rental Management System</p> <p align="center" class="style2">&nbsp;</p></td> </tr> </table> <table width="95%" border="0" align="center" bordercolor="#1a0000"> <tr> <td width="19%" height="34" bgcolor="#FF8C00"><div align="center"><strong><a href="index.php">Home</a></strong></div></td> <td width="20%" bgcolor="#FF8C00"><div align="center"><strong><a href="admin.php">Admin</a></strong></div></td> <td width="19%" bgcolor="#FF8C00"><div align="center"><strong><a href="guest.php">House Owner</a></strong></div></td> <td width="15%" bgcolor="#FF8C00"><div align="center"><strong><a href="user.php">User</a></strong></div></td> <td width="27%" bgcolor="#FF8C00"><div align="center"><strong><a href="forgot.php">Forgot Password</a></strong></div></td> </tr> </table> <p>&nbsp;</p> <table width="95%" border="0" align="center"> <tr> <td align="center"><p><span class="style3"><strong>House Rental</strong>:</span></p> <table width="90%" border="0" align="center"> <tr> <td>&nbsp;&nbsp; <img src="images\1.jpg" width="1340" height="200"/> </tr> </table> <p>&nbsp; </p></td> </tr> </table> <form id="form1" name="form1" method="post" action=""> <table width="46%" border="0" align="center"> <tr> <td colspan="2" rowspan="1"><div align="center" class="style2"><strong><font size="+1">Admin Login</font> </div></td> </tr> <tr> <td width="48%">&nbsp;</td> <td width="52%">&nbsp;</td> </tr> </tr> <tr> <td height="31"align="center"><span class="style2"><strong>User Name </strong></span></td> <td><label> <input name="uname" type="text" id="uname" /> </label></td> </tr> <tr> <td height="44" align="center"><span class="style2"><strong>Password</strong></span></td> <td><label> <input name="password" type="password" id="password" /> </label></td> </tr> <tr> <td>&nbsp;</td> <td rowspan="2"><label> <input name="btn" type="submit" id="btn" value="Login" /> <input type="reset" name="Submit2" value="Cancel" /> </label></td> </tr> </table> </form> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <table width="95%" border="1" align="center" bordercolor="#001a33"> <tr> <td height="80" valign="center" bgcolor="#001a33" align="center"><p class="style1"></p></td> </tr> </table> </body> </html> <file_sep>/house_rent.sql -- phpMyAdmin SQL Dump -- version 2.11.6 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: May 11, 2020 at 07:54 AM -- Server version: 5.0.51 -- PHP Version: 5.2.6 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `house_rent` -- -- -------------------------------------------------------- -- -- Table structure for table `admin` -- CREATE TABLE `admin` ( `name` varchar(50) NOT NULL, `psw` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `admin` -- INSERT INTO `admin` (`name`, `psw`) VALUES ('admin', '11'); -- -------------------------------------------------------- -- -- Table structure for table `gregister` -- CREATE TABLE `gregister` ( `id` int(50) NOT NULL auto_increment, `name` varchar(50) NOT NULL, `gender` varchar(50) NOT NULL, `age` varchar(50) NOT NULL, `email` varchar(50) NOT NULL, `phone` varchar(50) NOT NULL, `address` varchar(200) NOT NULL, `zip` varchar(50) NOT NULL, `uname` varchar(50) NOT NULL, `psw` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; -- -- Dumping data for table `gregister` -- INSERT INTO `gregister` (`id`, `name`, `gender`, `age`, `email`, `phone`, `address`, `zip`, `uname`, `psw`) VALUES (1, 'admin', 'male', '21', '<EMAIL>', '9087408476', 'trichy', '620008', 'admin', '111'); -- -------------------------------------------------------- -- -- Table structure for table `hregist` -- CREATE TABLE `hregist` ( `id` varchar(50) NOT NULL, `oname` varchar(50) NOT NULL, `loc` varchar(50) NOT NULL, `address` varchar(50) NOT NULL, `zip` varchar(50) NOT NULL, `htype` varchar(50) NOT NULL, `noh` varchar(50) NOT NULL, `rtype` varchar(50) NOT NULL, `hfor` varchar(50) NOT NULL, `rms` varchar(50) NOT NULL, `amnt` varchar(50) NOT NULL, `himg` blob NOT NULL, `dur` varchar(50) NOT NULL, `status` varchar(50) NOT NULL, `uid` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `hregist` -- INSERT INTO `hregist` (`id`, `oname`, `loc`, `address`, `zip`, `htype`, `noh`, `rtype`, `hfor`, `rms`, `amnt`, `himg`, `dur`, `status`, `uid`) VALUES ('1', 'admin', 'Trichy', ' trichy', '620008', 'Indvidual Villa', '1', 'rent', 'Family', '2', '4000', 0x626c6f67312e6a7067, '2yrs', '2', '1'), ('2', 'admin', 'Trichy', ' trichy', '62008', 'Apartment', '2', 'Lease', 'Family', '2', '5,00,000lks', 0x626c6f67322e6a7067, '2yrs', '2', '2'), ('3', 'admin', 'Madurai', ' trichy', '620008', 'Indvidual Villa', '2', 'rent', 'Family', '2', '4000', 0x626c6f67322e6a7067, '2yrs', '0', ''), ('4', 'admin', 'Trichy', ' trichy ', '620008', 'Apartment', '2', 'Lease', 'Family', '4', '5000', '', '2yrs', '0', ''); -- -------------------------------------------------------- -- -- Table structure for table `register` -- CREATE TABLE `register` ( `id` int(50) NOT NULL auto_increment, `name` varchar(50) NOT NULL, `gender` varchar(50) NOT NULL, `age` varchar(50) NOT NULL, `email` varchar(50) NOT NULL, `phone` varchar(50) NOT NULL, `address` varchar(200) NOT NULL, `details` varchar(100) NOT NULL, `uname` varchar(50) NOT NULL, `psw` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Dumping data for table `register` -- INSERT INTO `register` (`id`, `name`, `gender`, `age`, `email`, `phone`, `address`, `details`, `uname`, `psw`) VALUES (1, 'admin', 'male', '21', '<EMAIL>', '9087408476', 'trichy', 'testing', 'admin', '111'), (2, 'prasanna', 'male', '21', '<EMAIL>', '9087408476', 'trichy ', '', 'prasanna', '123'); <file_sep>/ghome.php <?php include("dbconnect.php"); extract($_POST); session_start(); $oname=$_SESSION['oname']; if(isset($_POST['btn'])) { $max_qry = mysql_query("select max(id) from hregist"); $max_row = mysql_fetch_array($max_qry); $id=$max_row['max(id)']+1; $qry=mysql_query("insert into hregist values('$id','$oname','$loc','$address','$zip','$htype','$noh','$rtype','$hfor','$rms','$amnt','$himg','$dur','0','$uid','$place','$date','$time')"); if($qry) { echo"<script> alert('Registerd sucessfully')</script>"; } else { echo "<script> alert('Enter the fields correctly')</script>"; } } ?> <html> <title>House Rent</title> <head> <style type="text/css"> <!-- .style1 { font-size: 36px; font-weight: bold; color: #ffffff; } .style2 {font-size: 18px; font-weight: bold; color: #000000; } a { text-decoration:none; color:#000000; } .style3 {font-size: 18px} --> </style> </head> <body> <table width="95%" border="1" align="center" bordercolor="#001a33"> <tr> <td height="144" valign="top" bgcolor="#001a33" align="center"><p class="style1">House Rental Management System</p> <p align="center" class="style2">&nbsp;</p></td> </tr> </table> <table width="95%" border="0" align="center" bordercolor="#1a0000"> <tr> <td width="19%" height="34" bgcolor="#FF8C00"><div align="center"><strong><a href="ghome.php">House Owner Home</a></strong></div></td> <td width="20%" bgcolor="#FF8C00"><div align="center"><strong><a href="viewr.php">View Request</a></strong></div></td> <td width="19%" bgcolor="#FF8C00"><div align="center"><strong><a href="viewc.php">View Clients</a></strong></div></td> <td width="27%" bgcolor="#FF8C00"><div align="center"><strong><a href="index.php">LogOut</a></strong></div></td> </tr> </table> <p>&nbsp;</p> <table width="95%" border="0" align="center"> <tr> <td align="center"><p><strong>House Rental</strong>:</p> <table width="90%" border="0" align="center"> <tr> <td>&nbsp;&nbsp; <img src="images\1.jpg" width="1340" height="200"/> </tr> </table> <p>&nbsp; </p></td> </tr> </table> <form id="f1" name="f1" method="post" action="#"> <table width="40%" border="0" align="center"> <tr> <td colspan="2" align="center"><strong>House Registration</strong></td> </tr> <tr> <td colspan="2">&nbsp;</td> <td width="4%"></td> <tr> <td width="46%">&nbsp;</td> <td width="50%">&nbsp;</td> </tr> <tr> <td align="justify"><strong> <div align="left">Location</div></td> <td><select name="loc"> <option value="Trichy">Trichy</option> <option value="Madurai">Madurai</option> <option value="Chennai">Chennai</option> <option value="Coimbatore">Coimbatore</option></select> </td> </tr> <tr> <td align="justify">Place</td> <td><label> <input name="place" type="text" id="place"> </label></td> </tr> <tr> <td align="justify"><strong> <div align="left">Address</div></td> <td><label> <textarea name="address" id="address"> </textarea></label></td> </tr> <tr> <td align="justify"><strong> <div align="left">Zip</div></td> <td><input name="zip" type="text" id="zip" /> </td> </tr> <tr> <td align="justify"><strong> <div align="left">House Type</div></td> <td><select name="htype" > <option value="">select</option> <option value="Apartment" >Apartment </option> <option value="Indvidual Villa" >Induvidial Villa </option></select> </td> </tr> <tr> <td align="justify"><strong> <div align="left">No of House</div></td> <td><input name="noh" type="text" id="noh" /> </td> </tr> <tr> <td align="justify"><strong> <div align="left">Rent Type</div></td> <td><select name="rtype"> <option value="">select</option> <option value="Lease"> Lease </option> <option value="rent"> Rent </option></select></td> </tr> <tr> <td align="justify"><strong> <div align="left">Duration</div></td> <td><input name="dur" type="text" id="dur" /></td> </tr> <tr> <td align="justify"><strong> <div align="left">House For</div></td> <td><select name= 'hfor'> <option value="">select</option> <option value="Family">Family</option> <option value="Bachelors">Bachelors</option> <option value="Paying guest">paying guest</option> <option value="all">For All</option></select> </td> </tr> <tr> <td align="justify"><strong> <div align="left">Number of Rooms</div></td> <td><input name="rms" type="text" id="rms" /></td> </tr> <tr> <td align="justify"><strong> <div align="left">Amount</div></td> <td><input name="amnt" type="text" id="amnt" /></td> </tr> <tr> <td align="justify"><strong> <div align="left">House Image</div></td> <td><input name="himg" type="file" id="himg" /></td> </tr> <tr> <td> <div align="left">Date </div></td> <td><label> <input name="date" type="date" id="date"> </label></td> </tr> <tr> <td><div align="left">Time</div></td> <td><label> <input name="time" type="time" id="time"> </label></td> </tr> <tr> <td>&nbsp;</td> <td><input name="btn" type="submit" id="btn" value="Submit" /> <input type="reset" name="Submit2" value="Reset" /></td> </tr> </table> </form> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <table width="95%" border="1" align="center" bordercolor="#001a33"> <tr> <td height="80" valign="center" bgcolor="#001a33" align="center"><p class="style1"></p></td> </tr> </table> </body> </html> <file_sep>/adminhome.php <?php include("dbconnect.php"); session_start(); extract($_POST); ?> <html> <title>House Rent</title> <head> <style type="text/css"> <!-- .style1 { font-size: 36px; font-weight: bold; color: #ffffff; } .style2 {font-size: 18px; font-weight: bold; color: #ffffff; } a { text-decoration:none; color:#000000; } .style3 {font-size: 18px} --> </style> </head> <body> <table width="95%" border="1" align="center" bordercolor="#001a33"> <tr> <td height="144" valign="top" bgcolor="#001a33" align="center"><p class="style1">House Rental Management System</p> <p align="center" class="style2">&nbsp;</p></td> </tr> </table> <table width="95%" border="0" align="center" bordercolor="#1a0000"> <tr> <td width="19%" height="34" bgcolor="#FF8C00"><div align="center"><strong><a href="adminhome.php">Home</a></strong></div></td> <td width="20%" bgcolor="#FF8C00"><div align="center"><strong><a href="viewg.php">View Owner </a></strong></div></td> <td width="15%" bgcolor="#FF8C00"><div align="center"><strong><a href="viewh.php">View Houses</a></strong></div></td> <td width="27%" bgcolor="#FF8C00"><div align="center"><strong><a href="index.php">LogOut</a></strong></div></td> </tr> </table> <p>&nbsp;</p> <table width="95%" border="0" align="center"> <tr> <td align="center"><p><span class="style3"><strong>House Rental</strong>:</span></p> <table width="90%" border="0" align="center"> <tr> <td>&nbsp;&nbsp; <img src="images\1.jpg" width="1340" height="200"/> </tr> </table> <p>&nbsp; </p></td> </tr> </table> <table width="98%" align="center"> <tr> <td colspan="10" align="center"><strong>User Details</strong></td> </tr> <tr> <td colspan="10">&nbsp;</td> </tr> <tr> <td width="1%">&nbsp;</td> <td width="7%"><div align="center" class="style6"><strong>Id</strong> </div></td> <td width="11%"><div align="center" class="style6"><strong>User Name</strong> </div></td> <td width="11%"><div align="center" class="style6"><strong>Gender</strong> </div></td> <td width="11%"><div align="center" class="style6"><strong>Age</strong> </div></td> <td width="9%"><div align="center" class="style6"><strong>Email</strong> </div></td> <td width="10%"><div align="center" class="style6"><strong>Contact No</strong> </div></td> <td width="10%"><div align="center" class="style6"><strong>Address</strong> </div></td> </tr> <tr> <td colspan="10">&nbsp;</td> </tr> <?php $qry=mysql_query("select * from register"); $i=1; while($row=mysql_fetch_array($qry)) { ?> <tr> <td width="1%">&nbsp;</td> <td><div align="center"><?php echo $row['id'];?></div></td> <td><div align="center"><?php echo $row['name'];?></div></td> <td><div align="center"><?php echo $row['gender'];?></div></td> <td><div align="center"><?php echo $row['age'];?></div></td> <td><div align="center"><?php echo $row['email'];?></div></td> <td><div align="center"><?php echo $row['phone'];?></div></td> <td><div align="center"><?php echo $row['address'];?></div></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <?php $i++; } ?> <tr> <td colspan="10" align="center">&nbsp;</td> </tr> </table> <table width="95%" border="1" align="center" bordercolor="#001a33"> <tr> <td height="80" valign="center" bgcolor="#001a33" align="center"><p class="style1"></p></td> </tr> </table> </body> </html> <file_sep>/viewc.php <?php session_start(); include("dbconnect.php"); extract($_POST); echo $oname=$_SESSION['oname']; if($_REQUEST["act"]==('add')) { $hid=$_REQUEST['hid']; $qt=mysql_query("update hregist set status='0' where hid='$hid'"); echo"Status Cleared"; } ?> <html> <title>House Rent</title> <head> <style type="text/css"> <!-- .style1 { font-size: 36px; font-weight: bold; color: #ffffff; } .style2 {font-size: 18px; font-weight: bold; color: #000000; } a { text-decoration:none; color:#000000; } .style3 {font-size: 18px} --> </style> </head> <body> <table width="95%" border="1" align="center" bordercolor="#001a33"> <tr> <td height="144" valign="top" bgcolor="#001a33" align="center"><p class="style1">House Rental Management System</p> <p align="center" class="style2">&nbsp;</p></td> </tr> </table> <table width="95%" border="0" align="center" bordercolor="#1a0000"> <tr> <td width="19%" height="34" bgcolor="#FF8C00"><div align="center"><strong><a href="ghome.php">House Owner Home</a></strong></div></td> <td width="20%" bgcolor="#FF8C00"><div align="center"><strong><a href="viewr.php">View Request</a></strong></div></td> <td width="19%" bgcolor="#FF8C00"><div align="center"><strong><a href="viewc.php">View Clients</a></strong></div></td> <td width="27%" bgcolor="#FF8C00"><div align="center"><strong><a href="index.php">LogOut</a></strong></div></td> </tr> </table> <p>&nbsp;</p> <table width="95%" border="0" align="center"> <tr> <td align="center"><p><strong>House Rental</strong>:</p> <table width="90%" border="0" align="center"> <tr> <td>&nbsp;&nbsp; <img src="images\1.jpg" width="1340" height="200"/> </tr> </table> <p>&nbsp; </p></td> </tr> </table> <table width="100%" align="center"> <tr> <td colspan="10">&nbsp;</td> </tr> <tr> <td colspan="10" align="center">House Booking Details</td> </tr> <tr> <td colspan="10">&nbsp;</td> </tr> <tr> <td width="5%">&nbsp;</td> <td width="14%"><div align="center" class="style6"><strong>Id</strong> </div></td> <td width="12%"><div align="center" class="style6"><strong>House Location</strong> </div></td> <td width="13%"><div align="center" class="style6"><strong>Address</strong> </div></td> <td width="17%"><div align="center" class="style6"><strong>Rent Type</strong> </div></td> <td width="17%"><div align="center" class="style6"><strong>User Name</strong> </div></td> <td width="17%"><div align="center" class="style6"><strong>Gender</strong> </div></td> <td width="17%"><div align="center" class="style6"><strong>Email</strong> </div></td> <td width="17%"><div align="center" class="style6"><strong>Phone</strong> </div></td> </tr> <tr> <td colspan="10">&nbsp;</td> </tr> <?php $qry=mysql_query("select * from hregist where oname='$oname' && status='2'"); $i=1; while($row=mysql_fetch_array($qry)) { $uid=$row['uid']; $qry1=mysql_query("select * from register where id='$uid'"); $row1=mysql_fetch_array($qry1); $status=$row['status']; ?> <tr> <td width="5%">&nbsp;</td> <td><div align="center"><?php echo $row['id'];?></div></td> <td><div align="center"><?php echo $row['loc'];?></div></td> <td><div align="center"><?php echo $row['address'];?></div></td> <td><div align="center"><?php echo $row['rtype'];?></div></td> <td><div align="center"><?php echo $row1['name'];?></div></td> <td><div align="center"><?php echo $row1['gender'];?></div></td> <td><div align="center"><?php echo $row1['email'];?></div></td> <td><div align="center"><?php echo $row1['phone'];?></div></td> <td><div align="center"><a href="viewc.php?act=del&hid=<?php echo $row['id'];?>">Cancel User</a></div></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td width="17%">&nbsp;</td> </tr> <?php } ?> <tr> <td colspan="10" align="center">&nbsp;</td> </tr> </table> <table width="95%" border="1" align="center" bordercolor="#001a33"> <tr> <td height="80" valign="center" bgcolor="#001a33" align="center"><p class="style1"></p></td> </tr> </table> </body> </html> <file_sep>/userhome.php <?php include("dbconnect.php"); extract($_POST); session_start(); echo $uid=$_SESSION['uid']; ?> <html> <title>House Rent</title> <head> <style type="text/css"> <!-- .style1 { font-size: 36px; font-weight: bold; color: #ffffff; } .style2 {font-size: 18px; font-weight: bold; color: #000000; } a { text-decoration:none; color:#000000; } .style3 {font-size: 18px} --> </style> </head> <body> <table width="95%" border="1" align="center" bordercolor="#001a33"> <tr> <td height="144" valign="top" bgcolor="#001a33" align="center"><p class="style1">House Rental Management System</p> <p align="center" class="style2">&nbsp;</p></td> </tr> </table> <table width="95%" border="0" align="center" bordercolor="#1a0000"> <tr> <td width="19%" height="34" bgcolor="#FF8C00"><div align="center"><strong><a href="userhome.php">User Home</a></strong></div></td> <td width="20%" bgcolor="#FF8C00"><div align="center"><strong><a href="view.php">View Details</a></strong></div></td> <td width="27%" bgcolor="#FF8C00"><div align="center"><strong><a href="index.php">LogOut</a></strong></div></td> </tr> </table> <p>&nbsp;</p> <table width="95%" border="0" align="center"> <tr> <td align="center"><p><strong>House Rental</strong>:</p> <table width="90%" border="0" align="center"> <tr> <td>&nbsp;&nbsp; <img src="images\1.jpg" width="1340" height="200"/> </tr> </table> <p>&nbsp; </p></td> </tr> </table> <form actio="#" method="post"> <table width="100%" border="0" align="center"> <tr> <td colspan="6">&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td align="center">Select location </td> <td align="center"> </td> <td align="center"> <table width="100%" border="0"> <tr> <td width="8%">Select City </td> <td width="8%"><select name="loc"> <option value="">Select</option> <option value="Trichy">Trichy</option> <option value="Madurai">Madurai</option> <option value="Chennai">Chennai</option> <option value="Coimbatore">Coimbatore</option></select>&nbsp;</td> <td width="8%">Select Place</td> <td width="8%"><select name="place" id="place"> <?php $qs=mysql_query("select * from hregist"); while($r=mysql_fetch_array($qs)) { ?> <option value="<?php echo $r['place'];?>"><?php echo $r['place'];?></option> <?php } ?> </select></td> <td width="8%"><label> Price:</label></td> <td width="13%"><label> <input name="price" type="text" id="price"> </label></td> <td width="54%"><input type="submit" name="btn"></td> <td width="1%">&nbsp;</td> </tr> </table></td> </tr> <tr> <td colspan="6">&nbsp;</td> </tr> </form> <tr> <td>&nbsp;</td> <td><div align="center" class="style6"><strong>Owner</strong> </div></td> <td><div align="center" class="style6"><strong>Location</strong> </div></td> <td><div align="center" class="style6"><strong>Address</strong> </div></td> <td><div align="center" class="style6"><strong>House Type</strong></div></td> <td><div align="center" class="style6"><strong>Only For</strong></div></td> <td><div align="center" class="style6"><strong>Rent Type</strong></div></td> <td><div align="center" class="style6"><strong>View Details</strong></div></td> </tr> <tr> <td colspan="7">&nbsp;</td> </tr> <?php $qry=mysql_query("select * from hregist where loc='$loc' && status='0' && place='$place' && amnt<='$price'"); $i=1; while($row=mysql_fetch_array($qry)) { ?> <tr> <td>&nbsp;</td> <td><div align="center"><?php echo $row['oname'];?></div></td> <td><div align="center"><?php echo $row['loc'];?></div></td> <td><div align="center"><?php echo $row['address'];?></div></td> <td><div align="center"><?php echo $row['htype'];?></div></td> <td><div align="center"><?php echo $row['hfor'];?></div></td> <td><div align="center"><?php echo $row['rtype']; ;?></div></td> <td><div align="center"><a href="uview.php?oname=<?php echo $row['oname'];?>&hid=<?php echo $row['id'];?>">House Details</a></div></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <?php $i++; } ?> </table> <table width="95%" border="1" align="center" bordercolor="#001a33"> <tr> <td height="80" valign="center" bgcolor="#001a33" align="center"><p class="style1"></p></td> </tr> </table> </body> </html>
426dad9e50e05b5d1134f9475287c19e7b0887c2
[ "SQL", "PHP" ]
12
PHP
Saisharan-24/Tourism-Superintendence
aa2137daad3e04d0597f210ba1dddc47f8673954
97f74775bb8f880659e27542e2dfdfab05c2244a
refs/heads/master
<file_sep>#!/usr/bin/python # -*- coding: utf-8 -*- import sys, codecs sys.stdin = codecs.getreader('utf-8')(sys.stdin) sys.stdout = codecs.getwriter('utf-8')(sys.stdout) conversion = { u'а': 'a', u'б': 'b', u'в': 'v', u'г': 'g', u'д': 'd', u'е': 'e', u'ё': 'e', u'ж': 'zh', u'з': 'z', u'и': 'i', u'й': 'y', u'к': 'k', u'л': 'l', u'м': 'm', u'н': 'n', u'о': 'o', u'п': 'p', u'р': 'r', u'с': 's', u'т': 't', u'у': 'u', u'ф': 'f', u'х': 'h', u'ц': 'c', u'ч': 'ch', u'ш': 'sh', u'щ': 'sch', u'ъ': '\'', u'ы': 'y', u'ь': '\'', u'э': 'e', u'ю': 'yu', u'я': 'ya', u'А': 'A', u'Б': 'B', u'В': 'V', u'Г': 'G', u'Д': 'D', u'Е': 'E', u'Ё': 'E', u'Ж': 'Zh', u'З': 'Z', u'И': 'I', u'Й': 'Y', u'К': 'K', u'Л': 'L', u'М': 'M', u'Н': 'N', u'О': 'O', u'П': 'P', u'Р': 'R', u'С': 'S', u'Т': 'T', u'У': 'U', u'Ф': 'F', u'Х': 'H', u'Ц': 'C', u'Ч': 'Ch', u'Ш': 'Sh', u'Щ': 'Sch', u'Ъ': '\'', u'Ы': 'Y', u'Ь': '\'', u'Э': 'E', u'Ю': 'Yu', u'Я': 'Ya' } def transliterate(str): result = '' for c in str: try: c = conversion[c] except KeyError: pass result += c return result for l in sys.stdin.readlines(): sys.stdout.write(transliterate(l)) <file_sep>#!/usr/bin/python # -*- coding: utf-8 -*- import sys, codecs sys.stdin = codecs.getreader('utf-8')(sys.stdin) sys.stdout = codecs.getwriter('utf-8')(sys.stdout) while 1: c = sys.stdin.read(1) if not c: break if c in u'abcABCабвгАБВГ': nc = '2' elif c in u'defDEFдеёжзДЕЁЖЗ': nc = '3' elif c in u'ghiGHIийклИЙКЛ': nc = '4' elif c in u'jklJKLмнопМНОП': nc = '5' elif c in u'mnoMNOрстуРСТУ': nc = '6' elif c in u'pqrsPQRSфхцчФХЦЧ': nc = '7' elif c in u'tuvTUVшщъыШЩЪЫ': nc = '8' elif c in u'wxyzWXYZьэюяЬЭЮЯ': nc = '9' else: nc = c sys.stdout.write(nc) <file_sep>#!/usr/bin/python # -*- coding: utf-8 -*- import sys, codecs sys.stdin = codecs.getreader('utf-8')(sys.stdin) sys.stdout = codecs.getwriter('utf-8')(sys.stdout) table_in = u'Ёё' table_out = u'Eе' def trans(str, table_in, table_out): result = '' for c in list(str): try: result += table_out[table_in.index(c)] except: result += c return result for l in sys.stdin.readlines(): if u'ё' in l or u'Ё' in l: sys.stdout.write(trans(l, table_in, table_out)) sys.stdout.write(l) <file_sep>#!/usr/bin/python # -*- coding: utf-8 -*- import sys, codecs sys.stdin = codecs.getreader('utf-8')(sys.stdin) sys.stdout = codecs.getwriter('utf-8')(sys.stdout) table_lower = u'abcdefghijkl<KEY>лмнопрстуфхцчшщъыьэюя' table_upper = u'ABCDEFGHIJKLMNOPQRSTUVWXYZАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ' def trans(str, table_in, table_out): result = '' for c in list(str): try: result += table_out[table_in.index(c)] except: result += c return result def lowercase(str): return trans(str, table_upper, table_lower) def uppercase(str): return trans(str, table_lower, table_upper) def variation(str): result = [] length = len(str) if length < 1: return result lowercasestr = lowercase(str) result.append(lowercasestr) for n in range(1, length - 1): for i in range(length - n): result.append(lowercasestr[:i] + uppercase(lowercasestr[i: i + n]) + lowercasestr[i + n:]) result.append(uppercase(str)) return result for l in sys.stdin.readlines(): for v in variation(l): sys.stdout.write(v) <file_sep>#!/bin/bash while read line; do [ ${#line} -gt 8 ] && echo $line; done <file_sep>#!/usr/bin/env ruby KEY_SIZE = 6 KEY_RANGE = 10 print "key128 db " KEY_SIZE.times { |x| print "0x%02x," % rand(KEY_RANGE) } print "%d dup (0x00)\n" % (16 - KEY_SIZE) <file_sep>misc ==== Different tools and scripts <file_sep>#!/bin/bash ruby random_key.rb > key128.inc fasm crypt.asm wine crypt.exe fasm decrypt.asm upx -9 decrypt.exe
2e4fcf23c290cce3c9b5dc3290d3a2290170892b
[ "Markdown", "Python", "Ruby", "Shell" ]
8
Python
jabb3rd/misc
f5787e1814aaff71768a83d5c7d2ef3e363e6c59
55ca9edff70bd89ba5c35c58645cc0e401790844
refs/heads/master
<repo_name>ayu-ahilan/AbgabeProjekt_PunchClock<file_sep>/src/main/java/ch/zli/m223/punchclock/domain/User.java package ch.zli.m223.punchclock.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import jdk.jfr.Enabled; import javax.persistence.*; import java.util.List; /** * Class: * * @Author: <NAME> * @Version: */ @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column private String username; @Column private String password; @Column private Boolean isAdmin; @OneToMany(mappedBy = "user") @JsonIgnore private List<Entry> entries; public long getId() { return id; } public Boolean getIsAdmin() { return isAdmin; } public void setIsAdmin(Boolean admin) { this.isAdmin = admin; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public List<Entry> getEntries() { return entries; } public void setId(long id) { this.id = id; } public void setEntries(List<Entry> entries) { this.entries = entries; } } <file_sep>/src/main/java/ch/zli/m223/punchclock/service/CategoryService.java package ch.zli.m223.punchclock.service; import ch.zli.m223.punchclock.domain.Category; import ch.zli.m223.punchclock.domain.Entry; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.transaction.Transactional; import java.util.List; /** * Class: * * @Author: <NAME> * @Version: */ @ApplicationScoped public class CategoryService { @Inject EntityManager entityManager; @Transactional public Category createCategory(Category category) { entityManager.persist(category); return category; } @Transactional public void deleteCategory(long id) { Category actuelCategory = entityManager.find(Category.class, id); entityManager.remove(actuelCategory); } @SuppressWarnings("unchecked") public List<Category> findAll() { var query = entityManager.createQuery("FROM Category"); return query.getResultList(); } public Category getCategory(Long id) { return entityManager.find(Category.class, id); } @Transactional public void delete(Long id) { Category e = getCategory(id); entityManager.remove(e); } } <file_sep>/src/main/java/ch/zli/m223/punchclock/controller/ProjectController.java package ch.zli.m223.punchclock.controller; import ch.zli.m223.punchclock.domain.Category; import ch.zli.m223.punchclock.domain.Project; import ch.zli.m223.punchclock.service.CategoryService; import ch.zli.m223.punchclock.service.ProjectService; import org.eclipse.microprofile.openapi.annotations.Operation; import org.eclipse.microprofile.openapi.annotations.tags.Tag; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.transaction.Transactional; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.List; /** * Class: * * @Author: <NAME> * @Version: */ @Path("/projects") @Tag(name = "Project", description = "Handling of Projects") public class ProjectController { @Inject ProjectService projectService; //gibt alle Einträge zurück @GET @Produces(MediaType.APPLICATION_JSON) @Operation(summary = "List all Projects", description = "It will return all Projects") public List<Project> list() { return projectService.findAll(); } // gibt einen Category zurück @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @Operation(summary = "Get a Project", description = "The Project with the right Id will be returned") public Project getProject(@PathParam("id") Long id) { return projectService.getProject(id); } // fügt einen Category hinzu @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Operation(summary = "Add a new Project", description = "The newly created Project is returned. The id may not be passed.") public Project add(Project project) { return projectService.createProject(project); } //Löschen eines Categories anhand von der ID @DELETE @Path("/{id}") @Operation(summary = "Delete a Project", description = "The Project with the right Id will be deleted") public void delete(@PathParam("id") Long id) { projectService.deleteProject(id); } } <file_sep>/src/main/java/ch/zli/m223/punchclock/controller/UserController.java package ch.zli.m223.punchclock.controller; import ch.zli.m223.punchclock.domain.Entry; import ch.zli.m223.punchclock.domain.User; import ch.zli.m223.punchclock.service.UserService; import org.eclipse.microprofile.openapi.annotations.Operation; import org.eclipse.microprofile.openapi.annotations.tags.Tag; import javax.inject.Inject; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.List; /** * Class: * * @Author: <NAME> * @Version: */ @Path("/users") @Tag(name = "User", description = "Handling of users") public class UserController { @Inject UserService userService; @GET @Produces(MediaType.APPLICATION_JSON) @Operation(summary = "List all Users", description = "It will return all Users") public List<User> list() { return userService.findAll(); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @Operation(summary = "Get a User", description = "The User with the right Id will be returned") public User getUser(@PathParam("id") Long id) { return userService.getUserById(id); } @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Operation(summary = "Add a new User", description = "The newly created User is returned. The id may not be passed.") public User add(User user) { return userService.createUser(user); } @DELETE @Path("/{id}") @Operation(summary = "Delete a User", description = "The User with the right Id will be deleted") public void delete(@PathParam("id") Long id) { userService.deleteUser(id); } //Updatet einen Eintrag @PUT @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Operation(summary = "Update a User", description = "The User with the right Id will be updated") public User updateUser(User user) { return userService.updateUser(user); } } <file_sep>/src/main/java/ch/zli/m223/punchclock/controller/AuthenticationController.java package ch.zli.m223.punchclock.controller; import ch.zli.m223.punchclock.domain.User; import ch.zli.m223.punchclock.service.AuthenticationService; import ch.zli.m223.punchclock.service.UserService; import org.eclipse.microprofile.openapi.annotations.Operation; import javax.inject.Inject; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; /** * Class: * * @Author: <NAME> * @Version: */ @Path("/auth") public class AuthenticationController { @Inject AuthenticationService authenticationService; @POST @Path("/User") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.TEXT_PLAIN) @Operation(summary = "login user", description = "The user tries to login into the application") public String login(User user) { if (authenticationService.checkifUserExists(user)) { return authenticationService.GenerateValidJwtToken(user.getUsername()); } else { throw new NotAuthorizedException("User ["+user.getUsername()+"]"); } } } <file_sep>/src/main/resources/import.sql INSERT INTO category (title) VALUES ('Admin'); INSERT INTO category (title) VALUES ('Project'); INSERT INTO category (title) VALUES ('IT-Support'); INSERT INTO user (username, password) VALUES ('test' '<PASSWORD>');<file_sep>/Readme.md M223 Punchclock Dieses Projekt ist eine PunchClock. (Auf Deutsch: Zeitstempflungsmaschine). Man kann sich Anmelden oder Registrieren und seinne Zeiten buchen. Man kann dazu auch noch eingeben, an welchem Projekt man gearbeitet hat. Und dann noch eine Kategorie eingeben. Beim Projekt ist gedacht, dass man zum Beispiel die Firma erwähnt. Bei Kategorie wer gearbeitet hat. Kann zum Beispiel für den Stundensatz verwendet werden. Dieses Projekt ist die Aschlussarbeit des Modules 223. Im ÜK haben wir ein Basis-Projekt erhalten. Dieses Projekt baut darauf auf. Folgende Schritte sind notwendig um die Applikation zu erstellen und zu starten: Stellen Sie sicher, dass OpenJDK 11 oder höher installiert und JAVA_HOME korrekt gesetzt ist. Installieren Sie (falls noch nicht vorhanden) Apache Maven 3.8.1 oder höher Wechseln Sie auf der Kommandozeile in den Ordner dieser Appliation. cd m223-helloworld-quarkus/ Starten Sie die Applikation mit (Dieses Projekt wure mit IntelliJ und mithilfe vom Chrome Browser entwickelt) ./mvnw compile quarkus:dev Die Anmelde Daten sind: Benutzername: test, Passwort: <PASSWORD> Folgende Dienste stehen während der Ausführung im Profil dev zur Verfügung: Swagger API: http://localhost:8080/q/swagger-ui/ H2 Console: http://localhost:8080/h2/ Datenquelle: jdbc:h2:mem:punchclock Benutzername: zli Passwort: zli Es hat schon einige Beispieldateien drin, zum testen. (import.sql) Abweichungen zur Planung Ich habe realisiert das CheckIn und CheckOut in Project überflüssig ist und weg gelassen. Die UserID ist eigentlich auch überflüssig, da es im Entry drin ist. Da jetzt keine UserID vorhanden ist, ist getUserID auch überflüssig. Bei Project habe ich das update, da man es lieber ganz löschen sollte. Ein paar methoden wurden namentlich geändert, wie zum Beispiel bei allen Klassen (getSingle...)
e8c97ea0a6fd22aaf236d25428d55aaf02a852a1
[ "Markdown", "Java", "SQL" ]
7
Java
ayu-ahilan/AbgabeProjekt_PunchClock
38813057288c3f64b55ffeddbfba51e07e7d28b8
fb8bf28231da6f59cf3fcb3900439eb649fb6b82
refs/heads/master
<repo_name>andrewscancari/angular-io-examples<file_sep>/async-await/src/app/app.component.ts import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; import { connectableObservableDescriptor } from 'rxjs/internal/observable/ConnectableObservable'; import { BrazilianDeputy, BrazilianDeputyData } from './models/brazilian-deputy.model'; const mockBrazilianDeputies: BrazilianDeputy[] = [{ email: '<EMAIL>', id: 204554, idLegislatura: 56, nome: '<NAME>', siglaPartido: 'PL', siglaUf: 'BA', uri: 'https://dadosabertos.camara.leg.br/api/v2/deputados/204554', uriPartido: 'https://dadosabertos.camara.leg.br/api/v2/partidos/37906', urlFoto: 'https://www.camara.leg.br/internet/deputado/bandep/204554.jpg', }] @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { public readonly title = 'async-await'; public tableDataSource = []; public readonly displayedColumns: string[] = ['nome', 'siglaPartido', 'siglaUf', 'urlFoto']; constructor( private httpclient: HttpClient ) {} private getBrazilianDeputies(): Promise<BrazilianDeputyData> { const url = 'https://dadosabertos.camara.leg.br/api/v2/deputados?itens=10&ordem=ASC&ordenarPor=nome'; return this.httpclient.get<BrazilianDeputyData>(url).toPromise(); } async ngOnInit(): Promise<void> { try { console.log('buscando lista de deputados...'); const brazilianDeputiesData = await this.getBrazilianDeputies(); console.log('lista carregada com sucesso!'); this.tableDataSource = brazilianDeputiesData.dados; } catch (error) { console.log(error); } } } <file_sep>/async-await/src/app/models/brazilian-deputy.model.ts export interface BrazilianDeputy { email: string; id: number; idLegislatura: number; nome: string; siglaPartido: string; siglaUf: string; uri: string; uriPartido: string; urlFoto: string; } export interface BrazilianDeputyDataLinks { href: string; rel: string; } export interface BrazilianDeputyData { dados: BrazilianDeputy[]; links: BrazilianDeputyDataLinks[]; } <file_sep>/observable/src/app/app.component.ts import { HttpClient } from '@angular/common/http'; import { Component, OnDestroy, OnInit } from '@angular/core'; import { Observable, Subscription } from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit, OnDestroy { constructor( private httpClient: HttpClient ) {} title = 'observable'; public auxValues: string[] = []; public deputiesList: []; private timeoutSubscription: Subscription; timeoutExample(): Observable<string> { return new Observable<string>(observable => { setTimeout(() => { observable.next('First timeout'); }, 2000); setTimeout(() => { observable.next('Second timeout'); // Uncomment this line to simulate an error // observable.error('Observable error!'); // Uncomment this line to force observable to complete before next steps // observable.complete(); }, 3000); setTimeout(() => { observable.next('Third timeout'); }, 5000); setTimeout(() => { observable.next('Fourth timeout'); }, 4000); }); } exampleHttpDeputies(): Observable<any> { const url = 'https://dadosabertos.camara.leg.br/api/v2/deputados?itens=5&ordem=ASC&ordenarPor=nome'; return this.httpClient.get(url); } ngOnInit() { const timeoutExample = this.timeoutExample(); this.timeoutSubscription = timeoutExample.subscribe( success => { this.auxValues.push(success); console.log(success); }, error => { this.auxValues.push(error); console.log(error); }, () => { const auxMsg = 'Observable completed'; this.auxValues.push(auxMsg); console.log(auxMsg); } ); } ngOnDestroy() { if (this.timeoutSubscription) { this.timeoutSubscription.unsubscribe(); } } }
c4cc8205bf6f1177f05ba43f885bbc8453184093
[ "TypeScript" ]
3
TypeScript
andrewscancari/angular-io-examples
2b81089f2b8997a50e8f593cedc3ad7c84439c2f
486e45b5fcb8be0613becd80a226c7f81a8f6bfb
refs/heads/main
<file_sep>#range 사용하기 #여러 개의 셀이 포함되어 있는 range를 사용하기 import openpyxl wb = openpyxl.Workbook() sheet = wb.active a = sheet['A1':'B9']# 범위를 불러왔을 때, 튜플이 이중으로 되어있음.하나의 행에 대한 정보가 튜플로 만들어져있음, 행을 모아놓은 것을 또 튜플로 가지고 있음 # ((<Cell 'Sheet'.A1>, <Cell 'Sheet'.B1>, <Cell 'Sheet'.C1>), (<Cell 'Sheet'.A2>, <Cell 'Sheet'.B2>, <Cell 'Sheet'.C2>), (<Cell 'Sheet'.A3>, <Cell 'Sheet'.B3>, <Cell 'Sheet'.C3>)) no = 1 for x,y in a: print(x, y) x.value = 2 y.value = no no += 1 for x,y in a: print(x.value, y.value)<file_sep>import openpyxl dest_filename = './myworkbook.xlsx' wb = openpyxl.Workbook() # Workbook은 클래스고 적어도 한 개 이상의 worksheet를 만들어낸다. active를 통해 활성화시킬 수 있다. sheet = wb.active #저장시킨 워크북을 wb.active를 통해서 시트를 활성화시킴. sheet.title = 'mysheet1' #시트의 이름을 설정함. sheet['A1'].value = 'name' #시트에 columns가 A, rows가 1인 셀을 만들어냄. sheet['A2'].value = 'yoon so young' sheet.cell(row=3, column=1).value = 20 wb.save(dest_filename) #엑셀을이름을 저장해주는 것.저장해 주는 것. <file_sep>import openpyxl import os print(os.getcwd()) os.chdir('/Users/baegmingi/pythonData/openpyxl연습/MyExcelFiles') print(os.getcwd()) target_filename ="./myworkbook.xlsx" dest_filename = './myworkbook_after.xlsx' wb = openpyxl.load_workbook(target_filename) #기존 workbook을 불러온다. print(wb.sheetnames) wb.create_sheet(index=0, title='mysheet0') #맨 앞에 시트에 title이 mysheet 0인 것을 삽입 wb.create_sheet(title='mysheet2') #생략해서 맨 뒤에 mysheet2인 것을 삽입함 print(wb.sheetnames) #리스트 형태로 전체 시트를 불러옴 snames = wb.sheetnames #시트 네임은 wb.sheeetnames sheet = wb['mysheet1'] #wb[snaems[1]] 1번 인덱스의 것. 모두다 mysheet에 대한 것 print(sheet['A1'].value) print(sheet['A2'].value) wb.save(dest_filename) #range 사용하기 #여러 개의 셀이 포함되어 있는 range를 사용하기<file_sep>import openpyxl target_filename = './(Yoon) 완료 68회 PreStarter 속성분석의 사본.xlsx' wb = openpyxl.load_workbook(target_filename) snames = wb.sheetnames ws = wb[snames[0]] ent_dic ={} col_dic1 = {} col_list = [] for sheet in snames: column = ws['F'] for i in column: if i.value != None: col_list.append(i.value) ent_dic[col_list[0]] = col_list[1:] col_dic2 = {} col_list2 = [] for sheet in snames: column = ws['P'] for i in column: if i.value != None: col_list2.append(i.value) ent_dic[col_list2[0]] = col_list2[1:] print(ent_dic) f = open('dic.txt', 'w') f.write("{}".format(ent_dic)) f.close() <file_sep># 하나의 문제별로 딕셔너리를 만들어보기 그 다음엔 반복하기 import openpyxl wb = openpyxl.load_workbook('./(Yoon)완료 68회 Basic - 문항속성분석.xlsx') sheet_names = wb.sheetnames #첫 번째 시트부터 ws = wb[sheet_names[0]] #문항번호마다 열기 exam_no_dic = {} # 문항번호 열기 # for i in ws.rows # for cell in column: # if i.value != None: # col_list2.append(i.value) for col in ws.iter_cols(min_row=1, min_col=15, max_row=2, max_col=27): for cell in col: print(cell) dic_no_1 = {} col_o = [] # 각 문항별 value 값을 저장 for col in ws.iter_cols(min_row=2, min_col=15, max_row=21, max_col=19): for cell in col: if cell.value != None: col_o.append(cell.value) dic_no_1["DistractorsVector[]"] = col_o col_t = [] for col in ws.iter_cols(min_row=1, min_col=20, max_row=21, max_col=20): for cell in col: if cell.value != None: if len(col_t) > 1: col_t.append(cell.value) dic_no_1["DistractorsVector[]"] = col_o else: col_t.append(cell.value) dic_no_1[col_t[0]] = col_t[-1] col_u = [] for col in ws.iter_cols(min_row=1, min_col=21, max_row=21, max_col=21): for cell in col: if cell.value != None: if len(col_u) > 2: col_u.append(cell.value) dic_no_1["DistractorsVector[]"] = col_u else: col_u.append(cell.value) dic_no_1[col_u[0]] = col_u[-1] col_v = [] for col in ws.iter_cols(min_row=1, min_col=22, max_row=21, max_col=22): for cell in col: if cell.value != None: if len(col_v) > 2: col_v.append(cell.value) dic_no_1["DistractorsVector[]"] = col_v else: col_v.append(cell.value) dic_no_1[col_v[0]] = None col_w = [] for col in ws.iter_cols(min_row=1, min_col=23, max_row=21, max_col=23): for cell in col: if cell.value != None: if len(col_w) > 2: col_w.append(cell.value) dic_no_1["DistractorsVector[]"] = col_w else: col_w.append(cell.value) dic_no_1[col_w[0]] = col_w[-1] col_x = [] for col in ws.iter_cols(min_row=1, min_col=24, max_row=21, max_col=24): for cell in col: if cell.value != None: if len(col_x) > 2: col_x.append(cell.value) dic_no_1["DistractorsVector[]"] = col_x else: col_x.append(cell.value) dic_no_1[col_x[0]] = col_x[-1] col_y = [] for col in ws.iter_cols(min_row=1, min_col=25, max_row=21, max_col=25): for cell in col: if cell.value != None: if len(col_y) > 2: col_y.append(cell.value) dic_no_1["DistractorsVector[]"] = col_y else: col_y.append(cell.value) dic_no_1[col_y[0]] = col_y[-1] col_z = [] for col in ws.iter_cols(min_row=1, min_col=26, max_row=21, max_col=26): for cell in col: if cell.value != None: if len(col_z) > 2: col_z.append(cell.value) dic_no_1["DistractorsVector[]"] = col_z else: col_z.append(cell.value) dic_no_1[col_z[0]] = col_z[-1] col_AA = [] for col in ws.iter_cols(min_row=1, min_col=27, max_row=21, max_col=27): for cell in col: if cell.value != None: if len(col_AA) > 2: col_AA.append(cell.value) dic_no_1["DistractorsVector[]"] = col_AA else: col_AA.append(cell.value) dic_no_1[col_AA[0]] = col_AA[-1] col_AB = [] for col in ws.iter_cols(min_row=1, min_col=28, max_row=21, max_col=28): for cell in col: if cell.value != None: if len(col_AB) > 2: col_AB.append(cell.value) dic_no_1["DistractorsVector[]"] = col_AB else: col_AB.append(cell.value) dic_no_1[col_AB[0]] = col_AB[-1] dic_no_1["QuestionType"] = dic_no_1.pop("유형") print("{} 1번".format(sheet_names[0])) print(dic_no_1) f = open("./roti.txt", 'w') f.write("{}".format(dic_no_1)) f.close() <file_sep># TIL_openpyxl openpyxl today i learned <file_sep>dic = {} list_str = ["a","b"] list_num= [1, 2, 3, 4, 5, 6, 7, 8, 9] list_tennum = [11,22,33,44,55,66,77,88,99] list2 = [list_num, list_tennum] for i in range(2): dic[list_str[i]] = list2[i] print(dic) <file_sep>import pandas as pd #엑셀 읽기 a1 = pd.read_excel('(Yoon) 완료 68회 PreStarter 속성분석의 사본.xlsx', header=1) #읽은 엑셀을 리스트로변환 alist = a1.values.tolist() #리스트에서 한 행씩 읽어서 str변수에 원하는 형태로 삽입 tupletext = "sign = {" for i in range(len(alist)): tupletext += "\""+str(alist[i][2])+"\" : " + str(alist[i][1]) + "," if i%7 == 0 :tupletext += "\n" tupletext += "}" #text 파일 만들기 f= open("sign2.txt","w",-1,encoding="utf-8") #만든 str을 text에 넣기 f.write(tupletext) #파일 닫기 f.close() print(tupletext)<file_sep>dic = {} for i in range(1,11): for i in range dic{i}<file_sep>import openpyxl wb = openpyxl.load_workbook("./(Yoon)완료 68회 Basic - 문항속성분석.xlsx") sheet_names = wb.sheetnames #첫 번째 시트부터 sheet_num = "Basic LC PartA" ws = wb[sheet_num] #함수 만들기 value를 리스트에 저장하는 함수 key_list = ["DistratorsVector[]", "Keywords", "Themes", "Difficulty", "PromptTense", "Word Class", "지능분류", "QuestionType", "Communication"] dic_no = {} col_o = [] for col in ws.iter_cols(min_row=2, min_col=15, max_row=21, max_col=19): for cell in col: if cell.value != None: col_o.append(cell.value) dic_no[key_list[0]] = col_o def find_col(row_num): col_num = 20 while col_num < 30: key_no = 1 value_list = [] for col in ws.iter_cols(min_row=row_num, min_col=col_num, max_row=row_num, max_col=col_num): for cell in col: if cell.value != None: value_list.append(cell.value) if len(value_list) > 2: dic_no[key_list[key_no]] = value_list else: dic_no[key_list[key_no]] = value_list[-1] col_num += 1 key_no += 1 return print("{}번 문항".format, dic_no) row_num = 2 #2부터 시작 while row_num < 104: find_col(row_num) row_num +=20
f6d0a57c4c5a715400189b63c7aa8b53c910e1db
[ "Markdown", "Python" ]
10
Python
toyo30/TIL_openpyxl
9a48e3121b2a102b4313f8700645e8eae419c527
af6c32a30e7258030917f74009f7df8c0d052ea6
refs/heads/master
<file_sep>// Big Matrix clock for ESP32 based on md_parola library // See below // <NAME> June 2020 // - MD_MAX72XX library can be found at https://github.com/MajicDesigns/MD_MAX72XX // // Each font file has the lower part of a character as ASCII codes 0-127 and the // upper part of the character in ASCII code 128-255. Adding 128 to each lower // character creates the correct index for the upper character. // The upper and lower portions are managed as 2 zones 'stacked' on top of each other // so that the module numbers are in the sequence shown below: // // * Modules (like FC-16) that can fit over each other with no gap // n n-1 n-2 ... n/2+1 <- this direction top row // n/2 ... 3 2 1 0 <- this direction bottom rowm // // * Modules (like Generic and Parola) that cannot fit over each other with no gap // n/2+1 ... n-2 n-1 n -> this direction top row // n/2 ... 3 2 1 0 <- this direction bottom row // // Sending the original string to the lower zone and the modified (+128) string to the // upper zone creates the complete message on the display. // #include <WiFi.h> #include <WiFiManager.h> // https://github.com/tzapu/WiFiManager #include <ESPmDNS.h> #include "time.h" #include <MD_Parola.h> #include <MD_MAX72xx.h> #include <SPI.h> #include "Font_Data.h" // Define the number of devices we have in the chain and the hardware interface // NOTE: These pin numbers will probably not work with your hardware and may // need to be adapted #define HARDWARE_TYPE MD_MAX72XX::FC16_HW #define MAX_DEVICES 32 //8 x 4 modules giving a display of 64 x 32 pixels #define CLK_PIN 18 #define DATA_PIN 23 #define CS_PIN 19 #define ldr 36 //LDR Light sensor +3V3 to LDR and a 1K resistor to ground // Hardware SPI connection MD_Parola P = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES); #define SPEED_TIME 50 //Was 75 the lower the number the faster the dispaly scrolls #define SPEED_TIME2 40 //Was 75 the lower the number the faster the dispaly scrolls #define PAUSE_TIME 0 WiFiServer server(80); // Dayligh savings / NTP settings const long gmtOffset_sec = 3600; const int daylightOffset_sec = 3600; const char* Timezone = "GMT0BST,M3.5.0/01,M10.5.0/02"; // UK //Example time zones //const char* Timezone = "GMT0BST,M3.5.0/01,M10.5.0/02"; // UK //const char* Timezone = "MET-2METDST,M3.5.0/01,M10.5.0/02"; // Most of Europe //const char* Timezone = "CET-1CEST,M3.5.0,M10.5.0/3"; // Central Europe //const char* Timezone = "EST-2METDST,M3.5.0/01,M10.5.0/02"; // Most of Europe //const char* Timezone = "EST5EDT,M3.2.0,M11.1.0"; // EST USA //const char* Timezone = "CST6CDT,M3.2.0,M11.1.0"; // CST USA //const char* Timezone = "MST7MDT,M4.1.0,M10.5.0"; // MST USA //const char* Timezone = "NZST-12NZDT,M9.5.0,M4.1.0/3"; // Auckland //const char* Timezone = "EET-2EEST,M3.5.5/0,M10.5.5/0"; // Asia //const char* Timezone = "ACST-9:30ACDT,M10.1.0,M4.1.0/3": // Australia // Global variables char szTimeL[6]; // mm:ss\0 char szTimeH[6]; char szSecs[3]; char szAmPm[3]; char szMesg[60]; char szMesg2[60]; int h, m, s, dd, dw, mm, yy, ds; #define ldr 36 // Analogue pin for Light sensor LDR int intensity = 0; // Display brightness int intensity_old = 0; int intenAcc = 0; // Intensity accumulator byte intenCtr = 0; // Intensity counter const int intenMax = 96; // Max number for Intensity counter bool Shutdown = false; float Etemperature; //Received External Temperature float Epressure; //Received External Pressure float Ehumidity; //Received External Humidity float Ebattery; float Erssi; float temperature; float humidity; float pressure; float battery; float rssi; const long timeoutSensor = 6 * 60 * 1000; long long s1Timer = -(timeoutSensor + 30000); long long s2Timer = -(timeoutSensor + 30000) ; // Current time unsigned long currentTime = millis(); // Previous time unsigned long previousTime = 0; // Define timeout time in milliseconds (example: 2000ms = 2s) const long timeoutTime = 2000; TaskHandle_t Task1, Task2, Task3; SemaphoreHandle_t baton; void getTime(char *, bool); void sendPage(void); void sendCSS(void); void setup(void) { pinMode(LED_BUILTIN, OUTPUT); Serial.begin(115200); // initialise the LED display P.begin(6); P.setZone(0, 2, 7); //Lower time Zone P.setZone(1, 10, 15); //Upper time Zone P.setZone(2, 0, 1); //Seconds Zone P.setZone(3, 8, 9); //AM / PM Zone P.setZone(4, 16, 23); //General Zone 1 P.setZone(5, 24, 31); //General Zone 2 P.setFont(0, BigFont); P.setFont(1, BigFont); P.setFont(2, Font6x8); P.setFont(3, SmallFont); P.setFont(4, SmallFont); P.setFont(5, SmallFont); P.displayZoneText(0, szTimeL, PA_RIGHT, SPEED_TIME, PAUSE_TIME, PA_PRINT, PA_NO_EFFECT); P.displayZoneText(1, szTimeH, PA_RIGHT, SPEED_TIME, PAUSE_TIME, PA_PRINT, PA_NO_EFFECT); P.displayZoneText(2, szSecs, PA_CENTER, SPEED_TIME, PAUSE_TIME, PA_PRINT, PA_NO_EFFECT); P.displayZoneText(3, szAmPm, PA_CENTER, SPEED_TIME, PAUSE_TIME, PA_PRINT, PA_NO_EFFECT); P.displayZoneText(4, szMesg, PA_CENTER, SPEED_TIME2, 0, PA_SCROLL_LEFT, PA_SCROLL_LEFT); P.displayZoneText(5, szMesg2, PA_CENTER, SPEED_TIME, 0, PA_SCROLL_LEFT, PA_SCROLL_LEFT); P.setIntensity(intensity); // Brightness 0 - 15 //Setup WiFi usinf WiFiManager WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP WiFiManager wm; bool res; res = wm.autoConnect("clock"); // auto generated AP name from chipid if(!res) { Serial.println("Failed to connect"); ESP.restart(); } else { //if you get here you have connected to the WiFi Serial.println("WiFi connected)"); } WiFi.setHostname("clock"); Serial.println(); Serial.println(WiFi.localIP()); Serial.println(WiFi.getHostname()); configTime(0, 0, "192.168.1.1", "pool.ntp.org", "time.nist.gov"); setenv("TZ", Timezone, 1); Serial.println("NTP Client started"); if (!MDNS.begin(WiFi.getHostname())) { Serial.println("Error setting up MDNS responder!"); delay(1000); } Serial.println("mDNS responder started"); // Add service to MDNS-SD MDNS.addService("http", "tcp", 80); // Start TCP (HTTP) server server.begin(); Serial.println("TCP server started"); //Start the tasks baton = xSemaphoreCreateMutex(); xTaskCreatePinnedToCore( clockTask, "ClockTask", 3000, NULL, 1, &Task1, 1); delay(500); // needed to start-up task1 xTaskCreatePinnedToCore( serverTask, "serverTask", 3000, NULL, 1, &Task2, 1) ; delay(500); xTaskCreatePinnedToCore( displayTask, "DisplayTask", 3000, NULL, 1, &Task3, 1); delay(500); } void loop(void) { // Average LDR ambient light level reading over a number of samples if (intenCtr == 0 ) { intenCtr = intenMax; intensity = round(((intenAcc / intenMax) - 1024) / 204); if (intensity < 0 ) intensity = 0; if (intensity > 15 ) intensity = 15; if (intensity != intensity_old) { P.setIntensity(intensity); // Brightness 0 - 15 Serial.printf("Intensity: %d\r\n", intensity); intensity_old = intensity; if(intensity == 0 && Shutdown == false){ Shutdown = true; Serial.println("Display Shutdown"); P.displayClear(); P.displayShutdown(1); P.displayShutdown(1); delay(100); } if(intensity > 0 && Shutdown == true){ Shutdown = false; Serial.println("Display On"); P.displayShutdown(0); P.displayShutdown(0); delay(100); P.displayClear(); delay(100); P.displayReset(); delay(100); } } intenAcc = 0; } else { intenAcc = intenAcc + analogRead(ldr); // Add current light intensity to accumulator intenCtr --; } delay(10); } //Clock Task void clockTask( void * parameter ) { for (;;) { static uint32_t lastTime; // millis() memory static bool flasher; // seconds passing flasher if (P.getZoneStatus(0) && P.getZoneStatus(1) && P.getZoneStatus(2) && P.getZoneStatus(3)) { // Adjust the time string if we have to. It will be adjusted // every second at least for the flashing colon separator. if (millis() - lastTime >= 1000) { lastTime = millis(); getTime(szTimeL, flasher); createHString(szTimeH, szTimeL); flasher = !flasher; digitalWrite(LED_BUILTIN, flasher); P.displayReset(0); P.displayReset(1); P.displayReset(2); P.displayReset(3); // synchronise the start //P.synchZoneStart(); } } delay(100); } } //Server Task void serverTask( void * parameter ) { String request; for (;;) { delay(10); WiFiClient client = server.available(); // Listen for incoming clients //if (client) { // If a new client connects, if (client.available() > 0) { currentTime = millis(); previousTime = currentTime; Serial.println("New Client."); // print a message out in the serial port String currentLine = ""; // make a String to hold incoming data from the client while (client.connected() && currentTime - previousTime <= timeoutTime) { currentTime = millis(); // loop while the client's connected if (client.available()) { // if there's bytes to read from the client, char c = client.read(); // read a byte, then Serial.write(c); // print it out the serial monitor request += c; if (c == '\n') { // if the byte is a newline character // if the current line is blank, you got two newline characters in a row. // that's the end of the client HTTP request, so send a response: if (currentLine.length() == 0) { // HTTP requests always start with a response code (e.g. HTTP/1.1 200 OK) // and a content-type so the client knows what's coming, then a blank line: client.println("HTTP/1.1 200 OK"); client.println("Content-type:text/html"); client.println("Connection: close"); client.println(); if (request.indexOf("/ethernetcss.css") != -1) { // Send Stylesheet sendCSS(client); break; } if (request.indexOf("/favicon.ico") != -1) { // ignore break; } if (request.indexOf("?temp1=") != -1) { String etempStr = request.substring(12, 16); Serial.print("Internal Temperature received: "); Serial.println(etempStr); temperature = etempStr.toFloat(); break; } if (request.indexOf("?press1=") != -1) { Serial.print("Internal Pressure received: "); String etempStr = request.substring(13, 20); Serial.println(etempStr); pressure = etempStr.toFloat(); break; } if (request.indexOf("?humid1=") != -1) { Serial.print("Internal Humidity received: "); String etempStr = request.substring(13, 17); Serial.println(etempStr); humidity = etempStr.toFloat(); break; } if (request.indexOf("?batt1=") != -1) { Serial.print("Internal Battery voltage received: "); String etempStr = request.substring(12, 16); Serial.println(etempStr); battery = etempStr.toFloat(); break; } if (request.indexOf("?rssi1=") != -1) { Serial.print("Internal RSSI received: "); String etempStr = request.substring(12, 16); Serial.println(etempStr); rssi = etempStr.toFloat(); s1Timer = millis(); //store time received break; } if (request.indexOf("?temp2=") != -1) { Serial.print("External Temperature received: "); String etempStr = request.substring(12, 16); Serial.println(etempStr); Etemperature = etempStr.toFloat(); break; } if (request.indexOf("?press2=") != -1) { Serial.print("External Pressure received: "); String etempStr = request.substring(13, 20); Serial.println(etempStr); Epressure = etempStr.toFloat(); break; } if (request.indexOf("?humid2=") != -1) { Serial.print("External Humidity received: "); String etempStr = request.substring(13, 17); Serial.println(etempStr); Ehumidity = etempStr.toFloat(); break; } if (request.indexOf("?batt2=") != -1) { Serial.print("External Battery voltage received: "); String etempStr = request.substring(12, 16); Serial.println(etempStr); Ebattery = etempStr.toFloat(); break; } if (request.indexOf("?rssi2=") != -1) { Serial.print("External RSSI received: "); String etempStr = request.substring(12, 16); Serial.println(etempStr); Erssi = etempStr.toFloat(); s2Timer = millis(); //store time received break; } sendPage(client); // Break out of the while loop break; } else { // if you got a newline, then clear currentLine currentLine = ""; } } else if (c != '\r') { // if you got anything else but a carriage return character, currentLine += c; // add it to the end of the currentLine } } } // Clear the request variable request = ""; // Close the connection client.stop(); Serial.println("Client disconnected."); Serial.println(""); } } } //Display Task void displayTask( void * parameter ) { uint8_t display = 0; // current display mode uint8_t display2 = 0; // current display mode for (;;) { if (P.getZoneStatus(4)) { // Calendar display = 0; getDate(szMesg); P.displayReset(4); } if (P.getZoneStatus(5)) { switch (display2) { case 0: // Outside Temperature deg C display2++; if (millis() > s2Timer + timeoutSensor) { sprintf(szMesg2, "Outside Sensor Timeout"); } else { dtostrf(Etemperature, 3, 1, szMesg2); strcat(szMesg2, " \x90\C Outside"); } break; case 1: // `Inside Temperature deg C if (millis() > s1Timer + timeoutSensor) { sprintf(szMesg2, "Inside Sensor Timeout"); display2 = 0; } else { dtostrf(temperature, 3, 1, szMesg2); strcat(szMesg2, " \x90\C Inside"); display2++; } break; case 2: // Air Pressure display2++; dtostrf(pressure, 4, 1, szMesg2); strcat(szMesg2, " hPa"); break; case 3: // Relative Humidity display2 = 0; dtostrf(humidity, 3, 1, szMesg2); strcat(szMesg2, "% RH"); break; } P.displayReset(5); } P.displayAnimate(); delay(10); } } void sendPage(WiFiClient wc) { // Function to send Web Page wc.println("<HTML>"); wc.println("<HEAD>"); wc.println("<link rel='stylesheet' type='text/css' href='/ethernetcss.css' />"); wc.println("<TITLE>ESP32 Big Matrix Clock</TITLE>"); wc.println("</HEAD>"); wc.println("<BODY>"); wc.println("<H1>ESP32 Big Matrix Clock</H1>"); wc.println("<hr />"); wc.println("<H2>"); wc.print("Connected to:<br />SSID: "); wc.print(WiFi.SSID()); wc.print("&nbsp&nbsp&nbspRSSI: "); wc.print(WiFi.RSSI()); wc.println(" dB"); wc.println("<br />"); wc.print("Use this URL : "); wc.print("http://"); wc.print(WiFi.getHostname()); wc.print(".local"); wc.println("<br />"); wc.print("or use this URL : "); wc.print("http://"); wc.print(WiFi.localIP()); wc.println("<br />"); wc.printf("Time now: %02d:%02d\n", h, m); wc.println("<br />"); wc.printf("Display Intensity: %2d\n", intensity); wc.println("<br />"); wc.printf("Internal Temperature: %2.1f &#186;C\n", temperature); wc.println("<br />"); wc.printf("External Temperature: %2.1f &#186;C\n", Etemperature); wc.println("<br />"); wc.printf("Internal Air Pressure: %4.1f hPa\n", pressure); wc.println("<br />"); wc.printf("External Air Pressure: %4.1f hPa\n", Epressure); wc.println("<br />"); wc.printf("Internal Humidity: %3.1f%% RH\n", humidity); wc.println("<br />"); wc.printf("External Humidity: %3.1f%% RH\n", Ehumidity); wc.println("<br />"); wc.printf("Internal Battery: %1.2f V\n", battery); wc.println("<br />"); wc.printf("External Battery: %1.2f V\n", Ebattery); wc.println("<br />"); wc.printf("Internal RSSI: %3.0f dB\n", rssi); wc.println("<br />"); wc.printf("External RSSI: %3.0f dB\n", Erssi); wc.println("<br />"); wc.println("<br />"); wc.println("<a href=\"/\"\">Refresh</a><br />"); wc.println("<br />"); wc.println("</H2>"); wc.println("</BODY>"); wc.println("</HTML>"); } void sendCSS(WiFiClient wc) { // function to send Stylesheet wc.println("body{font-size:200%; margin:60px 0px; padding:0px;text-align:center;}"); wc.println("h1{text-align: center; font-family:Arial, \"Trebuchet MS\", Helvetica, sans-serif;}"); wc.println("h2{text-align: center; font-family:Arial, \"Trebuchet MS\", Helvetica, sans-serif;}"); wc.println("a{text-decoration:none;width:75px;height:50px;"); wc.println("border-color:black;"); wc.println("border-top:2px solid;"); wc.println("border-bottom:2px solid;"); wc.println("border-right:2px solid;"); wc.println("border-left:2px solid;"); wc.println("border-radius:10px 10px 10px;"); wc.println("-o-border-radius:10px 10px 10px;"); wc.println("-webkit-border-radius:10px 10px 10px;"); wc.println("font-size:100%; font-family:\"Trebuchet MS\",Arial, Helvetica, sans-serif;"); wc.println("-moz-border-radius:10px 10px 10px;"); wc.println("background-color:#293F5E;"); wc.println("padding:8px;"); wc.println("text-align: center;}"); wc.println("a:link {color:white;}"); // unvisited link wc.println("a:visited {color:white;}"); // visited link wc.println("a:hover {color:white;}"); // mouse over link wc.println("a:active {color:white;}"); // selected link } void createHString(char *pH, char *pL) { for (; *pL != '\0'; pL++) *pH++ = *pL | 0x80; // offset character *pH = '\0'; // terminate the string } // Code for reading clock date void getDate(char *psz) { char szBuf[10]; char dd1[] = "th"; if (dd == 1 || dd == 21 || dd == 31) { dd1[0] = 's'; dd1[1] = 't'; } if (dd == 2 || dd == 22) { dd1[0] = 'n'; dd1[1] = 'd'; } if (dd == 3 || dd == 23) { dd1[0] = 'r'; dd1[1] = 'd'; } //sprintf(psz, "%d %s %04d", dd, mon2str(mm, szBuf, sizeof(szBuf) - 1), yy); //sprintf(psz, "%d%s %s %04d", dd, dd1, mon2str(mm, szBuf, sizeof(szBuf) - 1), yy); sprintf(psz, "%s %d%s %s %04d", dow2str(dw, szMesg, sizeof(szMesg) - 1), dd, dd1, mon2str(mm, szBuf, sizeof(szBuf) - 1), yy); } void getTime(char *psz, bool f = true) // Code for reading clock time { time_t now; time(&now); struct tm * timeinfo; timeinfo = localtime(&now); h = timeinfo->tm_hour; m = timeinfo->tm_min; s = timeinfo->tm_sec; dd = timeinfo->tm_mday; dw = timeinfo->tm_wday; mm = timeinfo->tm_mon; yy = 1900 + timeinfo->tm_year; //sprintf(psz, "%02d%c%02d", h, (f ? ':' : ' '), m); sprintf(psz, "%02d:%02d", h, m);; //sprintf(szMesg, "%02d:%02d", m, s); sprintf(szSecs, "%02d", s); if (h > 11) { sprintf(szAmPm, "PM"); } else { sprintf(szAmPm, "AM"); } } char *dow2str(uint8_t code, char *psz, uint8_t len) { static const __FlashStringHelper* str[] = { F("Sunday"), F("Monday"), F("Tuesday"), F("Wednesday"), F("Thursday"), F("Friday"), F("Saturday") }; //strncpy_P(psz, (const char PROGMEM *)str[code - 1], len); strncpy_P(psz, (const char PROGMEM *)str[code], len); psz[len] = '\0'; return (psz); } // Get a label from PROGMEM into a char array char *mon2str(uint8_t mon, char *psz, uint8_t len) { static const __FlashStringHelper* str[] = { F("January"), F("February"), F("March"), F("April"), F("May"), F("June"), F("July"), F("August"), F("September"), F("October"), F("November"), F("December") }; //strncpy_P(psz, (const char PROGMEM *)str[mon - 1], len); strncpy_P(psz, (const char PROGMEM *)str[mon], len); psz[len] = '\0'; return (psz); } <file_sep># ESP32-Big-Matrix-Clock
b6117e9b97632604e01e93484ccaed945bc3e644
[ "Markdown", "C++" ]
2
C++
djbottrill/ESP32-Big-Matrix-Clock
f6e526d441cc17bdb0e241275e23076da9f6e864
1d744128a3c2e729b7ac1c6441c4ffd8ab07656d
refs/heads/master
<file_sep>import { Terminal } from 'xterm'; import 'xterm/css/xterm.css'; import './ohtge.css'; export type InputCallback = (input: string | undefined) => void | Promise<void>; export type StyleCode = 'reset' | 'bold' | 'dim' | 'italic' | 'underline' | 'inverse' | 'hidden' | 'strikethrough' | 'black' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan' | 'white' | 'gray' | 'grey' | 'bgBlack' | 'bgRed' | 'bgGreen' | 'bgYellow' | 'bgBlue' | 'bgMagenta' | 'bgCyan' | 'bgWhite'; // Styles var styles: Record<StyleCode, { open: string; close: string; }> = {} as any; const styleCodes: Record<StyleCode, [number, number]> = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49] } Object.keys(styleCodes).forEach(function (styleCode) { const styleCodeKey = styleCode as StyleCode; const val = styleCodes[styleCodeKey]; styles[styleCodeKey] = { open: '\u001b[' + val[0] + 'm', close: '\u001b[' + val[1] + 'm' }; }) // Terminal init // https://xtermjs.org/docs/api/terminal/classes/terminal/ var term = new Terminal({ cols: 80, rows: 20, cursorBlink: true, cursorStyle: "underline", fontFamily: "monospace", fontWeight: "bold" }); term.open(document.getElementsByClassName('ohtge-terminal')[0] as HTMLElement); (document.getElementsByClassName('terminal')[0] as HTMLElement).focus() setTimeout(function () { var windowEl = document.getElementsByClassName('ohtge-window')[0]! windowEl.setAttribute('style', 'width: ' + (document.getElementsByClassName('xterm-screen')[0].clientWidth + 15) + 'px') windowEl.classList.remove('cloaked') }) colorFn("bold"); // State let cursorX = 0; let promptCallback: InputCallback | undefined = undefined; let promptResolve: Function | undefined = undefined; let promptData = ''; let isPause = false; let isEnd = false; // I/O & functions term.onKey((e: { key: string, domEvent: KeyboardEvent }) => { const { key, domEvent: ev } = e; if (isEnd) { return } var printable = !ev.altKey && !(ev as any).altGraphKey && !ev.ctrlKey && !ev.metaKey if (ev.keyCode == 13) { if (promptData || isPause) { if (!isPause) { term.write('\r\n') } if (promptResolve) { promptResolve(isPause ? undefined : promptData); promptResolve = undefined; } if (promptCallback) { var callback = promptCallback var wasPause = isPause promptCallback = undefined isPause = false setTimeout(function () { callback(wasPause ? undefined : promptData); }); } else { inputFn('?') } } } else if (ev.keyCode == 8) { if (cursorX > 0) { cursorX-- term.write('\b \b') promptData = promptData.slice(0, promptData.length - 1) } } else if (printable) { if (promptResolve) { promptData += key } term.write(key) cursorX++ } }); function writeFn(text?: string) { term.writeln(text !== undefined ? text : ""); } function pauseFn(callback?: InputCallback) { promptData = ''; promptCallback = callback; isPause = true; cursorX = 0; return new Promise((resolve, _reject) => { promptResolve = resolve; }) } function inputFn(textOrCallback: string | InputCallback, callback?: InputCallback): Promise<string> { let text = textOrCallback; if (typeof textOrCallback === 'function') { text = '' callback = textOrCallback; } promptData = ''; promptCallback = callback; term.write((text || '') + ' '); cursorX = 0; return new Promise((resolve, _reject) => { promptResolve = resolve; }) } function clearFn() { // Requires to be called in a separate tick then the text to clear term.clear(); } function colorFn(styleCode: StyleCode) { const styleCodeKey = styleCode; if (styles[styleCodeKey]) { term.write(styles[styleCodeKey].open) } } function endFn() { isEnd = true } function titleFn(title: string) { if (document.getElementsByTagName('title').length === 0) { var titleEl = document.createElement('title') document.getElementsByTagName('head')[0].appendChild(titleEl) } var titleTagEls = document.getElementsByTagName('title'); for (let index = 0; index < titleTagEls.length; index++) { titleTagEls.item(index)!.innerText = title } var titleIdEl = document.getElementsByClassName('ohtge-title')[0] as HTMLElement; if (titleIdEl) { titleIdEl.innerText = title; } } function resizeFn(rows: number, cols: number) { term.resize(rows, cols) } const global = globalThis as any; global.write = writeFn; global.pause = pauseFn; global.input = inputFn; global.clear = clearFn; global.color = colorFn; global.end = endFn; global.title = titleFn; global.resize = resizeFn; /** * Writes a line of text on the screen. */ export const write = writeFn; /** * Pauses the execution until the user presses Enter. */ export const pause = pauseFn; /** * Pauses the execution until the user writes input text and presses Enter. * The input is passed as the callback first argument. */ export const input = inputFn; /** * Clears the screen. */ export const clear = clearFn; /** * Sets the current text color, to be applied in all future `write` and `input` commands. */ export const color = colorFn; /** * Ends the program. */ export const end = endFn; /** * Changes the title of both the browser tab and the fake terminal. */ export const title = titleFn; /** * Resizes the fake terminal. */ export const resize = resizeFn; declare global { /** * Writes a line of text on the screen. */ export const write: (text?: string) => void; /** * Pauses the execution until the user presses Enter. */ export const pause: (callback?: InputCallback) => Promise<void>; /** * Pauses the execution until the user writes input text and presses Enter. * The input is passed as the callback first argument. */ export const input: (textOrCallback: string | InputCallback, callback?: InputCallback) => Promise<string>; /** * Clears the screen. */ export const clear: () => void; /** * Sets the current text color, to be applied in all future `write` and `input` commands. */ export const color: (styleCode: StyleCode) => void; /** * Ends the program. */ export const end: () => void; /** * Changes the title of both the browser tab and the fake terminal. */ export const title: (title: string) => void; /** * Resizes the fake terminal. */ export const resize: typeof resizeFn; } <file_sep>export declare type InputCallback = (input: string | undefined) => void | Promise<void>; export declare type StyleCode = 'reset' | 'bold' | 'dim' | 'italic' | 'underline' | 'inverse' | 'hidden' | 'strikethrough' | 'black' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan' | 'white' | 'gray' | 'grey' | 'bgBlack' | 'bgRed' | 'bgGreen' | 'bgYellow' | 'bgBlue' | 'bgMagenta' | 'bgCyan' | 'bgWhite'; declare function writeFn(text?: string): void; declare function pauseFn(callback?: InputCallback): Promise<unknown>; declare function inputFn(textOrCallback: string | InputCallback, callback?: InputCallback): Promise<string>; declare function clearFn(): void; declare function colorFn(styleCode: StyleCode): void; declare function endFn(): void; declare function titleFn(title: string): void; declare function resizeFn(rows: number, cols: number): void; /** * Writes a line of text on the screen. */ export declare const write: typeof writeFn; /** * Pauses the execution until the user presses Enter. */ export declare const pause: typeof pauseFn; /** * Pauses the execution until the user writes input text and presses Enter. * The input is passed as the callback first argument. */ export declare const input: typeof inputFn; /** * Clears the screen. */ export declare const clear: typeof clearFn; /** * Sets the current text color, to be applied in all future `write` and `input` commands. */ export declare const color: typeof colorFn; /** * Ends the program. */ export declare const end: typeof endFn; /** * Changes the title of both the browser tab and the fake terminal. */ export declare const title: typeof titleFn; /** * Resizes the fake terminal. */ export declare const resize: typeof resizeFn; declare global { /** * Writes a line of text on the screen. */ export const write: (text?: string) => void; /** * Pauses the execution until the user presses Enter. */ export const pause: (callback?: InputCallback) => Promise<void>; /** * Pauses the execution until the user writes input text and presses Enter. * The input is passed as the callback first argument. */ export const input: (textOrCallback: string | InputCallback, callback?: InputCallback) => Promise<string>; /** * Clears the screen. */ export const clear: () => void; /** * Sets the current text color, to be applied in all future `write` and `input` commands. */ export const color: (styleCode: StyleCode) => void; /** * Ends the program. */ export const end: () => void; /** * Changes the title of both the browser tab and the fake terminal. */ export const title: (title: string) => void; /** * Resizes the fake terminal. */ export const resize: typeof resizeFn; } export {}; <file_sep># One Hour Text Game Engine A small wrapper for [xterm.js](https://xtermjs.org/) to make small terminal games using a trivial API. [Docs available here](https://mkalam-alami.github.io/ohtge/docs/). ## Example `game.js` file ```javascript /// <reference path="node_modules/ohtge/lib/ohtge.d.ts" /> title("test.exe") loop() async function loop() { while (1) { write("Hello world") color("yellow") const a = await input("Say something?") // `input(string, callback)` syntax also supported color("white") write("You said " + a) write() await pause() } } ``` ![](https://raw.githubusercontent.com/mkalam-alami/ohtge/master/lib/ohtge-readme.gif) ## Simple setup 1. Download the [zip](https://github.com/mkalam-alami/ohtge/archive/master.zip) 2. Only keep the files you want (typically `dist/` + one of the examples) 3. Make a game! ## Setup from scratch 1. `npm install ohtge` *(Optional, only used as reference for IDE auto-completion)* 2. Insert the following HTML in your web page: ```html <div class="ohtge-window cloaked"> <div class="ohtge-title"></div> <div class="ohtge-terminal"></div> </div> <script src="https://cdn.jsdelivr.net/npm/ohtge"></script> <script src="[ YOUR OWN GAME SCRIPT ]"></script> ``` 3. Insert the following at the top of your own script (either JS or TS): ```javascript /// <reference path="node_modules/ohtge/lib/ohtge.d.ts" /> write('Hello world!'); ``` ## Complete API [![](https://i.imgur.com/mF5Yehw.png)](https://mkalam-alami.github.io/ohtge/docs/) ## Made with ohtge * ["freeze.exe"](https://marwane.kalam-alami.net/1hgj/286/) (1HGJ 286 entry, 2020) * ["prince.exe"](https://marwane.kalam-alami.net/jams/alakajam-k5/) (5th Kajam entry, 2018) * ["monster.exe"](https://marwane.kalam-alami.net/1hgj/167/) (1HGJ 167 entry, 2018) * ["Day Off Work"](https://marwane.kalam-alami.net/misc/dayoffwork/) (web port of a 1st Alakajam! entry, 2018) <file_sep>/// <reference path="../lib/ohtge.d.ts" /> title("test.exe") loop() async function loop () { while (1) { write("Hello world") color("yellow") const a = await input("Say something?") color("white") write("You said " + a) write() await pause() } }
e9ab539072093f9b8773473d5d2b8796f8ba48b8
[ "Markdown", "TypeScript" ]
4
TypeScript
mkalam-alami/ohtge
41dcc8e2ae1867e077d4edd459d3cffbf12b463b
0893d1aeac4ce974580f110a3bce834b12857fc9
refs/heads/master
<repo_name>ramshresh/osmuserstat<file_sep>/api.php <?php include ("httplib.php"); include ("xmlfunctions.php"); include ("updateUserChangesetsXML.php"); //include("test.php"); include ("GLOBAL_CONSTANTS.php"); include ("database_query.php"); /* File Structure - $resultXMLallchangesets='files/'."$username".'_Changesets.xml'; - $resultXMLallchangesetsstate='files/'."$username".'_Changesets_state.xml'; */ class OsmApi { function __construct($created_by = "PhpOsmApi", $api = "http://www.openstreetmap.org") { $this->_created_by = $created_by; $this->_api = $api; $this->_conn = new HTTPRequest($this->_api, true); } /*---------------- Using OSM API v0.6 --------------------*/ function changesetsGet($param = null) { $min_lon = null; $min_lat = null; $max_lon = null; $max_lat = null; $uid = null; $username = null; $created_after = null; $created_before = null; //Get parameters if ($param <> "") { foreach ($param as $key => $value) { if ($key == 'min_lon') { $min_lon = $param['min_lon']; } if ($key == 'min_lat') { $min_lat = $param['min_lat']; } if ($key == 'max_lon') { $max_lon = $param['max_lon']; } if ($key == 'max_lat') { $max_lat = $param['max_lat']; } if ($key == 'uid') { $uid = $param['uid']; } if ($key == 'username') { $username = $param['username']; } if ($key == 'created_after') { $created_after = $param['created_after']; } if ($key == 'created_before') { $created_before = $param['created_before']; } } /* if($param['bbox']<>""){ $bbox=$param['bbox']; $min_lon=$bbox['min_lon']; $min_lat=$bbox['min_lat']; $max_lon=$bbox['max_lon']; $max_lat=$bbox['max_lat']; } */ } $uri = "/api/0.6/changesets"; $params = array(); if (($min_lon <> "") && ($min_lat <> "") && ($max_lon <> "") && ($max_lat <> "")) { $a = array( (string )$min_lon, (string )$min_lat, (string )$max_lon, (string )$max_lat); $x = implode(',', $a); $params["bbox"] = $x; } if (($uid <> "")) { $params["user"] = $uid; } if (($username <> "")) { $params["display_name"] = $username; } if (($created_after) <> "") { if (!(($created_before) <> "")) { $params["time"] = $created_after; } } if (($created_before) <> "") { if (!(($created_after) <> "")) { $created_after = "1970-01-01T00:00:00Z"; $params["time"] = $created_after . "," . $created_before; } } if (($created_before <> "") && ($created_after <> "")) { $params["time"] = $created_after . "," . $created_before; } if (($params) <> "") { $uri = $uri . '?'; $count = 0; foreach ($params as $key => $value) { $s = $this->_conn->ParamEncode($key, $value); if ($count == 0) { $uri = $uri . $s; } else { $uri = $uri . "&" . $s; } $count = $count + 1; } } $url = $this->_api . $uri; //print $url; //print '<br><br>'; $obj = simplexml_load_file($url); return $obj; } /* ===============changesetGetDownload================*/ function changesetsGetDownload($id = null) { $uri = "/api/0.6/changeset"; if ($id <> "") { $uri = $uri . '/' . $id . '/download'; } $url = $this->_api . $uri; //print $url; //print '<br>'; $obj = simplexml_load_file($url); return $obj; } /* ===============User Information================*/ function userGet($param = null) { $uid = null; $username = null; foreach ($param as $key => $value) { if ($key == 'username') { $username = $param['username']; } if ($key == 'uid') { $uid = $value; } } $uri = "/api/0.6/user"; if ($uid <> "") { $uri = $uri . '/' . $uid; } elseif (($username <> "") && ($uid == "")) { $uid = $this->getuid($username); $uri = $uri . '/' . $uid; } elseif (($username <> "") && ($uid == "")) { return - 1; } $url = $this->_api . $uri; $obj = simplexml_load_file($url); return $obj; } function getuid($username = null) { $obj = $this->changesetsGet(array('username' => $username)); $changesetGet_uid = $obj->changeset->attributes()->uid; return $changesetGet_uid; } function getChangesetCount($param = null) { $uid = null; $username = null; if ($param <> null) { $obj = $this->userGet($param); $count = $obj->user->changesets->attributes()->count; } return $count; } function getAllChangesets($param = null) { set_time_limit(10000000000); //Declare variables $min_lon = null; $min_lat = null; $max_lon = null; $max_lat = null; $uid = null; $username = null; $created_after = null; $created_before = null; //Get variable values from parameters passed if ($param <> null) { foreach ($param as $key => $value) { if ($key == 'min_lon') { $min_lon = $param['min_lon']; } if ($key == 'min_lat') { $min_lat = $param['min_lat']; } if ($key == 'max_lon') { $max_lon = $param['max_lon']; } if ($key == 'max_lat') { $max_lat = $param['max_lat']; } if ($key == 'uid') { $uid = $param['uid']; } if ($key == 'username') { $username = $param['username']; } if ($key == 'created_after') { $created_after = $param['created_after']; } if ($key == 'created_before') { $created_before = $param['created_before']; } } } //Initialize $creted_before with current time if not in param if ($created_before == "") { $now = $this->getCurrentTimestamp(); $created_before = $now; } $allchangeset_obj = array(); /* //By BBox if ($param<>null && isset($param['bbox'])){ $bbox=$param['bbox']; $file=getFILE_PATH(array('bbox'=>$bbox)); $changesetsXML='files/result'; $resultXML=$file['resultXMLallchangesets']; $resultXMLstate=$file['resultXMLallchangesetsstate']; $tempXML='files/tempXML.xml'; $list_changesets=array(); $size=100; $loop_count=0; //|| while(!($size<100)){ if($loop_count==3){break;} print'yes'; print "Created Before = ".$created_before; print"</br>"; $data=$this->changesetsGet($param); $changesets=$data->changeset; if(isset($changesets[0])){ if ($loop_count==0){ $data->asXML($resultXML); } elseif($loop_count>0){ $data->asXML($tempXML); mergeXML(array('toxml'=>$tempXML, 'fromxml'=>$resultXML,'fileout'=>$resultXML)); unlink($tempXML); } $size=sizeof($changesets); print "Current size ".$size; print "</br>"; $lastindex=$size-1; foreach($changesets as $ch) { array_push($allchangeset_obj,$ch); } $firsttimestamp=$changesets[0]->attributes()->closed_at; $lasttimestamp=$changesets[$lastindex]->attributes()->closed_at; print "first timestamp = ".$firsttimestamp; print "</br>"; print "last timestamp = ".$lasttimestamp; print "</br>"; $currenttimestamp=new DateTime($lasttimestamp); $nexttimestamp=date_sub($currenttimestamp,new DateInterval('P0Y0M0DT0H2M00S')); $nexttimestamp_str = $nexttimestamp->format('Y-m-d H:i:s'); $result=explode(' ',$nexttimestamp_str); $nexttimestamp_str=$result[0].'T'.$result[1].'Z'; print '<br>'; $created_before=$nexttimestamp_str; $param['created_before']=$created_before; }else{print 'no more changeset';} $loop_count=$loop_count+1; } $allchangeset_obj=simplexml_load_file($resultXML); //unlink($resultXML); getChangesetsListStateBbox($allchangeset_obj); } //print 'sizeof $allchangeset_obj = '.sizeof($allchangeset_obj); //print "</br>";print "</br>"; */ //By user if ($param <> null && isset($param['username'])) { $obj = $this->userGet(array('username' => $username)); insert_users($obj); $file = getFILE_PATH(array('username' => $username)); $changeset_count = $this->getChangesetCount($param); $count = 0; $allchangeset_obj = array(); $list_changesets = array(); $size = 99; $loop_count = 0; $changesetsXML = 'files/result'; $resultXML = $file['resultXMLallchangesets']; $resultXMLstate = $file['resultXMLallchangesetsstate']; $tempXML = 'files/tempXML.xml'; while ($size >= 99) { //print '<br>size in while loop===<br>'.$size; set_time_limit(10000000000); //print "Created Before = ".$created_before; //print"</br>"; $data = $this->changesetsGet($param); insert_changesets($data); if ((isset($data))) { if ($loop_count == 0) { $data->asXML($resultXML); } elseif ($loop_count > 0) { unset($data->changeset[0]); $data->asXML($tempXML); mergeXML(array( 'toxml' => $tempXML, 'fromxml' => $resultXML, 'fileout' => $resultXML)); unlink($tempXML); } $changesets = $data->changeset; if (isset($changesets)) { $size = sizeof($changesets); $lastindex = $size - 1; if ($lastindex < 0) { break; } // print "Current size ".$size; //print "</br>"; //print '<br>Last index = '.$lastindex.'<br>'; $lasttimestamp = $changesets[$lastindex]->attributes()->closed_at; $param['created_before'] = $lasttimestamp; } else { //print 'no more changeset'; break; } } //print 'sizeof $allchangeset_obj = '.sizeof($allchangeset_obj); //print "</br>";print "</br>"; $loop_count = $loop_count + 1; //print '<br>Loop count<br>'.$loop_count; } //end of while loop $allchangeset_obj = simplexml_load_file($resultXML); //unlink($resultXML); getChangesetsListState($allchangeset_obj); } return $allchangeset_obj; } function countChangesInChangeset($id) { set_time_limit(10000000000); $data = $this->changesetsGetDownload($id); $created = $data->create; $modified = $data->modify; $deleted = $data->delete; //created $cnc = 0; $cwc = 0; $crc = 0; //modified $mnc = 0; $mwc = 0; $mrc = 0; //deleted $dnc = 0; $dwc = 0; $drc = 0; foreach ($data->create as $created) { foreach ($created->node as $cn) { $cnc += 1; } foreach ($created->way as $cw) { $cwc += 1; } foreach ($created->relation as $cr) { $crc += 1; } } foreach ($data->modify as $modified) { foreach ($modified->node as $mn) { $mnc += 1; } foreach ($modified->way as $mw) { $mwc += 1; } foreach ($modified->relation as $mr) { $mrc += 1; } } foreach ($data->delete as $deleted) { foreach ($deleted->node as $dn) { $dnc += 1; } foreach ($deleted->way as $dw) { $dwc += 1; } foreach ($deleted->relation as $dr) { $drc += 1; } } /* print '-----created-----'; print '<br>'; print 'nodes ='.$cnc; print '<br>'; print 'ways ='.$cwc; print '<br>'; print 'relations= '.$crc; print '<br>'; print '<br>'; print '-----modified-----'; print '<br>'; print 'nodes ='.$mnc; print '<br>'; print 'ways ='.$mwc; print '<br>'; print 'relations= '.$mrc; print '<br>'; print '<br>'; print '-----deleted-----'; print '<br>'; print 'nodes ='.$dnc; print '<br>'; print 'ways ='.$dwc; print '<br>'; print 'relations= '.$drc; print '<br>'; print '<br>'; */ $result = array( 'created' => array( 'node' => $cnc, 'way' => $cwc, 'relation' => $crc, ), 'modified' => array( 'node' => $mnc, 'way' => $mwc, 'relation' => $mrc, ), 'deleted' => array( 'node' => $dnc, 'way' => $dwc, 'relation' => $drc, )); return $result; } function getChangesetsDetails($id) { $data = $this->changesetsGetDownload($id); $data->asXML('files/changesetDetailsXML.xml'); } function countChangesInChangeset_user($param = null) { set_time_limit(10000000000); $min_lon = null; $min_lat = null; $max_lon = null; $max_lat = null; $uid = null; $username = null; $created_after = null; $created_before = null; //Get parameters if ($param <> "") { foreach ($param as $key => $value) { if ($key == 'min_lon') { $min_lon = $param['min_lon']; } if ($key == 'min_lat') { $min_lat = $param['min_lat']; } if ($key == 'max_lon') { $max_lon = $param['max_lon']; } if ($key == 'max_lat') { $max_lat = $param['max_lat']; } if ($key == 'uid') { $uid = $param['uid']; } if ($key == 'username') { $username = $param['username']; } if ($key == 'created_after') { $created_after = $param['created_after']; } if ($key == 'created_before') { $created_before = $param['created_before']; } } } $data = $this->getAllChangesets($param); $total = array( 'created' => array( 'node' => 0, 'way' => 0, 'relation' => 0, ), 'modified' => array( 'node' => 0, 'way' => 0, 'relation' => 0, ), 'deleted' => array( 'node' => 0, 'way' => 0, 'relation' => 0, )); $count = 0; foreach ($data->changeset as $chs) { $count += 1; $cid = $chs->attributes()->id; print $cid; print '<br>'; $result = $this->countChangesInChangeset($cid); print_r($result); print '<br>'; $total['created']['node'] = $total['created']['node'] + $result['created']['node']; $total['created']['way'] = $total['created']['way'] + $result['created']['way']; $total['created']['relation'] = $total['created']['relation'] + $result['created']['relation']; $total['modified']['node'] = $total['modified']['node'] + $result['modified']['node']; $total['modified']['way'] = $total['modified']['way'] + $result['modified']['way']; $total['modified']['relation'] = $total['modified']['relation'] + $result['modified']['relation']; $total['deleted']['node'] = $total['deleted']['node'] + $result['deleted']['node']; $total['deleted']['way'] = $total['deleted']['way'] + $result['deleted']['way']; $total['deleted']['relation'] = $total['deleted']['relation'] + $result['deleted']['relation']; } print '<br>'; print '<br>'; print "bbox = [ $min_lon, $min_lat, $max_lon, $max_lat ]"; print '<br>'; print 'The bbox Contains ' . $count . ' no. of changesets'; print '<br>'; return $total; } /************************helper********************************/ function getCurrentTimestamp($timezone = null) { /* if ($timezone<>""){ date_default_timezone_set($timezone); } */ $date = date('Y-m-d'); $time = date('H:i:s'); $current_timestamp = $date . 'T' . $time . 'Z'; return $current_timestamp; } } //End of Osm API ?> <file_sep>/README.md osmuserstat ===========
88ab9e51bc41bafdb85c85d1323fe8497cc69af3
[ "Markdown", "PHP" ]
2
PHP
ramshresh/osmuserstat
ee69e39ab9f35de144252eef4ada09315020a843
2fbc7df37239c5cf0403bf3ea1155845958cc50b
refs/heads/master
<repo_name>develop-mental/env-configs<file_sep>/bash/bash_profile parse_git_branch() { git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/' } if [ "$color_prompt" = yes ]; then PS1=$PS1 + "\$(parse_git_branch)\[\033[00m\] \$ " else PS1=$PS1 + "\$(parse_git_branch) \$ " fi # Windows WSL specific export DISPLAY=:0 export DOCKER_HOST=tcp://0.0.0.0:2375
282f3f7ccdd0acf791eaf914b4f7cdf1bd10d3dc
[ "Shell" ]
1
Shell
develop-mental/env-configs
bce6d080fd8e088efc180310925fd12bcdf4cf36
48c11fd837729c5c833288fa07926df718ccf044
refs/heads/master
<repo_name>flipchan/otw<file_sep>/dist/otw-1.4/README.rst Off the wire crypto ======================= one encryption library to rule them all. An easy to use encryption library mainly ment for LayerProx(github.com/flipchan/LayerProx) aims to be easy to use and provide strong crypto it comes with multiple functions the justencrypt() function encrypts the data with pgp -> aes-ctr 256 and adds a hmac ---- <file_sep>/README.md # otw off the wire crypto, otr with pgp + aes-ctr 256 instead of diffie hellman, with other words: pgp + aes-ctr with sha256hmac160 there is alot of different encryption libs u need to import in python to encrypt something this aims to be the only library u need to import, easy to use, secure and free :) you can install it with pip https://pypi.python.org/pypi/otw this is mostly a test script because i think that off the record crypto should have pgp instead of diffie hellman i like pgp 4096rsa keys more then the default diffie hellman 1024 dsa key but thats just my opinion, feel free to use this freely as the license says use it and if u like it and if we meet u can buy me a beer /* This is written by flipchan(<NAME>) do not use until stable version is out *\ How to: Bob wants to surf the web securely Alice has a server that Bob can proxy it connections throw Alice has a database where Bobs public key is but to know what key is Bobs key, Bob and alice agree on a shared key(a hmac), alice saves the shared key in her database with bobs public key. When alice server sees a package where Bobs and her's shared key is used she knows that it is bob who is useing her proxy so she encrypts the packages with Bobs public key <file_sep>/setup.py import os from setuptools import setup # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... #version 1.4 should work , tested on debian def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "off the wire", version = "1.4", author = "<NAME>", author_email = "<EMAIL>", description = ("Off the wire crypto"), license = "Beerware", keywords = "encryption layerprox aes aes-ctr pgp hmac secure", url = "https://github.com/flipchan/otw", packages=['otw'], install_requires=['gnupg'], long_description=read('README'), classifiers=[ "Development Status :: 5 - Stable", "Topic :: Utilities", "License :: OSI Approved :: BSD License", 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], )
a73f4d415e7a076eaef957a55cef534c847a502e
[ "Markdown", "Python", "reStructuredText" ]
3
reStructuredText
flipchan/otw
3f757accc3bf7d4a6a45da926625162bd74e2dee
e1d5485aa5751516053e0f82fd4932269061afd6
refs/heads/main
<file_sep>using Microsoft.Data.SqlClient; using Roommates.Models; using System.Collections.Generic; namespace Roommates.Repositories { /// <summary> /// This class is responsible for interacting with Chore data. /// It inherits from the BaseRepository class so that it can use the BaseRepository's Connection property /// </summary> public class ChoreRepository : BaseRepository { ///***REMEMBER to FIRST setup network(connection) first step is to CONSTRUCT that TUNNEL!**** ///connection string is method in base that takes the connection(address info) and makes new SLConnection public ChoreRepository(string connectionString) : base(connectionString) { } ///Now that there is a tunnel/connection to the database, we need a place to put the data we want ///So we want to make a list of ALL the information there and return it /// public List<Chore> GetAssignedChore() { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @"SELECT Chore.Id as Id, Name, RoommateId from Chore LEFT JOIN RoommateChore ON Chore.Id = RoommateChore.ChoreId WHERE RoommateId is NULL "; SqlDataReader reader = cmd.ExecuteReader(); List<Chore> assignedChores = new List<Chore>(); //remember, going to have more than one return, make sure to while loop while (reader.Read()) { Chore chore = new Chore { Id = reader.GetInt32(reader.GetOrdinal("Id")), Name = reader.GetString(reader.GetOrdinal("Name")) }; //add the new chores to a list of chores assignedChores.Add(chore); } reader.Close(); return assignedChores; } } } public List<Chore> GetAll() { ///Reminder, because the database is shared. we want to close our connection as soon as we ///get what we want. ///the "using" block will close our connection to the resource as soon as it is completed /// using (SqlConnection conn = Connection) { //although using closes the connection once it is finished, it DOES NOT open it for us //Therefore, we must open it manually conn.Open(); //Now we have must send the SQL what it is that we want, this will also be "using" using (SqlCommand cmd = conn.CreateCommand()) { //here we write our sql code for what it is and how we want it cmd.CommandText = "SELECT Id, Name From Chore"; //next we need to get access or... READ the data. we create a reader SqlDataReader reader = cmd.ExecuteReader(); //we now need a list format to read the data received, and store as chores List<Chore> chores = new List<Chore>(); //so long as there is data to return (remember, it goes row by row in forward motion //(it can never go back to a row it's alreay visited). chores will return true while (reader.Read()) { ///we want to get the index location of each column int idColumnPosition = reader.GetOrdinal("ID"); //we then get the value located inside of that column int idValue = reader.GetInt32(idColumnPosition); int nameColumnPosition = reader.GetOrdinal("Name"); string namevalue = reader.GetString(nameColumnPosition); //Now it's time to take the information received for each row of info, and make an //object out of the information received Chore chore = new Chore { Id = idValue, Name = namevalue }; //and lastly we need to send it to the chore list that was made chores.Add(chore); //once the reader ends and returns false, the while loop will end } //so now we need to close the reader connection reader.Close(); //and time to return the table information back return chores; } } } public void AssignChore(int roommateId, int choreId ) { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @"INSERT INTO RoommateChore (RoommateID), (Choreid) OUTPUT INSERT.Id VALUES (@roommateId, @choreId)"; cmd.Parameters.AddWithValue("@roommateId", roommateId); cmd.Parameters.AddWithValue("@choreId", choreId); int id = (int)cmd.ExecuteScalar(); roommateId = id; } } } //Now let's make a method that will allow use to get a room by id (will need to take an id parameter) public Chore GetChoreByid(int id) { //again, first step is to get connection address using (SqlConnection conn = Connection) { //remember, using does not open the connection... only closes it conn.Open(); //Now that connection is open, we need to let the end know what we want //request take up usage so we want to make sure it closes once completed using(SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "SELECT Id, Name FROM Chore WHERE ID = @id"; cmd.Parameters.AddWithValue("@id", id); //Now that the DB knows what to give use, we need to create a way to read it SqlDataReader reader = cmd.ExecuteReader(); Chore chore = null; //Since we only want one result, an if loop will replace the while loop if(reader.Read()) { chore = new Chore { Id = id, //we still need to get ordinal and the value of that location Name = reader.GetString(reader.GetOrdinal("Name")), }; } //Now that request was received and the needed object built. we need to close the reader reader.Close(); //and return the request chore return chore; } } } public void Insert(Chore chore) { //create connection with using statement using (SqlConnection conn = Connection) { //remember to open as using will not. conn.Open(); //then create and sent instructions to SQL Database using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @"INSERT INTO Chore (Name) OUTPUT INSERTED.Id VALUES (@name)"; cmd.Parameters.AddWithValue("@name", chore.Name); int id = (int)cmd.ExecuteScalar(); chore.Id = id; } } } } } <file_sep>using System; using System.Collections.Generic; using Roommates.Repositories; using Roommates.Models; namespace Roommates { class Program { // This is the address of the database. // We define it here as a constant since it will never change. private const string CONNECTION_STRING = @"server=localhost\SQLExpress;database=Roommates;integrated security=true"; static void Main(string[] args) { RoomRepository roomRepo = new RoomRepository(CONNECTION_STRING); ChoreRepository choreRepo = new ChoreRepository(CONNECTION_STRING); RoommateRepository roommateRepo = new RoommateRepository(CONNECTION_STRING); bool runProgram = true; while (runProgram) { string selection = GetMenuSelection(); switch (selection) { case ("Show all rooms"): //*Remember roomRepo is the address for the connection List<Room> rooms = roomRepo.GetAll(); foreach(Room r in rooms) { Console.WriteLine($"{r.Id} - {r.Name} Max Occupancy({r.MaxOccupancy})"); } Console.WriteLine("Press any key to continue"); Console.ReadLine(); break; case ("Search for room"): //*Remember roomRepo is the address for the connection Console.WriteLine("What room number would you like to search for?"); int roomResponse = int.Parse(Console.ReadLine()); Room room = roomRepo.GetById(roomResponse); Console.WriteLine($"{room.Id}.){room.Name} - Max Occupancy({room.MaxOccupancy})"); Console.WriteLine("Press any key to continue"); Console.ReadLine(); break; case ("Add a room"): Console.WriteLine("Enter Room Name:"); string name = Console.ReadLine(); Console.WriteLine("Enter Max Occupancy"); int maxOccupancy = int.Parse(Console.ReadLine()); Room roomToAdd = new Room() { Name = name, MaxOccupancy = maxOccupancy }; roomRepo.Insert(roomToAdd); Console.WriteLine($"{roomToAdd.Name} has been assigned an id of {roomToAdd.Id}"); Console.WriteLine("Press any key to continue"); Console.ReadLine(); // Do stuff break; case ("Search for roommate"): //*Remember roommateRepo is the address for the connection Console.WriteLine("Which roommate are you looking for?"); int roommateResponse = int.Parse(Console.ReadLine()); Roommate roommate = roommateRepo.GetRoommateById(roommateResponse); Console.WriteLine($"{roommate.Id}.){roommate.Firstname} lives in the {roommate.Name} and" + $" pays {roommate.RentPortion}% of the rent"); Console.WriteLine("Press any key to continue"); Console.ReadLine(); break; case ("Show all chores"): //*Remember roomRepo is the address for the connection List<Chore> chores = choreRepo.GetAll(); foreach (Chore c in chores) { Console.WriteLine($"{c.Id} - {c.Name}"); } Console.WriteLine("Press any key to continue"); Console.ReadLine(); break; case ("Show unassigned chores"): //*Remember roomRepo is the address for the connection List<Chore> assignedChores = choreRepo.GetAssignedChore(); Console.WriteLine("The current unassigned chores are:"); foreach (Chore c in assignedChores) { Console.WriteLine($"{c.Name}"); } Console.WriteLine("Press any key to continue"); Console.ReadLine(); break; case ("Assign a chore"): List<Chore> theChores = choreRepo.GetAssignedChore(); Console.WriteLine("The current unassigned chores are:"); foreach (Chore c in theChores) { Console.WriteLine($"{c.Id}.) {c.Name}"); } Console.WriteLine("Please choose the number of the chore you'd like to assign"); int choreId = int.Parse(Console.ReadLine()); Console.WriteLine($"You have chose {choreId}"); Console.WriteLine("Press any key to continue"); Console.ReadLine(); //Show list of all roommates List<Roommate> roommates = roommateRepo.GetAll(); Console.WriteLine("Please choose a roommate to assign your chosen chore to"); foreach (Roommate r in roommates) { Console.WriteLine($"{r.Id}.) {r.Firstname}"); } //assign the given roommate number to roommateId for assigning feature int roommateId = int.Parse(Console.ReadLine()); Console.WriteLine($"you have chose{roommateId}"); Console.ReadLine(); choreRepo.AssignChore(roommateId, choreId); Console.WriteLine("Chore assignment successful"); Console.WriteLine("Press any key to continue"); Console.ReadLine(); break; case ("Search for chores"): Console.WriteLine("What chore would you like to search for?"); int choreResponse = int.Parse(Console.ReadLine()); Chore chore= choreRepo.GetChoreByid(choreResponse); // Console.WriteLine($"Your search result is: {chore.Name}"); Console.WriteLine("Press any key to continue"); Console.ReadLine(); break; case ("Create new chore"): Console.WriteLine("What chore would you like to add?"); string choreName = Console.ReadLine(); Chore newChore = new Chore() { Name = choreName }; choreRepo.Insert(newChore); Console.WriteLine($"You have added {newChore.Name} as a new chore"); Console.WriteLine("Press any ket to continue:"); Console.ReadLine(); break; break; case ("Exit"): runProgram = false; break; } } } private static string GetMenuSelection() { Console.Clear(); List<string> options = new List<string>() { "Show all rooms", "Search for room", "Add a room", "Search for roommate", "Show all chores", "Show unassigned chores", "Assign a chore", "Search for chores", "Create new chore", "Exit" }; for (int i = 0; i < options.Count; i++) { Console.WriteLine($"{i + 1}. {options[i]}"); } while(true) { try { Console.WriteLine(); Console.Write("Select an option >"); string input = Console.ReadLine(); int index = int.Parse(input) - 1; return options[index]; } catch (Exception) { continue; } } } } } <file_sep>using Microsoft.Data.SqlClient; using Roommates.Models; using System.Collections.Generic; namespace Roommates.Repositories { public class RoommateRepository : BaseRepository { //First make first is to construct a tunnel public RoommateRepository(string ConnectionString) : base(ConnectionString) { } public List<Roommate> GetAll() { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "Select * FROM Roommate"; SqlDataReader reader = cmd.ExecuteReader(); List<Roommate> roomies = new List<Roommate>(); while (reader.Read()) { Roommate roommate = new Roommate { Id = reader.GetInt32(reader.GetOrdinal("Id")), Firstname = reader.GetString(reader.GetOrdinal("FirstName")) }; roomies.Add(roommate); } reader.Close(); return roomies; } } } //Second is to create a method for instructions public Roommate GetRoommateById(int id) { //make a request pathway by using using (SqlConnection conn = Connection) { //Remember to open that tunnel! conn.Open(); //Time to make the instruction packet! using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @"SELECT Roommate.ID, FirstName, RentPortion, Room.Name from Roommate LEFT JOIN Room ON Roommate.RoomId = Room.Id WHERE Roommate.ID = @id"; cmd.Parameters.AddWithValue("@id", id); //Now that we tell the DB what we want, we need to be able to read it SqlDataReader reader = cmd.ExecuteReader(); //want to go ahead and create the new room instance, so it can be instantiated later Roommate roommate = null; //Now that we have the data requested, and a way to reader once receive. LOGIC TIME! //This is just where we save the requested information so that it can be returned if (reader.Read()) { roommate = new Roommate() { Id = id, Firstname = reader.GetString(reader.GetOrdinal("FirstName")), RentPortion = reader.GetInt32(reader.GetOrdinal("RentPortion")), Name = reader.GetString(reader.GetOrdinal("Name")) }; } //return the new object so it can be viewed on console reader.Close(); return roommate; } } } } }
596726a2b1eec54938af2835c87e6844684566bd
[ "C#" ]
3
C#
joetid09/ADO.NET
ca04068ea7c460c2c6cf00898d317f25f4aec6eb
0b506776a00f5d73aa016dfd528f2979fe211ec7
refs/heads/master
<file_sep>var ObjectAdapter = function() {}; ObjectAdapter.prototype.build = function(Model, props) { return props; }; ObjectAdapter.prototype.save = function(doc, Model, cb) { process.nextTick(function() { cb(null, doc); }); }; ObjectAdapter.prototype.destroy = function(doc, Model, cb) {}; module.exports = ObjectAdapter; <file_sep>(function() { if (typeof module === 'undefined') { var _ = window._; } else { var _ = require('underscore'); } var Manufacturing = function(asyncLib) { if (!asyncLib) { asyncLib = require('async'); } var _definitionsStack = []; var _lastShipment = []; var manufacturing = this; manufacturing.pushDefinition = function(newDefinition) { global.before(function(){ _definitionsStack.push(newDefinition); }); global.after(function(){ _definitionsStack.pop(); }); }; manufacturing.createAll = function(target, done){ console.log('manufacturing.createAll', arguments); var flatDefinition = {} _.each(_definitionsStack, function(definition){ //This intentionally overwrites earlier keys as a form //of inheritance _.each(definition, function (v, k) { flatDefinition[k] = v; }); }); asyncLib.auto(flatDefinition, function(err, results){ if(err){ done(err); return; } _lastShipment = results; for (var prop in target) { target[prop] = null; } _.extend(target, results); done(); }); }; } if (typeof module === 'undefined') { this.manufacturing = {}; module = this.manufacturing; } module.exports = new Manufacturing(); module.exports.Manufacturing = Manufacturing; }());
6688fafcbd49ad48a438f0447ad98aa888d37c69
[ "JavaScript" ]
2
JavaScript
Hyperbase/factory-girl
81d84504b631502f32f5790054d44619a24233a8
a26f07dde0c7ac735fc436d03a8b0ed3c53dcb37
refs/heads/master
<file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class UserserviceService { private isUserLogged:any; constructor(private httpClient : HttpClient) { this.isUserLogged=false; } setUesrLoggedIn():void{ this.isUserLogged=true; } setUesrLoggedOut():void{ this.isUserLogged=false; } getUserLogged():any{ return this.isUserLogged; } register(user:any){ return this.httpClient.post('RESTAPI/webapi/myresource/registerUser' , user); } getUser(email: any,password:any) { return this.httpClient.get('RESTAPI/webapi/myresource/getUser/' + email +'/' + password); } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-tata', templateUrl: './tata.component.html', styleUrls: ['./tata.component.css'] }) export class TataComponent implements OnInit { constructor() { } public barChartOptions = { scaleShowVerticalLines: false, responsive: true }; public barChartLabels = ['2006', '2007', '2008', '2009', '2010', '2011', '2012']; public barChartType = 'line'; public barChartLegend = true; public dates=[]; public high=[]; public low=[]; public open=[]; public close=[]; public bardata=[{data :this.high,label :'High'},{data :this.low,label :'low'},{data :this.open,label :'open'},{data :this.close,label :'close'}]; async ngOnInit() { // const response = await fetch('testdata.csv'); const response = await fetch('assets/ExcelFiles/TATASTEEL.NS.csv'); const data = await response.text(); const rows = data.split('\n').slice(1); rows.forEach(row => { const cols = row.split(','); this.dates.push(cols[0]); this.open.push(parseFloat(cols[1])); this.close.push(parseFloat(cols[4])); this.high.push(parseFloat(cols[2])); this.low.push(parseFloat(cols[3])); }); console.log(open) } } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule, FormControlDirective } from '@angular/forms'; import { RouterModule, Routes } from '@angular/router'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { RegisterComponent } from './register/register.component'; import { LoginComponent } from './login/login.component'; import {HttpClientModule } from '@angular/common/http'; import { GraphsComponent } from './graphs/graphs.component'; import { ChartsModule } from 'ng2-charts'; import { MainpageComponent } from './mainpage/mainpage.component'; import { HomepageComponent } from './homepage/homepage.component'; import { EichermotComponent } from './eichermot/eichermot.component'; import { TataComponent } from './tata/tata.component'; import { CiplaComponent } from './cipla/cipla.component'; import { AshokleyComponent } from './ashokley/ashokley.component'; import { NseComponent } from './nse/nse.component'; import { BseComponent } from './bse/bse.component'; const appRoot: Routes = [{path: '', component: HomepageComponent}, {path: 'login', component: LoginComponent}, {path: 'register', component: RegisterComponent}, {path: 'mainpage', component: MainpageComponent}, {path: 'graph', component: GraphsComponent}, {path: 'ashokley', component: AshokleyComponent}, {path: 'cipla', component: CiplaComponent}, {path: 'tata', component: TataComponent}, {path: 'eichermot', component: EichermotComponent}, {path: 'Nifty', component: NseComponent}, {path: 'Sensex', component: BseComponent}, ]; @NgModule({ declarations: [ AppComponent, RegisterComponent, LoginComponent, GraphsComponent, MainpageComponent, HomepageComponent, EichermotComponent, TataComponent, CiplaComponent, AshokleyComponent, NseComponent, BseComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, HttpClientModule, ChartsModule, RouterModule.forRoot(appRoot), ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { UserserviceService } from '../userservice.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { email:String; password:String; user:any; constructor(private service : UserserviceService,private router : Router) { } ngOnInit(): void { } getUser():void{ console.log(this.email) this.service.getUser(this.email,this.password).subscribe((data: any) => { this.user = data; }); console.log(this.user) if(this.user === null){ alert('Invalid') }else{ alert('Success'); this.router.navigate(['mainpage']); } } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-bse', templateUrl: './bse.component.html', styleUrls: ['./bse.component.css'] }) export class BseComponent implements OnInit { public dates=[]; public high=[]; public low=[]; public open=[]; public close=[]; public n : number; public p : number; constructor() { } async ngOnInit() { // const response = await fetch('testdata.csv'); const response = await fetch('assets/ExcelFiles/BSE (Sensex).csv'); const data = await response.text(); const rows = data.split('\n').slice(1); rows.forEach(row => { const cols = row.split(','); this.dates.push(cols[0]); this.open.push(parseFloat(cols[1])); this.close.push(parseFloat(cols[4])); this.high.push(parseFloat(cols[2])); this.low.push(parseFloat(cols[3])); }); console.log(open); this.n = (this.open[this.open.length -1] + this.close[this.close.length - 2])/2; this.p = this.open[this.open.length -1] - this.close[this.close.length - 2]; } }
0938a6880a142c315f85477229143675351d9eea
[ "TypeScript" ]
5
TypeScript
madhumitha357/StockMarketAngular
9c9f0b68f92cf809863a3a021493609e5d53421b
d7bad51887a7d2b19e9ac3e3836331ef6a56089a
refs/heads/master
<file_sep>import React,{useState} from 'react' import HeaderView from '../View/HeaderView' const Header = () => { var counter=0; const [time,setTime]=useState(''); const countDownDate = new Date("Aug 08, 2021 18:00:00").getTime(); var clock=setInterval(()=>{ var current = new Date().getTime(); counter = countDownDate - current; var days = Math.floor(counter / (1000 * 60 * 60 * 24)); var hours = Math.floor((counter % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((counter % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((counter % (1000 * 60)) / 1000); var finalTime = days+" d "+hours+" h "+minutes+" m "+seconds+" s" setTime(finalTime) if(counter<0){ counter="expired"; clearInterval(clock); setTime(counter) } },1000); return ( <HeaderView time={time}/> ) } export default Header <file_sep>import React from 'react' const QuoteView = ({nameinput,emailinput,telinput,successMsg,handleSubmit}) => { return ( <section id="quoteSection"> <h3>Travelling a group? Get a Quote</h3> <form onSubmit={(e)=>handleSubmit(e)}> <div className="inputContainer"> <label htmlFor="userName">Your Name</label> <br /> <input type="text" className="name" id="userName" ref={nameinput}/> <p className="emptyErrorMsg">Name is required</p> </div> <div className="inputContainer"> <label htmlFor="contact">Contact No</label> <br /> <input type="text" id="contact" ref={telinput} /> <p className="emptyErrorMsg">Contact No is required</p> <p className="invalidErrorMsg">Invalid Contact No</p> </div> <div className="inputContainer"> <label htmlFor="email">Email</label> <br /> <input type="text" id="email" ref={emailinput} /> <p className="emptyErrorMsg">Email is required</p> <p className="invalidErrorMsg">Invalid Email</p> </div> <div className="successMsg" ref={successMsg}>We hear you! We will get back to you for planning your vacation</div> <input type="submit" value="SUBMIT" className="gradient"/> </form> </section> ) } export default QuoteView <file_sep>import React from 'react' const FooterView = () => { return ( <footer className="gradient" id="footerSection"> <div className="column"> <div className="columnContent"> <h4>Tripzone</h4> <ul> <li>About</li> <li>Awards</li> <li>Contact Us</li> <li>Feedback</li> </ul> </div> </div> <div className="column"> <div className="columnContent"> <h4>Main offices</h4> <ul> <li>The United</li> <li>India</li> <li>Braxil</li> <li>Canada</li> </ul> </div> </div> <div className="column"> <div className="columnContent"> <h4>Sub Offices</h4> <ul> <li>Australia</li> <li>England</li> <li>France</li> <li>Germany</li> </ul> </div> </div> <div className="column lastCol"> <div className="columnContent"> <h4>Disclaimer</h4> <ul> <li>This layout is created as a part of sirius UI Recruitments.</li> <li>All the above content has no direct relation with sirius buisness</li> <li></li> <li></li> </ul> </div> </div> </footer> ) } export default FooterView <file_sep>import React from 'react' const FeatureTile = ({tileInfo}) => { return ( <div className="featureTile"> <figure> <img src={tileInfo.imageUrl} alt="featured"/> <figcaption>{tileInfo.city}</figcaption> </figure> </div> ) } export default FeatureTile <file_sep>import React from 'react' import WeatherTile from './WeatherTile' const WeatherView = ({tiles}) => { return ( <section id="weatherSection"> <div className="weatherHeading"> THE WEATHER CHANNEL </div> <div className="weatherTileContainer"> { tiles.map( (tile,index) => <WeatherTile key={index} tileInfo={tile} tileIndex={index}/>) } </div> </section> ) } export default WeatherView <file_sep>import React from 'react' const NavigationView = () => { return ( <nav id="navSection"> <ul> <li> <a href="#weatherSection">WEATHER</a> </li> <li> <a href="#featureSection">DESTINATIONS</a> </li> <li> <a href="#quoteSection">GET A QUOTE</a> </li> </ul> </nav> ) } export default NavigationView <file_sep>import './App.css'; import Header from './Components/Logic/Header' import NavigationView from './Components/View/NavigationView' import WelcomeView from './Components/View/WelcomeView' import Weather from './Components/Logic/Weather' import Feature from './Components/Logic/Feature' import PromoView from './Components/View/PromoView' import Quote from './Components/Logic/Quote' import FooterView from './Components/View/FooterView' function App() { return ( <div className="App"> <Header/> <NavigationView/> <WelcomeView/> <Weather/> <Feature/> <PromoView/> <Quote/> <FooterView/> </div> ); } export default App; <file_sep>import React from 'react' import WelcomeSVG from '../../Assets/welcome-image.svg' const WelcomeView = () => { return ( <section id="welcomeSection"> <div className="imgContainer"> <figure> <img src={WelcomeSVG} alt="welcome" /> </figure> </div> <div className="textContainer"> <div className="welcomeText"> <h3>Life is short</h3> <h3>and the world is wide !</h3> <p>Stay at the comfort of your homes and book a trip to travel after the post pandemic era</p> <button className="gradient">PLAN A TRIP</button> </div> </div> </section> ) } export default WelcomeView <file_sep> const useTimer = () => { var counter=0; const countDownDate = new Date("Aug 10, 2022 18:00:00").getTime(); var clock=setInterval(()=>{ var current = new Date().getTime(); counter = countDownDate - current; if(counter<0){ counter="expired"; clearInterval(clock); } },1000); return counter; } export default useTimer <file_sep># Welcome to Sirius travel page layout This project was created by nitin as a testimony of his skills. The entire project was build from scratch using ReactJS. `Live Preview` - https://travel-layout.netlify.app/ Keep Reading, you are up for a wonderful ride.... ## Points Of Attraction ### Mobile Responsive The entire website is mobile responsive. No additional dependency or css frameworks were used to achieve this. Good old fashioned media query and display flex did the trick! ### React JS (Hooks) Its always good to use latest and newest of the technology. Who uses class based components anyways? ### SASS This project is awesome, but is our styling also is? Yep! Syntactically awesome style sheet in the houseeee!!! ### Custom Hooks Lets remove all the redundant code! Using custom hooks i have made sure to re-utilise the same code as much as feasible. (Extra points for that?No? Fine, wait for the next step) ### Live Preview No one likes to setup an entire project on their local machine. Dont worry buddy, as a fellow engineer, i got you covered! Test the entire application here- https://travel-layout.netlify.app/ . (You still have option to clone this repo and run it on your machine) ### Modular Code The code is made highly modular and i have made sure to follow SRP principle throughout the project. More details about this in the next heading ## Design Principles ## `SRP` - Single Responsibilty Principle Each component should be responsible for doing only one task. I have made sure to segregate buisness logic from Views. This helps to achieve SRP and code becomes alot more easier to debug ## `DRY` - Dont Repeat Your Self I have made sure to make the code more and more reusable. Using custom hooks i have reused the data fetching code for both weather and featured components And on that note.....+5 points to gryfinddor!! BTW, i was able to complete this enitre work in less than 24 hours... <file_sep>import React, { useRef } from 'react' import QuoteView from '../View/QuoteView' const Quote = () => { const nameinput = useRef(null); const emailinput = useRef(null); const telinput = useRef(null); const successMsg = useRef(null); const handleSubmit = (e) => { e.preventDefault(); let validName = false; let validEmail = false; let validTel = false; //name validation if (nameinput.current.value) { nameinput.current.classList.remove("hasEmpty"); validName = true; } else { nameinput.current.classList.add("hasEmpty") } //email validation if (emailinput.current.value) { emailinput.current.classList.remove("hasEmpty"); var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; if(emailPattern.test(emailinput.current.value)){ emailinput.current.classList.remove("hasInvalid") validEmail = true; }else{ emailinput.current.classList.add("hasInvalid") } } else { emailinput.current.classList.add("hasEmpty") } //number validation if (telinput.current.value) { telinput.current.classList.remove("hasEmpty"); var phonePattern = /^\d{10}$/; if(phonePattern.test(telinput.current.value)){ telinput.current.classList.remove("hasInvalid") validTel = true; }else{ telinput.current.classList.add("hasInvalid") } } else { telinput.current.classList.add("hasEmpty") } if (validEmail && validName && validTel) { telinput.current.value = ''; emailinput.current.value = ''; nameinput.current.value = ''; successMsg.current.classList.add("is-visible"); }else{ successMsg.current.classList.remove("is-visible"); } } return ( <QuoteView nameinput={nameinput} emailinput={emailinput} telinput={telinput} successMsg={successMsg} handleSubmit={handleSubmit} /> ) } export default Quote <file_sep>import React from 'react' import FeatureTile from './FeatureTile' const FeatureView = ({tiles}) => { return ( <section id="featureSection"> <div className="featureHeading"> <h3 className="">Featured Destinations</h3> </div> <div className="featureTileContainer"> { tiles.map( (tile,index) => <FeatureTile key={index} tileInfo={tile} tileIndex={index}/>) } </div> </section> ) } export default FeatureView
af0f67b2e92995f1af84a0e15a3a59c0cbaed35b
[ "JavaScript", "Markdown" ]
12
JavaScript
Nitintin/travel-page
734d4c485add0c40898eec4d6bb273a9b128f805
2ff1dc88f171229e2cd256abfef48131c9900f53
refs/heads/main
<file_sep>--Create the student table CREATE TABLE STUDENT( Student_ID int NOT NULL, Student_Department varchar(25), Student_Name varchar(25), PRIMARY KEY (Student_ID) ); --Create the course table CREATE TABLE COURSE( Course_Num int NOT NULL, Course_Name varchar(25), Course_Dept varchar(25), Course_Semester varchar(25), Course_Year varchar(4), PRIMARY KEY(Course_Num) ); --Create the grade table CREATE TABLE GRADE( Grade_ID int NOT NULL, Grade_StudentID int NOT NULL, Grade_CourseID int NOT NULL, Grade_Value varchar(2), Grade_Percent varchar (3), Grade_Type varchar(25), PRIMARY KEY (Grade_ID), foreign KEY (Grade_StudentID) REFERENCES STUDENT(Student_ID), foreign KEY (Grade_CourseID) REFERENCES COURSE(Course_Num) );<file_sep># csc4480-final-project To run this project you will need an Oracle SQL enviroment. For online use, consider this: https://livesql.oracle.com First run "table_creation.sql" to setup the backbone of our database Next run "table_population.sql" to populate the database with sample database Finally you can run "commands.sql" to see a list of different commands to run for an example of what powerful operations you can do. <file_sep>--Read Out Student Table SELECT * From STUDENT; --Read Out Course Table SELECT * FROM COURSE; --Read Out Gradebook SELECT * FROM GRADE; --List All Students With Grades SELECT DISTINCT STUDENT_NAME FROM STUDENT, GRADE WHERE Grade.Grade_StudentID = Student.Student_ID ORDER by Student_Name; --List All Courses For 2021 SELECT COURSE_NAME FROM COURSE WHERE Course_Year = '2021'; --List All Courses For 2022 SELECT COURSE_NAME FROM COURSE WHERE Course_Year = '2022'; --List All Spring Courses SELECT COURSE_NAME FROM COURSE WHERE Course_Semester = 'Spring'; --List All Fall Courses SELECT COURSE_NAME FROM COURSE WHERE Course_Semester = 'Fall'; --Find Students With Grade Above a 90 SELECT STUDENT.STUDENT_NAME, GRADE.GRADE_VALUE, GRADE.GRADE_TYPE FROM STUDENT, GRADE WHERE Grade.Grade_StudentID = Student.Student_ID and Grade.Grade_Value > '90' ORDER BY STUDENT_NAME; --Find Students With Grade Below 70 SELECT STUDENT.STUDENT_NAME, GRADE.GRADE_VALUE, GRADE.GRADE_TYPE FROM STUDENT, GRADE WHERE Grade.Grade_StudentID = Student.Student_ID and Grade.Grade_Value < '70' ORDER BY STUDENT_NAME; --Find the Classes <NAME> is Taking SELECT COURSE_NAME, COURSE_NUM FROM COURSE WHERE COURSE_NUM IN (SELECT GRADE_COURSEID FROM GRADE WHERE GRADE_STUDENTID IN (SELECT Student_ID FROM STUDENT WHERE Student_Name = '<NAME>')) ORDER BY COURSE_NAME; --Find the Classes Andre the Giant is Taking SELECT COURSE_NAME, COURSE_NUM FROM COURSE WHERE COURSE_NUM IN (SELECT GRADE_COURSEID FROM GRADE WHERE GRADE_STUDENTID IN (SELECT Student_ID FROM STUDENT WHERE Student_Name = '<NAME>')) ORDER BY COURSE_NAME;<file_sep>--Import the students INSERT INTO STUDENT(Student_ID, Student_Department, Student_Name) VALUES(1,'Computer Science','<NAME>'); INSERT INTO STUDENT(Student_ID, Student_Department, Student_Name) VALUES(2,'Business','<NAME>'); INSERT INTO STUDENT(Student_ID, Student_Department, Student_Name) VALUES(3,'Business','<NAME>'); INSERT INTO STUDENT(Student_ID, Student_Department, Student_Name) VALUES(4,'Computer Science','<NAME>'); INSERT INTO STUDENT(Student_ID, Student_Department, Student_Name) VALUES(5,'Computer Science','<NAME>'); INSERT INTO STUDENT(Student_ID, Student_Department, Student_Name) VALUES(6,'Math','<NAME>'); INSERT INTO STUDENT(Student_ID, Student_Department, Student_Name) VALUES(7,'Math','<NAME>'); INSERT INTO STUDENT(Student_ID, Student_Department, Student_Name) VALUES(8,'English','<NAME>'); INSERT INTO STUDENT(Student_ID, Student_Department, Student_Name) VALUES(9,'Computer Science','<NAME>'); --Import the courses INSERT INTO COURSE(Course_Num, Course_Name, Course_Dept, Course_Semester, Course_Year) VALUES('4780', 'Intro to SQL', 'Computer Science', 'Fall', '2021'); INSERT INTO COURSE(Course_Num, Course_Name, Course_Dept, Course_Semester, Course_Year) VALUES('5600', 'Android Development', 'Computer Science', 'Fall', '2021'); INSERT INTO COURSE(Course_Num, Course_Name, Course_Dept, Course_Semester, Course_Year) VALUES('4200', 'Intro to Python', 'Computer Science', 'Spring', '2022'); INSERT INTO COURSE(Course_Num, Course_Name, Course_Dept, Course_Semester, Course_Year) VALUES('3200', 'Calculus 4', 'Math', 'Fall', '2021'); INSERT INTO COURSE(Course_Num, Course_Name, Course_Dept, Course_Semester, Course_Year) VALUES('3300', 'Differential Equations', 'Math', 'Spring', '2022'); --Import the grade INSERT INTO GRADE(Grade_ID, Grade_StudentID, Grade_CourseID, Grade_Value, Grade_Percent, Grade_Type) VALUES(1, 4, 4780, '98','20','Test'); INSERT INTO GRADE(Grade_ID, Grade_StudentID, Grade_CourseID, Grade_Value, Grade_Percent, Grade_Type) VALUES(2, 1, 4780, '95','20','Test'); INSERT INTO GRADE(Grade_ID, Grade_StudentID, Grade_CourseID, Grade_Value, Grade_Percent, Grade_Type) VALUES(3, 2, 4780, '55','20','Test'); INSERT INTO GRADE(Grade_ID, Grade_StudentID, Grade_CourseID, Grade_Value, Grade_Percent, Grade_Type) VALUES(4, 2, 4780, '76','20','Test'); INSERT INTO GRADE(Grade_ID, Grade_StudentID, Grade_CourseID, Grade_Value, Grade_Percent, Grade_Type) VALUES(5, 3, 4780, '37','20','Test'); INSERT INTO GRADE(Grade_ID, Grade_StudentID, Grade_CourseID, Grade_Value, Grade_Percent, Grade_Type) VALUES(6, 1, 5600, '88','20','Test'); INSERT INTO GRADE(Grade_ID, Grade_StudentID, Grade_CourseID, Grade_Value, Grade_Percent, Grade_Type) VALUES(7, 5, 4780, '84','40','Midterm'); INSERT INTO GRADE(Grade_ID, Grade_StudentID, Grade_CourseID, Grade_Value, Grade_Percent, Grade_Type) VALUES(8, 5, 5600, '78','40','Midterm'); INSERT INTO GRADE(Grade_ID, Grade_StudentID, Grade_CourseID, Grade_Value, Grade_Percent, Grade_Type) VALUES(9, 6, 5600, '68','10','Homework'); INSERT INTO GRADE(Grade_ID, Grade_StudentID, Grade_CourseID, Grade_Value, Grade_Percent, Grade_Type) VALUES(10, 4, 4780, '94','10','Homework'); INSERT INTO GRADE(Grade_ID, Grade_StudentID, Grade_CourseID, Grade_Value, Grade_Percent, Grade_Type) VALUES(11, 2, 4780, '90','10','Homework'); INSERT INTO GRADE(Grade_ID, Grade_StudentID, Grade_CourseID, Grade_Value, Grade_Percent, Grade_Type) VALUES(12, 3, 4780, '91','10','Homework'); INSERT INTO GRADE(Grade_ID, Grade_StudentID, Grade_CourseID, Grade_Value, Grade_Percent, Grade_Type) VALUES(13, 6, 4200, '81','10','Homework'); INSERT INTO GRADE(Grade_ID, Grade_StudentID, Grade_CourseID, Grade_Value, Grade_Percent, Grade_Type) VALUES(14, 6, 4780, '55','10','Homework'); INSERT INTO GRADE(Grade_ID, Grade_StudentID, Grade_CourseID, Grade_Value, Grade_Percent, Grade_Type) VALUES(15, 6, 4200, '78','20','Quiz'); INSERT INTO GRADE(Grade_ID, Grade_StudentID, Grade_CourseID, Grade_Value, Grade_Percent, Grade_Type) VALUES(16, 1, 4200, '84','20','Quiz'); INSERT INTO GRADE(Grade_ID, Grade_StudentID, Grade_CourseID, Grade_Value, Grade_Percent, Grade_Type) VALUES(17, 2, 4780, '90','20','Quiz'); INSERT INTO GRADE(Grade_ID, Grade_StudentID, Grade_CourseID, Grade_Value, Grade_Percent, Grade_Type) VALUES(18, 4, 4200, '99','20','Quiz');
f69f5fc3aa3c318fd323f27136fe1fa80ac25f6b
[ "Markdown", "SQL" ]
4
SQL
adyum/csc4480-final-project
228486e70d42eb2ea1ed8227c9be2bb174ffc952
50134ae917384e058b88fddabf72ab72a740fb4b
refs/heads/master
<repo_name>kip7evans/Mall<file_sep>/README.md # Mall Stop For A buy!! Buy somethings <file_sep>/app/src/main/java/com/example/mall/fragment_main.java package com.example.mall; import android.os.Bundle; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.navigation.NavigationView; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; public class fragment_main extends Fragment { private BottomNavigationView navigationView; private RecyclerView recyclerViewNewItem,recyclerViewSuggestedItem,recyclerViewPopularItem; private GroceryAdapter NewItemAdapter,/*SuggestedItemAdapter,*/PopularItemAdapter; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v =inflater.inflate(R.layout.fragment_main,container,false); initViews(v); initSelected(); initAdapters(); return v; } private void initAdapters() { NewItemAdapter =new GroceryAdapter(getActivity()); recyclerViewNewItem.setAdapter(NewItemAdapter); recyclerViewNewItem.setLayoutManager(new LinearLayoutManager(getActivity(),RecyclerView.HORIZONTAL,false)); GroceryAdapter suggestedViewAdapter = new GroceryAdapter(getActivity()); recyclerViewSuggestedItem.setAdapter(suggestedViewAdapter); recyclerViewSuggestedItem.setLayoutManager(new LinearLayoutManager(getActivity(),RecyclerView.HORIZONTAL,false)); PopularItemAdapter = new GroceryAdapter(getActivity()); recyclerViewPopularItem.setAdapter(PopularItemAdapter); recyclerViewPopularItem.setLayoutManager(new LinearLayoutManager(getActivity(),RecyclerView.HORIZONTAL,false)); ArrayList<GroceryItems> NewItems =utils.getAllItems(getActivity()); if (null !=NewItems){ Comparator<GroceryItems> NewItemComparator =new Comparator<GroceryItems>() { @Override public int compare(GroceryItems o1, GroceryItems o2) { return o1.getId()-o2.getId(); } }; Collections.sort(NewItems,NewItemComparator); NewItemAdapter.setGroceryItemsList(NewItems); } ArrayList<GroceryItems> PopularItems = utils.getAllItems(getActivity()); if (null !=PopularItems){ Comparator<GroceryItems> PopularItemComparator = new Comparator<GroceryItems>() { @Override public int compare(GroceryItems o1, GroceryItems o2) { return o1.getPopularityPoint()-o2.getPopularityPoint(); } }; Comparator<GroceryItems> comparatorReverse =Collections.reverseOrder(PopularItemComparator); Collections.sort(PopularItems,comparatorReverse); PopularItemAdapter.setGroceryItemsList(PopularItems); } ArrayList<GroceryItems> suggestedItems =utils.getAllItems(getActivity()); if(null != suggestedItems){ Comparator<GroceryItems> suggestedComparator = new Comparator<GroceryItems>() { @Override public int compare(GroceryItems o1, GroceryItems o2) { return o1.getUserPoint()-o2.getUserPoint(); } }; Comparator<GroceryItems> comparatorReverse =Collections.reverseOrder(suggestedComparator); Collections.sort(suggestedItems,suggestedComparator); suggestedViewAdapter.setGroceryItemsList(suggestedItems); } } private void initSelected() { navigationView.setSelectedItemId(R.id.hommm); navigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()){ case R.id.shoppingCart: Toast.makeText(getActivity(), "wannna do some shoppings ", Toast.LENGTH_SHORT).show(); break; case R.id.hommm: break; case R.id.search: break; default: break; } return true; } }); } private void initViews(View v){ navigationView =v.findViewById(R.id.navigation_bottom_bottom); recyclerViewNewItem =v.findViewById(R.id.RecyclerNewItem); recyclerViewPopularItem =v.findViewById(R.id.RecyclerPopularItem); recyclerViewSuggestedItem =v.findViewById(R.id.RecyclerSuggestedItem); } } <file_sep>/app/src/main/java/com/example/mall/GroceryAdapter.java package com.example.mall; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import java.util.ArrayList; public class GroceryAdapter extends RecyclerView.Adapter<GroceryAdapter.Viewholder> { private ArrayList<GroceryItems> groceryItemsList =new ArrayList<>(); private Context context; public GroceryAdapter(Context context) { this.context = context; } @NonNull @Override public Viewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.items,parent,false); return new Viewholder(v); } @Override public void onBindViewHolder(@NonNull Viewholder holder, final int position) { holder.txtName.setText(groceryItemsList.get(position).getName()); holder.txtPrice.setText(String.valueOf(groceryItemsList.get(position).getPrice())); Glide.with(context) .asBitmap() .load(groceryItemsList.get(position).getImageUrl()) .into(holder.imageView); holder.pare.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context,Grocery_Activity.class); intent.putExtra("key",groceryItemsList.get(position)); context.startActivity(intent); } }); } @Override public int getItemCount() { return groceryItemsList.size(); } public class Viewholder extends RecyclerView.ViewHolder { private ImageView imageView; private TextView txtName; private TextView txtPrice; private CardView pare; public Viewholder(@NonNull View itemView) { super(itemView); imageView =itemView.findViewById(R.id.image); txtName=itemView.findViewById(R.id.txtname); txtPrice=itemView.findViewById(R.id.txtprice); pare=itemView.findViewById(R.id.parent); } } public void setGroceryItemsList(ArrayList<GroceryItems> groceryItemsList) { this.groceryItemsList = groceryItemsList; notifyDataSetChanged(); } } <file_sep>/app/src/main/java/com/example/mall/utils.java package com.example.mall; import android.content.Context; import android.content.SharedPreferences; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; public class utils { private static int ID=0; private static final String ALTERNATIVE_DB="fake database"; private static final String GROCERY_FIRST_ITEMS="grocery"; private static final Gson gson = new Gson(); private static final Type type = new TypeToken<ArrayList<GroceryItems>>(){}.getType(); public static void initSharedPreference(Context context){ SharedPreferences sharedPreferences =context.getSharedPreferences(ALTERNATIVE_DB,Context.MODE_PRIVATE); ArrayList<GroceryItems> allItems =gson.fromJson(sharedPreferences.getString(GROCERY_FIRST_ITEMS,null),type); if (null ==allItems){ intiAllData(context); } } private static void intiAllData(Context c) { ArrayList<GroceryItems> items = new ArrayList<>(); GroceryItems milk =new GroceryItems("Milk Tuzo",440.0, "this is a quality kind of milks from tuzo milk campany", "https://images.unsplash.com/photo-1549395156-e0c1fe6fc7a5?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60","9",7); milk.setPopularityPoint(20); items.add(milk); GroceryItems TotoBread =new GroceryItems("icebergs",909.0, "this is a quality kind of milks from tuzo milk campany", "https://i2.wp.com/butterwithasideofbread.com/wp-content/uploads/2019/07/White-Bread_7.bsb_.jpg?ssl=1","9",7); TotoBread.setPopularityPoint(3); TotoBread.getUserPoint(); items.add(TotoBread); GroceryItems pespi =new GroceryItems("icebergs",909.0, "this is a quality kind of milks from tuzo milk campany", "https://images-na.ssl-images-amazon.com/images/I/515Lwr5CyxL.jpg","9",7); pespi.setPopularityPoint(34); pespi.getUserPoint(); items.add(pespi); GroceryItems soda =new GroceryItems("cocacola",405.0, "this is a quality kind of milks from tuzo milk campany", "https://images.unsplash.com/photo-1534260164206-2a3a4a72891d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60","9",7); soda.setPopularityPoint(2); soda.getUserPoint(); items.add(soda); GroceryItems ice_cream =new GroceryItems("icebergs",909.0, "ice cream of the sweet taste for kids", "https://images.unsplash.com/photo-1497034825429-c343d7c6a68f?ixlib=rb-1.2.1&w=1000&q=80","9",7); ice_cream.setPopularityPoint(34); ice_cream.getUserPoint(); items.add(ice_cream); GroceryItems Tuzo =new GroceryItems("icebergs",909.0, "this is a quality kind of milks from tuzo milk campany think of trying it", "https://res-1.cloudinary.com/afsk/c_lpad,dpr_1.0,f_auto,h_533,q_100,w_400/media/catalog/product/t/u/tuzo_1.jpg","9",7); Tuzo.setPopularityPoint(34); Tuzo.getUserPoint(); items.add(Tuzo); SharedPreferences sharedPreferences=c.getSharedPreferences(ALTERNATIVE_DB,Context.MODE_PRIVATE); SharedPreferences.Editor editor =sharedPreferences.edit(); editor.putString(GROCERY_FIRST_ITEMS,gson.toJson(items)); editor.commit(); } public static ArrayList<GroceryItems> getAllItems(Context context){ SharedPreferences sharedPreferences=context.getSharedPreferences(ALTERNATIVE_DB,Context.MODE_PRIVATE); ArrayList<GroceryItems> allItems =gson.fromJson(sharedPreferences.getString(GROCERY_FIRST_ITEMS,null),type); return allItems; } public static int getID() { ID++; return ID; } }
c324e0832a2f23f16c2b395fb3507005d0627bca
[ "Markdown", "Java" ]
4
Markdown
kip7evans/Mall
bb4ccbfc0cde9d20070f1ae952da4bab6f4cd219
49c4ee4a84fe2e752f7f2e51c1fad71282060240
refs/heads/master
<file_sep>print("这是第二次上传合作项目")
6b6b05d0b091482e5995e8775c2684e0bf55e617
[ "Python" ]
1
Python
dreamkid-hack/share
0ad01e211b90d319bab4d6b8033ea565a9cf8c2e
c77782c60fcb00b83c172d88c43c16f7c8b67a95
refs/heads/master
<repo_name>yuliyasychikova/aventures_prod<file_sep>/javascripts/vendor/youtube.js window.YouTube = (function($, window, document) { window.disableScroll = function(){ $('body').addClass('noscroll'); }; window.enableScroll = function(){ if (!$('.modal-container:visible').length){ $('body').removeClass('noscroll'); } }; var $ytVideo = $(".yt-video").on('click', function (event) { event.preventDefault(); event.stopPropagation(); $('#bg-video').get(0).pause() showVideo($(this).data('id'), function() { }); }); // attach our YT listener once the API is loaded function _initVideo(id, videoId, callback) { window.onYouTubeIframeAPIReady = function() { window.player = new YT.Player(id, { height: '315', width: '560', videoId: videoId, playerVars: { modestbranding: 0, rel: 0, feature: 'player_detailpage', wmode: 'transparent', iv_load_policy: 3, showinfo: 0, autohide: 1 }, events: { onStateChange: function(e){ if (e["data"] == YT.PlayerState.PLAYING && YT.gtmLastAction == "play") { callback(); YT.gtmLastAction = ""; } }, onReady: function() { window.player.playVideo(); } } }); $(window).trigger('scroll'); YT.gtmLastAction = "play"; }; _loadYoutubeIfNotLoadedYet(); } function _loadYoutubeIfNotLoadedYet() { if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') { // load the Youtube JS api and get going var tag = document.createElement('script'); tag.src = "//www.youtube.com/player_api"; tag.async = true; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); } else { window.onYouTubeIframeAPIReady(); } } function _showVideoPopup() { var $popup = $('#video-popup'); disableScroll(); $popup.fadeIn('fast', function(){ $(window).trigger('modalShow'); }).find('.close').on('click', function(e){ e.preventDefault(); $('#bg-video').get(0).play() $popup.fadeOut(function(){ window.player.destroy(); enableScroll(); $popup.find('.close').off('click'); }); }) } function showVideo(id, callback) { _showVideoPopup(); _initVideo('popup-player', id, function(){ if (typeof callback == 'function') { callback(); } }); } return { showVideo: showVideo } })(jQuery, window, document);
9c258ce8329a3e84a49fe9d26a6111b9da1d21a0
[ "JavaScript" ]
1
JavaScript
yuliyasychikova/aventures_prod
64f5cd73e46d5658cb74f7c9c89c7669f9754c7a
e91d76bf7d99b18ba3b65768335a65ffc9db14d3
refs/heads/master
<repo_name>linksplatform/HelloWorld.Doublets.DotNet<file_sep>/Program.cs using System; using Platform.Data; using Platform.Data.Doublets; using Platform.Data.Doublets.Memory.United.Generic; // A doublet links store is mapped to "db.links" file: using var links = new UnitedMemoryLinks<uint>("db.links"); // A creation of the doublet link: var link = links.Create(); // The link is updated to reference itself twice (as a source and a target): link = links.Update(link, newSource: link, newTarget: link); // Read operations: Console.WriteLine($"The number of links in the data store is {links.Count()}."); Console.WriteLine("Data store contents:"); var any = links.Constants.Any; // Means any link address or no restriction on link address // Arguments of the query are interpreted as restrictions var query = new Link<uint>(index: any, source: any, target: any); links.Each((link) => { Console.WriteLine(links.Format(link)); return links.Constants.Continue; }, query); // The link's content reset: link = links.Update(link, newSource: default, newTarget: default); // The link deletion: links.Delete(link); <file_sep>/README.md [![Actions Status](https://github.com/linksplatform/Examples.Doublets.CRUD.DotNet/workflows/CI/badge.svg)](https://github.com/linksplatform/Examples.Doublets.CRUD.DotNet/actions?workflow=CI) # Examples.Doublets.CRUD.DotNet ([русская версия](https://github.com/linksplatform/Examples.Doublets.CRUD.DotNet/blob/master/README.ru.md)) A quick start example that shows how to create, read, update and delete the first [link](https://github.com/Konard/LinksPlatform/wiki/FAQ#what-does-the-link-mean) using [Doublets](https://github.com/linksplatform/Data.Doublets). ## Prerequisites * Linux, macOS or Windows * [.NET 5+ or .NET Core 2.2+](https://dotnet.microsoft.com/download) * [Platform.Data.Doublets](https://www.nuget.org/packages/Platform.Data.Doublets) NuGet package with 0.6.0 or above ## [The code](https://github.com/linksplatform/Examples.Doublets.CRUD.DotNet/blob/master/Program.cs) ```C# using System; using Platform.Data; using Platform.Data.Doublets; using Platform.Data.Doublets.Memory.United.Generic; // A doublet links store is mapped to "db.links" file: using var links = new UnitedMemoryLinks<uint>("db.links"); // A creation of the doublet link: var link = links.Create(); // The link is updated to reference itself twice (as a source and a target): link = links.Update(link, newSource: link, newTarget: link); // Read operations: Console.WriteLine($"The number of links in the data store is {links.Count()}."); Console.WriteLine("Data store contents:"); var any = links.Constants.Any; // Means any link address or no restriction on link address // Arguments of the query are interpreted as restrictions var query = new Link<uint>(index: any, source: any, target: any); links.Each((link) => { Console.WriteLine(links.Format(link)); return links.Constants.Continue; }, query); // The link's content reset: link = links.Update(link, newSource: default, newTarget: default); // The link deletion: links.Delete(link); ``` [Expected output](https://github.com/linksplatform/Examples.Doublets.CRUD.DotNet/runs/2646250538#step:3:4) is: ``` The number of links in the the data store is 1. Data store contents: (1: 1 1) ``` Run [this example at .NET fiddle](https://dotnetfiddle.net/Y7Zvt0). Look at [ILinks\<TLinkAddress\> documentation](https://linksplatform.github.io/Data/csharp/api/Platform.Data.ILinks-2.html) for more details. ## Looking for something more interesting? * [Comparison between SQLite and Doublets](https://github.com/linksplatform/Comparisons.SQLiteVSDoublets) * [Search engine with its web crawler, that stores web-pages in the Doublets](https://github.com/linksplatform/Crawler) <file_sep>/README.ru.md [![Состояние сборки](https://github.com/linksplatform/Examples.Doublets.CRUD.DotNet/workflows/CI/badge.svg)](https://github.com/linksplatform/Examples.Doublets.CRUD.DotNet/actions?workflow=CI) # Examples.Doublets.CRUD.DotNet ([english version](https://github.com/linksplatform/Examples.Doublets.CRUD.DotNet/blob/master/README.md)) Пример для быстрого старта, который показывает как создать, прочитать, обновить и удалить первую [связь](https://github.com/Konard/LinksPlatform/wiki/%D0%A7%D0%90%D0%92%D0%9E#%D0%A7%D1%82%D0%BE-%D1%82%D0%B0%D0%BA%D0%BE%D0%B5-%D1%81%D0%B2%D1%8F%D0%B7%D1%8C) используя [Дуплеты](https://github.com/linksplatform/Data.Doublets). ## Для запуска требуется * Linux, macOS или Windows * [.NET 5+ или .NET Core 2.2+](https://dotnet.microsoft.com/download) * NuGet пакет [Platform.Data.Doublets](https://www.nuget.org/packages/Platform.Data.Doublets) с версией 0.6.0 или выше ## [Код](https://github.com/linksplatform/Examples.Doublets.CRUD.DotNet/blob/master/Program.cs) ```C# using System; using Platform.Data; using Platform.Data.Doublets; using Platform.Data.Doublets.Memory.United.Generic; // Хранилище дуплетов привязывается к файлу "db.links": using var links = new UnitedMemoryLinks<uint>("db.links"); // Создание связи-дуплета: var link = links.Create(); // Связь обновляется чтобы ссылаться на себя дважды (в качестве начала и конца): link = links.Update(link, newSource: link, newTarget: link); // Операции чтения: Console.WriteLine($"Количество связей в хранилище данных: {links.Count()}."); Console.WriteLine("Содержимое хранилища данных:"); var any = links.Constants.Any; // Означает любой адрес связи или отсутствие ограничения на адрес связи // Аргументы запроса интерпретируются как органичения var query = new Link<uint>(index: any, source: any, target: any); links.Each((link) => { Console.WriteLine(links.Format(link)); return links.Constants.Continue; }, query); // Сброс содержимого связи: link = links.Update(link, newSource: default, newTarget: default); // Удаление связи: links.Delete(link); ``` [Ожидаемый вывод](https://github.com/linksplatform/Examples.Doublets.CRUD.DotNet/runs/2646250538#step:3:4): ``` Количество связей в хранилище данных: 1. Содержимое хранилища данных: (1: 1 1) ``` Запустите [этот пример в .NET fiddle](https://dotnetfiddle.net/8J5BQS). Посмотрите [документацию по ILinks\<TLinkAddress\>](https://linksplatform.github.io/Data/csharp/api/Platform.Data.ILinks-2.html) чтобы изучить подробности. ## Ищите что-то интереснее? * [Сравнение между SQLite и Дуплетами](https://github.com/linksplatform/Comparisons.SQLiteVSDoublets) * [Поисковый движок со встроенным поисковым роботом, который хранит веб-страницы в Дуплетах](https://github.com/linksplatform/Crawler)
54e342fb1c9428f3e7577f91ce7393ff95bca2f4
[ "Markdown", "C#" ]
3
C#
linksplatform/HelloWorld.Doublets.DotNet
07321b31da764504c703c1ceb4c9ba1ed7034dcd
aab86506a0620c1d0de7be3ad216b976baaa5e4b
refs/heads/master
<repo_name>cfdezperez/proxectoE3<file_sep>/src/elementos/personaje/Paisano.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package elementos.personaje; import elementos.Civilizacion; import elementos.ContRecurso; import elementos.Edificio; import elementos.Personaje; import elementos.cr.Pradera; import elementos.Recurso; import elementos.cr.Cantera; import elementos.edificio.Casa; import elementos.edificio.Ciudadela; import elementos.edificio.Cuartel; import excepciones.celda.FueraDeMapaException; import excepciones.ParametroIncorrectoException; import excepciones.celda.CeldaEnemigaException; import excepciones.celda.CeldaOcupadaException; import excepciones.celda.NoAlmacenableException; import excepciones.edificio.EdificioException; import excepciones.edificio.NoNecRepararException; import excepciones.personaje.EstarEnGrupoException; import excepciones.personaje.InsuficientesRecException; import interfazUsuario.Juego; import vista.Celda; import excepciones.recursos.NoRecolectableException; import excepciones.personaje.PersonajeLlenoException; import excepciones.recursos.RecursosException; /** * * @author celia y maria */ public class Paisano extends Personaje { private final double[] capRecoleccion = new double[4]; //0 capacidad total, 1 capacidad madera, //2 capacidad comida, 3 capacidad piedra private final double capRecoleccionInicial; private static int[] numeroPaisanos = new int[Civilizacion.getNumDeCivilizaciones()]; public Paisano() throws ParametroIncorrectoException { this(100, 25, 25, 150); } public Paisano(int salud, int armadura, int ataque, int capacidad) throws ParametroIncorrectoException { super(salud, armadura, ataque, true, Juego.TPAISANO); this.capRecoleccion[0] = capacidad < 0 ? 0 : capacidad; this.capRecoleccionInicial = this.capRecoleccion[0]; } @Override public void inicializaNombre(Civilizacion civil) { numeroPaisanos[civil.getIdCivilizacion()]++; setNombre("Paisano-" + numeroPaisanos[civil.getIdCivilizacion()]); } /** * Capacidad recoleccion total del personaje * * @return int capacidad recolección total */ public double getCapRecoleccion() { return this.capRecoleccion[0]; } /** * Capacidad de recolección para la madera, cantidad de madera que tiene * * @return int capacidad madera */ public double getMadera() { return this.capRecoleccion[Recurso.TRMADERA]; } /** * Capacidad de recolección para la comida, cantidad de comida que tiene * * @return int capacidad comida */ public double getComida() { return this.capRecoleccion[Recurso.TRCOMIDA]; } /** * Capacidad de recolección para la piedra, cantidad de piedra que tiene * * @return int capacidad piedra */ public double getPiedra() { return this.capRecoleccion[Recurso.TRPIEDRA]; } public double getCRInicial() { return this.capRecoleccionInicial; } public double getRecursoTipo(int tipo) throws ParametroIncorrectoException { switch (tipo) { case Recurso.TRMADERA: return capRecoleccion[Recurso.TRMADERA]; case Recurso.TRCOMIDA: return capRecoleccion[Recurso.TRCOMIDA]; case Recurso.TRPIEDRA: return capRecoleccion[Recurso.TRPIEDRA]; default: throw new ParametroIncorrectoException("El recurso no existe"); } } /** * * @param cap */ public void setCapRecoleccion(double cap) { if (cap < 0) { this.capRecoleccion[0] = 0; } else { this.capRecoleccion[0] = cap; } } public void setCapRecoleccionTipo(double cap, int tipo) { if (cap < 0) { cap = 0; } this.capRecoleccion[tipo] = cap; } public void setMadera(double a) { this.capRecoleccion[Recurso.TRMADERA] = a; } public void setComida(double a) { this.capRecoleccion[Recurso.TRCOMIDA] = a; } public void setPiedra(double a) { this.capRecoleccion[Recurso.TRPIEDRA] = a; } @Override public String toString() { String s = super.toString(); s += "\n\tCapacidad de recolección: " + this.getCapRecoleccion(); s += "\n\tDispone de " + this.getMadera() + " madera, " + this.getPiedra() + " piedra y " + this.getComida() + " comida."; return (s); } /** * Recolecta recursos en la direcciín indicada * * @param direccion * @return Mensaje de acción * @throws excepciones.personaje.EstarEnGrupoException * @throws excepciones.celda.FueraDeMapaException * @throws excepciones.ParametroIncorrectoException * @throws excepciones.recursos.NoRecolectableException * @throws excepciones.personaje.PersonajeLlenoException */ @Override public String recolectar(String direccion) throws EstarEnGrupoException, FueraDeMapaException, ParametroIncorrectoException, NoRecolectableException, PersonajeLlenoException, RecursosException { if (getEstarGrupo()) { throw new EstarEnGrupoException("El personaje no se puede mover, ya que está en el grupo " + getGrupo()); } String s; Celda actual = this.getCelda(); Celda vecina = actual.getMapa().obtenerCeldaVecina(actual, direccion); if ((vecina.getContRecurso() instanceof Pradera) || (vecina.getContRecurso() == null)) { throw new NoRecolectableException("La celda no contiene un contenedor de recursos"); } ContRecurso cr = vecina.getContRecurso(); //Solo va a haber un elemento en la celd que va a ser un contenedor de recurso //se restan de la capacidad del contenedor de recursos la capacidad // que tiene el personaje para recolectar if (cr instanceof Cantera) { cr.procesar(); } double disponible = cr.getRecurso().getCapacidad(); //Capacidad disponible en ese momento double recolectado; if (this.getCapRecoleccion() == 0) { throw new PersonajeLlenoException("El personaje agotó su capacidad de recolección"); } else if (disponible > this.getCapRecoleccion()) { recolectado = this.getCapRecoleccion(); cr.getRecurso().setCapacidad(disponible - recolectado); //cambia capacidad para recolectar en funcion de la recolectado this.capRecoleccion[0] = 0; this.capRecoleccion[cr.getRecurso().getTipo()] += recolectado; s = ("El paisano ha conseguido " + recolectado + " unidades de " + cr.getRecurso().getNombre()); } else if (this.getCapRecoleccion() >= disponible) { recolectado = disponible; this.capRecoleccion[0] -= recolectado; this.capRecoleccion[cr.getRecurso().getTipo()] += recolectado; // Convertimos la celda en pradera vecina.restartCelda(); s = ("Has conseguido " + recolectado + " unidades de " + cr.getRecurso().getNombre()); } else { //Si disponible, que throw new RecursosException("Error al recolectar"); } return s; } /** * * @param nedificio: nombre edificio(casa, ciudadela o cuartel) * @param direccion * @throws excepciones.personaje.InsuficientesRecException * @throws excepciones.celda.FueraDeMapaException * @throws excepciones.ParametroIncorrectoException * @throws excepciones.celda.CeldaOcupadaException * @throws excepciones.celda.CeldaEnemigaException * @throws excepciones.personaje.EstarEnGrupoException */ @Override public String construirEdificio(String nedificio, String direccion) throws InsuficientesRecException, ParametroIncorrectoException, CeldaOcupadaException, FueraDeMapaException, CeldaEnemigaException, EstarEnGrupoException { if (getEstarGrupo()) { throw new EstarEnGrupoException("El personaje no se puede mover, ya que está en el grupo " + getGrupo()); } String s; Celda vecina = this.getCelda().getMapa().obtenerCeldaVecina(this.getCelda(), direccion); Edificio ed = null; switch (nedificio) { case "ciudadela": ed = new Ciudadela(); break; case "cuartel": ed = new Cuartel(); break; case "casa": ed = new Casa(); break; default: throw new ParametroIncorrectoException("Tipo de edificio desconocido"); } if (this.capRecoleccion[1] >= ed.getCRM() && this.capRecoleccion[3] >= ed.getCRP()) { ed.inicializaNombre(Juego.getCivilizacionActiva()); Juego.getCivilizacionActiva().anhadeEdificio(ed); vecina.anhadeEdificio(ed); vecina.setVisible(true); vecina.setTransitable(true); //Ponerlo a true this.capRecoleccion[Recurso.TRMADERA] = this.capRecoleccion[Recurso.TRMADERA] - ed.getCRM(); this.capRecoleccion[Recurso.TRPIEDRA] = this.capRecoleccion[Recurso.TRPIEDRA] - ed.getCRP(); this.capRecoleccion[0] = 100 - (this.capRecoleccion[Recurso.TRMADERA] + this.capRecoleccion[Recurso.TRPIEDRA]); s = ("Se ha construído " + ed.getNombre() + " en la posicion " + "(" + vecina.getX() + "," + vecina.getY() + ")"); } else { throw new InsuficientesRecException("El paisano no tiene suficientes recursos, no puede construír"); } return s; } @Override public String reparar(String direccion) throws FueraDeMapaException, ParametroIncorrectoException, NoNecRepararException, InsuficientesRecException, EdificioException, EstarEnGrupoException { String s; if (getEstarGrupo()) { throw new EstarEnGrupoException("El personaje no se puede mover, ya que está en el grupo " + getGrupo()); } Celda vecina = this.getCelda().getMapa().obtenerCeldaVecina(this.getCelda(), direccion); if (vecina.getEdificio() != null) { // La celda contiene un edificio Edificio e = vecina.getEdificio(); if (this.capRecoleccion[Recurso.TRMADERA] >= e.getCRM() && this.capRecoleccion[Recurso.TRPIEDRA] >= e.getCRP()) { if (e.getSalud() != e.getSaludInicial()) { e.reiniciarSalud(); //edificio recobra la salud this.capRecoleccion[Recurso.TRMADERA] -= e.getCRM(); this.capRecoleccion[Recurso.TRPIEDRA] -= e.getCRP(); this.capRecoleccion[0] -= (e.getCRM() + e.getCRP()); s = "Reparado el edificio " + e.getNombre() + "\n"; s += "Coste de la reparacion: " + (this.capRecoleccion[Recurso.TRMADERA] - e.getCRM()) + " de madera y " + (this.capRecoleccion[0] - e.getCRP()) + " de piedra"; } else { throw new NoNecRepararException("El edificio no necesita ser reparado"); } } else { throw new InsuficientesRecException("El paisano no tiene los suficientes recursos para reparar"); } } else { throw new EdificioException("No hay ningún edificio que reparar en esta posición"); } return s; } /** * * @param direccion * @return * @throws excepciones.personaje.InsuficientesRecException * @throws excepciones.celda.FueraDeMapaException * @throws excepciones.ParametroIncorrectoException * @throws excepciones.celda.NoAlmacenableException * @throws excepciones.personaje.EstarEnGrupoException */ @Override public String almacenar(String direccion) throws InsuficientesRecException, FueraDeMapaException, ParametroIncorrectoException, NoAlmacenableException, EstarEnGrupoException { if (getEstarGrupo()) { throw new EstarEnGrupoException("El paisano puede almacenar, ya que está en el grupo " + getGrupo()); } String s; Celda vecina = this.getCelda().getMapa().obtenerCeldaVecina(this.getCelda(), direccion); if (vecina.getEdificio() != null) { // La celda contiene un edificio Edificio e = vecina.getEdificio(); if (e instanceof Casa) { throw new NoAlmacenableException("Una casa no puede almacenar"); } else { if (this.getCapRecoleccion() == (this.getCRInicial())) { throw new InsuficientesRecException("El paisano no tiene recursos que almacenar"); } else { e.almacenar(this.capRecoleccion); //todo lo que tiene el personaje se le pasa a la ciudadela s = ("Almacenado " + this.capRecoleccion[Recurso.TRMADERA] + " madera, " + this.capRecoleccion[Recurso.TRCOMIDA] + " comida, y " + this.capRecoleccion[Recurso.TRPIEDRA] + " piedra en el edificio " + e.getNombre()); // Restauramos las capacidades del paisano this.capRecoleccion[0] = this.capRecoleccionInicial; //capacidad recoleccion vuelve a ser la inicial this.capRecoleccion[Recurso.TRMADERA] = 0; this.capRecoleccion[Recurso.TRCOMIDA] = 0; this.capRecoleccion[Recurso.TRPIEDRA] = 0; } } } else { throw new NoAlmacenableException("En esa celda no se puede almacenar"); } return s; } } <file_sep>/src/vista/ConsolaVentana.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package vista; import interfazUsuario.Consola; /** * * @author <NAME> maria */ public class ConsolaVentana extends javax.swing.JFrame implements Consola { private static String civ1, civ2; private static int tamX, tamY; /** * Crea una ventana para mostrar el mapa * * @param civ1 Civilización 1 * @param civ2 Civilización 2 * @param tamX Número de columnas del mapa * @param tamY Número de filas del mapa */ public ConsolaVentana(String civ1, String civ2, int tamX, int tamY) { ConsolaVentana.civ1 = civ1; ConsolaVentana.civ2 = civ2; ConsolaVentana.tamX = tamX+5; ConsolaVentana.tamY = tamY+5; /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ConsolaVentana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } initComponents(); this.pack(); this.setVisible(true); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jTextArea1 = new javax.swing.JTextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Civilización "+civ1+" contra Civilización "+civ2); setAlwaysOnTop(true); setAutoRequestFocus(false); setPreferredSize(tamanhoMarco()); setResizable(false); setSize(tamanhoMarco()); jPanel1.setPreferredSize(tamanhoMarco()); jTextArea1.setEditable(false); jTextArea1.setColumns(tamX); jTextArea1.setFont(new java.awt.Font("Courier New", 0, 24)); // NOI18N jTextArea1.setRows(tamY); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jTextArea1, javax.swing.GroupLayout.PREFERRED_SIZE, 617, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jTextArea1, javax.swing.GroupLayout.PREFERRED_SIZE, 694, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 617, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 694, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private java.awt.Dimension tamanhoMarco() { return new java.awt.Dimension(35*tamX, 28*tamY); //return jTextArea1.getSize(); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel jPanel1; private javax.swing.JTextArea jTextArea1; // End of variables declaration//GEN-END:variables @Override public void imprimir(String s) { jTextArea1.setText(null); jTextArea1.append(s); } @Override public String leer(String descripcion) { throw new UnsupportedOperationException("No se puede leer de esta consola"); } @Override public void salir() { this.setVisible(false); this.dispose(); } } <file_sep>/src/elementos/personaje/Arquero.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package elementos.personaje; import elementos.Civilizacion; import elementos.Edificio; import excepciones.ParametroIncorrectoException; import interfazUsuario.Juego; import vista.Celda; /** * * @author celia y maria */ public class Arquero extends Soldado { private static int[] numeroArqueros = new int[Civilizacion.getNumDeCivilizaciones()]; public Arquero() throws ParametroIncorrectoException { super(Juego.TARQUERO); } public Arquero(int salud, int armadura, int ataque) throws ParametroIncorrectoException { super(salud, armadura, ataque, Juego.TARQUERO); } @Override public void inicializaNombre(Civilizacion civil) { numeroArqueros[civil.getIdCivilizacion()]++; setNombre("Arquero-" + numeroArqueros[civil.getIdCivilizacion()]); } @Override public int getAtaque(Edificio enemigo) { // Si el que ataca a un edificio es un arquero, el daño se reduce a la mitad return ((this.getAtaque() - enemigo.getDefensa())/2); } } <file_sep>/src/elementos/edificio/Casa.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package elementos.edificio; import elementos.Civilizacion; import elementos.Edificio; import elementos.Personaje; import excepciones.celda.CeldaOcupadaException; import excepciones.ParametroIncorrectoException; import excepciones.celda.CeldaEnemigaException; import excepciones.celda.FueraDeMapaException; import excepciones.celda.NoTransitablebleException; import excepciones.edificio.EdificioException; import interfazUsuario.Juego; import vista.Celda; /** * * @author celia y maria */ public class Casa extends Edificio{ private static int[] numeroCasas = new int[Civilizacion.getNumDeCivilizaciones()]; /** * Crea una casa con parámetros por defecto. * * @throws CeldaOcupadaException * @throws ParametroIncorrectoException */ public Casa() throws CeldaOcupadaException, ParametroIncorrectoException { this(10); } /** * Crea una casa especificando la capacidad de alojamiento * * @param capAlojar Número de personajes que puede alojar * @throws CeldaOcupadaException * @throws ParametroIncorrectoException */ public Casa(int capAlojar) throws CeldaOcupadaException, ParametroIncorrectoException { this(10, 50, 40, 25, 20, capAlojar); } /** * Crea una casa especificando todos los parámetros * * @param salud * @param CRM * @param CRP * @param CCC * @param capAl * @param capAlojar * @throws CeldaOcupadaException * @throws ParametroIncorrectoException */ public Casa(int salud, int CRM, int CRP, int CCC, int capAl, int capAlojar) throws CeldaOcupadaException, ParametroIncorrectoException { super(salud, CRM, CRP, CCC, capAl, Juego.TCASA); // Una casa puede alojar personajes this.setCapAlojar(true); this.setCapAlojamiento(capAlojar); setCapPersonajes(capAlojar); Edificio.addCapAlojamientoTotal(capAlojar); // Una casa no puede crear paisanos ni soldados ni almacednar setCrearPaisanos(false); setCrearSoldados(false); setCapAlmacenar(false); } @Override public void inicializaNombre(Civilizacion civil) { numeroCasas[civil.getIdCivilizacion()]++; setNombre("Casa-" + numeroCasas[civil.getIdCivilizacion()]); } @Override public Personaje creaPersonaje(Celda vecina, String tipoPersonaje) throws EdificioException, ParametroIncorrectoException, CeldaEnemigaException, NoTransitablebleException, FueraDeMapaException { throw new EdificioException("Las casas no crean personajes"); } } <file_sep>/src/vista/Celda.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package vista; import elementos.Personaje; import java.util.ArrayList; import java.util.List; import elementos.Civilizacion; import elementos.ContRecurso; import elementos.Edificio; import elementos.cr.Pradera; import elementos.personaje.Grupo; import excepciones.ParametroIncorrectoException; import excepciones.celda.CeldaEnemigaException; import excepciones.celda.CeldaOcupadaException; import excepciones.celda.FueraDeMapaException; import excepciones.celda.NoTransitablebleException; import excepciones.personaje.NoAgrupableException; import interfazUsuario.Juego; /** * Clase que define una celda en el mapa * * @author celia y maria */ public class Celda { private int x, y; // Posición del elemento en la pantalla private final Mapa mapa; private int tipoCelda; private List<Personaje> listaPersonajes; private Edificio edificio = null; private ContRecurso contRecurso = null; private Civilizacion civilizacion; private boolean transitable = true; private boolean visible = false; private Civilizacion visitadaPor; /** * Crea una nueva celda vacía en un mapa * * @param m El mapa donde colocamos la celda * @param x Posición x de la celda * @param y Posición y de la celda */ public Celda(Mapa m, int x, int y) { this.visitadaPor = null; this.x = x; this.y = y; this.mapa = m; this.civilizacion = null; } //GETTERS Y SETTERS public int getX() { return this.x; } public int getY() { return this.y; } public Mapa getMapa() { return this.mapa; } public int getTipoCelda() { return this.tipoCelda; } public Civilizacion getCivilizacion() { return this.civilizacion; } public int getNumElementos() { int count = 0; if (contRecurso != null) { return 1; } else if (edificio != null) { count = 1; } return count + this.listaPersonajes.size(); } public boolean getTransitable() { return this.transitable; } public boolean getVisible() { return this.visible; } public Edificio getEdificio() { return this.edificio; } public ContRecurso getContRecurso() { return this.contRecurso; } public List<Personaje> getPersonajes() { return this.listaPersonajes; } public Civilizacion getVisitadaPor() { return this.visitadaPor; } public void setX(int x_ej) { if (x_ej > 0) { this.x = x_ej; } else { this.x = 0; } } public void setY(int y_ej) { if (y_ej > 0) { this.y = y_ej; } else { this.y = 0; } } public void setTipoCelda(int tipo) { this.tipoCelda = tipo; } public void setTransitable(boolean transitable) { this.transitable = transitable; } public void setVisible(boolean visible) { this.visible = visible; } public void setCivilizacion(Civilizacion civ) { this.civilizacion = civ; } public void setContRecurso(ContRecurso x) { this.contRecurso = x; } public void setVisitadaPor(Civilizacion civ) { this.visitadaPor = civ; } //FUNCIONES /** * Añade un personaje a la celda * * @param p Personaje a añadir * @throws excepciones.celda.CeldaEnemigaException * @throws excepciones.celda.NoTransitablebleException * @throws excepciones.celda.FueraDeMapaException */ public void anhadePersonaje(Personaje p) throws CeldaEnemigaException, NoTransitablebleException, FueraDeMapaException { if (getTransitable()) { // Si es una pradera, la elimino if ((this.contRecurso != null) && (this.contRecurso instanceof Pradera)) { this.contRecurso = null; } // Si la celda pertenece a otra civilización, tiro una excepción if ((this.getCivilizacion() != null) && (this.getCivilizacion() != p.getCivilizacion())) { throw new CeldaEnemigaException("La celda está ocupada por el enemigo"); } // Añado el personaje a la lista de personajes this.listaPersonajes.add(p); p.setCelda(this); // Haz visible esta celda y las que la rodean this.setVisible(true); p.actualizaVisibilidad(); // Haz la celda transitable, ponle la civilizacion del personaje y corrige el tipo this.setTransitable(true); this.setCivilizacion(p.getCivilizacion()); this.setTipo(); } else { throw new NoTransitablebleException("La celda no es transitable"); } } /** * Añade un edificio a la celda * * @param e Edificio a añadir * @throws excepciones.celda.CeldaOcupadaException * @throws excepciones.celda.CeldaEnemigaException */ public void anhadeEdificio(Edificio e) throws CeldaOcupadaException, CeldaEnemigaException { if (getTransitable()) { // Si es una pradera, la elimino if ((this.contRecurso != null) && (this.contRecurso instanceof Pradera)) { this.contRecurso = null; } // Si la celda pertenece a otra civilización, tiro una excepción if ((this.getCivilizacion() != null) && (this.getCivilizacion() != e.getCivilizacion())) { throw new CeldaEnemigaException("La celda está ocupada por el enemigo"); } if (this.edificio == null) { this.edificio = e; e.setCelda(this); // Haz la celda no transitable, ponle la civilizacion del personaje y corrige el tipo this.setTransitable(false); this.setCivilizacion(e.getCivilizacion()); this.setTipo(); } else { throw new CeldaOcupadaException("La celda está ocupada."); } } else { throw new CeldaOcupadaException("La celda no es transitable."); } } /** * Añade un contenedor de recursos a la celda * * @param cr Contenedor a añadir * @throws excepciones.celda.CeldaOcupadaException */ public void anhadeCR(ContRecurso cr) throws CeldaOcupadaException { if ((this.listaPersonajes.isEmpty()) && (this.edificio == null)) { this.contRecurso = cr; cr.setCelda(this); this.civilizacion = null; // Solo las praderas son transitables this.transitable = (cr instanceof Pradera); setTipo(); } else { throw new CeldaOcupadaException("No se puede añadir el contenedor, la celda está ocupada."); } } public String agrupar(String nombreGrupo, Civilizacion civ) throws NoAgrupableException, ParametroIncorrectoException, CeldaEnemigaException, NoTransitablebleException, FueraDeMapaException { //Dentro de los edificios no se puede agrupar if(this.getEdificio() != null){ throw new NoAgrupableException("Dentro de un edificio no se puede agrupar"); } if (this.getPersonajes().size() <= 1) { throw new NoAgrupableException("No hay personajes suficientes para agrupar"); } // Crea e inicializa el grupo Grupo grupo = new Grupo(); grupo.inicializaNombre(civ); grupo.setNombre(nombreGrupo); civ.anhadeGrupo(grupo); return agrupar(grupo); } public String agrupar() throws ParametroIncorrectoException, NoAgrupableException, CeldaEnemigaException, NoTransitablebleException, FueraDeMapaException { //Dentro de un edificio no se puede agrupar if(this.getEdificio() != null){ throw new NoAgrupableException("Dentro de un edificio no se puede agrupar"); } if (this.getPersonajes().size() <= 1) { throw new NoAgrupableException("No hay personajes suficientes para agrupar"); } // Crea e inicializa el grupo Grupo grupo = new Grupo(); grupo.inicializaNombre(Juego.getCivilizacionActiva()); Juego.getCivilizacionActiva().anhadeGrupo(grupo); return agrupar(grupo); } /** * Devuelve un String con información sobre el contenido de la celda * * @return Información sobre la celda */ public String mirar() { String s = "Celda en fila " + getY() + " columna " + getX(); s += "\nContenido:\n"; // Si hay un CR no puede haber nada más if (this.contRecurso != null) { s += this.contRecurso.toString(); } else { if (this.edificio != null) { s += "\t" + this.edificio.toString() + "\n"; } for (Personaje p : listaPersonajes) { s += "\t" + p.toString() + "\n"; } } return s; } /** * Reinicializa la lista de personajes de la celda */ public void restartPersonajes() { this.listaPersonajes = new ArrayList<Personaje>(); } /** * Elimina un personaje de la celda * @param p Personaje a eliminar */ public void eliminarPersonaje(Personaje p) { this.listaPersonajes.remove(p); // Fijo el tipo después de eliminar el personaje this.setTipo(); } /** * Elimina el edificio de la celda */ public void eliminaEdificio() { this.edificio = null; // Fijo el tipo después de eliminar el personaje this.setTipo(); } /** * Reinicializa la celda */ public void restartCelda() { this.restartPersonajes(); this.edificio = null; Pradera pr = new Pradera(); this.contRecurso = pr; pr.setCelda(this); this.tipoCelda = Juego.TPRADERA; this.civilizacion = null; this.transitable = true; } /** * Devuelve una cadena con las coordenadas de la celdas * * @return Las coordenadas de la celda */ @Override public String toString() { String s = "(" + this.getY() + "," + this.getX() + ")"; return s; } private void setTipo() { // Si no tiene elementos, la convierto en pradera if (getNumElementos() <= 0) { restartCelda(); } else if (getNumElementos() > 1) { // Queda más de un elemento this.setTipoCelda(Juego.TVARIOS); } else { // Si queda solo un tipo de elemento, miramos si es un CR, edificio o un personaje if (this.contRecurso != null) { this.setTipoCelda(this.contRecurso.getTipo()); } else if (this.edificio != null) { this.setTipoCelda(this.edificio.getTipo()); } else if (!this.getPersonajes().isEmpty()) { this.setTipoCelda(this.getPersonajes().get(0).getTipo()); } } } private String agrupar(Grupo grupo) throws CeldaEnemigaException, NoTransitablebleException, FueraDeMapaException { // Recorre la lista de personajes grupo.setTipo(Juego.TGRUPO); for (Personaje p : this.getPersonajes()) { grupo.anhadirPersonaje(p); p.setGrupo(grupo); } // Una vez añadidos, restauro la lista de personajes de la celda y añado el grupo this.restartPersonajes(); this.anhadePersonaje(grupo); this.setTipo(); String s = "Se ha creado el " + grupo.getNombre() + " de la civilización " + Juego.getCivilizacionActiva() + "\n" + grupo; return s; } } <file_sep>/src/elementos/personaje/Legionario.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package elementos.personaje; import elementos.Civilizacion; import excepciones.ParametroIncorrectoException; import interfazUsuario.Juego; import vista.Celda; /** * * @author celia y maria */ public class Legionario extends Soldado{ private static int [] numeroLegionarios = new int[Civilizacion.getNumDeCivilizaciones()]; public Legionario() throws ParametroIncorrectoException{ super(Juego.TLEGIONARIO); } public Legionario(int salud, int armadura, int ataque) throws ParametroIncorrectoException { super(salud, armadura, ataque, Juego.TLEGIONARIO); } @Override public void inicializaNombre(Civilizacion civil) { numeroLegionarios[civil.getIdCivilizacion()]++; setNombre("Legionario-"+numeroLegionarios[civil.getIdCivilizacion()]); } } <file_sep>/src/elementos/Edificio.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package elementos; import elementos.edificio.Casa; import elementos.edificio.Ciudadela; import elementos.edificio.Cuartel; import excepciones.CivilizacionDestruidaException; import excepciones.celda.CeldaOcupadaException; import excepciones.ParametroIncorrectoException; import excepciones.celda.CeldaEnemigaException; import excepciones.celda.FueraDeMapaException; import excepciones.celda.NoTransitablebleException; import excepciones.edificio.EdificioException; import excepciones.personaje.AtaqueExcepcion; import excepciones.personaje.EstarEnGrupoException; import vista.*; /** * * @author celia y maria */ public abstract class Edificio { private Celda celda; private String nombre; private int tipoEdificio; //1 es ciudadela, 2 es Casa y 3 Cuartel private Civilizacion civilizacion; private int salud; private final int saludInicial; private boolean estado; private int costeReparacionMadera; private int costeReparacionPiedra; private int ataque; private int defensa; private boolean crearPaisanos = false; private int costeCrearComida; private final double[] capAlmacenamiento = new double[4]; private boolean capAlmacenar = false; private boolean capAlojar = false; private static int capAlojamientoTotal = 0; private int capAlojamiento; private boolean crearSoldados = false; private int capPersonajes; private boolean estarVacio; //CONSTRUCTORES /*public Edificio(Celda c) { //Inicializa sus atributos con unos datos predeterminados //Crea una ciudadela this(c, "Ciudadela", Mapa.TCIUDADELA); }*/ public Edificio(int tipo) throws CeldaOcupadaException, ParametroIncorrectoException { //Inicializa sus atributos con unos datos predeterminados this(10, 50, 40, 50, 50, tipo); } /** * Creamos un edificio * * @param salud1 Salud del edificio * @param CRM * @param CRP * @param CCC * @param capAlm * @param tipo * @throws CeldaOcupadaException * @throws ParametroIncorrectoException */ public Edificio(int salud1, int CRM, int CRP, int CCC, double capAlm, int tipo) throws CeldaOcupadaException, ParametroIncorrectoException { if (salud1 <= 0 || CRM < 0 || CRP < 0) { //Si no tiene salud no existe //this.estado = false; //this.saludInicial = 0; throw new ParametroIncorrectoException("La salud no puede ser negativa o nula"); } else { this.tipoEdificio = tipo; this.estado = true; this.salud = salud1; this.saludInicial = salud1; this.costeReparacionMadera = CRM; this.costeReparacionPiedra = CRP; this.ataque = 0; this.defensa = 0; this.costeCrearComida = CCC; this.capAlmacenamiento[0] = capAlm; this.estarVacio = true; } } //GETTERS Y SETTERS public Celda getCelda() { return this.celda; } public String getNombre() { return this.nombre; } public int getTipo() { return this.tipoEdificio; } public Civilizacion getCivilizacion() { return this.civilizacion; } public boolean getEstado() { return this.estado; } public int getSalud() { return this.salud; } public int getSaludInicial() { return this.saludInicial; } public int getCRM() { return this.costeReparacionMadera; } public int getCRP() { return this.costeReparacionPiedra; } public int getAtaque() { return this.ataque; } public int getDefensa() { return this.defensa; } public int getCosteCrearComida() { return this.costeCrearComida; } public boolean getCrearPaisanos() { return this.crearPaisanos; } public boolean getCrearSoldados() { return this.crearSoldados; } public double[] getCapAlmacenamiento() { //Devuelve el vector con las capacidades de almacenamiento return this.capAlmacenamiento; } public double getCapAlmacenamientoTotal() { return this.capAlmacenamiento[0]; } public double getMadera() { return this.capAlmacenamiento[Recurso.TRMADERA]; } public double getComida() { return this.capAlmacenamiento[Recurso.TRCOMIDA]; } public double getPiedra() { return this.capAlmacenamiento[Recurso.TRPIEDRA]; } public boolean getCapAlmacenar() { //es true si es ciudadela, solo se almacena recursos ahí return this.capAlmacenar; } public int getCapAlojamiento() { //devuelve la capacidad de alojamiento de la casa return this.capAlojamiento; } public int getCapPersonajes() { return this.capPersonajes; } public boolean getEstarVacio() { return this.estarVacio; } public void setCelda(Celda c) { this.celda = c; } public void setNombre(String n) { this.nombre = n; } //No se define un setTipoCelda() ni un setTipo() pues no se puede cambiar el tipo de edificio despues de creado public void setSalud(int s) { if (s <= 0) { this.salud = 0; this.estado = false; } else { this.salud = s; } } public void setCivilizacion(Civilizacion civ) { this.civilizacion = civ; } public final void setCrearPaisanos(boolean b) { this.crearPaisanos = b; } public final void setCrearSoldados(boolean b) { this.crearSoldados = b; } public final void setCapAlmacenar(boolean b) { this.capAlmacenar = b; } public void setCRM(int CRM) { if (CRM < 0) { this.costeReparacionMadera = 0; this.estado = false; } this.costeReparacionMadera = CRM; } public void setCRP(int CRP) { if (CRP < 0) { this.costeReparacionPiedra = 0; this.estado = false; } this.costeReparacionPiedra = CRP; } public void setEstado(boolean estado) { this.estado = estado; } public void setCapAlmacenamientoTotal(double capAl) throws ParametroIncorrectoException { if (this.getCapAlmacenar() == true) { if (capAl <= 0) { throw new ParametroIncorrectoException("Se supera la capacidad de almacenamiento de "+this.getNombre()); } else { this.capAlmacenamiento[0] = capAl; } } } /** * Almacena lo recolectado por un personaje * * @param recolectado * @throws ParametroIncorrectoException */ public void almacenar(double[] recolectado) throws ParametroIncorrectoException { setCapAlmacenamientoTotal(getCapAlmacenamiento()[0]-(recolectado[Recurso.TRMADERA]+recolectado[Recurso.TRCOMIDA]+recolectado[Recurso.TRPIEDRA])); setMadera(getCapAlmacenamiento()[Recurso.TRMADERA] + recolectado[Recurso.TRMADERA]); setComida(getCapAlmacenamiento()[Recurso.TRCOMIDA] + recolectado[Recurso.TRCOMIDA]); setPiedra(getCapAlmacenamiento()[Recurso.TRPIEDRA] + recolectado[Recurso.TRPIEDRA]); } public void setMadera(double capM) throws ParametroIncorrectoException { if (this.getCapAlmacenar() == true) { if (capM < 0) { throw new ParametroIncorrectoException("No es posible esa capacidad"); } else { this.capAlmacenamiento[Recurso.TRMADERA] = capM; } } } public void setComida(double capA) throws ParametroIncorrectoException { if (this.getCapAlmacenar() == true) { if (capA < 0) { throw new ParametroIncorrectoException("No es posible esa capacidad"); } else { this.capAlmacenamiento[Recurso.TRCOMIDA] = capA; } } } public void setPiedra(double capP) throws ParametroIncorrectoException { if (this.getCapAlmacenar() == true) { if (capP < 0) { throw new ParametroIncorrectoException("No es posible esa capacidad"); } else { this.capAlmacenamiento[Recurso.TRPIEDRA] = capP; } } } public void setAtaque(int ataq) { if (ataq <= 0) { this.ataque = 0; this.estado = false; } else { this.ataque = ataq; } } public void setDefensa(int def) { if (def <= 0) { this.defensa = 0; this.estado = false; } else { this.defensa = def; } } public void setCosteCrearComida(int CCC) { if (CCC < 0) { this.costeCrearComida = 0; this.estado = false; } else { this.costeCrearComida = CCC; } } public final void setCapAlojar(boolean b) { this.capAlojar = b; } public final void setCapAlojamiento(int capAlojar) throws ParametroIncorrectoException { if (this.capAlojar == true) { if (capAlojar < 0) { throw new ParametroIncorrectoException("La capacidad de alojamiento no puede ser negativa"); } else { this.capAlojamiento = capAlojar; } } else { this.capAlojamiento = 0; } } public static final void addCapAlojamientoTotal(int cap) { Edificio.capAlojamientoTotal += cap; } public final void setCapPersonajes(int numPer) { if (numPer < 0) { this.capPersonajes = 0; //PUEDE NO DEJAR ENTRAR A NINGUN PERSONAJE this.estado = false; } else { this.capPersonajes = numPer; } } public void setEstarVacio(boolean a) { this.estarVacio = a; } public void reiniciarSalud() { this.salud = this.saludInicial; } @Override public String toString() { String s = "Tipo edificio: "; if (this instanceof Casa) { s += "Casa"; } if (this instanceof Ciudadela) { s += "Ciudadela"; } if (this instanceof Cuartel) { s += "Cuartel"; } s += ", Nombre: " + this.getNombre(); s += "\n\tCivilización a la que pertenece: " + this.getCivilizacion().getNomCivilizacion(); s += "\n\tSalud: " + this.getSalud(); s += "\n\tCapacidad de almacenamiento: " + this.getCapAlmacenamiento()[0]; s += "\n\tComida almacenada " + this.getComida(); s += "\n\tMadera almacenada " + this.getMadera(); s += "\n\tPiedra almacenada " + this.getPiedra(); s += "\n\tCoste de reparación en piedra: " + this.getCRP(); s += "\n\tCoste de reparación en madera: " + this.getCRM(); s += "\n\tCapacidad de ataque: " + getAtaque(); s += "\n\tCapacidad de defensa: " + getDefensa(); return (s); } // Clases abstractas /** * Se encarga de fijar el nombre a partir del tipo de personaje y la * civilización a la que pertenece * * @param civil Civilización a la que pertenece */ public abstract void inicializaNombre(Civilizacion civil); /** * Determina si podemos crear un personaje y la celda en la cuál podemos * crear el personaje * * @param tipoPersonaje * @return La celda en la cuál podemos crear el personaje * * @throws EdificioException * @throws FueraDeMapaException * @throws ParametroIncorrectoException * @throws excepciones.celda.CeldaEnemigaException * @throws excepciones.celda.NoTransitablebleException */ public Personaje crear(String tipoPersonaje) throws EdificioException, FueraDeMapaException, ParametroIncorrectoException, CeldaEnemigaException, NoTransitablebleException { if (Edificio.capAlojamientoTotal <= this.civilizacion.numeroPersonajes()) { throw new EdificioException("No se pueden crear más personajes, necesitan más casas donde alojarse."); } if (this.getComida() < this.costeCrearComida) { throw new EdificioException("No hay suficiente comida como para crear un personaje"); } // Determina la celda en la que crear Celda actual = this.getCelda(); Celda vecina; Celda vecinaNorte = actual.getMapa().obtenerCeldaVecina(actual, "norte"); Celda vecinaSur = actual.getMapa().obtenerCeldaVecina(actual, "sur"); Celda vecinaEste = actual.getMapa().obtenerCeldaVecina(actual, "este"); Celda vecinaOeste = actual.getMapa().obtenerCeldaVecina(actual, "oeste"); if (vecinaNorte.getTransitable()) { vecina = vecinaNorte; } else if (vecinaOeste.getTransitable()) { vecina = vecinaOeste; } else if (vecinaSur.getTransitable()) { vecina = vecinaSur; } else if (vecinaEste.getTransitable()) { vecina = vecinaEste; } else { throw new EdificioException("Imposible crear en ninguna celda de las que rodean al edificio."); } Personaje p = creaPersonaje(vecina, tipoPersonaje); this.setComida(this.getComida() - this.costeCrearComida); this.setCapAlmacenamientoTotal(this.getCapAlmacenamientoTotal() + this.costeCrearComida); return p; } public abstract Personaje creaPersonaje(Celda vecina, String tipoPersonaje) throws EdificioException, ParametroIncorrectoException, CeldaEnemigaException, NoTransitablebleException, FueraDeMapaException; /** * Ataca a una celda vecina * * @param direccion Dirección hacia la que atacar * @return Mensaje de estado * @throws FueraDeMapaException * @throws ParametroIncorrectoException * @throws NoTransitablebleException * @throws CeldaEnemigaException * @throws AtaqueExcepcion * @throws EstarEnGrupoException * @throws excepciones.CivilizacionDestruidaException */ public String atacar(String direccion) throws FueraDeMapaException, ParametroIncorrectoException, NoTransitablebleException, CeldaEnemigaException, AtaqueExcepcion, EstarEnGrupoException, CivilizacionDestruidaException { String s; Celda actual = this.getCelda(); Celda vecina = actual.getMapa().obtenerCeldaVecina(actual, direccion); Civilizacion vecinaCivil = vecina.getCivilizacion(); if(vecinaCivil == null) { throw new ParametroIncorrectoException("Civilización desconocida"); } if (vecina.getContRecurso() != null) { throw new NoTransitablebleException("No puedes atacar a un " + vecina.getContRecurso().getNombre()); } if (vecinaCivil == this.getCivilizacion()) { throw new CeldaEnemigaException("No puedes atacar a una celda amiga."); } // Comprobamos si hay personajes y atacamos al más débil if (!vecina.getPersonajes().isEmpty()) { int saludEnemigo = Integer.MAX_VALUE; Personaje pEnemigo = null; for (Personaje p : vecina.getPersonajes()) { if (p.getSalud() < saludEnemigo) { saludEnemigo = p.getSalud(); pEnemigo = p; } } if (pEnemigo != null) { // Intentamos atacar al personaje int danhoCausado = this.getAtaque() - pEnemigo.getArmadura(); if (danhoCausado < 1) { s = this.getNombre() + " no puede atacar: la defensa enemiga es demasiado fuerte."; } else { int nuevaSalud = pEnemigo.getSalud() - danhoCausado; if (nuevaSalud > 0) { pEnemigo.setSalud(nuevaSalud); s = this.getNombre() + " ha inflingido " + danhoCausado + " de daño a " + pEnemigo.getNombre() + " (" + pEnemigo.getCivilizacion().getNomCivilizacion() + "): la salud de " + pEnemigo.getNombre() + " es ahora " + pEnemigo.getSalud(); } else { s = this.getNombre() + " ha inflingido " + danhoCausado + " de daño a " + pEnemigo.getNombre() + " (" + pEnemigo.getCivilizacion().getNomCivilizacion() + "): " + pEnemigo.getNombre() + " ha muerto"; vecina.eliminarPersonaje(pEnemigo); pEnemigo.getCivilizacion().eliminaPersonaje(pEnemigo); vecina.setVisitadaPor(this.getCivilizacion()); } } return s; } else { throw new AtaqueExcepcion("Error desconocido al atacar"); } // Si no hay personajes, atacamos al edificio } else if (vecina.getEdificio() != null) { Edificio edificioEnemigo = vecina.getEdificio(); // Intentamos atacar al edificio int danhoCausado = this.getAtaque() - edificioEnemigo.getDefensa(); if (danhoCausado < 1) { s = this.getNombre() + " no puede atacar a " + edificioEnemigo.getNombre() + " (" + edificioEnemigo.getCivilizacion().getNomCivilizacion() + "): su defensa es demasiado fuerte."; } else { int nuevaSalud = edificioEnemigo.getSalud() - danhoCausado; if (nuevaSalud > 0) { edificioEnemigo.setSalud(nuevaSalud); s = this.getNombre() + " ha inflingido " + danhoCausado + " de daño a " + edificioEnemigo.getNombre() + " (" + edificioEnemigo.getCivilizacion().getNomCivilizacion() + "): la salud de " + edificioEnemigo.getNombre() + " es ahora " + edificioEnemigo.getSalud(); } else { s = this.getNombre() + " ha inflingido " + danhoCausado + " de daño a " + edificioEnemigo.getNombre() + " (" + edificioEnemigo.getCivilizacion().getNomCivilizacion() + "): " + edificioEnemigo.getNombre() + " ha quedado destruido"; vecina.eliminaEdificio(); edificioEnemigo.getCivilizacion().eliminaEdificio(edificioEnemigo); vecina.setVisitadaPor(this.getCivilizacion()); } } // Comprueba si hamos destruido la civilizacion if(vecinaCivil.determinaDestruccion()) { throw new CivilizacionDestruidaException("La civilización "+vecinaCivil.getNomCivilizacion()+" ha sido destruida!"); } return s; } else { throw new AtaqueExcepcion("No hay nadie a quién atacar"); } } // // private void eliminarPersonaje(Mapa m, Celda c) { // switch (c.getTipoCelda()) { // case Mapa.TARBUSTO: // case Mapa.TBOSQUE: // case Mapa.TCANTERA: // Iterator it = m.getContRecursos().entrySet().iterator(); // while (it.hasNext()) { // Map.Entry e = (Map.Entry) it.next(); // ContRecurso cr = (ContRecurso) e.getValue(); // if (cr.getCelda().getX() == c.getX() // && cr.getCelda().getY() == c.getY()) { // it.remove(); // } // } // break; // // case Mapa.TCASA: // case Mapa.TCIUDADELA: // case Mapa.TCUARTEL: // Iterator it2 = m.getCivActiva().getMapaEdificios().entrySet().iterator(); // while (it2.hasNext()) { // Map.Entry e = (Map.Entry) it2.next(); // Edificio ed = (Edificio) e.getValue(); // if (ed.getCelda().getX() == c.getX() // && ed.getCelda().getY() == c.getY()) { // it2.remove(); // } // } // break; // // case Mapa.TPAISANO: // case Mapa.TSOLDADO: // Iterator it3 = m.getCivActiva().getPerCivilizacion().entrySet().iterator(); // while (it3.hasNext()) { // Map.Entry e = (Map.Entry) it3.next(); // Personaje p = (Personaje) e.getValue(); // if (p.getCelda().getX() == c.getX() // && p.getCelda().getY() == c.getY()) { // it3.remove(); // } // } // break; // // } // } // } <file_sep>/src/interfazUsuario/Juego.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package interfazUsuario; import elementos.cr.Arbusto; import elementos.personaje.Arquero; import elementos.cr.Bosque; import elementos.personaje.Caballero; import elementos.cr.Cantera; import elementos.edificio.Casa; import elementos.edificio.Ciudadela; import java.util.HashMap; import java.util.Map; import elementos.ContRecurso; import elementos.Civilizacion; import elementos.recursos.Comida; import elementos.edificio.Cuartel; import elementos.Edificio; import elementos.personaje.Legionario; import elementos.recursos.Madera; import elementos.personaje.Paisano; import elementos.Personaje; import elementos.personaje.Grupo; import elementos.recursos.Piedra; import excepciones.CivilizacionDestruidaException; import excepciones.celda.CeldaEnemigaException; import excepciones.celda.CeldaOcupadaException; import excepciones.celda.FueraDeMapaException; import excepciones.celda.NoTransitablebleException; import excepciones.ParametroIncorrectoException; import excepciones.celda.CeldaException; import excepciones.celda.NoAlmacenableException; import excepciones.edificio.EdificioException; import excepciones.edificio.NoNecRepararException; import excepciones.personaje.AtaqueExcepcion; import excepciones.personaje.CapMovimientoException; import excepciones.personaje.EstarEnGrupoException; import excepciones.personaje.InsuficientesRecException; import excepciones.personaje.NoAgrupableException; import excepciones.personaje.PersonajeLlenoException; import excepciones.personaje.SolAlmacenarException; import excepciones.personaje.SolConstruirException; import excepciones.personaje.SolRepararException; import excepciones.personaje.SoldadoRecException; import excepciones.recursos.RecursosException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import vista.Celda; import vista.Mapa; /** * Clase principal para inciar el juego * * @author <NAME> maria */ public class Juego implements Comando { public static final int TPAISANO = 4; public static final int TSOLDADO = 5; public static final int TCIUDADELA = 6; public static final int TCASA = 7; public static final int TCUARTEL = 8; public static final int TBOSQUE = 1; public static final int TARBUSTO = 2; public static final int TCANTERA = 3; public static final int TPRADERA = 0; public static final int TGRUPO = 9; public static final int TVARIOS = 10; public static final int TARQUERO = 11; public static final int TCABALLERO = 12; public static final int TLEGIONARIO = 13; public static final String[][] SIMBOLOS = {{" X ", " B ", " A ", " C ", " P ", " S ", " M ", " L ", " N ", " G ", " V ", " Q ", " O ", " I "}, {" X ", " B ", " A ", " C ", " p ", " s ", " m ", " l ", " n ", " g ", " v ", " q ", " o ", " i "}}; private final Map<String, Civilizacion> civilizaciones; private Map<String, ContRecurso> contRecursos; private static Civilizacion civilizacionActiva; private final Mapa mapa; private int[] contador; // Para los contenedores de recursos private int[][] contadorElementos; //Primer campo es la civilizacion, segundo campo es el tipo de dato private final int tamX; private final int tamY; /** * Construye un juego por defecto * * @param tamX Número de columnas del mapa * @param tamY Número de filas del mapa * * @param nombreCivilizaciones Nombres de las civilizaciones que participan * en el juego */ public Juego(int tamX, int tamY, String[] nombreCivilizaciones) { this.tamX = tamX; this.tamY = tamY; //mapa = new Mapa(tamX, tamY); mapa = new Mapa(nombreCivilizaciones[0], nombreCivilizaciones[1], tamX, tamY); this.contRecursos = new HashMap<String, ContRecurso>(); this.contador = new int[9]; String[] nc = new String[nombreCivilizaciones.length]; // Creamos las civilizaciones civilizaciones = new HashMap<String, Civilizacion>(2); int idCiv = 0; for (String nombreCiv : nombreCivilizaciones) { nc[idCiv] = nombreCiv.trim(); civilizaciones.put(nc[idCiv].trim(), new Civilizacion(nc[idCiv], idCiv)); // La civilización inicialmente activa es la que tiene id = 0 if (idCiv == 0) { Juego.civilizacionActiva = this.civilizaciones.get(nc[idCiv]); } idCiv++; } } /** * Construye un juego a partie de una lista de personajes, edificios y * recursos * * @param personajes Campos: * Coordenada;Tipo;Codigo;Descripcion;Ataque;Defensa;Salud;Capacidad;Grupo;Civilizacion * @param edificios * @param recursos # Coordenada;Tipo;Codigo;Descripcion;Cantidad * @throws excepciones.celda.FueraDeMapaException * @throws excepciones.ParametroIncorrectoException * @throws excepciones.celda.CeldaOcupadaException * @throws excepciones.celda.CeldaEnemigaException * @throws excepciones.celda.NoTransitablebleException * @throws excepciones.personaje.NoAgrupableException */ public Juego(List<List<String>> personajes, List<List<String>> edificios, List<List<String>> recursos) throws FueraDeMapaException, ParametroIncorrectoException, CeldaOcupadaException, CeldaEnemigaException, NoTransitablebleException, NoAgrupableException { this.civilizaciones = new HashMap<String, Civilizacion>(2); int maxX = 0, maxY = 0; // Obtenemos el tamaño del mapa for (List<String> recurso : recursos) { int y = new Integer(recurso.get(0).split(",")[0]); int x = new Integer(recurso.get(0).split(",")[1]); if (x > maxX) { maxX = x; } if (y > maxY) { maxY = y; } } this.tamX = maxX+1; this.tamY = maxY+1; // Creo las civilizaciones creaCivilizaciones(personajes, edificios); // Si el número de civilizaciones no es 2, uso la consola if(civilizaciones.size() != 2) { // Creo el mapa con todo praderas mapa = new Mapa(this.tamX, this.tamY); } else { List<String> nCivs = new ArrayList<String>(civilizaciones.keySet()); mapa = new Mapa(nCivs.get(0), nCivs.get(1), this.tamX, this.tamY); } // Meto los contenedores de recursos introduceCR(recursos); // Le meto los personajes introducePersonajes(personajes); // Creo los grupos creaGruposDeFichero(personajes); // Le meto los edificios introduceEdificios(edificios); } public static Civilizacion getCivilizacionActiva() { return civilizacionActiva; } /** * Devuelve una civilización a partir de un nombre * * @param nombre El nombre de la civilización * @return La civilicación asociada a ese nombre * @throws excepciones.ParametroIncorrectoException */ public Civilizacion getCivilizacion(String nombre) throws ParametroIncorrectoException { if (civilizaciones.containsKey(nombre)) { return civilizaciones.get(nombre); } else { throw new ParametroIncorrectoException("Nombre de civilización incorrecto"); } } public Mapa getMapa() { return this.mapa; } public Map<String, ContRecurso> getContRecursos() { return this.contRecursos; } @Override public String mover(String nombre, String direccion) throws EstarEnGrupoException, NoTransitablebleException, FueraDeMapaException, ParametroIncorrectoException, CeldaEnemigaException, CeldaOcupadaException, CapMovimientoException { Personaje p = Juego.civilizacionActiva.getPersonaje(nombre); // Si el personaje puede moverse más una casilla, preguntamos if(p.capacidadMovimiento() > 1) { throw new CapMovimientoException(String.valueOf(p.capacidadMovimiento())); } // Si la capacidad de movimiento es 1 return mover(nombre, direccion, 1); } @Override public String mover(String nombre, String direccion, int distancia) throws EstarEnGrupoException, NoTransitablebleException, FueraDeMapaException, ParametroIncorrectoException, CeldaEnemigaException, CeldaOcupadaException { Personaje p = Juego.civilizacionActiva.getPersonaje(nombre); String s; if(p instanceof Caballero) { s = p.mover(mapa, direccion, distancia); } else if(distancia != 1) { throw new ParametroIncorrectoException("Solo los caballeros pueden avanzar más de una celda."); } else { s = p.mover(mapa, direccion); } getMapa().imprimir(); return s; } @Override public String listar(String tipo) throws ParametroIncorrectoException { switch (tipo.toLowerCase()) { case "personajes": return getCivilizacionActiva().listarPersonajes(); case "edificios": return getCivilizacionActiva().listarEdificios(); case "civilizaciones": return listarCivilizaciones(); default: throw new ParametroIncorrectoException("Elementos a listar desconocidos."); } } @Override public String describir(String nombre) throws ParametroIncorrectoException { return describir(nombre, getCivilizacionActiva().getNomCivilizacion()); } @Override public String describir(String nombre, String civilizacion) throws ParametroIncorrectoException { Civilizacion civ = this.getCivilizacion(civilizacion); if (civ.getMapaPersonajes().containsKey(nombre)) { return (civ.getMapaPersonajes().get(nombre).toString()); } else if (civ.getMapaEdificios().containsKey(nombre)) { return (civ.getMapaEdificios().get(nombre).toString()); } else if (civ.getMapaGrupos().containsKey(nombre)) { return (civ.getMapaGrupos().get(nombre).toString()); } else { throw new ParametroIncorrectoException(nombre + " no corresponde a un personaje ni a un edificio."); } } @Override public String mirar(String coordenadasCelda) throws ParametroIncorrectoException, NumberFormatException, FueraDeMapaException { String[] fc = coordenadasCelda.split(""); if(fc.length != 5){ throw new ParametroIncorrectoException("Coordenadas mal indicadas"); } int f = Integer.parseInt(fc[1]); int c = Integer.parseInt(fc[3]); return ((mapa.obtenerCelda(c, f)).mirar()); } @Override public String construir(String Personaje, String nEdificio, String direccion) throws InsuficientesRecException, ParametroIncorrectoException, CeldaOcupadaException, FueraDeMapaException, CeldaEnemigaException, SolConstruirException, EstarEnGrupoException { Personaje p = civilizacionActiva.getPersonaje(Personaje); String s = p.construirEdificio(nEdificio, direccion); getMapa().imprimir(); return s; } @Override public String recolectar(String nPersonaje, String direccion) throws PersonajeLlenoException, SoldadoRecException, RecursosException, FueraDeMapaException, ParametroIncorrectoException, CeldaOcupadaException, EstarEnGrupoException { String s = getCivilizacionActiva().getPersonaje(nPersonaje).recolectar(direccion); getMapa().imprimir(); return s; } @Override public void cambiarCivilizacion(String nCivilizacion) throws ParametroIncorrectoException { Juego.civilizacionActiva = this.getCivilizacion(nCivilizacion); getMapa().imprimir(); } @Override public void imprimirCivilizacion() throws ParametroIncorrectoException { this.getMapa().imprimirVisitadasCivilizacion(getCivilizacionActiva()); } @Override public void imprimirCivilizacion(String nCivilizacion) throws ParametroIncorrectoException { this.getMapa().imprimirVisitadasCivilizacion(getCivilizacion(nCivilizacion)); } @Override public String agrupar(String coordenadasCelda) throws ParametroIncorrectoException, NumberFormatException, FueraDeMapaException, ParametroIncorrectoException, NoAgrupableException, CeldaEnemigaException, NoTransitablebleException { String[] fc = coordenadasCelda.split(""); if(fc.length != 5){ throw new ParametroIncorrectoException("Coordenadas mal introducidas"); } int f = Integer.parseInt(fc[1]); int c = Integer.parseInt(fc[3]); String s = this.getMapa().obtenerCelda(c, f).agrupar(); getMapa().imprimir(); return s; } @Override public String desagrupar(String nGrupo) throws NoAgrupableException, ParametroIncorrectoException, CeldaEnemigaException, NoTransitablebleException, FueraDeMapaException { String s; Personaje p = getCivilizacionActiva().getPersonaje(nGrupo); if(p instanceof Grupo) { s = ((Grupo) p).desagrupar(); } else { throw new ParametroIncorrectoException(nGrupo+" no es el nombre de un grupo"); } this.getMapa().imprimir(); return s; } @Override public String desligar(String nPersonaje) throws NoAgrupableException, EstarEnGrupoException, ParametroIncorrectoException, CeldaEnemigaException, NoTransitablebleException, FueraDeMapaException { String s; Personaje p = getCivilizacionActiva().getPersonaje(nPersonaje); s = p.getGrupo().desligar(p); this.getMapa().imprimir(); return s; } @Override public String crear(String nEdificio, String tipoPersonaje) throws EdificioException, FueraDeMapaException, CeldaEnemigaException, NoTransitablebleException, ParametroIncorrectoException { Edificio e = getCivilizacionActiva().getEdificio(nEdificio); Personaje p = e.crear(tipoPersonaje); this.mapa.imprimir(); return("Creado personaje:\n"+p.toString()); } @Override public String almacenar(String nPersonaje, String direccion) throws InsuficientesRecException, NoAlmacenableException, SolAlmacenarException, NoTransitablebleException, FueraDeMapaException, ParametroIncorrectoException, CeldaEnemigaException, CeldaOcupadaException, EstarEnGrupoException { return getCivilizacionActiva().getPersonaje(nPersonaje).almacenar(direccion); } @Override public String reparar(String nPersonaje, String direccion) throws SolRepararException, FueraDeMapaException, ParametroIncorrectoException, NoNecRepararException, InsuficientesRecException, EdificioException, EstarEnGrupoException { String s = getCivilizacionActiva().getPersonaje(nPersonaje).reparar(direccion); getMapa().imprimir(); return s; } @Override public String defender(String nPersonaje, String direccion) throws FueraDeMapaException, ParametroIncorrectoException, CeldaEnemigaException, NoTransitablebleException, CeldaOcupadaException, EstarEnGrupoException, EdificioException, CeldaException { String s = getCivilizacionActiva().getPersonaje(nPersonaje).defender(direccion); getMapa().imprimir(); return s; } @Override public String atacar(String nombre, String direccion) throws FueraDeMapaException, ParametroIncorrectoException, NoTransitablebleException, CeldaEnemigaException, AtaqueExcepcion, EstarEnGrupoException, CivilizacionDestruidaException { String s; if(getCivilizacionActiva().getMapaPersonajes().containsKey(nombre) || getCivilizacionActiva().getMapaGrupos().containsKey(nombre)) { s = getCivilizacionActiva().getPersonaje(nombre).atacar(direccion); } else if (getCivilizacionActiva().getMapaEdificios().containsKey(nombre)) { s = getCivilizacionActiva().getEdificio(nombre).atacar(direccion); } else { throw new ParametroIncorrectoException("No existe ningún personaje, grupo o edificio de nombre "+nombre); } getMapa().imprimir(); return s; } @Override public void salir() { getMapa().salir(); } // Métodos privados private void creaCivilizaciones(List<List<String>> personajes, List<List<String>> edificios) throws FueraDeMapaException { // Creamos las civilizaciones Civilizacion.resetNumDeCivilizaciones(); int idCiv = 0; // civilizaciones definidas en el fichero de edificios for (List<String> edificio : edificios) { int y = new Integer(edificio.get(0).split(",")[0]); int x = new Integer(edificio.get(0).split(",")[1]); if (x < 0 || y < 0 || x >= tamX || y >= tamY) { throw new FueraDeMapaException("La posición (" + x + ", " + y + ") del edificio " + edificio.get(2) + " se sale del mapa"); } else { String nombreCivilizacion = edificio.get(4); // Creamos la civilizacion Civilizacion civ; if (!civilizaciones.containsKey(nombreCivilizacion)) { // Si la civilizacion no existe, la creamos civ = new Civilizacion(nombreCivilizacion, idCiv); civilizaciones.put(nombreCivilizacion, civ); if (idCiv == 0) { Juego.civilizacionActiva = civ; } idCiv++; } } } idCiv = civilizaciones.size(); // civilizaciones definidas en el fichero de personajes for (List<String> personaje : personajes) { int y = new Integer(personaje.get(0).split(",")[0]); int x = new Integer(personaje.get(0).split(",")[1]); if (x < 0 || y < 0 || x >= tamX || y >= tamY) { throw new FueraDeMapaException("La posición (" + x + ", " + y + ") del personaje " + personaje.get(2) + " se sale del mapa"); } else { String nombreCivilizacion = personaje.get(9); // Creamos la civilizacion si no existe Civilizacion civ; if (!civilizaciones.containsKey(nombreCivilizacion)) { // Si la civilizacion no existe, la creamos civ = new Civilizacion(nombreCivilizacion, idCiv); civilizaciones.put(nombreCivilizacion, civ); if (idCiv == 0) { Juego.civilizacionActiva = civ; } idCiv++; } } } } private void introduceCR(List<List<String>> recursos) throws ParametroIncorrectoException, CeldaOcupadaException, FueraDeMapaException { for (List<String> recurso : recursos) { int y = new Integer(recurso.get(0).split(",")[0]); int x = new Integer(recurso.get(0).split(",")[1]); String tipo = recurso.get(1); if (!tipo.equals("Pradera")) { String codigo = recurso.get(2); String descripcion = recurso.get(3); int cantidad = new Integer(recurso.get(4)); Celda c = mapa.obtenerCelda(x, y); ContRecurso cr = null; switch (tipo) { case "Arbusto": cr = new Arbusto(new Comida(cantidad)); break; case "Bosque": cr = new Bosque(new Madera(cantidad)); break; case "Cantera": cr = new Cantera(new Piedra(cantidad)); break; default: throw new ParametroIncorrectoException("Tipo de contenedor de recursos desconocido"); } c.anhadeCR(cr); } } } private void introduceEdificios(List<List<String>> edificios) throws FueraDeMapaException, CeldaOcupadaException, ParametroIncorrectoException, CeldaEnemigaException { // Metemos los edificios for (List<String> edificio : edificios) { int y = new Integer(edificio.get(0).split(",")[0]); int x = new Integer(edificio.get(0).split(",")[1]); if (x < 0 || y < 0 || x >= mapa.getTamX() || y >= mapa.getTamY()) { throw new FueraDeMapaException("La posición (" + x + ", " + y + ") del edificio " + edificio.get(2) + " se sale del mapa"); } else { String tipo = edificio.get(1); String codigo = edificio.get(2); String descripcion = edificio.get(3); Civilizacion civilizacion = getCivilizacion(edificio.get(4)); Celda c = mapa.obtenerCelda(x, y); Edificio e = null; switch (tipo) { case "Casa": e = new Casa(); break; case "Ciudadela": e = new Ciudadela(); break; case "Cuartel": e = new Cuartel(); break; default: throw new ParametroIncorrectoException("Tipo de edificio desconocido"); } if (e != null) { // Inicializo el nombre para que se actualice el contador e.inicializaNombre(civilizacion); // Le pongo el nombre del fichero e.setNombre(codigo); civilizacion.anhadeEdificio(e); c.anhadeEdificio(e); } } } } private void introducePersonajes(List<List<String>> personajes) throws ParametroIncorrectoException, CeldaEnemigaException, FueraDeMapaException, NoTransitablebleException { // Recorremos la infprmación de los personajes for (List<String> personaje : personajes) { int y = new Integer(personaje.get(0).split(",")[0]); int x = new Integer(personaje.get(0).split(",")[1]); if (x < 0 || y < 0 || x >= mapa.getTamX() || y >= mapa.getTamY()) { throw new FueraDeMapaException("La posición (" + x + ", " + y + ") del personaje " + personaje.get(2) + " se sale del mapa"); } else { String tipo = personaje.get(1); String codigo = personaje.get(2); String descripcion = personaje.get(3); int ataque = new Integer(personaje.get(4)); int defensa = new Integer(personaje.get(5)); int salud = new Integer(personaje.get(6)); int capacidad = new Integer(personaje.get(7)); Civilizacion civilizacion = getCivilizacion(personaje.get(9)); Celda c = mapa.obtenerCelda(x, y); // Anhadimos el personaje Personaje per = null; switch (tipo) { case "Paisano": per = new Paisano(salud, defensa, ataque, capacidad); break; case "Arquero": per = new Arquero(salud, defensa, ataque); break; case "Caballero": per = new Caballero(salud, defensa, ataque); break; case "Legionario": per = new Legionario(salud, defensa, ataque); break; default: throw new ParametroIncorrectoException("Tipo de personaje desconocido"); } if (per != null) { per.inicializaNombre(civilizacion); per.setNombre(codigo); civilizacion.anhadePersonaje(per); c.anhadePersonaje(per); } } } } private void creaGruposDeFichero(List<List<String>> personajes) throws FueraDeMapaException, ParametroIncorrectoException, NoAgrupableException, CeldaEnemigaException, NoTransitablebleException { // Recorremos de nuevo en busca de grupos int fAnterior = -1; int cAnterior = -1; for (List<String> personaje : personajes) { int f = new Integer(personaje.get(0).split(",")[0]); int c = new Integer(personaje.get(0).split(",")[1]); if (c < 0 || f < 0 || c >= mapa.getTamX() || f >= mapa.getTamY()) { throw new FueraDeMapaException("El personaje " + personaje.get(2) + " se sale del mapa"); } else { String nombreGrupo = personaje.get(8); Civilizacion civilizacion = getCivilizacion(personaje.get(9)); if (c != cAnterior || f != fAnterior) { // Empezamos una nueva celda // Agrupamos la celda Celda celda = mapa.obtenerCelda(c, f); if(celda.getPersonajes().size() > 1) { celda.agrupar(nombreGrupo, civilizacion); } cAnterior = c; fAnterior = f; } } } } public void juegoPorDefecto() throws CeldaOcupadaException, ParametroIncorrectoException, CeldaEnemigaException, NoTransitablebleException, FueraDeMapaException { // Obtiene una lista con las dos civilizaciones List<Civilizacion> civs = new ArrayList<Civilizacion>(civilizaciones.values()); Civilizacion civ0 = civs.get(0); Civilizacion civ1 = civs.get(1); Mapa m = getMapa(); // Añadimos elementos por columnas // columna 0 (primera coordenada = columna, segunda = fila) // Bosque en (0, 0) con 10 Madera anhadeCR(new Bosque(new Madera(100)), m.obtenerCelda(0, 0)); // Arbusto en (0, 4) con 5 Comida anhadeCR(new Arbusto(new Comida(500)), m.obtenerCelda(0, 4)); // Arbusto en (0, 9) con 5 Comida anhadeCR(new Arbusto(new Comida(50)), m.obtenerCelda(0, 9)); // Columna 1 anhadeEdificio(new Ciudadela(), m.obtenerCelda(1, 1), civ0); anhadePersonaje(new Paisano(), m.obtenerCelda(1, 2), civ0); anhadeCR(new Cantera(new Piedra(400)), m.obtenerCelda(1, 6)); anhadeCR(new Bosque(new Madera(100)), m.obtenerCelda(1, 7)); anhadeCR(new Arbusto(new Comida(200)), m.obtenerCelda(1, 9)); // Columna 2 anhadeEdificio(new Casa(), m.obtenerCelda(2, 2), civ0); anhadeCR(new Bosque(new Madera(100)), m.obtenerCelda(2, 4)); anhadeCR(new Arbusto(new Comida(100)), m.obtenerCelda(2, 9)); // Columna 3 anhadeCR(new Cantera(new Piedra(800)), m.obtenerCelda(3, 0)); anhadeCR(new Cantera(new Piedra(200)), m.obtenerCelda(3, 4)); anhadePersonaje(new Caballero(), m.obtenerCelda(3, 8), civ0); // Columna 4 anhadeCR(new Cantera(new Piedra(400)), m.obtenerCelda(4, 0)); anhadeEdificio(new Ciudadela(), m.obtenerCelda(4, 6), civ0); anhadePersonaje(new Paisano(), m.obtenerCelda(4, 7), civ0); anhadeEdificio(new Cuartel(), m.obtenerCelda(4, 8), civ0); // Columna 5 anhadeCR(new Bosque(new Madera(800)), m.obtenerCelda(5, 1)); anhadeCR(new Bosque(new Madera(100)), m.obtenerCelda(5, 2)); anhadeCR(new Cantera(new Piedra(400)), m.obtenerCelda(5, 5)); anhadeCR(new Cantera(new Piedra(400)), m.obtenerCelda(5, 6)); // Columna 6 anhadeCR(new Bosque(new Madera(200)), m.obtenerCelda(6, 1)); anhadeCR(new Bosque(new Madera(600)), m.obtenerCelda(6, 2)); anhadePersonaje(new Arquero(), m.obtenerCelda(6, 4), civ1); anhadeCR(new Arbusto(new Comida(200)), m.obtenerCelda(6, 8)); anhadeCR(new Arbusto(new Comida(400)), m.obtenerCelda(6, 9)); // Columna 7 anhadeEdificio(new Cuartel(), m.obtenerCelda(7, 4), civ1); anhadePersonaje(new Paisano(), m.obtenerCelda(7, 5), civ1); anhadeEdificio(new Ciudadela(), m.obtenerCelda(7, 6), civ1); anhadeCR(new Bosque(new Madera(800)), m.obtenerCelda(7, 9)); // Columna 8 anhadeCR(new Arbusto(new Comida(100)), m.obtenerCelda(8, 0)); anhadePersonaje(new Legionario(), m.obtenerCelda(8, 4), civ1); anhadeEdificio(new Casa(), m.obtenerCelda(8, 5), civ1); // Columna 9 anhadeCR(new Arbusto(new Comida(400)), m.obtenerCelda(9, 0)); anhadeCR(new Cantera(new Piedra(1000)), m.obtenerCelda(9, 2)); anhadeCR(new Bosque(new Madera(900)), m.obtenerCelda(9, 3)); anhadeCR(new Bosque(new Madera(300)), m.obtenerCelda(9, 4)); anhadeCR(new Cantera(new Piedra(400)), m.obtenerCelda(9, 7)); anhadeCR(new Cantera(new Piedra(800)), m.obtenerCelda(9, 8)); anhadeCR(new Cantera(new Piedra(200)), m.obtenerCelda(9, 9)); } // Método auxiliar para añadir un CR a una celda private void anhadeCR(ContRecurso cr, Celda c) throws CeldaOcupadaException { c.anhadeCR(cr); } // Método auxiliar para añadir un personaje a una civilización y a una celda private void anhadePersonaje(Personaje p, Celda c, Civilizacion civ) throws CeldaEnemigaException, NoTransitablebleException, FueraDeMapaException { p.inicializaNombre(civ); civ.anhadePersonaje(p); c.anhadePersonaje(p); } // Método auxiliar para añadir un edificio a una civilización y a una celda private void anhadeEdificio(Edificio e, Celda c, Civilizacion civ) throws CeldaOcupadaException, CeldaEnemigaException { e.inicializaNombre(civ); civ.anhadeEdificio(e); c.anhadeEdificio(e); } private String listarCivilizaciones() { String s = "Civilizaciones:\n"; Iterator it = this.civilizaciones.entrySet().iterator(); while (it.hasNext()) { Map.Entry e = (Map.Entry) it.next(); s += "\t"+e.getKey(); } return s; } } <file_sep>/src/elementos/cr/Pradera.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package elementos.cr; import elementos.ContRecurso; import elementos.Recurso; import excepciones.recursos.NoProcesableException; import interfazUsuario.Juego; /** * * @author celia y maria */ public class Pradera extends ContRecurso{ public Pradera() { super(new Recurso(Juego.TPRADERA, 0)); setTransitable(true); } @Override public String toString() { return("\tContenedor de recursos de tipo Pradera, no productiva"); } @Override public Recurso procesar() throws NoProcesableException { throw new NoProcesableException("Las praderas no se procesan"); } } <file_sep>/src/elementos/cr/Bosque.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package elementos.cr; import elementos.ContRecurso; import elementos.Recurso; import excepciones.recursos.NoProcesableException; /** * * @author celia y maria */ public class Bosque extends ContRecurso { public Bosque(Recurso rec) { super(rec); } @Override public String toString() { return("\tContenedor de recursos de tipo Bosque\n\tCantidad de madera "+this.getRecurso().getCapacidad()); } @Override public Recurso procesar() throws NoProcesableException { throw new NoProcesableException("Los bosques no se procesan"); } } <file_sep>/src/elementos/personaje/Soldado.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package elementos.personaje; import elementos.Personaje; import excepciones.ParametroIncorrectoException; import excepciones.personaje.SoldadoRecException; import excepciones.personaje.SolConstruirException; import excepciones.personaje.SolRepararException; import excepciones.personaje.SolAlmacenarException; /** * * @author celia y maria */ public abstract class Soldado extends Personaje { public Soldado(int tipo) throws ParametroIncorrectoException { this(100, 50, 75, tipo); } public Soldado(int salud, int armadura, int ataque, int tipo) throws ParametroIncorrectoException { super(salud, armadura, ataque, false, tipo); } /** * * @param direccion * @throws SoldadoRecException */ @Override public String recolectar(String direccion) throws SoldadoRecException { throw new SoldadoRecException("Un soldado no puede recolectar"); } @Override public String construirEdificio(String nedificio, String direccion) throws SolConstruirException { throw new SolConstruirException("Un soldado no puede construir"); } @Override public String reparar(String direccion) throws SolRepararException { throw new SolRepararException("Un soldado no puede reparar"); } @Override public String almacenar(String direccion) throws SolAlmacenarException { throw new SolAlmacenarException("Un soldado no puede almacenar"); } } <file_sep>/src/interfazUsuario/ConsolaNormal.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package interfazUsuario; import java.util.Scanner; /** * * @author <NAME> maria */ public class ConsolaNormal implements Consola { Scanner escanear = new Scanner(System.in); @Override public void imprimir(String s) { System.out.print(s); } @Override public String leer(String descripcion) { imprimir(descripcion); return escanear.nextLine(); } @Override public void salir() { } } <file_sep>/src/elementos/Personaje.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package elementos; import elementos.personaje.Arquero; import elementos.personaje.Caballero; import elementos.personaje.Grupo; import elementos.personaje.Legionario; import elementos.personaje.Paisano; import excepciones.CivilizacionDestruidaException; import excepciones.celda.CeldaEnemigaException; import excepciones.celda.CeldaOcupadaException; import excepciones.celda.FueraDeMapaException; import excepciones.recursos.NoRecolectableException; import excepciones.celda.NoTransitablebleException; import excepciones.ParametroIncorrectoException; import excepciones.celda.CeldaException; import excepciones.celda.NoAlmacenableException; import excepciones.edificio.EdificioException; import excepciones.edificio.NoNecRepararException; import excepciones.personaje.AtaqueExcepcion; import excepciones.personaje.EstarEnGrupoException; import excepciones.personaje.InsuficientesRecException; import excepciones.personaje.PersonajeLlenoException; import excepciones.personaje.SolAlmacenarException; import excepciones.personaje.SolConstruirException; import excepciones.personaje.SolRepararException; import excepciones.recursos.RecursosException; import excepciones.personaje.SoldadoRecException; import vista.Celda; import interfazUsuario.Juego; import vista.Mapa; /** * Clase genérica para los personajes (paisanos, soldados y grupos) * * @author celia y maria */ public abstract class Personaje { private Celda celda; private String nombre = null; private Civilizacion civilizacion; private boolean estado; // True vivo, False Muerto private int tipoPersonaje; private int salud; private int saludInicial; private int armadura; private int ataque; private boolean capEdificacion; private boolean estarGrupo; private Grupo grupo; private int capMovimiento; /** * Crea un personaje en una celda y asociado a una civilización * * @param salud Salud inicial del personaje * @param armadura Capacidad de defensa inicial * @param ataque Capacidad de ataque inicial * @param capEdificacion Indica si puede edificar * @param tipo Tipo de personaje * @throws excepciones.ParametroIncorrectoException */ public Personaje(int salud, int armadura, int ataque, boolean capEdificacion, int tipo) throws ParametroIncorrectoException { if (salud < 0) { throw new ParametroIncorrectoException("La salud no puede ser negativa"); } else { //this.celda = celda; this.estado = true; this.salud = salud; this.saludInicial = salud; this.armadura = armadura < 0 ? 0 : armadura; this.ataque = ataque < 0 ? 0 : ataque; this.capEdificacion = capEdificacion; this.tipoPersonaje = tipo; // No estamos en ningun grupo this.estarGrupo = false; grupo = null; // Todos los personajes tienen capacidad de movimiento 1 menos los caballeros, que tienen 2 this.capMovimiento = 1; } } //GETTERS Y SETTERS /** * Obtiene la celda en la que se encuentra el personaje * * @return La celda en la que se encuentra el personaje */ public Celda getCelda() { return this.celda; } /** * Obtiene el nombre del personaje * * @return String ombre personaje */ public String getNombre() { return this.nombre; } /** * Obtiene la civilizacion a la que pertenece el personaje * * @return Civilizacion a la que pertenece personaje */ public Civilizacion getCivilizacion() { return this.civilizacion; } // /** // * Estado del personaje // * // * @return boolean determinando su estado // */ // public boolean getEstado() { // return this.estado; // } /** * Tipo de personaje: paisano, soldado o grupo * * @return int con tipo */ public int getTipo() { return this.tipoPersonaje; } /** * Salud personaje * * @return int salud personaje */ public int getSalud() { return this.salud; } /** * Armadura personaje * * @return int armadura personaje */ public int getArmadura() { return this.armadura; } /** * Ataque personaje * * @return int ataque personaje */ public int getAtaque() { return this.ataque; } public boolean getEstarGrupo() { return this.estarGrupo; } public boolean getCapEdificacion() { return this.capEdificacion; } public Grupo getGrupo() throws EstarEnGrupoException { if (estarGrupo) { return this.grupo; } else { throw new EstarEnGrupoException("El personaje " + getNombre() + " no está en ningún grupo"); } } /** * Devuelve un entero que indoca cuantas casillas como máximo se puede mover * el personaje de una vez * * @return La capacidad de movimiento */ public int capacidadMovimiento() { return capMovimiento; } /** * Establece el nombre del personaje * * @param nombre El nombre */ public void setNombre(String nombre) { this.nombre = nombre; } /** * Establece la civilización del personaje * * @param civ */ public void setCivilizacion(Civilizacion civ) { this.civilizacion = civ; } /** * Cambia la celda en la que está situado el personaje * * @param c La nueva celda del personaje */ public void setCelda(Celda c) { this.celda = c; } /** * * @param s */ public void setSalud(int s) { if (s < 0) { this.salud = 0; this.estado = false; } else { this.salud = s; } } public void setSaludInicial(int s){ this.saludInicial = s; } /** * * @param armadura */ public void setArmadura(int armadura) { this.armadura = armadura < 0 ? 0 : armadura; } /** * * @param ataque */ public void setAtaque(int ataque) { this.ataque = ataque < 0 ? 0 : ataque; } /** * * @param estado */ public void setEstado(boolean estado) { this.estado = estado; } public void setEstarGrupo(boolean grupo) { this.estarGrupo = grupo; } public void setGrupo(Grupo g) { this.estarGrupo = true; this.grupo = g; } public void setTipo(int tipo) { this.tipoPersonaje = tipo; } /** * Solo las subclases pueden cambiar la capacidad de movimiento del * personaje * * @param cap */ protected void setCapMovimiento(int cap) { this.capMovimiento = cap; } //FUNCIONES /** * Mueve el personaje una celda hacia una dirección * * @param mapa El mapa en el que nos movemos * @param direccion La dirección hacia la que nos movemos (norte, sur, esye * u oeste) * @return Mensaje de accion completada * * @throws excepciones.celda.NoTransitablebleException * @throws excepciones.celda.FueraDeMapaException * @throws excepciones.ParametroIncorrectoException * @throws excepciones.celda.CeldaEnemigaException * @throws excepciones.celda.CeldaOcupadaException * @throws excepciones.personaje.EstarEnGrupoException */ public String mover(Mapa mapa, String direccion) throws NoTransitablebleException, FueraDeMapaException, ParametroIncorrectoException, CeldaEnemigaException, CeldaOcupadaException, EstarEnGrupoException, NoTransitablebleException { return mover(mapa, direccion, 1); } /** * Mueve el personaje varias celdas hacia una dirección * * @param mapa El mapa en el que nos movemos * @param direccion La dirección hacia la que nos movemos (norte, sur, esye * u oeste) * @param distancia El número de celdas a las que avanzamos * @return Mensaje de accion completada * * @throws excepciones.celda.NoTransitablebleException * @throws excepciones.celda.FueraDeMapaException * @throws excepciones.ParametroIncorrectoException * @throws excepciones.celda.CeldaEnemigaException * @throws excepciones.celda.CeldaOcupadaException * @throws excepciones.personaje.EstarEnGrupoException */ public String mover(Mapa mapa, String direccion, int distancia) throws NoTransitablebleException, FueraDeMapaException, ParametroIncorrectoException, CeldaEnemigaException, CeldaOcupadaException, EstarEnGrupoException, NoTransitablebleException { if (getEstarGrupo()) { throw new EstarEnGrupoException("El personaje no se puede mover, ya que está en el grupo " + getGrupo().getNombre()); } Celda actual = this.getCelda(); Celda vecina = mapa.obtenerCeldaVecina(actual, direccion, distancia); if (!vecina.getTransitable()) { throw new NoTransitablebleException("La celda no permite la entrada."); } else if (vecina.getCivilizacion() != null && vecina.getCivilizacion() != this.getCivilizacion()) { throw new CeldaEnemigaException("La celda está ocupada por el enemigo."); } else { // Elimina el personaje de la celda actual actual.eliminarPersonaje(this); // Añade el personaje a la celda vecina y cambia la celda del personaje vecina.anhadePersonaje(this); this.setCelda(vecina); vecina.setCivilizacion(Juego.getCivilizacionActiva()); // Actualiza la visibilidad this.actualizaVisibilidad(); // Si la celda que abandonamos tenía edificio, le aumentamos su capacidad de acogida y le reducimos la defensa Edificio e = actual.getEdificio(); if (e != null) { e.setDefensa(e.getDefensa() - this.getArmadura()); e.setCapPersonajes(e.getCapPersonajes() + 1); } return ("El " + this.getNombre() + " se ha movido a la celda " + vecina); } } /** * Entra en un edificio para defenderlo * @param direccion Dirección hacia la que entramos * @return Mensaje de estado * @throws FueraDeMapaException * @throws ParametroIncorrectoException * @throws CeldaEnemigaException * @throws NoTransitablebleException * @throws CeldaOcupadaException * @throws EstarEnGrupoException * @throws EdificioException * @throws CeldaException */ public String defender(String direccion) throws FueraDeMapaException, ParametroIncorrectoException, CeldaEnemigaException, NoTransitablebleException, CeldaOcupadaException, EstarEnGrupoException, EdificioException, CeldaException { if (getEstarGrupo()) { throw new EstarEnGrupoException("El personaje no puede defender, ya que está en el grupo " + getGrupo()); } String s; Celda vecina = this.getCelda().getMapa().obtenerCeldaVecina(this.getCelda(), direccion); //igual que en mirar comprueba que la direccion sea válida if (vecina.getEdificio() != null) {// La celda contiene un edificio //Una celda con un edificio solo tendría ese edificio, no más elementos Edificio e = vecina.getEdificio(); if (vecina.getCivilizacion() != this.getCivilizacion()) { throw new CeldaEnemigaException("El edificio pertenece a la civilización enemiga\n"); } else { if (e.getCapPersonajes() > 0) { // Hago la celda vecina transitable para poder entrar vecina.setTransitable(true); mover(this.getCelda().getMapa(), direccion); vecina.setTransitable(false); e.setDefensa(e.getDefensa() + this.getArmadura()); e.setCapPersonajes(e.getCapPersonajes() - 1); this.setSalud(this.saludInicial); s = "El " + this.getNombre() + " ha entrado en el " + e.getNombre() + " (capacidad restante edificio es " + e.getCapPersonajes() + ")\n"; } else { throw new EdificioException("El edificio está al máximo de capacidad de personajes, no puede entrar\n"); } } } else { //la celda no contiene un edificio throw new CeldaException("La celda no contiene un edificio, no se puede defender\n"); } return s; } /** * Ataca a una celda vecina * * @param direccion Dirección hacia la que atacar * @return Mensaje de estado * @throws FueraDeMapaException * @throws ParametroIncorrectoException * @throws NoTransitablebleException * @throws CeldaEnemigaException * @throws AtaqueExcepcion * @throws EstarEnGrupoException */ public String atacar(String direccion) throws FueraDeMapaException, ParametroIncorrectoException, NoTransitablebleException, CeldaEnemigaException, AtaqueExcepcion, EstarEnGrupoException, CivilizacionDestruidaException { if (getEstarGrupo()) { throw new EstarEnGrupoException("El personaje no puede atacar, ya que está en el grupo " + getGrupo()); } String s; Celda actual = this.getCelda(); Celda vecina = actual.getMapa().obtenerCeldaVecina(actual, direccion); Civilizacion vecinaCivil = vecina.getCivilizacion(); if (vecina.getContRecurso() != null || vecinaCivil == null) { throw new NoTransitablebleException("No puedes atacar a un " + vecina.getContRecurso().getNombre()); } else if (vecinaCivil != null && vecinaCivil == this.getCivilizacion()) { throw new CeldaEnemigaException("No puedes atacar a una celda amiga."); } // Comprobamos si hay personajes y atacamos al más débil if (!vecina.getPersonajes().isEmpty()) { int saludEnemigo = Integer.MAX_VALUE; Personaje pEnemigo = null; for (Personaje p : vecina.getPersonajes()) { if (p.getSalud() < saludEnemigo) { saludEnemigo = p.getSalud(); pEnemigo = p; } } if (pEnemigo != null) { // Intentamos atacar al personaje int danhoCausado = this.danhoAtaque(pEnemigo); if (danhoCausado < 1) { s = this.getNombre() + " no puede atacar: la defensa enemiga es demasiado fuerte."; } else { int nuevaSalud = pEnemigo.getSalud() - danhoCausado; if (nuevaSalud > 0) { pEnemigo.setSalud(nuevaSalud); s = this.getNombre() + " ha inflingido " + danhoCausado + " de daño a " + pEnemigo.getNombre() + " (" + pEnemigo.getCivilizacion().getNomCivilizacion() + "): la salud de " + pEnemigo.getNombre() + " es ahora " + pEnemigo.getSalud(); } else { s = this.getNombre() + " ha inflingido " + danhoCausado + " de daño a " + pEnemigo.getNombre() + " (" + pEnemigo.getCivilizacion().getNomCivilizacion() + "): " + pEnemigo.getNombre() + " ha muerto"; vecina.eliminarPersonaje(pEnemigo); pEnemigo.getCivilizacion().eliminaPersonaje(pEnemigo); vecina.setVisitadaPor(this.getCivilizacion()); // Si la celda que abandonamos tenía edificio, le aumentamos su capacidad de acogida y le reducimos la defensa Edificio e = vecina.getEdificio(); if (e != null) { e.setDefensa(e.getDefensa() - pEnemigo.getArmadura()); e.setCapPersonajes(e.getCapPersonajes() + 1); } } } return s; } else { throw new AtaqueExcepcion("Error desconocido al atacar"); } // Si no hay personajes, atacamos al edificio } else if (vecina.getEdificio() != null) { Edificio edificioEnemigo = vecina.getEdificio(); // Intentamos atacar al edificio int danhoCausado = this.getAtaque(edificioEnemigo); if (danhoCausado < 1) { s = this.getNombre() + " no puede atacar a " + edificioEnemigo.getNombre() + " (" + edificioEnemigo.getCivilizacion().getNomCivilizacion() + "): su defensa es demasiado fuerte."; } else { int nuevaSalud = edificioEnemigo.getSalud() - danhoCausado; if (nuevaSalud > 0) { edificioEnemigo.setSalud(nuevaSalud); s = this.getNombre() + " ha inflingido " + danhoCausado + " de daño a " + edificioEnemigo.getNombre() + " (" + edificioEnemigo.getCivilizacion().getNomCivilizacion() + "): la salud de " + edificioEnemigo.getNombre() + " es ahora " + edificioEnemigo.getSalud(); } else { s = this.getNombre() + " ha inflingido " + danhoCausado + " de daño a " + edificioEnemigo.getNombre() + " (" + edificioEnemigo.getCivilizacion().getNomCivilizacion() + "): " + edificioEnemigo.getNombre() + " ha quedado destruido"; vecina.eliminaEdificio(); edificioEnemigo.getCivilizacion().eliminaEdificio(edificioEnemigo); vecina.setVisitadaPor(this.getCivilizacion()); } } // Comprueba si hamos destruido la civilizacion if(vecinaCivil.determinaDestruccion()) { throw new CivilizacionDestruidaException("La civilización "+vecinaCivil.getNomCivilizacion()+" ha sido destruida!"); } return s; } else { throw new AtaqueExcepcion("No hay nadie a quién atacar"); } } public int danhoAtaque(Personaje enemigo){ return (this.getAtaque() - enemigo.getArmadura()); } public int getAtaque(Edificio enemigo){ return (this.getAtaque() - enemigo.getDefensa()); } // FUNCIONES ABSTRACTAS /** * Se encarga de fijar el nombre a partir del tipo de personaje y la * civilización a la que pertenece * * @param civil Civilización a la que pertenece */ public abstract void inicializaNombre(Civilizacion civil); /** * Recolecta de una celda * * @param direccion Dirección hacia la que recolectar * @return Mensaje de estado * @throws excepciones.personaje.EstarEnGrupoException * @throws RecursosException * @throws PersonajeLlenoException * @throws FueraDeMapaException * @throws ParametroIncorrectoException * @throws NoRecolectableException * @throws CeldaOcupadaException * @throws SoldadoRecException */ public abstract String recolectar(String direccion) throws EstarEnGrupoException, RecursosException, PersonajeLlenoException, FueraDeMapaException, ParametroIncorrectoException, NoRecolectableException, CeldaOcupadaException, SoldadoRecException; /** * Almacena en una celda * * @param direccion Dirección hacia la que almacenar * @return Mensaje de estado * @throws excepciones.personaje.InsuficientesRecException * @throws excepciones.personaje.SolAlmacenarException * @throws excepciones.personaje.EstarEnGrupoException * @throws FueraDeMapaException * @throws excepciones.celda.NoAlmacenableException * @throws ParametroIncorrectoException */ public abstract String almacenar(String direccion) throws InsuficientesRecException, SolAlmacenarException, FueraDeMapaException, ParametroIncorrectoException, NoAlmacenableException, EstarEnGrupoException; /** * Repara un edificio en una celda * * @param direccion Dirección hacia la que reparar * @return Mensaje de estado * @throws excepciones.personaje.SolRepararException * @throws excepciones.personaje.InsuficientesRecException * @throws excepciones.personaje.EstarEnGrupoException * @throws excepciones.edificio.NoNecRepararException * @throws FueraDeMapaException * @throws ParametroIncorrectoException */ public abstract String reparar(String direccion) throws SolRepararException, FueraDeMapaException, ParametroIncorrectoException, NoNecRepararException, InsuficientesRecException, EdificioException, EstarEnGrupoException; /** * Construye un edificio en una celda * * @param nedificio Nombre del edificio * @param direccion Dirección hacia la que reparar * @return Mensaje de estado * @throws excepciones.personaje.SolConstruirException * @throws excepciones.personaje.InsuficientesRecException * @throws excepciones.personaje.EstarEnGrupoException * @throws excepciones.celda.CeldaOcupadaException * @throws FueraDeMapaException * @throws excepciones.celda.CeldaEnemigaException * @throws ParametroIncorrectoException */ public abstract String construirEdificio(String nedificio, String direccion) throws SolConstruirException, InsuficientesRecException, ParametroIncorrectoException, CeldaOcupadaException, FueraDeMapaException, CeldaEnemigaException, EstarEnGrupoException; // FUNCIONES ÚTILES /** * Haz visibles las celdas que rodean al personaje * * @throws excepciones.celda.FueraDeMapaException */ public void actualizaVisibilidad() throws FueraDeMapaException { Celda c = this.getCelda(); Mapa mapa = c.getMapa(); int x = c.getX(); int y = c.getY(); mapa.obtenerCelda(x, y).setVisible(true); mapa.obtenerCelda(x, y).setVisitadaPor(this.civilizacion); Celda vecina; if (x > 0) { vecina = mapa.obtenerCelda(x - 1, y); vecina.setVisible(true); // Si la celda vecina no tiene personajes, la marcamos como visitada // por la civilización actual if (vecina.getPersonajes().isEmpty()) { vecina.setVisitadaPor(this.civilizacion); } } if (x < (mapa.getTamX() - 1)) { vecina = mapa.obtenerCelda(x + 1, y); vecina.setVisible(true); // Si la celda vecina no tiene personajes, la marcamos como visitada // por la civilización actual if (vecina.getPersonajes().isEmpty()) { vecina.setVisitadaPor(this.civilizacion); } } if (y > 0) { vecina = mapa.obtenerCelda(x, y - 1); vecina.setVisible(true); // Si la celda vecina no tiene personajes, la marcamos como visitada // por la civilización actual if (vecina.getPersonajes().isEmpty()) { vecina.setVisitadaPor(this.civilizacion); } } if (y < (mapa.getTamY() - 1)) { vecina = mapa.obtenerCelda(x, y + 1); vecina.setVisible(true); // Si la celda vecina no tiene personajes, la marcamos como visitada // por la civilización actual if (vecina.getPersonajes().isEmpty()) { vecina.setVisitadaPor(this.civilizacion); } } } @Override public String toString() { String s = "Tipo personaje: "; if (this instanceof Paisano) { s += "Paisano"; } if (this instanceof Arquero) { s += "Arquero"; } if (this instanceof Caballero) { s += "Caballero"; } if (this instanceof Legionario) { s += "Legionario"; } if (this instanceof Grupo) { s += "Grupo"; } s += ", Nombre: " + this.getNombre(); s += "\n\tCivilización a la que pertenece: " + this.getCivilizacion().getNomCivilizacion(); s += "\n\tSalud: " + this.getSalud(); s += "\n\tArmadura: " + this.getArmadura(); s += "\n\tAtaque: " + this.getAtaque(); return (s); } }
74f8aef79a62e49aa48926e01c8254f9e3511b49
[ "Java" ]
13
Java
cfdezperez/proxectoE3
496db7bf23a0f4897e0b7215caec111c1b3b66e0
c0bb61b2113e488a821771e6cc08df8cc9dc5990
refs/heads/master
<file_sep><?php $r = rand(0,100); if($r > 50) { setcookie ("license", "true", time()+3600);/* период действия - 1 час */ } else { setcookie ("license", "false", time()+3600);/* период действия - 1 час */ } header('Location: ' . $_SERVER[REQUEST_URI]); die(); ?><file_sep><?php print("<a href=/>go to main</a>"); print("<h1>Sorry, you not have license</h1>"); print("<pre>Cookie:\r\n"); print_r($_COOKIE); print("\r\nRequest params: \r\n"); print_r($_REQUEST); print("</pre>"); ?>
789938f3b485f3c023f77f68aaca8fc8bda2f43d
[ "PHP" ]
2
PHP
ivang7/apache_mod_rewrite_cookie_check_redirect
46353a9783c3827d54cd4aac699cafd3b2eeab0f
b8c1e608bc130d7de7f09d80146547edc87187f7
refs/heads/master
<file_sep># script rapido para mover archivos en grupos a folders import os import shutil from os import listdir from os.path import isfile, join mypath = "C:\\Dev\\py\\filespoc" f = [] folderNum = 1 fileNumber = 0 every = 25 fotosSubFolder = "imagesNo" currentFolder = fotosSubFolder + str(folderNum) newFolder = os.path.join(mypath, fotosSubFolder + str(folderNum)) os.mkdir(newFolder) currentFolder = newFolder onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] for file in onlyfiles: fileNumber = fileNumber + 1 if (fileNumber >= every): fileNumber = 1 folderNum = folderNum + 1 newFolder = os.path.join(mypath, fotosSubFolder + str(folderNum)) os.mkdir(newFolder) currentFolder = newFolder shutil.move(mypath + "\\" + file, currentFolder + "\\" + file)
8245edfd7a2819bfcd3a11fff55ab40f20e5756b
[ "Python" ]
1
Python
hlzn/funnypy
47a730dc1be9e325c47e2166c53a6ce154cbda02
ddc6e52bbff346a2619ac9d39c79f09a8ea8d6a8
refs/heads/main
<file_sep>const Engine = Matter.Engine; const World = Matter.World; const Bodies = Matter.Bodies; const Constraint = Matter.Constraint; var engine, world; var canvas; var player, PlayerBase, playerArcher; var computer, computerBase; var playerArrow, computerArrow; var arrow; var baseImg1, baseImg2; var computerArcherImg, playerArcherImg; var arrowImg, playerImg; function preload(){ arrowImg = loadImage("assets/arrow.png"); baseImg1 = loadImage("assets/base1.png"); baseImg2 = loadImage("assets/base2.png"); playerImg = loadImage("assets/player.png"); computerArcherImg = loadImage("assets/computerArcher.png"); playerArcherImg = loadImage("assets/playerArcher.png"); } function setup() { canvas = createCanvas(windowWidth, windowHeight); engine = Engine.create(); world = engine.world; PlayerBase = new PlayerBase(300, random(450, height - 300), 180, 150); player = new player(285, PlayerBase.body.position.y - 153, 50, 180); //Create Player Archer Object playerArcher = new PlayerArcher(400,500,height-300, 200, 170); computerBase = new computerBase( width - 300, random(450, height - 300), 180, 150 ); computer = new Computer( width - 280, computerBase.body.position.y - 153, 50, 180 ); computerArcher = new ComputerArcher( width - 340, computerBase.body.position.y - 180, 120, 120 ); //Create an arrow Object } function draw() { background(180); Engine.update(engine); // Title fill("#FFFF"); textAlign("center"); textSize(40); text("<NAME>", width / 2, 100); playerBase.display(); player.display(); playerArcher.display(); computerBase.display(); computer.display(); //Display arrow(); playerArrow.display() //if Space (32) key is pressed call shoot function of playerArrow if(keyCode === 32){ //Call shoot() function and pass angle of playerArcher if(move ==="UP" && computerArcher.body.angle<1.77){ angleValue= 0.1 }else{ angleValue= -0.1 } if(move === "DOWN" && computerArcher.body.angle > 1.47){ angleValue = -0.1; }else{ angleValue= 0.1; } } }
b27dc1aad1bae4e8aa8efc8ab236e62159b6b2df
[ "JavaScript" ]
1
JavaScript
Godbless1994/archery-project-2
8446f2be1a61b4de74a3ac9ee463499882880cf9
057fe8c4352c819982b7439e585d7dcf07a52fd5
refs/heads/master
<file_sep> import React from 'react'; import { Link } from 'react-router-dom'; import PubSub from 'pubsub-js'; import Progress from '../components/progress'; import Background from '../components/background'; import './player.less'; let duration = null; let model = ['once', 'cycle', 'random']; class Player extends React.Component{ constructor(props) { super(props); this.state = { progress: 0, leftTime: 0, isPlay: true, volume: 0 }; } componentWillReceiveProps(nextProps) { console.log(nextProps) if(nextProps !== this.props){ alert(1); return false; } return true; } componentDidMount() { $('#player').bind($.jPlayer.event.timeupdate, (e) => { duration = e.jPlayer.status.duration; this.setState({ progress: e.jPlayer.status.currentPercentAbsolute, leftTime: this.formatTime(duration * (1 - e.jPlayer.status.currentPercentAbsolute / 100)), volume: e.jPlayer.options.volume * 100 }); }); } componentWillUnmount() { $("#player").unbind($.jPlayer.event.timeupdate); } progressChangeHandler(progress) { let state = (this.state.isPlay) ? 'play' : 'pause'; $("#player").jPlayer(state, duration * progress); } volumeChangeHandler(progress) { $("#player").jPlayer('volume', progress); this.setState({ volume: progress * 100 }) } play() { let state = (this.state.isPlay) ? 'pause' : 'play'; $("#player").jPlayer(state); this.setState({ isPlay: !this.state.isPlay }) } playPrev() { PubSub.publish("PREV"); } playNext() { PubSub.publish("NEXT"); } formatTime(time) { time = Math.floor(time); let m = Math.floor(time / 60); let s = Math.floor(time % 60); m = (m < 10) ? `0${m}` : m; s = (s < 10) ? `0${s}` : s; return `${m}:${s}`; } changePlayModel() { let index = model.indexOf(this.props.model); PubSub.publish("CHANGE_PLAY_MODEL", model[(index + 1) % model.length]); } render() { return ( <div> <Background bg={this.props.currentMusicItem.cover}/> <div className="player-page"> <div className='player-page'> <h1 className='caption'><Link to="/list">我的私人音乐坊</Link></h1> <div className="mt20 row"> <div className="controll-wrapper"> <h2 className="music-title">{this.props.currentMusicItem.title}</h2> <h3 className="music-artist mt10">{this.props.currentMusicItem.artist}</h3> <div className="row mt20"> <div className="volume-container"> <i className="icon-volume rt" style={{top:5,left:-5}} /> <div className="volume-wrapper"> <Progress progress={this.state.volume} barColor="red" onProgressChange={this.volumeChangeHandler.bind(this)} /> </div> </div> </div> <div style={{height:10,lineHeight:'10px'}}> <Progress progress={this.state.progress} onProgressChange={this.progressChangeHandler.bind(this)} /> <div className="left-time -col-auto">{this.state.leftTime} s</div> </div> <div className="mt35 row"> <div> <i className="icon prev" onClick={this.playPrev} /> <i className={`icon ml20 ${this.state.isPlay ? 'pause':'play'}`} onClick={this.play.bind(this)} /> <i className="icon next ml20" onClick={this.playNext} /> </div> <div className="-col-auto"> <i className={`icon repeat-${this.props.model}`} onClick={this.changePlayModel.bind(this)} /> </div> </div> </div> <div className='-col-auto cover' > <img className={`${this.state.isPlay ? '':'pause'}`} src={this.props.currentMusicItem.cover} alt={this.props.currentMusicItem.title}/> </div> </div> </div> </div> </div> ); } } Player.defaultProps = { model: 'cycle' }; export default Player;<file_sep> import React from 'react'; import {HashRouter as Router,Route} from 'react-router-dom'; import PubSub from 'pubsub-js'; import Header from './components/header'; import Player from './page/player'; import MusicList from './page/musiclist'; import { MUSIC_LIST } from './config/musiclist'; class Root extends React.Component{ constructor(props) { super(props); this.state = { musicList: MUSIC_LIST, currentMusicItem: MUSIC_LIST[0], model: 'cycle' } } playMusic(musicItem, state) { let _state = state ? state : "play"; $("#player").jPlayer('setMedia', { mp3: musicItem.file }).jPlayer(_state); } playNext(type) { let musicListLen = this.state.musicList.length; let currentIndex = this.getCurrentIndex(this.state.currentMusicItem); let newIndex = null; if(type == 'prev'){ switch (this.state.model){ case 'random': newIndex = Math.floor(Math.random() * musicListLen); break; case 'once': case 'cycle': default: newIndex = (currentIndex - 1 + musicListLen) % musicListLen; break; } }else if(type == 'next'){ switch (this.state.model){ case 'random': newIndex = Math.floor(Math.random() * musicListLen); break; case 'once': case 'cycle': default: newIndex = (currentIndex + 1) % musicListLen; break; } }else { switch (this.state.model){ case 'once': newIndex = currentIndex; break; case 'cycle': newIndex = (currentIndex + 1) % musicListLen; break; case 'random': newIndex = Math.floor(Math.random() * musicListLen); break; default: newIndex = (currentIndex + 1) % musicListLen; break; } } this.playMusic(this.state.musicList[newIndex]); this.setState({ currentMusicItem: this.state.musicList[newIndex] }); } getCurrentIndex(currentItem) { return this.state.musicList.indexOf(currentItem); } componentDidMount() { $('#player').jPlayer({ supplied: 'mp3', wmode: 'window', volume: 0.1 // 初始音量设置 }).bind($.jPlayer.event.ended, (e) => { this.playNext(); }); this.playMusic(this.state.currentMusicItem); PubSub.subscribe("PLAY", (msg, musicItem) => { this.setState({ currentMusicItem: musicItem }); this.playMusic(musicItem); }); PubSub.subscribe("DELETE", (msg, musicItem) => { if(musicItem == this.state.currentMusicItem){ this.playNext(); } this.setState({ musicList: this.state.musicList.filter(item => { return item !== musicItem; }) }); }); PubSub.subscribe("PREV", () => { this.playNext("prev"); }); PubSub.subscribe("NEXT", () => { this.playNext("next"); }); PubSub.subscribe("CHANGE_PLAY_MODEL", (msg, model) => { this.setState({ model: model }) }); } componentWillUnmount() { PubSub.unsubscribe("PLAY"); PubSub.unsubscribe("DELETE"); PubSub.unsubscribe("PREV"); PubSub.unsubscribe("NEXT"); PubSub.unsubscribe("CHANGE_PLAY_MODEL"); $("#player").unbind($.jPlayer.event.ended); } render() { const Home = () => ( <Player currentMusicItem={this.state.currentMusicItem} model={this.state.model} /> ); const List = () => ( <MusicList currentMusicItem={this.state.currentMusicItem} musiclist={this.state.musicList} /> ); return ( <Router> <div> <Header/> <Route exact path="/" component={Home}/> <Route path="/list" component={List}/> </div> </Router> ); } } export default Root;<file_sep># xiaoGuaishow.github.io
4c9a4efbbf1015f55542c13122f30db15af11d60
[ "JavaScript", "Markdown" ]
3
JavaScript
XiaoGuaiShow/xiaoGuaishow.github.io
11c4932dbc35722fc5a01c64892fa58a4788ee97
c6595c0f2e1c5acaabc27a8418170783f0d888f6
refs/heads/master
<file_sep># Redux Proxy Selectors [![Build Status](https://travis-ci.org/luwes/redux-proxy-selectors.svg?branch=master)](https://travis-ci.org/luwes/redux-proxy-selectors) [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier) Redux enhancer to access selectors directly from state as getters. ## Install ``` npm i --save redux-proxy-selectors ``` ## API `createProxySelectors(selectors)` **selectors** A single map containing all the selectors with a similar shape as your reducer. ## Usage ```js const store = createStore(reducer, createProxySelectors(selectors)) ``` <file_sep>export function createProxySelectors(selectors = {}) { const map = generateSelectorsMap(selectors) return createStore => (...args) => { const store = createStore(...args) let cachedState = getState() let oldState function dispatch(action) { oldState = cachedState cachedState = null return store.dispatch(action) } function getState() { if (cachedState) { return cachedState } cachedState = createSelectors(oldState, store.getState(), map, store) return cachedState } return { ...store, dispatch, getState } } } function createSelectors(oldState, newState, map, store) { for (const key in map) { const value = map[key] if (typeof value === 'function') { defineSelector(newState, key, value, store) } else if (typeof value === 'object') { const oldSlice = get(oldState, key) const newSlice = get(newState, key) // If the slice didn't get updated the defined props are still there. if (oldSlice !== newSlice) { for (const method in value) { defineSelector(newSlice, method, value[method], store) } } } } return newState } function defineSelector(target, property, selector, store) { if (!Object.getOwnPropertyDescriptor(target, property)) { Object.defineProperty(target, property, { get: () => selector(store.getState()) }) } } function generateSelectorsMap(obj, keys = []) { return Object.keys(obj).reduce((acc, key) => { if (typeof obj[key] === 'function' && key !== 'default') { const path = keys.join('.') if (path) { const pathObj = acc[path] || {} pathObj[key] = obj[key] return Object.assign(acc, { [path]: pathObj }) } return Object.assign(acc, { [key]: obj[key] }) } if (typeof obj[key] === 'object') { return Object.assign( acc, generateSelectorsMap(obj[key], keys.concat(key)) ) } return acc }, {}) } function get(obj, path, defaultValue) { if (typeof obj === 'undefined') { return defaultValue } const keys = path.split('.') for (let i = 0; i < keys.length; i++) { if (typeof obj === 'undefined') { return defaultValue } obj = obj[keys[i]] } return obj[path] || obj } <file_sep>{ "name": "redux-proxy-selectors", "version": "1.0.0", "description": "Redux enhancer to access selectors directly from state as getters.", "main": "lib/redux-proxy-selectors.js", "module": "es/redux-proxy-selectors.js", "scripts": { "clean": "rimraf lib dist es coverage", "format": "prettier --write '{src,test}/**/*.js'", "format:check": "prettier --list-different '{src,test}/**/*.js'", "lint": "eslint src test build", "pretest": "npm run build:commonjs", "test": "cross-env BABEL_ENV=commonjs jest", "test:watch": "npm test -- --watch", "test:cov": "npm test -- --coverage", "build:commonjs": "cross-env NODE_ENV=cjs rollup -c -o lib/redux-proxy-selectors.js", "build:es": "cross-env BABEL_ENV=es NODE_ENV=es rollup -c -o es/redux-proxy-selectors.js", "build:umd": "cross-env BABEL_ENV=es NODE_ENV=development rollup -c -o dist/redux-proxy-selectors.js", "build:umd:min": "cross-env BABEL_ENV=es NODE_ENV=production rollup -c -o dist/redux-proxy-selectors.min.js", "build": "npm run build:commonjs && npm run build:es && npm run build:umd && npm run build:umd:min", "prepare": "npm run clean && npm run format:check && npm run lint && npm test && npm run build" }, "repository": "https://github.com/luwes/redux-proxy-selectors", "author": "<NAME> <<EMAIL>> (https://github.com/luwes)", "license": "MIT", "devDependencies": { "@babel/core": "^7.0.0-beta.31", "@babel/preset-env": "^7.0.0-beta.31", "babel-7-jest": "^21.3.1", "babel-eslint": "^7.2.3", "cross-env": "^5.1.3", "eslint": "^4.14.0", "eslint-config-react-app": "^2.0.1", "eslint-plugin-flowtype": "^2.39.1", "eslint-plugin-import": "^2.2.0", "eslint-plugin-jsx-a11y": "^5.1.1", "eslint-plugin-react": "^7.4.0", "jest": "^21.2.1", "lodash": "^4.17.4", "prettier": "1.9.2", "redux": "^3.7.2", "rimraf": "^2.6.2", "rollup": "^0.52.2", "rollup-plugin-babel": "^4.0.0-beta", "rollup-plugin-node-resolve": "^3.0.0", "rollup-plugin-replace": "^2.0.0", "rollup-plugin-uglify": "^2.0.1", "uglify-js": "^3.2.2" }, "jest": { "testRegex": "(/test/.*\\.spec.js)$", "transform": { ".js": "babel-7-jest" } } }
1d4c7ba5e385c37c50f1c0dec4a8eb664916d96b
[ "Markdown", "JSON", "JavaScript" ]
3
Markdown
sgml/redux-proxy-selectors
783e29ac5addc4d8a1474324445aca1e20c3ddd9
a5668c5adea8b797a4540c7688b45f17031889cb
refs/heads/master
<repo_name>Torsi007/ksno3<file_sep>/ksno3/src/java/ksno/dao/hibernate/ArticleDaoImpl.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.dao.hibernate; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import ksno.dao.ArticleDao; import ksno.model.Article; import ksno.model.Category; import ksno.util.HibernateUtil; import org.hibernate.Query; import org.hibernate.Session; /** * * @author halsnehauge */ public class ArticleDaoImpl implements ArticleDao { private Logger getLogService(){ return Logger.getLogger(ArticleDaoImpl.class.getName()); } public Article getArticle(Long id) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); //session.beginTransaction(); Article article = (Article)session.get(Article.class,id); return article; } public Article getArticle(String prettyPrintId) { Article toReturn = null; try{ Query q = null; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); q=session.createQuery("from Article a where a.prettyPrintId = :ppid"); q.setParameter("ppid",prettyPrintId); toReturn = (Article) q.list().get(0); }catch(Exception e){ getLogService().log(Level.SEVERE,"Not able to find article with pretty print id " + prettyPrintId + ". Technical error message: " + e.getMessage()); } return toReturn; } public Long newArticle(Article article){ Session session = HibernateUtil.getSessionFactory().getCurrentSession(); //session.beginTransaction(); Long l; try{ l = (Long)session.save(article); }finally{ //session.getTransaction().commit(); //session.close(); } return l; } public void updateArticle(Article article) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); //session.beginTransaction(); try{ session.saveOrUpdate(article); }catch(Exception e){ session.merge(article); }finally{ //session.getTransaction().commit(); //session.close(); } } public void deleteArticle(Article article) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); //session.beginTransaction(); try{ session.delete(article); }finally{ //session.getTransaction().commit(); //session.close(); } } public List<Article> getArticles() { Query q = null; List returnVal = null; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); //session.beginTransaction(); q=session.createQuery("from Article a order by a.createdDate desc"); returnVal = q.list(); return returnVal; } public Category getCategory(String name){ Query q = null; List returnVal = null; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); //session.beginTransaction(); q=session.createQuery("from Category ac where ac.name = :pun"); q.setParameter("pun",name); returnVal = q.list(); return (Category)returnVal.get(0); } public List<Category> getCategories() { Query q = null; List returnVal = null; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); //session.beginTransaction(); q=session.createQuery("from Category a order by a.name desc"); returnVal = q.list(); return returnVal; } public Category getCategory(Long id) { Query q = null; List returnVal = null; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); //session.beginTransaction(); q=session.createQuery("from Category ac where ac.id = :pun"); q.setParameter("pun",id); returnVal = q.list(); return (Category)returnVal.get(0); } public List<Article> getVisibleArticles() { Query q = null; List<Article> returnVal = null; try{ Session session = HibernateUtil.getSessionFactory().getCurrentSession(); //session.beginTransaction(); q=session.createQuery("from Article a where a.visible = '1' order by a.createdDate desc"); returnVal = q.list();} catch(Exception ex){ String s = ex.getMessage(); } return returnVal; } } <file_sep>/ksno3/src/java/ksno/util/ParticipationGroupComparator.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.util; import java.util.Comparator; import ksno.model.Participation; /** * * @author HalsneHauge */ public class ParticipationGroupComparator implements Comparator<Participation> { public int compare(Participation o1, Participation o2) { return o1.getWorkGroup().compareTo(o2.getWorkGroup()); } } <file_sep>/ksno3/src/java/ksno/ui/jsf/backing/CourseParticipantsMaintain.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.backing; import java.util.ArrayList; import java.util.Calendar; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.component.UIData; import javax.faces.model.SelectItem; import ksno.model.Event; import ksno.model.Instruction; import ksno.model.Instructor; import ksno.model.Participation; import ksno.model.Person; import ksno.service.EventService; import ksno.service.ParticipationService; import ksno.service.PersonService; import ksno.util.JSFUtil; import org.apache.myfaces.component.html.ext.HtmlOutputText; import org.apache.myfaces.component.html.ext.HtmlSelectOneMenu; /** * * @author tor.hauge */ public class CourseParticipantsMaintain { private UIData dataConfirmedParticipants; private UIData dataUnconfirmedParticipants; private HtmlOutputText errorMsg; private EventService eventService; private PersonService personService; private ParticipationService participationService; private HtmlSelectOneMenu eventSelect; private SelectItem[] eventInstructors; private SelectItem[] eventSelectItems; private SelectItem[] workGroupSelectItems; // <editor-fold defaultstate="collapsed" desc="Getters and setters"> public HtmlSelectOneMenu getEventSelect() { return eventSelect; } public void setEventSelect(HtmlSelectOneMenu eventSelect) { this.eventSelect = eventSelect; } private Logger getLogService() { return Logger.getLogger(this.getClass().getName()); } public PersonService getPersonService() { return personService; } public void setPersonService(PersonService personService) { this.personService = personService; } public ParticipationService getParticipationService() { return participationService; } public void setParticipationService(ParticipationService participationService) { this.participationService = participationService; } public EventService getEventService() { return eventService; } public void setEventService(EventService eventService) { this.eventService = eventService; } public UIData getDataConfirmedParticipants() { return dataConfirmedParticipants; } public void setDataConfirmedParticipants(UIData dataConfirmedParticipants) { this.dataConfirmedParticipants = dataConfirmedParticipants; } public UIData getDataUnconfirmedParticipants() { return dataUnconfirmedParticipants; } public void setDataUnconfirmedParticipants(UIData dataUnconfirmedParticipants) { this.dataUnconfirmedParticipants = dataUnconfirmedParticipants; } public HtmlOutputText getErrorMsg() { return errorMsg; } public void setErrorMsg(HtmlOutputText errorMsg) { this.errorMsg = errorMsg; } // </editor-fold> public SelectItem[] getWorkGroupSelectItems() { if (workGroupSelectItems == null || workGroupSelectItems.length == 0) { workGroupSelectItems = new SelectItem[getEventInstructors().length * 4]; int i = 0; for (int j = 0; j < getEventInstructors().length; j++) { SelectItem item = getEventInstructors()[j]; i = j * 4; int index = i; int print = 1; workGroupSelectItems[index] = new SelectItem(item.getLabel() + " " + print, item.getLabel() + " " + print); index++; print++; workGroupSelectItems[index] = new SelectItem(item.getLabel() + " " + print, item.getLabel() + " " + print); index++; print++; workGroupSelectItems[index] = new SelectItem(item.getLabel() + " " + print, item.getLabel() + " " + print); index++; print++; workGroupSelectItems[index] = new SelectItem(item.getLabel() + " " + print, item.getLabel() + " " + print); } } return workGroupSelectItems; } public SelectItem[] getEventInstructors(){ if(eventInstructors == null || eventInstructors.length == 0){ Event eventToModify = (Event) JSFUtil.getSessionMap().get(JSFUtil.sessionBeanEventModify); eventInstructors = new SelectItem[eventToModify.getInstructors().length + 1]; for(int i = 0; i< eventToModify.getInstructors().length; i++ ){ Instructor instructor = eventToModify.getInstructors()[i]; eventInstructors[i] = new SelectItem(instructor,instructor.getLabel()); } eventInstructors[eventToModify.getInstructors().length] = new SelectItem(eventToModify.getInstructor(),eventToModify.getInstructor().getLabel()); } return eventInstructors; } public SelectItem[] getEventSelectItems(){ if(eventSelectItems == null || eventSelectItems.length == 0){ List events = eventService.getEvents(); Event eventToModify = (Event) JSFUtil.getSessionMap().get(JSFUtil.sessionBeanEventModify); SelectItem[] arr = JSFUtil.toSelectItemArray(events, true); List<SelectItem> result = new ArrayList<SelectItem>(); for(SelectItem item : arr){ if(Long.parseLong(item.getValue().toString()) != eventToModify.getId()){ result.add(item); } } SelectItem[] arr2 = new SelectItem[result.size()]; for(int i = 0; i<arr2.length; i++){ arr2[i] = result.get(i); } eventSelectItems = arr2; } return eventSelectItems; } public String unConfirmedParticipantDelete() { String returnVal = "sucess"; try { Participation participation = (Participation) this.getDataUnconfirmedParticipants().getRowData(); Event event = (Event) JSFUtil.getSessionMap().get(JSFUtil.sessionBeanEventModify); if (event.getParticipations().contains(participation)) { event.getParticipations().remove(participation); eventService.updateEvent(event); participationService.deleteParticipation(participation); } } catch (Exception e) { getLogService().log(Level.SEVERE, "Unable to delete article", e); errorMsg.setRendered(true); errorMsg.setValue("Operasjonen feilet, forsøk på nytt. Detaljert feilmelding: " + e.getMessage()); returnVal = "no"; } return returnVal; } public String confirmParticipants() { String returnVal = "sucess"; errorMsg.setRendered(false); try { Event event = (Event) JSFUtil.getSessionMap().get(JSFUtil.sessionBeanEventModify); Iterator iterParticipations = event.getParticipations().iterator(); while (iterParticipations.hasNext()) { Participation particiption = (Participation) iterParticipations.next(); if(particiption.isuIChecked()){ particiption.setConfirmed(true); } particiption.setuIChecked(false); } eventService.updateEvent(event); } catch (Exception e) { getLogService().log(Level.SEVERE, "Unable to confirm participations", e); errorMsg.setRendered(true); errorMsg.setValue("Operasjonen feilet, forsøk på nytt. Detaljert feilmelding: " + e.getMessage()); returnVal = "no"; } return returnVal; } public String unConfirmParticipants() { String returnVal = "sucess"; try { Event event = (Event) JSFUtil.getSessionMap().get(JSFUtil.sessionBeanEventModify); Iterator iterParticipations = event.getParticipations().iterator(); while (iterParticipations.hasNext()) { Participation particiption = (Participation) iterParticipations.next(); if(particiption.isuIChecked()){ particiption.setConfirmed(false); } particiption.setuIChecked(false); } eventService.updateEvent(event); } catch (Exception e) { errorMsg.setRendered(true); getLogService().log(Level.SEVERE, "Unable to unconfirm participations", e); errorMsg.setValue("Operasjonen feilet, forsøk på nytt. Detaljert feilmelding: " + e.getMessage()); returnVal = "no"; } return returnVal; } public String deleteParticipants() { String returnVal = "sucess"; try { Event event = (Event) JSFUtil.getSessionMap().get(JSFUtil.sessionBeanEventModify); Iterator iterParticipations = event.getParticipations().iterator(); HashSet<Participation> participationToRemove = new HashSet<Participation>(); while (iterParticipations.hasNext()) { Participation particiption = (Participation) iterParticipations.next(); if(particiption.isuIChecked()){ //event.removeParticipation(particiption); participationToRemove.add(particiption); } } event.removeParticipations(participationToRemove); eventService.updateEvent(event); } catch (Exception e) { getLogService().log(Level.SEVERE, "Unable to unconfirm participations", e); errorMsg.setRendered(true); errorMsg.setValue("Operasjonen feilet, forsøk på nytt. Detaljert feilmelding: " + e.getMessage()); returnVal = "no"; } return returnVal; } public String moveParticipantsToCourse(){ getLogService().log(Level.INFO, "Start moveParticipantsToCourse"); String returnVal = "sucess"; try { Event event = (Event) JSFUtil.getSessionMap().get(JSFUtil.sessionBeanEventModify); Iterator iterParticipations = event.getParticipations().iterator(); HashSet<Participation> participations = new HashSet<Participation>(); getLogService().log(Level.INFO, "Found the following particpants to move from event " + event.getStartDate().toString() + ":"); while (iterParticipations.hasNext()) { Participation particiption = (Participation) iterParticipations.next(); if(particiption.isuIChecked()){ participations.add(particiption); getLogService().log(Level.INFO, particiption.getParticipant().getFirstName() + " " + particiption.getParticipant().getLastName()); } } Event moveToEvent = getEventService().getEvent(Long.parseLong(getEventSelect().getValue().toString())); if(moveToEvent != null){ getLogService().log(Level.INFO, "To event " + moveToEvent.getStartDate().toString() + ":"); moveToEvent.addParticipations(participations); eventService.updateEvent(moveToEvent); }else{ getLogService().log(Level.WARNING, "Unable to move participants, seems like the event to move participants to is not selected"); errorMsg.setRendered(true); errorMsg.setValue("Operasjonen feilet, det ser ut til at du ikke har valgt kurs for flytting av deltagere"); returnVal = "no"; } getEventSelect().setValue(null); } catch (Exception e) { getLogService().log(Level.SEVERE, "Unable to move participations", e); errorMsg.setRendered(true); errorMsg.setValue("Operasjonen feilet, forsøk på nytt. Detaljert feilmelding: " + e.getMessage()); returnVal = "no"; } return returnVal; } public String participantUnknownAdd() { String returnVal = "sucess"; try{ Event event = (Event)JSFUtil.getSessionMap().get(JSFUtil.sessionBeanEventModify); Set participants = event.getParticipations(); Iterator iter = participants.iterator(); int maxDummy = 0; while(iter.hasNext()){ Participation participant = (Participation)iter.next(); String userName = participant.getParticipant().getUserName(); if(userName.startsWith("dummy") && userName.endsWith("kitesurfing.no")){ String num = userName.split("@")[0].replaceAll("dummy", ""); maxDummy = Math.max(Integer.parseInt(num), maxDummy); } } maxDummy++; String dummyUserName = "dummy" + Integer.toString(maxDummy) + "@kitesurfing.no"; if(maxDummy > 0 && maxDummy < 11){ Person dummy = personService.getPerson(dummyUserName); Participation participation = new Participation(); participation.setOnWaitList(false); participation.setEvent(event); participation.setConfirmed(true); event.getParticipations().add(participation); dummy.addParticipation(participation); }else{ errorMsg.setRendered(true); errorMsg.setValue("Operasjonen feilet, da det ikke er definert noen person med brukernavn: " + dummyUserName); returnVal = "no"; } eventService.updateEvent(event); }catch(Exception e){ errorMsg.setRendered(true); getLogService().log(Level.SEVERE,"Unable to delete article", e); errorMsg.setValue("Operasjonen feilet, forsøk på nytt. Detaljert feilmelding: " + e.getMessage()); returnVal = "no"; } return returnVal; } public String save(){ String returnVal = "success"; try{ Event event = (Event)JSFUtil.getSessionMap().get(JSFUtil.sessionBeanEventModify); eventService.updateEvent(event); }catch(Exception e){ errorMsg.setRendered(true); getLogService().log(Level.SEVERE,"Unable to update event", e); returnVal = "no"; } return returnVal; } public String close(){ String returnVal = "success"; try{ JSFUtil.getSessionMap().remove(JSFUtil.sessionBeanEventModify); }catch(Exception e){ errorMsg.setRendered(true); getLogService().log(Level.SEVERE,"Unable to update event", e); returnVal = "no"; } return returnVal; } } <file_sep>/ksno3/src/java/ksno/ui/jsf/backing/TextsMaintain.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.backing; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.component.UIData; import ksno.model.Email; import ksno.model.Text; import ksno.service.TextService; import ksno.util.JSFUtil; import org.apache.myfaces.component.html.ext.HtmlInputText; import org.apache.myfaces.component.html.ext.HtmlOutputText; /** * * @author tor.hauge */ public class TextsMaintain { TextService textService; private HtmlInputText name; private UIData data; private HtmlOutputText errorMsg; public UIData getData() { return data; } public void setData(UIData data) { this.data = data; } public HtmlInputText getName() { return name; } public void setName(HtmlInputText name) { this.name = name; } public TextService getTextService() { return textService; } public void setTextService(TextService textService) { this.textService = textService; } public HtmlOutputText getErrorMsg() { return errorMsg; } public void setErrorMsg(HtmlOutputText errorMsg) { this.errorMsg = errorMsg; } private Logger getLogService(){ return Logger.getLogger(this.getClass().getName()); } public List getTexts(){ return textService.getTexts(); } public String textDelete(){ String returnVal = "sucess"; try{ Text text = (Text)this.getData().getRowData(); textService.deleteText(text); }catch(Exception e){ getLogService().log(Level.SEVERE,"Unable to delete Text", e); errorMsg.setValue("Operasjonen feilet, forsøk på nytt. Detaljert feilmelding: " + e.getMessage()); returnVal = "no"; } return returnVal; } public String textUpdate(){ String returnVal = "textUpdate"; try{ Text textModify = (Text)this.getData().getRowData(); if(textModify instanceof Email){ returnVal = "emailUpdate"; } JSFUtil.getSessionMap().put(JSFUtil.sessionBeanTextModify, textModify); }catch(Exception e){ getLogService().log(Level.SEVERE,"Unable to select Text", e); errorMsg.setValue("Operasjonen feilet, forsøk på nytt. Detaljert feilmelding: " + e.getMessage()); returnVal = "no"; } return returnVal; } } <file_sep>/ksno3/src/java/ksno/util/YoutubeClient.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.util; import com.google.gdata.client.youtube.*; //import com.google.gdata.data.media.*; //import com.google.gdata.data.media.mediarss.*; import com.google.gdata.data.youtube.*; import com.google.gdata.util.AuthenticationException; import com.google.gdata.util.ServiceException; import java.io.IOException; import com.google.gdata.util.common.xml.*; import com.google.gdata.data.extensions.Email; import com.google.gdata.data.media.mediarss.MediaCategory; import com.google.gdata.data.media.mediarss.MediaDescription; import com.google.gdata.data.media.mediarss.MediaKeywords; import com.google.gdata.data.media.mediarss.MediaTitle; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.component.UIData; import ksno.model.Video; import ksno.service.VideoService; import ksno.util.JSFUtil; import javax.faces.context.ExternalContext; import ksno.model.Video; public class YoutubeClient { /** * Constructs a new un-authenticated client. */ public YoutubeClient() { ExternalContext context = JSFUtil.getServletContext(); String applicationName = context.getInitParameter("applicationName"); String userName = context.getInitParameter("youtube.userName"); String passWord = context.getInitParameter("youtube.passWord"); String developerKey = context.getInitParameter("youtube.devKey"); this.baseUrl = context.getInitParameter("youtube.baseUrl"); try{ service = new YouTubeService(applicationName,"<KEY>tgLJkYkr<KEY>"); service.setUserCredentials(userName, passWord); } catch (AuthenticationException e) { throw new IllegalArgumentException("Illegal username/password combination. " + e.getMessage()); } catch (Exception e) { String msg = e.getMessage(); } } public String getCurrentState(Video video) { String state = YoutubeClient.statePublished; getLogService().info("starting getCurrentState()"); try{ getLogService().info("attempting to open videoentry for video with id " + video.getYouTubeId()); VideoEntry entry = service.getEntry(new URL(video.getYouTubeId()), VideoEntry.class); if(entry.isDraft()){ getLogService().info("The video is a draft in state " + entry.getPublicationState().getState().toString()); state = entry.getPublicationState().getState().toString(); }else{ getLogService().info("The video is already published, who called me?"); } }catch(Exception ex){ getLogService().warning("Something failed, unable to get state, fallcack to " + YoutubeClient.stateProcessing + ex.getMessage()); state = YoutubeClient.stateProcessing; } return state; } private final String baseUrl; private YouTubeService service = null; public static final String statePublished = "PUBLISHED"; public static final String stateProcessing = "PROCESSING"; public static final String stateRejected = "REJECTED"; public static final String stateFailed = "FAILED"; private Logger getLogService() { return Logger.getLogger(YoutubeClient.class.getName()); } public YouTubeUploadUrlAndToken uploadVideo(Video video){ VideoEntry newEntry = new VideoEntry(); YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup(); mg.setTitle(new MediaTitle()); mg.getTitle().setPlainTextContent(video.getName()); mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, "Sports")); //mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, "Travel")); mg.setKeywords(new MediaKeywords()); mg.getKeywords().addKeyword("kitesurfing"); mg.getKeywords().addKeyword("norway"); mg.getKeywords().addKeyword("kite"); mg.getKeywords().addKeyword("kiteboarding"); mg.getKeywords().addKeyword("drageurfing"); mg.getKeywords().addKeyword("norge"); mg.getKeywords().addKeyword("drage"); mg.getKeywords().addKeyword("www.kitesurfing.no"); mg.setDescription(new MediaDescription()); mg.getDescription().setPlainTextContent(video.getDescription()); mg.setPrivate(false); mg.addCategory(new MediaCategory(YouTubeNamespace.DEVELOPER_TAG_SCHEME, "kitesurfingno")); mg.addCategory(new MediaCategory(YouTubeNamespace.DEVELOPER_TAG_SCHEME, "web")); //newEntry.setGeoCoordinates(new GeoRssWhere(37.0, -122.0)); URL uploadUrl = null; try { uploadUrl = new URL("http://gdata.youtube.com/action/GetUploadToken"); } catch (MalformedURLException ex) { Logger.getLogger(YoutubeClient.class.getName()).log(Level.SEVERE, null, ex); } FormUploadToken token = null; try { token = service.getFormUploadToken(uploadUrl, newEntry); } catch (ServiceException ex) { Logger.getLogger(YoutubeClient.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(YoutubeClient.class.getName()).log(Level.SEVERE, null, ex); } return new YouTubeUploadUrlAndToken(token.getUrl(), token.getToken()); } /** * Retrieves the videos for the given user. */ public List<VideoEntry> getVideos() throws IOException, ServiceException { VideoFeed videoFeed = getFeed(this.baseUrl, VideoFeed.class); List<VideoEntry> entries = videoFeed.getEntries(); return entries; } public VideoEntry getVideoEntry(String id) throws IOException, ServiceException{ String videoEntryUrl = "http://gdata.youtube.com/feeds/api/videos/" + id; getLogService().info("attempting to open videoentry on " + videoEntryUrl); return service.getEntry(new URL(videoEntryUrl), VideoEntry.class); } public VideoEntry getVideoEntryInProgress(String id) throws ServiceException, IOException{ String videoEntryUrl = "http://gdata.youtube.com/feeds/api/users/default/uploads/" + id; getLogService().info("attempting to open videoentry on " + videoEntryUrl); return service.getEntry(new URL(videoEntryUrl), VideoEntry.class); } public Video getVideoInProgress(String id) throws ServiceException, IOException{ String videoEntryUrl = "http://gdata.youtube.com/feeds/api/users/default/uploads/" + id; VideoEntry entry = service.getEntry(new URL(videoEntryUrl), VideoEntry.class); Video video = new Video(); video.setName(entry.getMediaGroup().getTitle().getPlainTextContent()); video.setDescription(entry.getMediaGroup().getDescription().getPlainTextContent()); video.setDuration(Util.prettyPrintTime(entry.getMediaGroup().getDuration())); //video.setUrl(entry.getHtmlLink().getHref()); video.setUrl(entry.getMediaGroup().getContents().get(0).getUrl()); //); video.setYouTubeId(entry.getId()); if(entry.isDraft()){ video.setState(entry.getPublicationState().getState().toString()); } video.setThumbnail(entry.getMediaGroup().getThumbnails().get(1).getUrl()); return video; } /** * Helper function to allow retrieval of a feed by string url, which will * create the URL object for you. Most of the Link objects have a string * href which must be converted into a URL by hand, this does the conversion. */ public <T extends VideoFeed> T getFeed(String feedHref, Class<T> feedClass) throws IOException, ServiceException { getLogService().info("Get Feed URL: " + feedHref); return service.getFeed(new URL(feedHref), feedClass); } public Long getDuration(Video video) { VideoEntry entry; Long toBeReturned = null; try { entry = service.getEntry(new URL(video.getYouTubeId()), VideoEntry.class); toBeReturned = entry.getMediaGroup().getDuration(); } catch (IOException ex) { Logger.getLogger(YoutubeClient.class.getName()).log(Level.SEVERE, null, ex); } catch (ServiceException ex) { Logger.getLogger(YoutubeClient.class.getName()).log(Level.SEVERE, null, ex); } return toBeReturned; } } <file_sep>/ksno3/src/java/ksno/ui/jsf/backing/Current.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.backing; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import ksno.model.Video; import ksno.service.PersonService; import ksno.service.ArticleService; import ksno.service.VideoService; import ksno.util.JSFUtil; /** * * @author halsnehauge */ public class Current { List persons; PersonService personService; ArticleService articleService; VideoService videoService; public String getContextPath(){ return JSFUtil.getRequest().getContextPath(); } public VideoService getVideoService() { return videoService; } public void setVideoService(VideoService videoService) { this.videoService = videoService; } public String getArticleUrl() { return "Article.jsp"; } public String getArticle1Url() { return "Article1.jsp"; } public ArticleService getArticleService() { return articleService; } public void setArticleService(ArticleService articleService) { this.articleService = articleService; } public List<ksno.model.Article> getArticles() { return articleService.getVisibleArticles(); } public List getFirstTwoArticles() { List<ksno.model.Article> visibleArticles = this.getArticles(); Iterator <ksno.model.Article> articleIterator = visibleArticles.iterator(); List<ksno.model.Article> returnList = new LinkedList<ksno.model.Article>(); while(articleIterator.hasNext() && returnList.size()<2){ ksno.model.Article article = articleIterator.next(); if(article.getFrontPagePosition().equals("default")){ returnList.add(article); } } return returnList; } public List getArticlesFromThreeToTen() { List<ksno.model.Article> visibleArticles = this.getArticles(); Iterator <ksno.model.Article> articleIterator = visibleArticles.iterator(); List<ksno.model.Article> returnList = new LinkedList<ksno.model.Article>(); int i = 0; while(articleIterator.hasNext()){ ksno.model.Article article = articleIterator.next(); if(article.getFrontPagePosition().equals("default")){ i++; if(i>2 && i<11){ returnList.add(article); } } } return returnList; } public List getFirstThreeVideos() { List<ksno.model.Video> visibleVideos = this.getVideoService().getPublishedVideos(); Iterator <ksno.model.Video> videoIterator = visibleVideos.iterator(); List<ksno.model.Video> returnList = new LinkedList<ksno.model.Video>(); while(videoIterator.hasNext() && returnList.size()<3){ ksno.model.Video video = videoIterator.next(); returnList.add(video); } return returnList; } public List getVideos() { return this.getVideoService().getPublishedVideos(); } static final Comparator<ksno.model.Article> ORDER_BY_CAT = new Comparator<ksno.model.Article>(){ public int compare(ksno.model.Article a1, ksno.model.Article a2){ return a2.getCategory().getName().compareTo(a1.getCategory().getName()); } }; public List<ksno.model.Article> getHeadlines(){ List<ksno.model.Article> visibleArticles = this.getArticles(); Collections.sort(visibleArticles, ORDER_BY_CAT); Iterator <ksno.model.Article> articleIterator = visibleArticles.iterator(); List<ksno.model.Article> headl = new LinkedList<ksno.model.Article>(); ksno.model.Article prevArticle = null; while(articleIterator.hasNext()){ ksno.model.Article article = articleIterator.next(); if(article.getFrontPagePosition().equals("top")){ if(prevArticle != null){ if(article.getCategory().equals(prevArticle.getCategory())){ article.setSameAsPrevCat(true); } }else{ article.setSameAsPrevCat(false); } headl.add(article); prevArticle = article; } } return headl; } public boolean isHaveArticles(){ List<Article> result = articleService.getArticles(); if(result != null && !result.isEmpty()){ return false; }else{ return true; } } // <editor-fold defaultstate="collapsed" desc=" UML Marker "> // #[regen=yes,id=DCE.65B316FE-0B9C-47D0-CDF0-4F463826DBA2] // </editor-fold> public PersonService getPersonService () { return null; } // <editor-fold defaultstate="collapsed" desc=" UML Marker "> // #[regen=yes,id=DCE.48605C27-C826-C69A-F815-926F42E1CA7C] // </editor-fold> public void setPersonService (PersonService personService) { } // <editor-fold defaultstate="collapsed" desc=" UML Marker "> // #[regen=yes,id=DCE.552E08F5-6B88-44FF-A984-CCBC2B9C6BEA] // </editor-fold> public List getPersons () { return null; } // <editor-fold defaultstate="collapsed" desc=" UML Marker "> // #[regen=yes,id=DCE.CEB8D580-C6A8-9418-7BFF-CFD154EF868F] // </editor-fold> public void setPersons (List persons) { } } <file_sep>/ksno3/src/java/ksno/ui/jsf/backing/ArticleCategoryMaintain.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.backing; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.component.UIData; import ksno.model.Category; import ksno.service.ArticleCategoryService; import org.apache.myfaces.component.html.ext.HtmlInputText; import org.apache.myfaces.component.html.ext.HtmlOutputText; /** * * @author tor.hauge */ public class ArticleCategoryMaintain { ArticleCategoryService articleCategoryService; private HtmlInputText name; private HtmlInputText description; private HtmlInputText newName; private HtmlInputText newDescription; private UIData data; private HtmlOutputText errorMsg; // <editor-fold defaultstate="collapsed" desc=" getters and setters"> public HtmlInputText getNewDescription() { return newDescription; } public void setNewDescription(HtmlInputText newDescription) { this.newDescription = newDescription; } public HtmlInputText getNewName() { return newName; } public void setNewName(HtmlInputText newName) { this.newName = newName; } public UIData getData() { return data; } public void setData(UIData data) { this.data = data; } public HtmlInputText getName() { return name; } public void setName(HtmlInputText name) { this.name = name; } public HtmlInputText getDescription() { return description; } public void setDescription(HtmlInputText description) { this.description = description; } public ArticleCategoryService getArticleCategoryService() { return articleCategoryService; } public void setArticleCategoryService(ArticleCategoryService articleCategoryService) { this.articleCategoryService = articleCategoryService; } public HtmlOutputText getErrorMsg() { return errorMsg; } public void setErrorMsg(HtmlOutputText errorMsg) { this.errorMsg = errorMsg; } private Logger getLogService(){ return Logger.getLogger(this.getClass().getName()); } // </editor-fold> public List getArticleCategorys(){ return articleCategoryService.getArticleCategorys(); } public String articleCategoryDelete(){ String returnVal = "sucess"; try{ Category category = (Category)this.getData().getRowData(); articleCategoryService.deleteArticleCategory(category); }catch(Exception e){ getLogService().log(Level.SEVERE,"Unable to delete article", e); errorMsg.setValue("Operasjonen feilet, forsøk på nytt. Detaljert feilmelding: " + e.getMessage()); returnVal = "no"; } return returnVal; } public String articleCategoryCreate(){ String returnVal = "success"; try{ Category category = new Category(); category.setName(getNewName().getValue().toString()); category.setDescription(getNewDescription().getValue().toString()); articleCategoryService.newArticleCategory(category); }catch(Exception e){ getLogService().log(Level.SEVERE,"Unable to create article", e); errorMsg.setValue("Artikkelen ble ikke lagret, forsøk på nytt. Detaljert feilmelding: " + e.getMessage()); returnVal = "no"; } return returnVal; } public String articleCategorysUpdate(){ String returnVal = "sucess"; try{ List articleCategorys = (List)getData().getValue(); for(int i = 0; i< articleCategorys.size(); i++){ Category category = (Category)articleCategorys.get(i); articleCategoryService.updateArticleCategory(category); } }catch(Exception e){ getLogService().log(Level.SEVERE,"Unable to update articles", e); errorMsg.setValue("Operasjonen feilet, forsøk på nytt. Detaljert feilmelding: " + e.getMessage()); returnVal = "no"; } return returnVal; } } <file_sep>/ksno3/src/java/ksno/service/ExperienceLevelServiceImpl.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.service; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import ksno.dao.ExperienceLevelDao; import ksno.model.ExperienceLevel; import ksno.util.JSFUtil; /** * * @author tor.hauge */ public class ExperienceLevelServiceImpl implements ExperienceLevelService { private ExperienceLevelDao experienceLevelDao; private Logger getLogService(){ return Logger.getLogger(ExperienceLevelServiceImpl.class.getName()); } public ExperienceLevelDao getExperienceLevelDao() { return experienceLevelDao; } public void setExperienceLevelDao(ExperienceLevelDao ExperienceLevelDao) { this.experienceLevelDao = ExperienceLevelDao; } public ExperienceLevel getExperienceLevel(Long id) { return experienceLevelDao.getExperienceLevel(id); } public Long newExperienceLevel(ExperienceLevel experienceLevel) { Class c = null; try { c = Class.forName("java.util.List"); } catch (ClassNotFoundException ex) { getLogService().log(Level.SEVERE, null, ex); } List<ExperienceLevel> experienceLevels = (List)JSFUtil.getValue("#{ApplicationBean1." + JSFUtil.appCacheExperienceLevels + "}", c); for(ExperienceLevel el: experienceLevels){ if(el.getRank() >= experienceLevel.getRank()){ el.setRank(el.getRank() +1); updateExperienceLevel(el); } } JSFUtil.clearApplicationCache(JSFUtil.appCacheExperienceLevels); return experienceLevelDao.newExperienceLevel(experienceLevel); } public void updateExperienceLevel(ExperienceLevel experienceLevel) { JSFUtil.clearApplicationCache(JSFUtil.appCacheExperienceLevels); experienceLevelDao.updateExperienceLevel(experienceLevel); } public void deleteExperienceLevel(ExperienceLevel experienceLevel) { Class c = null; try { c = Class.forName("java.util.List"); } catch (ClassNotFoundException ex) { getLogService().log(Level.SEVERE, null, ex); } List<ExperienceLevel> experienceLevels = (List)JSFUtil.getValue("#{ApplicationBean1." + JSFUtil.appCacheExperienceLevels + "}", c); for(ExperienceLevel el: experienceLevels){ if(el.getRank() > experienceLevel.getRank()){ el.setRank(el.getRank() -1); updateExperienceLevel(el); } } JSFUtil.clearApplicationCache(JSFUtil.appCacheExperienceLevels); experienceLevelDao.deleteExperienceLevel(experienceLevel); } public List<ExperienceLevel> getExperienceLevels() { Class c = null; try { c = Class.forName("java.util.List"); } catch (ClassNotFoundException ex) { getLogService().log(Level.SEVERE, null, ex); } List<ExperienceLevel> returnList = (List)JSFUtil.getValue("#{ApplicationBean1." + JSFUtil.appCacheExperienceLevels + "}", c); if(returnList == null){ returnList = experienceLevelDao.getExperienceLevels(); JSFUtil.setValue("#{ApplicationBean1." + JSFUtil.appCacheExperienceLevels + "}", returnList, c); } return returnList; } } <file_sep>/ksno3/src/java/ksno/dao/hibernate/WorkTaskDaoImpl.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.dao.hibernate; import java.util.List; import ksno.dao.WorkTaskDao; import ksno.model.WorkTask; import ksno.util.HibernateUtil; import org.hibernate.Query; import org.hibernate.Session; /** * * @author tor.hauge */ public class WorkTaskDaoImpl implements WorkTaskDao { public WorkTask getWorkTask(Long id) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); WorkTask task = (WorkTask)session.get(WorkTask.class,id); return task; } public Long newWorkTask(WorkTask task) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Long l = (Long)session.save(task); return l; } public void updateWorkTask(WorkTask task) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); try{ session.saveOrUpdate(task); }catch(Exception e){ session.merge(task); } } public void deleteWorkTask(WorkTask task) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.delete(task); } public List<WorkTask> getWorkTasks() { Query q = null; List returnVal = null; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); q=session.createQuery("from WorkTask c order by c.name desc"); returnVal = q.list(); return returnVal; } } <file_sep>/ksno3/src/java/ksno/service/WorkHoursService.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.service; import java.util.List; import ksno.model.Instructor; import ksno.model.WorkHours; /** * * @author tor.hauge */ public interface WorkHoursService { public WorkHours getWorkHours(Long id); public Long newWorkHours(WorkHours workHours); public void updateWorkHours(WorkHours workHours); public void deleteWorkHours(WorkHours workHours); public List<WorkHours> getWorkHoursList(); public List<WorkHours> getWorkHoursListByInstructor(Instructor instructor); } <file_sep>/ksno3/src/java/ksno/dao/hibernate/VideoDaoImpl.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.dao.hibernate; import java.util.List; import ksno.dao.VideoDao; import ksno.model.Video; import ksno.model.Category; import ksno.util.HibernateUtil; import org.hibernate.Session; import org.hibernate.Query; /** * * @author halsnehauge */ public class VideoDaoImpl implements VideoDao { public Long newVideo(Video video){ Session session = HibernateUtil.getSessionFactory().getCurrentSession(); //session.beginTransaction(); Long l; try{ l = (Long)session.save(video); }finally{ //session.getTransaction().commit(); //session.close(); } return l; } public Video getVideo(Long id) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); //session.beginTransaction(); Video Video = (Video)session.get(Video.class,id); return Video; } public void updateVideo(Video video) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); //session.beginTransaction(); try{ session.saveOrUpdate(video); }catch(Exception e){ session.merge(video); }finally{ //session.getTransaction().commit(); //session.close(); } } public void deleteVideo(Video video) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); //session.beginTransaction(); try{ session.delete(video); }finally{ //session.getTransaction().commit(); //session.close(); } } public List<Video> getVideos() { Query q = null; List returnVal = null; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); //session.beginTransaction(); q=session.createQuery("from Video a order by a.createdDate desc"); returnVal = q.list(); return returnVal; } } <file_sep>/ksno3/src/java/ksno/service/DocumentService.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.service; import java.io.InputStream; /** * * @author tor.hauge */ public interface DocumentService { public String uploadDocument(String path, String userName) throws Exception; } <file_sep>/ksno3/src/java/java/io/Serializable.java package java.io; // <editor-fold defaultstate="collapsed" desc=" UML Marker "> // #[regen=yes,id=DCE.F99B6A3B-DAFE-7501-D009-199019BBFF7B] // </editor-fold> public interface Serializable { } <file_sep>/ksno3/src/java/ksno/dao/ArticleCategoryDao.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.dao; import java.util.List; import ksno.model.Category; /** * * @author tor.hauge */ public interface ArticleCategoryDao { public Category getArticleCategory(Long id); public Long newArticleCategory(Category category); public void updateArticleCategory(Category category); public void deleteArticleCategory(Category category); public List<Category> getArticleCategorys(); } <file_sep>/ksno3/src/java/ksno/ui/jsf/backing/ArticleImageUpload.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.backing; import java.io.IOException; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import ksno.model.Article; import ksno.model.Image; import ksno.model.Person; import ksno.service.ArticleService; import ksno.service.ImageService; import ksno.service.PersonService; import ksno.util.ImageMeta; import ksno.util.JSFUtil; import org.apache.myfaces.component.html.ext.HtmlInputHidden; import org.apache.myfaces.component.html.ext.HtmlOutputText; import org.apache.myfaces.custom.fileupload.UploadedFile; /** * * @author halsnehauge */ public class ArticleImageUpload { private ArticleService articleService; private PersonService personService; private HtmlOutputText uploadFailedText; private HtmlOutputText upLoadImgResult; private UploadedFile upImg; private HtmlInputHidden renderHidden; public HtmlInputHidden getRenderHidden() { return renderHidden; } public void setRenderHidden(HtmlInputHidden renderHidden) { this.renderHidden = renderHidden; } ImageService imageService; public ImageService getImageService() { return imageService; } public void setImageService(ImageService imageService) { this.imageService = imageService; } public PersonService getPersonService() { return personService; } public void setPersonService(PersonService personService) { this.personService = personService; } public ArticleService getArticleService() { return articleService; } public void setArticleService(ArticleService articleService) { this.articleService = articleService; } public HtmlOutputText getUploadFailedText() { return uploadFailedText; } public void setUploadFailedText(HtmlOutputText uploadFailedText) { this.uploadFailedText = uploadFailedText; } public UploadedFile getUpImg() { return upImg; } public void setUpImg(UploadedFile upImg) { this.upImg = upImg; } public HtmlOutputText getUpLoadImgResult() { return upLoadImgResult; } public void setUpLoadImgResult(HtmlOutputText upLoadImgResult) { this.upLoadImgResult = upLoadImgResult; } } <file_sep>/ksno3/src/java/ksno/service/ArticleCategoryServiceImpl.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.service; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import ksno.dao.ArticleCategoryDao; import ksno.model.Category; import ksno.util.JSFUtil; /** * * @author tor.hauge */ public class ArticleCategoryServiceImpl implements ArticleCategoryService { private ArticleCategoryDao articleCategoryDao; private Logger getLogService(){ return Logger.getLogger(ArticleServiceImpl.class.getName()); } public ArticleCategoryDao getArticleCategoryDao() { return articleCategoryDao; } public void setArticleCategoryDao(ArticleCategoryDao ArticleCategoryDao) { this.articleCategoryDao = ArticleCategoryDao; } public Category getArticleCategory(Long id) { return articleCategoryDao.getArticleCategory(id); } public Long newArticleCategory(Category category) { JSFUtil.clearApplicationCache("articleCategorys"); return articleCategoryDao.newArticleCategory(category); } public void updateArticleCategory(Category category) { JSFUtil.clearApplicationCache("articleCategorys"); articleCategoryDao.updateArticleCategory(category); } public void deleteArticleCategory(Category category) { JSFUtil.clearApplicationCache("articleCategorys"); articleCategoryDao.deleteArticleCategory(category); } public List<Category> getArticleCategorys() { Class c = null; try { c = Class.forName("java.util.List"); } catch (ClassNotFoundException ex) { getLogService().log(Level.SEVERE, null, ex); } List<Category> returnList = (List)JSFUtil.getValue("#{ApplicationBean1.articleCategorys}", c); if(returnList == null){ returnList = articleCategoryDao.getArticleCategorys(); JSFUtil.setValue("#{ApplicationBean1.articleCategorys}", returnList, c); } return returnList; } } <file_sep>/ksno3/src/java/ksno/dao/VideoDao.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.dao; import java.util.List; import ksno.model.Video; /** * * @author halsnehauge */ public interface VideoDao { public Long newVideo(Video video); public Video getVideo(Long id); public void updateVideo(Video video); public void deleteVideo(Video video); public List<Video> getVideos(); } <file_sep>/ksno3/src/java/ksno/model/Participation.java package ksno.model; import java.io.Serializable; import java.util.Calendar; public class Participation implements LabelObjectValuePair, LabelValuePair, Serializable { private Long id; private int version; private Person participant; private Event event; private String shoeSize; private String helmetSize; private String wetSuitSize; private String harnessSize; private int price; private Calendar createdDate; private String comment; private String commentKSNO; boolean onWaitList; boolean confirmed; boolean uIChecked; boolean thirdDay; private String weight; private String partner; private ExperienceLevel level; private Instructor instructor; private String workGroup; public String getWorkGroup() { return workGroup; } public void setWorkGroup(String workGroup) { this.workGroup = workGroup; } public Instructor getInstructor() { return instructor; } public void setInstructor(Instructor instructor) { this.instructor = instructor; } public ExperienceLevel getLevel() { return level; } public String getHarnessSize() { return harnessSize; } public void setHarnessSize(String harnessSize) { this.harnessSize = harnessSize; } public void setLevel(ExperienceLevel level) { this.level = level; } public String getPartner() { return partner; } public void setPartner(String partner) { this.partner = partner; } public String getWeight() { return weight; } public void setWeight(String weight) { this.weight = weight; } public boolean isThirdDay() { return thirdDay; } public void setThirdDay(boolean thirdDay) { this.thirdDay = thirdDay; } public boolean isuIChecked() { return uIChecked; } public void setuIChecked(boolean uIChecked) { this.uIChecked = uIChecked; } public boolean isConfirmed() { return confirmed; } public void setConfirmed(boolean confirmed) { this.confirmed = confirmed; } public String getCommentKSNO() { return commentKSNO; } public void setCommentKSNO(String commentKSNO) { this.commentKSNO = commentKSNO; } public void appendCommentKSNO(String comment){ this.commentKSNO = this.commentKSNO + "\n" + comment; } public boolean getOnWaitList() { return onWaitList; } public void setOnWaitList(boolean onWaitList) { this.onWaitList = onWaitList; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public Calendar getCreatedDate() { return createdDate; } public void setCreatedDate(Calendar createdDate) { this.createdDate = createdDate; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public Event getEvent() { return event; } public void setEvent(Event event) { this.event = event; } public String getHelmetSize() { return helmetSize; } public void setHelmetSize(String helmetSize) { this.helmetSize = helmetSize; } public Person getParticipant() { return participant; } public void setParticipant(Person participant) { this.participant = participant; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String getShoeSize() { return shoeSize; } public void setShoeSize(String shoeSize) { this.shoeSize = shoeSize; } public String getWetSuitSize() { return wetSuitSize; } public void setWetSuitSize(String wetSuitSize) { this.wetSuitSize = wetSuitSize; } public Participation () { } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Participation other = (Participation) obj; if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 41 * hash + (this.id != null ? this.id.hashCode() : 0); return hash; } public String getLabel() { return this.getParticipant().getFirstName() + " " + this.getParticipant().getLastName(); } public Object getObject() { return this; } public String getValue() { return this.getId().toString(); } } <file_sep>/ksno3/src/java/ksno/service/TextService.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.service; import java.util.List; import ksno.model.Email; import ksno.model.Text; /** * * @author tor.hauge */ public interface TextService { public Text getText(Long id); public Text getText(String name); public Long newText(Text Text); public void updateText(Text Text); public void deleteText(Text Text); public List getTexts(); public Email getEmail(String name); } <file_sep>/ksno3/src/java/ksno/ui/jsf/backing/TransactionsMaintain.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.backing; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.component.UIData; import ksno.model.Transaction; import ksno.service.TransactionService; import ksno.util.JSFUtil; import org.apache.myfaces.component.html.ext.HtmlOutputText; /** * * @author tor.hauge */ public class TransactionsMaintain { private TransactionService transactionService; private HtmlOutputText errorMsg; private UIData data; // <editor-fold defaultstate="collapsed" desc=" getters and setters"> private Logger getLogService(){ return Logger.getLogger(this.getClass().getName()); } public UIData getData() { return data; } public void setData(UIData data) { this.data = data; } public HtmlOutputText getErrorMsg() { return errorMsg; } public void setErrorMsg(HtmlOutputText errorMsg) { this.errorMsg = errorMsg; } public TransactionService getTransactionService() { return transactionService; } public void setTransactionService(TransactionService transactionService) { this.transactionService = transactionService; } // </editor-fold> public List getTransactions(){ List l = null; try{ l = transactionService.getTransactions(); }catch(Exception e){ int i = 0; } return l; } public String selectEditTransaction(){ String returnVal = "transactionUpdate"; try{ Transaction transactionModify = (Transaction)this.getData().getRowData(); JSFUtil.getSessionMap().put(JSFUtil.sessionBeanTransactionModify, transactionModify); }catch(Exception e){ getLogService().log(Level.SEVERE,"Unable to select transaction", e); errorMsg.setValue("Operasjonen feilet, forsøk på nytt. Detaljert feilmelding: " + e.getMessage()); returnVal = "no"; } return returnVal; } public String transactionDelete(){ String returnVal = "sucess"; try{ Transaction transaction = (Transaction)this.getData().getRowData(); transactionService.deleteTransaction(transaction); }catch(Exception e){ getLogService().log(Level.SEVERE,"Unable to delete transaction", e); errorMsg.setValue("Operasjonen feilet, forsøk på nytt. Detaljert feilmelding: " + e.getMessage()); returnVal = "no"; } return returnVal; } } <file_sep>/ksno3/web/resources/js/main.js function setStyle(styleName) { $("link[@rel*=style][title]").each(function(i) { this.disabled = true; if (this.getAttribute("title") == styleName){ this.disabled = false; } }); } var viewport = { o: function() { if (self.innerHeight) { this.pageYOffset = self.pageYOffset; this.pageXOffset = self.pageXOffset; this.innerHeight = self.innerHeight; this.innerWidth = self.innerWidth; } else if (document.documentElement && document.documentElement.clientHeight) { this.pageYOffset = document.documentElement.scrollTop; this.pageXOffset = document.documentElement.scrollLeft; this.innerHeight = document.documentElement.clientHeight; this.innerWidth = document.documentElement.clientWidth; } else if (document.body) { this.pageYOffset = document.body.scrollTop; this.pageXOffset = document.body.scrollLeft; this.innerHeight = document.body.clientHeight; this.innerWidth = document.body.clientWidth; } return this; }, init: function(el, w, h) { var imgW = (parseInt($(el).width()) > 50) ? $(el).width() : w; var imgH = (parseInt($(el).height()) > 50) ? $(el).height() : h; $(el).css("left",Math.round(viewport.o().innerWidth/2) + viewport.o().pageXOffset - Math.round(imgW/2)); $(el).css("top",Math.round(viewport.o().innerHeight/2) + viewport.o().pageYOffset - Math.round(imgH/2)); return parseInt($(el).width()); } }; function openModalVideo(url, flashDivs){ fd = flashDivs; var id = '#dialog'; //Get the screen height and width var maskHeight = Math.max(document.body.scrollHeight, document.body.clientHeight); var maskWidth = Math.max(document.body.scrollWidth, document.body.clientWidth); //Set height and width to mask to fill up the whole screen $('#mask').css({ 'width':maskWidth, 'height':maskHeight, 'left':'0', 'top':'0' }); //transition effect $('#mask').fadeIn(1000); $('#mask').fadeTo("slow",0.8); //Get the window height and width var winH = $(window).height(); var winW = $(window).width(); var videoWidth = '650'; var videoHeight = '505'; var val ="<object width='"+videoWidth+"' height='"+videoHeight+"'><param name='movie' value='"+url+"'></param><param name='allowFullScreen' value='true'></param><param name='allowscriptaccess' value='always'></param><embed src='"+url+"' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='"+videoWidth+"' height='"+videoHeight+"'></embed></object>"; $(id).html(val); //Set the popup window to center viewport.init(id, videoWidth, videoHeight ); //transition effect $(id).fadeIn(2000); } function openModalImage(image, flashDivs){ fd = flashDivs; //Get the A tag var url = image.attr("src"); var imgHeight = image.height(); var imgWidth = image.width(); var factor = 1; try{ if(url != undefined && url.indexOf("s288") > 0){ url = url.replace(/s288/,"s800"); factor = 800/Math.max(imgHeight, imgWidth); }else if(url != undefined && url.indexOf("s400") > 0){ url = url.replace(/s400/,"s800"); factor = 800/Math.max(imgHeight, imgWidth); } }catch(err){} imgHeight = Math.round(imgHeight * factor); imgWidth = Math.round(imgWidth * factor); var val ="<img src='"+ url +"'/>"; var id = '#dialog'; $(id).html(val); //Get the screen height and width var maskHeight = Math.max(document.body.scrollHeight, document.body.clientHeight); var maskWidth = Math.max(document.body.scrollWidth, document.body.clientWidth); //Set height and width to mask to fill up the whole screen $('#mask').css({ 'width':maskWidth, 'height':maskHeight, 'left':'0', 'top':'0' }); //transition effect $('#mask').fadeIn(1000); $('#mask').fadeTo("slow",0.8); //Get the window height and width //var winH = $(window).height(); //var winW = $(window).width(); viewport.init(id, imgWidth, imgHeight ); $(id).fadeIn(2000); $(id).click(function(event){ $('#mask, .window').hide(); }); } function openModalElement(domElem, flashDivs){ fd = flashDivs; //Get the A tag var imgHeight = domElem.height(); var imgWidth = domElem.width(); var id = '#dialog'; $(id).add(domElem); //Get the screen height and width var maskHeight = Math.max(document.body.scrollHeight, document.body.clientHeight); var maskWidth = Math.max(document.body.scrollWidth, document.body.clientWidth); //Set height and width to mask to fill up the whole screen $('#mask').css({ 'width':maskWidth, 'height':maskHeight, 'left':'0', 'top':'0' }); //transition effect $('#mask').fadeIn(1000); $('#mask').fadeTo("slow",0.8); //Get the window height and width //var winH = $(window).height(); //var winW = $(window).width(); viewport.init(id, imgWidth, imgHeight ); $(id).fadeIn(2000); $(id).click(function(event){ $('#mask, .window').hide(); }); } var fd; $(document).ready(function(){ //select all the a tag with name equal to modal //if close button is clicked $('.window .close').click(function (e) { //Cancel the link behavior e.preventDefault(); $('#mask, .window').hide(); }); //if mask is clicked $('#mask').click(function () { $("#dialog").html(""); $(this).hide(); $('.window').hide(); if(fd != undefined){ fd.css("display","block"); } fd = null; $('#translateMenu').hide(); }); var queryParams = $(this).attr("location").search; if(queryParams != undefined && queryParams.indexOf("content")> 0){ var url = queryParams.substring(queryParams.indexOf("content=")+8); if(url != undefined && url != "" && url.toLowerCase().indexOf("jsp") > 0 || url.toLowerCase().indexOf("html") > 0){ $('#content').attr('src',url); } } if ($.browser.mozilla) { // $('#searchcontrol').css('left','800'); } if ($.browser.msie) { // $('#searchcontrol').css('left','790'); } var windW = $(window).width(); var contW = 940; var compW = 300; var w = Math.max(((windW - contW )/2), 0) + contW - compW; $('#searchcontrol').css('left',w); $(window).resize(function(){ var windW = $(window).width(); var contW = 940; var compW = 300; var w = Math.max(((windW - contW )/2), 0) + contW - compW; $('#searchcontrol').css('left',w); }); positionSearcBox(); }); function positionSearcBox(){ var divSearchWrapper = $("#searchcontrol"); if(divSearchWrapper.length > 0){ if($.browser.mozilla){ divSearchWrapper.css("top","92px"); } } } function openTranslateMenu(){ var id = '#translateMenu'; var menuElement = $(id); //Get the screen height and width var maskHeight = Math.max(document.body.scrollHeight, document.body.clientHeight); var maskWidth = Math.max(document.body.scrollWidth, document.body.clientWidth); //Set height and width to mask to fill up the whole screen $('#mask').css({ 'width':maskWidth, 'height':maskHeight, 'left':'0', 'top':'0' }); //transition effect $('#mask').fadeIn(1000); $('#mask').fadeTo("slow",0.8); viewport.init(id, 200, 300); menuElement.fadeIn(2000); menuElement.find("select").change(function() { menuElement.hide(); $('#mask').hide(); $('#content').attr('src', $('#content').attr('src')); }); } google.load("search", "1", { "nocss" : true }); var app; function OnLoad() { app = new App(); } function App() { // Create a search control var searchControl = new google.search.SearchControl(); searchControl.setSearchStartingCallback(this, App.prototype.OnSearchStarting); searchControl.setSearchCompleteCallback(this, App.prototype.OnSearchComplete); // Add in a full set of searchers var siteSearch = new google.search.WebSearch(); siteSearch.setSiteRestriction("kitesurfing.no"); options = new google.search.SearcherOptions(); options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN); searchControl.addSearcher(siteSearch, options); // Tell the searcher to draw itself and tell it where to attach searchControl.draw(document.getElementById("searchcontrol")); $(searchControl.input).css("width","100px"); var txtSearch = "Søk..." $(searchControl.input).attr("value",txtSearch); $(searchControl.input).focus(function(){if(this.value == txtSearch){this.value = ''};}) $(searchControl.input).parent().attr("align","right"); $(".gsc-branding").remove(); $(".gsc-search-button").attr("value","").attr("title",""); $("td.gsc-clear-button").css("display","none"); $("form.gsc-search-box").prepend("<div id='branding'></div>"); google.search.Search.getBranding(document.getElementById("branding")); // Execute an inital search //searchControl.execute("Google"); } google.setOnLoadCallback(OnLoad); App.prototype.OnSearchStarting = function(sc, searcher, query) { //Get the screen height and width $(sc.input).css("width","100px"); var maskHeight = Math.max(document.body.scrollHeight, document.body.clientHeight); var maskWidth = Math.max(document.body.scrollWidth, document.body.clientWidth); } App.prototype.OnSearchComplete = function(sc, searcher) { //Get the screen height and width $(".gs-webResult a").attr("target","content"); $(".gsc-configLabelCell").html($("td.gsc-clear-button").html()); $(".gsc-title").html("Resultater"); $(sc.input).css("width","100px"); $(".gsc-configLabelCell").click(function () { sc.clearAllResults(); }); } <file_sep>/ksno3/src/java/ksno/service/EventServiceImpl.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.service; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import ksno.dao.EventDao; import ksno.model.BeginnerCourse; import ksno.model.Event; import ksno.util.JSFUtil; import ksno.util.KSNOutil; /** * * @author halsnehauge */ public class EventServiceImpl implements EventService { private EventDao eventDao; private Logger getLogService() { return Logger.getLogger(this.getClass().getName()); } public EventDao getEventDao() { return eventDao; } public void setEventDao(EventDao eventDao) { this.eventDao = eventDao; } public List getEvents() { Class c = null; try { c = Class.forName("java.util.List"); } catch (ClassNotFoundException ex) { Logger.getLogger(EventServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } List returnList = (List)JSFUtil.getValue("#{ApplicationBean1.events}", c); if(returnList == null){ returnList = eventDao.getEvents(); JSFUtil.setValue("#{ApplicationBean1.events}", returnList, c); } return returnList; } public List getEventsFromThisYear(){ Class c = null; int year = Calendar.getInstance().get(Calendar.YEAR); //TODO: To be removed year = year - 1; try { c = Class.forName("java.util.List"); } catch (ClassNotFoundException ex) { Logger.getLogger(EventServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } List returnList = (List)JSFUtil.getValue("#{ApplicationBean1.eventsFromThisYear}", c); if(returnList != null && returnList.size()>0){ Event event = (Event)returnList.get(0); Calendar evStart = Calendar.getInstance(); evStart.setTime(event.getStartDate()); if(evStart.get(Calendar.YEAR)< Calendar.getInstance().get(Calendar.YEAR)){ returnList = null; clearEventsFromThisYearApplicationCache(); } } if(returnList == null){ Calendar start = Calendar.getInstance(); start.set(Calendar.YEAR,year); start.set(Calendar.DAY_OF_YEAR,1); //first day of the year. returnList = eventDao.getEvents(start); JSFUtil.setValue("#{ApplicationBean1.eventsFromThisYear}", returnList, c); } return returnList; } public List getBeginnerCourses() { return eventDao.getOpenBeginnerCourses(); } public List<BeginnerCourse> getBeginnerCoursesFromThisYear(){ Class c = null; getLogService().log(Level.INFO,"About to get beginnercourses from start of current year..."); int year = Calendar.getInstance().get(Calendar.YEAR); try { c = Class.forName("java.util.List"); } catch (ClassNotFoundException ex) { Logger.getLogger(EventServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } List returnList = (List)JSFUtil.getValue("#{ApplicationBean1.beginnerCoursesFromThisYear}", c); if(returnList != null){ getLogService().log(Level.INFO,"Found it in the cache"); if(returnList.size()>0){ BeginnerCourse course = (BeginnerCourse)returnList.get(0); Calendar evStart = Calendar.getInstance(); evStart.setTime(course.getStartDate()); if(evStart.get(Calendar.YEAR)< Calendar.getInstance().get(Calendar.YEAR)){ returnList = null; clearEventsApplicationCache(); getLogService().log(Level.INFO,"But we have entered a new year since last time we accesses the list, need to clear cache"); } } } if(returnList == null){ getLogService().log(Level.INFO,"Cache was empty need to query dao"); Calendar start = Calendar.getInstance(); start.set(Calendar.YEAR,year); start.set(Calendar.DAY_OF_YEAR,1); //first day of the year. returnList = eventDao.getBeginnerCourses(start); JSFUtil.setValue("#{ApplicationBean1.beginnerCoursesFromThisYear}", returnList, c); } getLogService().log(Level.INFO,"Returning a list of " + returnList.size() + " courses"); return returnList; } public List<BeginnerCourse> getOpenUpcommingWinterBeginnerCourses() { getLogService().log(Level.INFO,"About to get winter courses from this year"); List<BeginnerCourse> returnList = new LinkedList<BeginnerCourse>(); List<BeginnerCourse> beginnerCoursesFromThisYear = getBeginnerCoursesFromThisYear(); getLogService().log(Level.INFO,"Found " + beginnerCoursesFromThisYear.size() + " courses from this year"); for (BeginnerCourse beginnerCourse : beginnerCoursesFromThisYear) { getLogService().log(Level.INFO,"About to get winter courses from this year"); Date now = new Date(); if (beginnerCourse.getLocation().equalsIgnoreCase("haukeliseter") && beginnerCourse.isOpen() && now.getTime() < beginnerCourse.getStartDate().getTime()) { returnList.add(beginnerCourse); getLogService().log(Level.INFO, "Course had location " + beginnerCourse.getLocation() + " and open = " + beginnerCourse.isOpen() + " hence adding it to the returnlist"); } } getLogService().log(Level.INFO, "Return a list of " + returnList.size() + " courses"); return returnList; } public List getUpcommingWinterBeginnerCourses() { getLogService().log(Level.INFO,"About to get winter courses from this year"); List<BeginnerCourse> returnList = new LinkedList<BeginnerCourse>(); List<BeginnerCourse> beginnerCoursesFromThisYear = getBeginnerCoursesFromThisYear(); getLogService().log(Level.INFO,"Found " + beginnerCoursesFromThisYear.size() + " courses from this year"); for (BeginnerCourse beginnerCourse : beginnerCoursesFromThisYear) { getLogService().log(Level.INFO,"About to get winter courses from this year"); if (beginnerCourse.getLocation().equalsIgnoreCase("haukeliseter")) { returnList.add(beginnerCourse); getLogService().log(Level.INFO, "Course had location " + beginnerCourse.getLocation() + " hence adding it to the returnlist"); } } getLogService().log(Level.INFO, "Return a list of " + returnList.size() + " courses"); return returnList; } public List getOpenUpcommingSummerBeginnerCourses() { getLogService().log(Level.INFO,"About to get summer courses from this year"); List<BeginnerCourse> returnList = new LinkedList<BeginnerCourse>(); List<BeginnerCourse> beginnerCoursesFromThisYear = getBeginnerCoursesFromThisYear(); getLogService().log(Level.INFO,"Found " + beginnerCoursesFromThisYear.size() + " courses from this year"); for (BeginnerCourse beginnerCourse : beginnerCoursesFromThisYear) { getLogService().log(Level.INFO,"About to get winter courses from this year"); Date now = new Date(); if (beginnerCourse.getLocation().equalsIgnoreCase("jæren") && beginnerCourse.isOpen() && now.getTime() < beginnerCourse.getStartDate().getTime()) { returnList.add(beginnerCourse); getLogService().log(Level.INFO, "Course had location " + beginnerCourse.getLocation() + " and open = " + beginnerCourse.isOpen() + " hence adding it to the returnlist"); } } getLogService().log(Level.INFO, "Return a list of " + returnList.size() + " courses"); return returnList; } public List getUpcommingSummerBeginnerCourses() { getLogService().log(Level.INFO,"About to get summer courses from this year"); List<BeginnerCourse> returnList = new LinkedList<BeginnerCourse>(); List<BeginnerCourse> beginnerCoursesFromThisYear = getBeginnerCoursesFromThisYear(); getLogService().log(Level.INFO,"Found " + beginnerCoursesFromThisYear.size() + " courses from this year"); for (BeginnerCourse beginnerCourse : beginnerCoursesFromThisYear) { getLogService().log(Level.INFO,"About to get winter courses from this year"); if (beginnerCourse.getLocation().equalsIgnoreCase("jæren")) { returnList.add(beginnerCourse); getLogService().log(Level.INFO, "Course had location " + beginnerCourse.getLocation() + " hence adding it to the returnlist"); } } getLogService().log(Level.INFO, "Return a list of " + returnList.size() + " courses"); return returnList; } public Long newEvent(Event event) { clearEventsApplicationCache(); clearEventsFromThisYearApplicationCache(); event.setPrettyPrintId("/" + event.getLocation().toLowerCase() + KSNOutil.getPrettyPrintId(event.getStartDate())); return eventDao.newEvent(event); } public Event getEvent(Long id) { return eventDao.getEvent(id); } public void deleteEvent(Event event) { clearEventsApplicationCache(); clearEventsFromThisYearApplicationCache(); eventDao.deleteEvent(event); } public void updateEvent(Event event) { clearEventsApplicationCache(); clearEventsFromThisYearApplicationCache(); event.setPrettyPrintId("/" + event.getLocation().toLowerCase() + KSNOutil.getPrettyPrintId(event.getStartDate())); eventDao.updateEvent(event); } public BeginnerCourse getBeginnerCourse(Long id) { return eventDao.getBeginnerCourse(id); } public BeginnerCourse getBeginnerCourse(String prettyPrintId) { return eventDao.getBeginnerCourse(prettyPrintId); } private void clearEventsApplicationCache(){ Class c = null; try { c = Class.forName("java.util.List"); } catch (ClassNotFoundException ex) { Logger.getLogger(EventServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } JSFUtil.setValue("#{ApplicationBean1.events}", null, c); } private void clearEventsFromThisYearApplicationCache(){ Class c = null; try { c = Class.forName("java.util.List"); } catch (ClassNotFoundException ex) { Logger.getLogger(EventServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } JSFUtil.setValue("#{ApplicationBean1.eventsFromThisYear}", null, c); JSFUtil.setValue("#{ApplicationBean1.beginnerCoursesFromThisYear}", null, c); } public String getAwailableSeatsOnOpenUpcommingWinterBeginnerCourses(){ String returnval = ""; List courses = getOpenUpcommingWinterBeginnerCourses(); Iterator courseIterator = courses.iterator(); while(courseIterator.hasNext()){ BeginnerCourse course = (BeginnerCourse)courseIterator.next(); int numberOfParticipants = 0; if(course.getParticipations() != null){ numberOfParticipants = course.getParticipations().size(); } int awailSeats = course.getMaxSize() - numberOfParticipants; returnval += course.getId().toString() + ":" + Integer.toString(awailSeats); if(courseIterator.hasNext()){ returnval += "~"; } } return returnval; } } <file_sep>/ksno3/src/java/ksno/dao/WorkHoursDao.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.dao; import java.util.List; import ksno.model.Instructor; import ksno.model.WorkHours; /** * * @author tor.hauge */ public interface WorkHoursDao { public WorkHours getWorkHours(Long id); public Long newWorkHours(WorkHours hours); public void updateWorkHours(WorkHours hours); public void deleteWorkHours(WorkHours hours); public List<WorkHours> getWorkHoursList(); public List<WorkHours> getWorkHoursListByInstructor(Instructor instructor); } <file_sep>/ksno3/src/java/ksno/ui/jsf/backing/SendMail.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.backing; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.component.UIData; import javax.faces.component.html.HtmlSelectOneMenu; import javax.faces.model.SelectItem; import ksno.model.Event; import ksno.model.Participation; import ksno.model.Person; import ksno.service.EventService; import ksno.service.PersonService; import ksno.util.JSFUtil; import org.apache.myfaces.component.html.ext.HtmlInputText; import org.apache.myfaces.component.html.ext.HtmlInputTextarea; import org.apache.myfaces.component.html.ext.HtmlOutputText; import org.apache.myfaces.component.html.ext.HtmlSelectBooleanCheckbox; /** * * @author tor.hauge */ public class SendMail { private UIData dataRecipients; private HtmlOutputText errorMsg; private HtmlOutputText confirmMsg; private HtmlInputText subject; private HtmlInputTextarea body; private HtmlSelectBooleanCheckbox induvidualMails; PersonService personService; EventService eventService; private HtmlSelectOneMenu coursesSelect; public HtmlOutputText getConfirmMsg() { return confirmMsg; } public void setConfirmMsg(HtmlOutputText confirmMsg) { this.confirmMsg = confirmMsg; } private Logger getLogService(){ return Logger.getLogger(this.getClass().getName()); } // <editor-fold defaultstate="collapsed" desc=" getters and setters"> public HtmlSelectBooleanCheckbox getInduvidualMails() { return induvidualMails; } public void setInduvidualMails(HtmlSelectBooleanCheckbox induvidualMails) { this.induvidualMails = induvidualMails; } public HtmlInputTextarea getBody() { return body; } public void setBody(HtmlInputTextarea body) { this.body = body; } public HtmlInputText getSubject() { return subject; } public void setSubject(HtmlInputText subject) { this.subject = subject; } public HtmlSelectOneMenu getCoursesSelect() { return coursesSelect; } public void setCoursesSelect(HtmlSelectOneMenu coursesSelect) { this.coursesSelect = coursesSelect; } public EventService getEventService() { return eventService; } public void setEventService(EventService eventService) { this.eventService = eventService; } public PersonService getPersonService() { return personService; } public void setPersonService(PersonService personService) { this.personService = personService; } public UIData getDataRecipients() { return dataRecipients; } public void setDataRecipients(UIData dataRecipients) { this.dataRecipients = dataRecipients; } public HtmlOutputText getErrorMsg() { return errorMsg; } public void setErrorMsg(HtmlOutputText errorMsg) { this.errorMsg = errorMsg; } // </editor-fold> public List getRecipients(){ Class c = null; try { c = Class.forName("java.lang.Long"); } catch (ClassNotFoundException ex) { getLogService().log(Level.SEVERE,null,ex); } List lstRecipients = null; Long selectedCourseId = (Long) JSFUtil.getValue("#{SessionBean1.longVal1}", c); if(selectedCourseId == null || selectedCourseId < 1){ lstRecipients = personService.getPersons(); }else{ lstRecipients = new ArrayList(); Event e = eventService.getEvent(selectedCourseId); Iterator iter = e.getParticipations().iterator(); while(iter.hasNext()){ Participation p = (Participation)iter.next(); lstRecipients.add(p.getParticipant()); } } return lstRecipients; } public SelectItem[] getCourses(){ List events = eventService.getEvents(); return JSFUtil.toSelectItemArray(events, true); } public String filter(){ try { JSFUtil.setValue("#{SessionBean1.longVal1}", coursesSelect.getValue().toString(), Class.forName("java.lang.Long")); } catch (ClassNotFoundException ex) { getLogService().log(Level.SEVERE, null, ex); } return "hj"; } public String send(){ String returnVal = "success"; try{ List recipients = (List)getDataRecipients().getValue(); ArrayList<String> tos = new ArrayList<String>(); boolean ivMails = Boolean.valueOf(getInduvidualMails().getValue().toString()); StringBuffer sb = new StringBuffer("Mail sent successfully to: "); if(ivMails){ for(int i = 0; i< recipients.size(); i++){ Person person = (Person)recipients.get(i); if(person.isUiSendMail()){ ksno.util.SendMail sendMail = new ksno.util.SendMail(person.getUserName(), "<EMAIL>", getSubject().getValue().toString() , getBody().getValue().toString()); sendMail.send(); sb.append(person.getUserName() + ", "); } } }else{ String[] ccs = {"<EMAIL>"}; for(int i = 0; i< recipients.size(); i++){ Person person = (Person)recipients.get(i); if(person.isUiSendMail()){ tos.add(person.getUserName()); } } String s[] = new String[tos.size()]; s = tos.toArray(s); ksno.util.SendMail sendMail = new ksno.util.SendMail(s, ccs, getSubject().getValue().toString(), getBody().getValue().toString()); sendMail.send(); for(String sElem : s){ sb.append(sElem).append(", "); } } confirmMsg.setValue(sb.toString()); }catch(Exception e){ getLogService().log(Level.SEVERE,"Unable to create send mail", e); errorMsg.setValue("Mailen ble ikke sendt. Detaljert feilmelding: " + e.getMessage()); returnVal = "no"; } return returnVal; } } <file_sep>/ksno3/web/resources/js/layout.js function slideProjector(obj,ownCall){ this.slideShowSpeed = 5000; this.crossFadeDuration = 2000; this.pics = new Array(); this.links = new Array(); this.target = obj; this.currentPicture = 0; this.ownCall = ownCall; } slideProjector.prototype.setSpeed = function(speed){ this.slideShowSpeed = speed } slideProjector.prototype.setFade = function(duration){ this.crossFadeDuration = duration; } slideProjector.prototype.loadPictures = function(){ for(var i=0; i<arguments.length; i++){ this.pics[i] = arguments[i] } } slideProjector.prototype.loadLinks = function(){ for(var i=0; i<arguments.length; i++){ this.links[i] = arguments[i] } } slideProjector.prototype.run = function(){ this.target.style.filter="blendTrans(duration=this.crossFadeDuration)" this.target.filters.blendTrans.Apply() this.target.src = this.pics[this.currentPicture]; link = this.links[this.currentPicture]; if(link){ this.target.onclick = function(){window.open(link)}; } this.target.filters.blendTrans.Play() this.currentPicture = (this.currentPicture + 1) % this.pics.length; if (this.currentPicture < this.pics.length){ setTimeout(this.ownCall, this.slideShowSpeed) } } function expandCollapse(e){ var currentRow = event.srcElement.parentElement.parentElement; var contentCell = currentRow.cells.length - 2 if(currentRow.isCollapsed){ currentRow.cells[contentCell].children[0].style.overflow = 'visible' event.srcElement.parentElement.children[0].style.display = 'none'; event.srcElement.parentElement.children[1].style.display = 'none'; event.srcElement.parentElement.children[2].style.display = 'none'; event.srcElement.parentElement.children[3].style.display = 'inline'; currentRow.isCollapsed = false; } else if(!currentRow.isCollapsed){ currentRow.cells[contentCell].children[0].style.overflow = 'hidden' event.srcElement.parentElement.children[0].style.display = 'inline'; event.srcElement.parentElement.children[1].style.display = 'inline'; event.srcElement.parentElement.children[2].style.display = 'none'; event.srcElement.parentElement.children[3].style.display = 'none'; currentRow.isCollapsed = true; } } function updateLinksTable(){ tblRows = document.getElementById("linksTable").rows for(i=0;i<tblRows.length;i++){ if(tblRows[i].cells[1]){ if(Boolean(tblRows[i].isCollapsed)){ if((tblRows[i].cells[1].children[0].scrollHeight - 1) > tblRows[i].cells[1].children[0].clientHeight){ tblRows[i].cells[2].children[0].style.display = 'inline'; tblRows[i].cells[2].children[1].style.display = 'inline'; tblRows[i].cells[2].children[2].style.display = 'none'; tblRows[i].cells[2].children[3].style.display = 'none'; } else{ tblRows[i].cells[2].children[0].style.display = 'none'; tblRows[i].cells[2].children[1].style.display = 'none'; tblRows[i].cells[2].children[2].style.display = 'inline'; tblRows[i].cells[2].children[3].style.display = 'none'; } } } } }<file_sep>/ksno3/src/java/ksno/ui/jsf/backing/Preferences.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.backing; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.component.html.HtmlOutputText; import ksno.model.Person; import ksno.service.PersonService; import ksno.util.JSFUtil; import org.apache.myfaces.component.html.ext.HtmlInputSecret; import org.apache.myfaces.component.html.ext.HtmlSelectBooleanCheckbox; /** * * @author tor.hauge */ public class Preferences { private PersonService personService; private HtmlSelectBooleanCheckbox allowMail; private HtmlInputSecret inpPw1; private HtmlOutputText errorMsg; private HtmlOutputText outTxtPassword; private String test; public String getTest() { return test; } public void setTest(String test) { this.test = test; } // <editor-fold defaultstate="collapsed" desc=" getters and setters"> public HtmlInputSecret getInpPw1() { return inpPw1; } public void setInpPw1(HtmlInputSecret inpPw1) { this.inpPw1 = inpPw1; } public HtmlOutputText getErrorMsg() { return errorMsg; } public void setErrorMsg(HtmlOutputText errorMsg) { this.errorMsg = errorMsg; } private Logger getLogService(){ return Logger.getLogger(this.getClass().getName()); } private Person user; public Person getUser() { if(user == null){ user = personService.getPerson(JSFUtil.getCurrentUserName()); } return user; } public PersonService getPersonService() { return personService; } public void setPersonService(PersonService personService) { this.personService = personService; } public HtmlSelectBooleanCheckbox getAllowMail() { if(allowMail != null){ allowMail.setValue(getUser().isAllowMail()); return allowMail; }else{ return allowMail; } } public void setAllowMail(HtmlSelectBooleanCheckbox allowMail) { this.allowMail = allowMail; } // </editor-fold> public String update(){ String returnvalue = "success"; try{ Person person = this.getUser(); //person.setAllowMail(Boolean.getBoolean(this.getAllowMail().toString())); if(inpPw1.getValue() != null && inpPw1.getValue().toString().length() > 5){ person.setPassWord(inpPw1.getValue().toString()); } personService.updatePerson(person); }catch(Exception ex){ getLogService().log(Level.SEVERE,"Unable to create article", ex); errorMsg.setValue("Artikkelen ble ikke lagret, forsøk på nytt. Detaljert feilmelding: " + ex.getMessage()); returnvalue = "nogo"; } try{ JSFUtil.getSessionMap().remove(JSFUtil.sessionBeanArticleModify); }catch(Exception ex){ returnvalue = "nogo"; } return returnvalue; } } <file_sep>/ksno3/src/java/ksno/dao/hibernate/TextDaoImpl.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.dao.hibernate; import java.util.List; import ksno.dao.TextDao; import ksno.model.Email; import ksno.model.Text; import ksno.util.HibernateUtil; import org.hibernate.Query; import org.hibernate.Session; /** * * @author tor.hauge */ public class TextDaoImpl implements TextDao { public Text getText(Long id) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Text Text = (Text)session.get(Text.class,id); return Text; } public Text getText(String name){ Query q = null; List returnVal = null; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); //session.beginTransaction(); q=session.createQuery("from Text t where t.name = :nm"); q.setParameter("nm",name); returnVal = q.list(); return (Text)returnVal.get(0); } public Long newText(Text Text){ Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Long l = (Long)session.save(Text); return l; } public void updateText(Text Text) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); try{ session.saveOrUpdate(Text); }catch(Exception e){ session.merge(Text); } } public void deleteText(Text Text) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.delete(Text); } public List getTexts() { Query q = null; List returnVal = null; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); q=session.createQuery("from Text t order by t.createdDate desc"); returnVal = q.list(); return returnVal; } public Email getEmail(String name){ Query q = null; List returnVal = null; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); //session.beginTransaction(); q=session.createQuery("from Email e where e.name = :nm"); q.setParameter("nm",name); returnVal = q.list(); return (Email)returnVal.get(0); } } <file_sep>/ksno3/src/java/ksno/dao/ExperienceLevelDao.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.dao; import java.util.List; import ksno.model.ExperienceLevel; /** * * @author tor.hauge */ public interface ExperienceLevelDao { public ExperienceLevel getExperienceLevel(Long id); public Long newExperienceLevel(ExperienceLevel experienceLevel); public void updateExperienceLevel(ExperienceLevel experienceLevel); public void deleteExperienceLevel(ExperienceLevel experienceLevel); public List<ExperienceLevel> getExperienceLevels(); } <file_sep>/ksno3/src/java/ksno/ui/jsf/backing/CourseSummer.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.backing; import ksno.model.Category; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.model.SelectItem; import ksno.model.BeginnerCourse; import ksno.model.Email; import ksno.model.Participation; import ksno.model.Person; import ksno.model.Text; import ksno.service.ArticleService; import ksno.service.EventService; import ksno.service.ParticipationService; import ksno.service.PersonService; import ksno.service.TextService; import ksno.util.JSFUtil; import ksno.util.SendMail; import org.apache.myfaces.component.html.ext.HtmlInputText; import org.apache.myfaces.component.html.ext.HtmlInputTextarea; import org.apache.myfaces.component.html.ext.HtmlOutputText; import org.apache.myfaces.component.html.ext.HtmlSelectOneMenu; import org.apache.myfaces.component.html.ext.HtmlSelectOneListbox; /** * * @author tor.hauge */ public class CourseSummer { private HtmlInputText email; private HtmlInputText firstName; private HtmlInputText lastName; private HtmlInputText phone; private HtmlSelectOneMenu wetSuitSize; private HtmlSelectOneMenu shoeSize; private HtmlSelectOneMenu helmetSize; private HtmlSelectOneMenu coursesSelect; private HtmlSelectOneListbox lstBxcoursesSelect; private Long id; private EventService eventService; private PersonService personService; private TextService textService; private ArticleService articleService; private ParticipationService participationService; private HtmlOutputText errorMsg; private HtmlInputTextarea comment; private String prettyPrintId; public String getPrettyPrintId() { return prettyPrintId; } public void setPrettyPrintId(String prettyPrintId) { this.prettyPrintId = prettyPrintId; } public ArticleService getArticleService() { return articleService; } public void setArticleService(ArticleService articleService) { this.articleService = articleService; } public HtmlSelectOneListbox getLstBxcoursesSelect() { return lstBxcoursesSelect; } public void setLstBxcoursesSelect(HtmlSelectOneListbox lstBxcoursesSelect) { this.lstBxcoursesSelect = lstBxcoursesSelect; } public TextService getTextService() { return textService; } public void setTextService(TextService textService) { this.textService = textService; } public HtmlInputTextarea getComment() { return comment; } public void setComment(HtmlInputTextarea comment) { this.comment = comment; } private Logger getLogService(){ return Logger.getLogger(BeginnerCourseCreate.class.getName()); } public HtmlOutputText getErrorMsg() { return errorMsg; } public void setErrorMsg(HtmlOutputText errorMsg) { this.errorMsg = errorMsg; } public HtmlSelectOneMenu getCoursesSelect() { return coursesSelect; } public void setCoursesSelect(HtmlSelectOneMenu coursesSelect) { this.coursesSelect = coursesSelect; } public ParticipationService getParticipationService() { return participationService; } public List<ksno.model.Article> getCourseArticles(){ getLogService().log(Level.INFO, "Start getCourseArticles()"); Category category = new Category(); category.setName("Sommerkurs"); List<ksno.model.Article> returnList = getArticleService().getArticlesByCategory(category); getLogService().log(Level.INFO, "Found a list of " + returnList.size() + " articles."); while(returnList.size() > 5){ returnList.remove(returnList.size()-1); } return returnList; } public void setParticipationService(ParticipationService participationService) { this.participationService = participationService; } public PersonService getPersonService() { return personService; } public void setPersonService(PersonService personService) { this.personService = personService; } public EventService getEventService() { return eventService; } public void setEventService(EventService eventService) { this.eventService = eventService; } public Long getId() { return id; } public void setId(Long id) { getLogService().log(Level.INFO, "Setting course id to " + id); this.id = id; } public HtmlInputText getEmail() { return email; } public void setEmail(HtmlInputText email) { getLogService().log(Level.INFO, "Setting email"); this.email = email; } public HtmlInputText getFirstName() { return firstName; } public void setFirstName(HtmlInputText firstName) { this.firstName = firstName; } public HtmlSelectOneMenu getHelmetSize() { return helmetSize; } public void setHelmetSize(HtmlSelectOneMenu helmetSize) { this.helmetSize = helmetSize; } public HtmlInputText getLastName() { return lastName; } public void setLastName(HtmlInputText lastName) { this.lastName = lastName; } public HtmlInputText getPhone() { return phone; } public void setPhone(HtmlInputText phone) { this.phone = phone; } public HtmlSelectOneMenu getShoeSize() { return shoeSize; } public void setShoeSize(HtmlSelectOneMenu shoeSize) { this.shoeSize = shoeSize; } public HtmlSelectOneMenu getWetSuitSize() { return wetSuitSize; } public BeginnerCourse getCourse(){ BeginnerCourse returnCourse = null; if(this.getId() != null){ getLogService().log(Level.INFO, "About to get course object for id " + getId()); returnCourse = eventService.getBeginnerCourse(this.getId()); }else{ getLogService().log(Level.INFO, "About to get course object for prettyprintid " + this.getPrettyPrintId()); returnCourse = eventService.getBeginnerCourse(this.getPrettyPrintId()); } return returnCourse; } public List getUpCommingCourses(){ return eventService.getUpcommingSummerBeginnerCourses(); } public void setWetSuitSize(HtmlSelectOneMenu wetSuitSize) { this.wetSuitSize = wetSuitSize; } public SelectItem[] getCoursesSelectItems() { List events = eventService.getOpenUpcommingSummerBeginnerCourses(); return JSFUtil.toSelectItemArray(events); } public String signOn(){ getLogService().log(Level.INFO, "About to sign on"); String returnVal = "SignUpConfirmed"; try{ Person person = null; try{ person = personService.getPerson(email.getValue().toString()); }catch (IndexOutOfBoundsException ioobe){ getLogService().log(Level.INFO,"Could not find person with username " + email.getValue().toString() + " hence creating a new"); } if(person != null){ getLogService().log(Level.SEVERE,"Unable to sign on participant"); errorMsg.setValue("Brukeren " + person.getFirstName() + " " + person.getLastName() + " er allerede registrert med mail: " + email.getValue().toString() + ". Kitesurfing.no beklager at vår web løsning ikke håndterer dette, vennligst meld deg på via mail eller telefon (se kontakt detaljer nederst på siden)."); returnVal = "no"; }else{ person = new Person(); } person.setUserName(email.getValue().toString()); person.setFirstName(firstName.getValue().toString()); person.setLastName(lastName.getValue().toString()); person.setPhone(Integer.parseInt(phone.getValue().toString())); BeginnerCourse course = eventService.getBeginnerCourse(Long.parseLong(coursesSelect.getValue().toString())); Participation participation = new Participation(); participation.setEvent(course); boolean wait = (course.getParticipations().size() >= course.getMaxSize())?true:false; participation.setOnWaitList(wait); course.getParticipations().add(participation); //event.addParticipation(participation); person.addParticipation(participation); if(comment.getValue() != null){ participation.setComment(comment.getValue().toString()); } setSummerValues(participation); participationService.newParticipation(participation); HashMap<String, String> hm = new HashMap<String, String>(); hm.put("course", course.getStartDate().toString() + " - " + course.getEndDate().toString()); hm.put("name", person.getFirstName() + " " + person.getLastName()); if(wait){ int pos = course.getNumberOfParticipants() - course.getMaxSize(); hm.put("position", Integer.toString(pos)); try{ Email mail = textService.getEmail("SignOnWaitSummer"); SendMail sendMail = new SendMail(mail.getTos(hm),mail.getCCs(hm), mail.getSubject(hm), mail.getBody(hm)); sendMail.send(); }catch(Exception e){ getLogService().log(Level.SEVERE,"Participant will be signed on, but mail transport failed", e); participation.appendCommentKSNO("Bekreftelses mail gikk ikke igjennom."); } }else{ try{ Email mail = textService.getEmail("SignOnConfirmedSummer"); SendMail sendMail = new SendMail(mail.getTos(hm),mail.getCCs(hm), mail.getSubject(hm), mail.getBody(hm)); sendMail.send(); }catch(Exception e){ getLogService().log(Level.SEVERE,"Participant will be signed on, but mail transport failed", e); participation.appendCommentKSNO("Bekreftelses mail gikk ikke igjennom."); } } JSFUtil.getSessionMap().put(JSFUtil.sessionBeanSignedOnEvent, course.getId()); }catch(Exception e){ getLogService().log(Level.SEVERE,"Unable to sign on participant", e); errorMsg.setValue("Påmeldingen feilet, vennligst forsøk på nytt. Om det fortsatt ikke fungerer, ta kontakt med oss på email eller telefon (kontakt info nederst på siden)"); returnVal = "no"; } return returnVal; } private void setSummerValues(Participation participation){ participation.setHelmetSize(helmetSize.getValue().toString()); participation.setShoeSize(shoeSize.getValue().toString()); participation.setWetSuitSize(wetSuitSize.getValue().toString()); } public String test(){ return "jall"; } } <file_sep>/ksno3/src/java/ksno/ui/jsf/backing/BeginnerCourseCreate.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.backing; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.component.html.HtmlOutputText; import javax.faces.component.html.HtmlSelectManyListbox; import javax.faces.model.SelectItem; import ksno.model.BeginnerCourse; import ksno.model.Instruction; import ksno.model.Instructor; import ksno.model.Person; import ksno.service.EventService; import ksno.service.PersonService; import ksno.util.JSFUtil; import org.apache.myfaces.component.html.ext.HtmlInputText; import org.apache.myfaces.component.html.ext.HtmlSelectOneMenu; import org.apache.myfaces.component.html.ext.HtmlSelectBooleanCheckbox; /** * * @author halsnehauge */ public class BeginnerCourseCreate { private HtmlInputText startDate; private HtmlInputText endDate; private HtmlInputText comment; private HtmlInputText maxSize; private HtmlInputText name; private HtmlSelectOneMenu location; private HtmlSelectOneMenu slctOneInstructor; private HtmlSelectOneMenu comboResponsible; private HtmlSelectBooleanCheckbox open; private HtmlOutputText errorMsg; private EventService eventService; private PersonService personService; private HtmlSelectManyListbox slctManyInstructors; public HtmlInputText getName() { return name; } public void setName(HtmlInputText name) { this.name = name; } public HtmlSelectOneMenu getSlctOneInstructor() { return slctOneInstructor; } public void setSlctOneInstructor(HtmlSelectOneMenu slctOneInstructor) { this.slctOneInstructor = slctOneInstructor; } public HtmlSelectManyListbox getSlctManyInstructors() { return slctManyInstructors; } public void setSlctManyInstructors(HtmlSelectManyListbox slctManyInstructors) { this.slctManyInstructors = slctManyInstructors; } public HtmlSelectOneMenu getComboResponsible() { return comboResponsible; } public void setComboResponsible(HtmlSelectOneMenu comboResponsible) { this.comboResponsible = comboResponsible; } public PersonService getPersonService() { return personService; } /*public String getResponsibleId(){ String userName = JSFUtil.getRequest().getUserPrincipal().getName(); Person currentUser = personService.getPerson(userName); return Long.toString(currentUser.getId()); }*/ public void setPersonService(PersonService personService) { this.personService = personService; } public HtmlSelectBooleanCheckbox getOpen() { return open; } public void setOpen(HtmlSelectBooleanCheckbox open) { this.open = open; } public HtmlOutputText getErrorMsg() { return errorMsg; } public void setErrorMsg(HtmlOutputText errorMsg) { this.errorMsg = errorMsg; } private Logger getLogService(){ return Logger.getLogger(BeginnerCourseCreate.class.getName()); } public HtmlSelectOneMenu getLocation() { return location; } public void setLocation(HtmlSelectOneMenu location) { this.location = location; } public EventService getCourseService() { return eventService; } public void setEventService(EventService eventService) { this.eventService = eventService; } public HtmlInputText getComment() { return comment; } public void setComment(HtmlInputText comment) { this.comment = comment; } public HtmlInputText getEndDate() { return endDate; } public void setEndDate(HtmlInputText endDate) { this.endDate = endDate; } public HtmlInputText getMaxSize() { return maxSize; } public void setMaxSize(HtmlInputText maxSize) { this.maxSize = maxSize; } public HtmlInputText getStartDate() { return startDate; } public void setStartDate(HtmlInputText startDate) { this.startDate = startDate; } public SelectItem[] getInstructorSelectItems() { List instructors = personService.getInstructors(); return JSFUtil.toSelectItemArray(instructors, true); } public SelectItem[] getMainInstructorSelectItems() { List instructors = personService.getInstructors(); return JSFUtil.toSelectItemArray(instructors); } public String createCourse(){ String returnVal = "eventsMaintain"; try{ BeginnerCourse course = new BeginnerCourse(); course.setStartDate((Date)startDate.getValue()); course.setEndDate((Date)endDate.getValue()); course.setName(name.getValue().toString()); course.setComment(comment.getValue().toString()); course.setMaxSize(Integer.parseInt(maxSize.getValue().toString())); Object[] selectedInstructors = slctManyInstructors.getSelectedValues(); String mainInsId = getSlctOneInstructor().getValue().toString(); Long mainInstructorId = Long.parseLong(mainInsId); Instructor mainInstructor = personService.getInstructor(mainInstructorId); course.setInstructor(mainInstructor); for(int i = 0; i<selectedInstructors.length; i++){ String insId = (String)selectedInstructors[i]; Long instructorId = Long.parseLong(insId); if(instructorId.intValue() != -1){ Instructor instructor = personService.getInstructor(instructorId); if(instructor.equals(mainInstructor)){ errorMsg.setValue("Instruktør: " + instructor.getFirstName() + " kan ikke være både hovedinstruktør og hjelpeinstruktør"); return "no"; } Instruction instruction = new Instruction(); instruction.setInstructor(instructor); course.addInstruction(instruction); } } course.setLocation(location.getValue().toString()); boolean op = (Boolean)open.getValue(); course.setOpen(op); eventService.newEvent(course); }catch(Exception e){ getLogService().log(Level.SEVERE,"Unable to create course", e); errorMsg.setValue("Kurset ble ikke lagret, forsøk på nytt. Detaljert feilmelding: " + e.getMessage()); returnVal = "no"; } return returnVal; } } <file_sep>/ksno3/src/java/ksno/ui/jsf/backing/Article.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.backing; import ksno.service.ArticleService; /** * * @author halsnehauge */ public class Article { Long id; String prettyPrintId; public String getPrettyPrintId() { return prettyPrintId; } public void setPrettyPrintId(String prettyPrintId) { this.prettyPrintId = prettyPrintId; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public ksno.model.Article getArticle() { ksno.model.Article returnArticle = null; if(this.getId() != null){ returnArticle = articleService.getArticle(id); }else{ returnArticle = articleService.getArticle(prettyPrintId); } return returnArticle; } public ArticleService getArticleService() { return articleService; } public void setArticleService(ArticleService articleService) { this.articleService = articleService; } ArticleService articleService; } <file_sep>/ksno3/src/java/ksno/ui/jsf/converter/ParticipationConverter.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.converter; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import ksno.model.Participation; import ksno.service.ParticipationService; import ksno.service.ParticipationServiceImpl; import ksno.util.JSFUtil; /** * * @author tor.hauge */ public class ParticipationConverter implements Converter { private Logger getLogService(){ return Logger.getLogger(ParticipationConverter.class.getName()); } private ParticipationService getParticipationService(){ ParticipationService service = null; try { service = (ParticipationService) JSFUtil.getBeanValue("#{ParticipationService}", ParticipationService.class); } catch (Exception ex) { Logger.getLogger(CategoryConverter.class.getName()).log(Level.SEVERE, null, ex); } return service; } public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException { getLogService().log(Level.INFO,"About to convert " + value + " to a Participation"); //ArticleCategoryDaoImpl dao = new ArticleCategoryDaoImpl(); //return dao.getArticleCategory(Long.parseLong(value)); Object participation = null; try{ participation = getParticipationService().getParticipation(Long.parseLong(value)); }catch(Exception ex){ } return participation; } public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException { if(null == value){ getLogService().log(Level.INFO,"Value is null, and null is returned"); return null; } getLogService().log(Level.INFO,"About to convert " + value.toString() + " to a string"); Participation participation = (Participation)value; return participation.getId().toString(); } } <file_sep>/ksno3/src/java/ksno/model/Article.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.model; import java.io.Serializable; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * * @author Tor-Erik */ public class Article implements Serializable { private Long id; private int version; private String prettyPrintId; private String name; private String body; private String intro; private Category category; private boolean sameAsPrevCat = false; private String frontPagePosition = "default"; private String avatarUrl; private Date createdDate; private Date lastUpdatedDate; private Set images = new HashSet(); private Person author; private boolean visible; public String getPrettyPrintId() { return prettyPrintId; } public void setPrettyPrintId(String prettyPrintId) { this.prettyPrintId = prettyPrintId; } public void addImage(Image image){ if(image == null){ throw new IllegalArgumentException("Image to be added is null"); } if(image.getArticle() != null){ image.getArticle().getImages().remove(image); } image.setArticle(this); images.add(image); } // <editor-fold defaultstate="collapsed" desc=" Getters and setters"> public boolean isSameAsPrevCat() { return sameAsPrevCat; } public void setSameAsPrevCat(boolean val) { this.sameAsPrevCat = val; } public String getFrontPagePosition() { return frontPagePosition; } public void setFrontPagePosition(String frontPagePosition) { this.frontPagePosition = frontPagePosition; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } public String getAvatarUrl() { return avatarUrl; } public void setAvatarUrl(String avatarUrl) { this.avatarUrl = avatarUrl; } public Long getId() { return id; } private void setId(Long id) { this.id = id; } public String getIntro() { return intro.replaceAll("<p>", "").replaceAll("</p>", ""); } public void setIntro(String intro) { this.intro = intro; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public Person getAuthor() { return author; } public void setAuthor(Person author) { this.author = author; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public Set getImages() { return images; } public void setImages(Set images) { this.images = images; } public Date getLastUpdatedDate() { return lastUpdatedDate; } public void setLastUpdatedDate(Date lastUpdatedDate) { this.lastUpdatedDate = lastUpdatedDate; } public String getName() { return name; } public void setName(String name) { this.name = name; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" equals and hashcode"> @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Article other = (Article) obj; if (this.name != other.name && (this.name == null || !this.name.equals(other.name))) { return false; } if (this.createdDate != other.createdDate && (this.createdDate == null || !this.createdDate.equals(other.createdDate))) { return false; } return true; } @Override public int hashCode() { int hash = 5; hash = 17 * hash + (this.name != null ? this.name.hashCode() : 0); hash = 17 * hash + (this.createdDate != null ? this.createdDate.hashCode() : 0); return hash; } // </editor-fold> } <file_sep>/ksno3/src/java/ksno/ui/jsf/backing/EventsMaintain.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.backing; import java.util.Calendar; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.component.UIData; import javax.faces.component.html.HtmlOutputText; import ksno.model.Event; import ksno.service.EventService; import ksno.util.JSFUtil; import org.apache.myfaces.component.html.ext.HtmlInputText; /** * * @author halsnehauge */ public class EventsMaintain { EventService eventService; private HtmlInputText name; private UIData data; private HtmlOutputText errorMsg; public HtmlOutputText getErrorMsg() { return errorMsg; } public void setErrorMsg(HtmlOutputText errorMsg) { this.errorMsg = errorMsg; } private Logger getLogService(){ return Logger.getLogger(this.getClass().getName()); } public EventService getEventService() { return eventService; } public void setEventService(EventService eventService) { this.eventService = eventService; } public UIData getData() { return data; } public void setData(UIData data) { this.data = data; } public HtmlInputText getName() { return name; } public void setName(HtmlInputText name) { this.name = name; } public List getEvents(){ return eventService.getEvents(); } public List getEventsFromThisYear(){ return eventService.getEventsFromThisYear(); } public String eventDelete(){ String returnVal = "sucess"; try{ Event event = (Event)this.getData().getRowData(); eventService.deleteEvent(event); }catch(Exception e){ getLogService().log(Level.SEVERE,"Unable to delete event", e); errorMsg.setRendered(true); errorMsg.setValue("Operasjonen feilet, forsøk på nytt. Detaljert feilmelding: " + e.getMessage()); returnVal = "no"; } return returnVal; } public String eventUpdate(){ String returnVal = "success"; try{ Event eventModify = (Event)this.getData().getRowData(); JSFUtil.getSessionMap().put(JSFUtil.sessionBeanEventModify, eventModify); }catch(Exception e){ getLogService().log(Level.SEVERE,"Unable to select event", e); errorMsg.setRendered(true); errorMsg.setValue("Operasjonen feilet, forsøk på nytt. Detaljert feilmelding: " + e.getMessage()); returnVal = "no"; } return returnVal; } public String participantsMaintain(){ String returnVal = "success"; try{ Event eventModify = (Event)this.getData().getRowData(); JSFUtil.getSessionMap().put(JSFUtil.sessionBeanEventModify, eventModify); }catch(Exception e){ getLogService().log(Level.SEVERE,"Unable to select event", e); errorMsg.setRendered(true); errorMsg.setValue("Operasjonen feilet, forsøk på nytt. Detaljert feilmelding: " + e.getMessage()); returnVal = "no"; } return returnVal; } } <file_sep>/ksno3/src/java/ksno/ui/jsf/converter/CalendarConverter.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.converter; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import javax.faces.component.UIComponent; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import javax.faces.convert.DateTimeConverter; import ksno.util.JSFUtil; /** * * @author tor.hauge */ public class CalendarConverter implements Converter { DateTimeConverter dateTimeConverter; public CalendarConverter(){ dateTimeConverter = new DateTimeConverter(); dateTimeConverter.setPattern("yyyy-MM-dd"); ExternalContext context = JSFUtil.getServletContext(); String strTimeZone = context.getInitParameter("timeZone"); dateTimeConverter.setTimeZone(TimeZone.getTimeZone(strTimeZone)); } public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException { Date date = (Date)dateTimeConverter.getAsObject(context, component, value); Calendar calendar = null; if(date != null){ calendar = Calendar.getInstance(); calendar.setTimeInMillis(date.getTime()); calendar.add(Calendar.HOUR, 12); } return calendar; } public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException { if(null == value){ return null; } Calendar tcalendar = (Calendar)value; Calendar calendar = (Calendar)tcalendar.clone(); Date d = new Date(calendar.getTimeInMillis()); return dateTimeConverter.getAsString(context, component, d); } } <file_sep>/ksno3/src/java/ksno/dao/hibernate/OnDutyDaoImpl.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.dao.hibernate; import java.util.List; import ksno.dao.OnDutyDao; import ksno.model.OnDuty; import ksno.util.HibernateUtil; import org.hibernate.Session; import org.hibernate.Query; /** * * @author HalsneHauge */ public class OnDutyDaoImpl implements OnDutyDao { public Long newOnDuty(OnDuty onDuty) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Long l = (Long)session.save(onDuty); return l; } public OnDuty getOnDuty(Long id) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); OnDuty onDuty = (OnDuty)session.get(OnDuty.class,id); return onDuty; } public void updateOnDuty(OnDuty onDuty) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); try{ session.saveOrUpdate(onDuty); }catch(Exception e){ session.merge(onDuty); } } public void deleteOnDuty(OnDuty onDuty) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.delete(onDuty); } public List<OnDuty> getOnDutys() { Query q = null; List returnVal = null; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); q=session.createQuery("from OnDuty a order by a.fromDate asc"); returnVal = q.list(); return returnVal; } } <file_sep>/ksno3/src/java/ksno/dao/PersonDao.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.dao; import java.util.List; import ksno.model.Instructor; import ksno.model.Person; /** * * @author Tor-Erik */ public interface PersonDao { public List getPersons(); public List getInstructors(); public Person getPerson(Long id); public Person getPerson(String userName); public Instructor getInstructor(Long id); public Long newPerson(Person person); public void updatePerson(Person person); } <file_sep>/ksno3/src/java/ksno/service/DocumentServiceImpl.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.service; import java.io.InputStream; import java.util.logging.Level; import java.util.logging.Logger; import ksno.util.GoogleDocsClient; /** * * @author tor.hauge */ public class DocumentServiceImpl implements DocumentService { private Logger getLogService(){ return Logger.getLogger(this.getClass().getName()); } public String uploadDocument(String path, String userName) throws Exception { getLogService().log(Level.SEVERE, "start"); try { GoogleDocsClient client = new GoogleDocsClient(); getLogService().log(Level.SEVERE, "return"); return client.uploadFile(path, "test"); } catch (Exception ex) { getLogService().log(Level.SEVERE, "An error occured on attempt to upload the image", ex); throw new Exception("An error occured on attemt to upload the image",ex); } } } <file_sep>/ksno3/src/java/ksno/service/ImageServiceImpl.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.service; import java.io.InputStream; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import ksno.dao.ImageDao; import ksno.model.Image; import ksno.util.ImageMeta; import ksno.util.PicasawebClient; /** * * @author halsnehauge */ public class ImageServiceImpl implements ImageService { private Logger getLogService(){ return Logger.getLogger(ImageServiceImpl.class.getName()); } public ImageDao getImageDao() { return imageDao; } public void setImageDao(ImageDao imageDao) { this.imageDao = imageDao; } private ImageDao imageDao; public Long newImage(Image image) { return imageDao.newImage(image); } public HashMap<ImageMeta,String> uploadImage(InputStream stream, String userName) throws Exception { getLogService().log(Level.SEVERE, "start"); try { PicasawebClient client = new PicasawebClient(); getLogService().log(Level.SEVERE, "return"); return client.uploadImage(stream, userName); } catch (Exception ex) { getLogService().log(Level.SEVERE, "An error occured on attempt to upload the image", ex); throw new Exception("An error occured on attemt to upload the image",ex); } } } <file_sep>/ksno3/src/java/ksno/ui/jsf/backing/TextUpdate.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.backing; import java.util.logging.Level; import java.util.logging.Logger; import ksno.model.Text; import ksno.service.TextService; import ksno.util.JSFUtil; import org.apache.myfaces.component.html.ext.HtmlOutputText; /** * * @author tor.hauge */ public class TextUpdate { private HtmlOutputText errorMsg; private TextService textService; public HtmlOutputText getErrorMsg() { return errorMsg; } public void setErrorMsg(HtmlOutputText errorMsg) { this.errorMsg = errorMsg; } public TextService getTextService() { return textService; } public void setTextService(TextService textService) { this.textService = textService; } private Logger getLogService(){ return Logger.getLogger(this.getClass().getName()); } public String update(){ String returnVal = "success"; try{ Text text = (Text)JSFUtil.getSessionMap().get(JSFUtil.sessionBeanTextModify); textService.updateText(text); JSFUtil.getSessionMap().remove(JSFUtil.sessionBeanTextModify); }catch(Exception e){ getLogService().log(Level.SEVERE,"Unable to update event", e); returnVal = "no"; } return returnVal; } } <file_sep>/ksno3/web/resources/js/default.js //default.js var framHeightCheckCount = 0; $(document).ready(function(){ setMainMenuItems(); if(frameElement == undefined || frameElement.id != "content"){ $("body").css("background-position","0px 158px"); $(".topMenu").css("display","block"); }else{ $(".topMenu").css("display","none"); } setFrameHeight(); // check for what is/isn't already checked and match it on the fake ones $("input:checkbox").each( function() { (this.checked) ? $("#fake"+this.id).addClass('fakechecked') : $("#fake"+this.id).removeClass('fakechecked'); }); // function to 'check' the fake ones and their matching checkboxes $(".fakecheck").click(function(){ ($(this).hasClass('fakechecked')) ? $(this).removeClass('fakechecked') : $(this).addClass('fakechecked'); $(this.hash).trigger("click"); return false; }); }); function setFrameHeight(){ try{ if(framHeightCheckCount == 0){ this.frameElement.style.height = 100; } framHeightCheckCount++; if(parseInt(this.frameElement.style.height) < parseInt(document.body.scrollHeight)){ this.frameElement.style.height = document.body.scrollHeight; } if(framHeightCheckCount < 8){ setTimeout("setFrameHeight()",250); } }catch(err){} } function setMainMenuItems(){ if(this.frameElement != undefined && this.frameElement.id == "content"){ var domElemMainMenu = this.frameElement.ownerDocument.getElementById("mainMenu"); var domElemAnchors = (domElemMainMenu.querySelectorAll != undefined)?domElemMainMenu.querySelectorAll("a"):domElemMainMenu.getElementsByTagName("a"); for(var i = 0; i< domElemAnchors.length; i++){ var domElemAnchor = domElemAnchors[i]; if(document.URL.toLowerCase().search(domElemAnchor.href.toLowerCase()) > -1){ domElemAnchor.style.fontWeight = "bolder"; }else if(document.URL.toLowerCase().search("article.jsp") > -1 && domElemAnchor.href.toLowerCase().search("articles.jsp") > -1){ domElemAnchor.style.fontWeight = "bolder"; }else if(document.URL.toLowerCase().search("articles.jsp") > -1 && domElemAnchor.href.toLowerCase().search("articles.jsp") > -1){ domElemAnchor.style.fontWeight = "bolder"; }else if(document.URL.toLowerCase().search("signupsummer.jsp") > -1 && domElemAnchor.href.toLowerCase().search("coursejaren.jsp") > -1){ domElemAnchor.style.fontWeight = "bolder"; }else if(document.URL.toLowerCase().search("coursehaukeliseter.jsp") > -1 && domElemAnchor.href.toLowerCase().search("courseshaukeliseter.jsp") > -1){ domElemAnchor.style.fontWeight = "bolder"; }else{ domElemAnchor.style.fontWeight = "normal"; } } }else{ //Seems like we have opened outside the iframe } }<file_sep>/ksno3/src/java/ksno/model/Event.java package ksno.model; import com.mysql.jdbc.Util; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import ksno.util.ParticipationGroupComparator; public class Event implements LabelValuePair, LabelObjectValuePair { protected Long id; private String prettyPrintId; protected int version; protected Date startDate; protected Date endDate; protected String comment; protected String location; protected String name; private boolean open; private Instructor instructor; private Set instructions = new HashSet(); private Set<Participation> participations = new HashSet<Participation>(); public Instructor getInstructor() { return instructor; } public void setInstructor(Instructor instructor) { this.instructor = instructor; } public String getPrettyPrintId() { return prettyPrintId; } public void setPrettyPrintId(String prettyPrintId) { this.prettyPrintId = prettyPrintId; } // <editor-fold desc=" Getters and Setters "> public Instructor[] getInstructors(){ Instructor[] list = new Instructor[instructions.size()]; Iterator it = instructions.iterator(); int i = 0; while (it.hasNext()){ Instruction instruction = (Instruction)it.next(); list[i] = instruction.getInstructor(); i++; } return list; } public void setInstructors(Instructor[] instructors){ for(int i = 0; i< instructors.length; i++){ Instructor instructor = instructors[i]; Instruction instruction = new Instruction(); instructor.addInstruction(instruction); addInstruction(instruction); } } public Instructor getCourseResponsible(){ return this.getInstructor(); } public String getInstructorsCSV(){ String returnVal = ""; Iterator it = instructions.iterator(); while (it.hasNext()){ Instruction instruction = (Instruction)it.next(); returnVal += instruction.getInstructor().getFirstName(); returnVal += ","; } return returnVal; } public Set getInstructions() { return instructions; } public void setInstructions(Set instructions) { this.instructions = instructions; } public Set<Participation> getParticipations() { return participations; } private Logger getLogService() { return Logger.getLogger(this.getClass().getName()); } public List getConfirmedParticipations() { getLogService().log(Level.INFO, "Start getting confirmed participations"); Iterator <Participation> participationIterator = participations.iterator(); List<Participation> returnList = new LinkedList<Participation>(); while(participationIterator.hasNext()){ Participation participation = participationIterator.next(); if(participation.isConfirmed()){ returnList.add(participation); } } getLogService().log(Level.INFO, "Return " + returnList.size() + " confirmed participations"); return returnList; } public List getUnConfirmedParticipations() { getLogService().log(Level.INFO, "Start getting unconfirmed participations"); Iterator <Participation> participationIterator = participations.iterator(); List<Participation> returnList = new LinkedList<Participation>(); while(participationIterator.hasNext()){ Participation participation = participationIterator.next(); if(!participation.isConfirmed()){ returnList.add(participation); } } getLogService().log(Level.INFO, "Return " + returnList.size() + " unconfirmed participations"); return returnList; } public List getCourseSetUpList() { getLogService().log(Level.INFO, "Start getting confirmed participations"); Iterator <Participation> participationIterator = participations.iterator(); List<Participation> returnList = new LinkedList<Participation>(); while(participationIterator.hasNext()){ Participation participation = participationIterator.next(); if(participation.isConfirmed()){ returnList.add(participation); } } getLogService().log(Level.INFO, "Return " + returnList.size() + " confirmed participations"); Collections.sort(returnList, new ParticipationGroupComparator()); return returnList; } public int getNumberOfUnConfirmedParticipations(){ List list = this.getUnConfirmedParticipations(); if(list != null){ return list.size(); }else{ return 0; } } public void setParticipations(Set<Participation> participations) { this.participations = participations; } public Set getResponsible() { return instructions; } public void setResponsible(Set instructions) { this.instructions = instructions; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public boolean isOpen() { return open; } public void setOpen(boolean open) { this.open = open; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumberOfParticipants(){ return getParticipations().size(); } public String getComment () { return comment; } public void setComment (String val) { this.comment = val; } public Date getEndDate () { return endDate; } public void setEndDate (Date val) { this.endDate = val; } public Long getId () { return id; } public void setId (Long val) { this.id = val; } public Date getStartDate () { return startDate; } public void setStartDate (Date val) { this.startDate = val; } public int getVersion () { return version; } public void setVersion (int val) { this.version = val; } // </editor-fold> // <editor-fold desc=" Equals and HashCode "> @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Event other = (Event) obj; if (this.startDate != other.startDate && (this.startDate == null || !this.startDate.equals(other.startDate))) { return false; } if (this.endDate != other.endDate && (this.endDate == null || !this.endDate.equals(other.endDate))) { return false; } if (this.comment != other.comment && (this.comment == null || !this.comment.equals(other.comment))) { return false; } if (this.location != other.location && (this.location == null || !this.location.equals(other.location))) { return false; } if (this.name != other.name && (this.name == null || !this.name.equals(other.name))) { return false; } if (this.open != other.open) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 71 * hash + (this.startDate != null ? this.startDate.hashCode() : 0); hash = 71 * hash + (this.endDate != null ? this.endDate.hashCode() : 0); hash = 71 * hash + (this.comment != null ? this.comment.hashCode() : 0); hash = 71 * hash + (this.location != null ? this.location.hashCode() : 0); hash = 71 * hash + (this.name != null ? this.name.hashCode() : 0); hash = 71 * hash + (this.open ? 1 : 0); return hash; } @Override public String toString() { return ksno.util.DateConverter.getAsString(this.getStartDate()) + " - " + ksno.util.DateConverter.getAsString(this.getEndDate()); } // </editor-fold> public void addParticipation(Participation participation){ getLogService().log(Level.INFO, "Start method addParticipation."); if(participation == null){ throw new IllegalArgumentException("Participation to be added is null"); } if(participation.getEvent() != null){ participation.getEvent().getParticipations().remove(participation); } if(this.containParticipation(participation)){ getLogService().log(Level.WARNING, "Ended addPartipation, not able to add participant: " + participation.getParticipant().getFirstName() + " " + participation.getParticipant().getLastName() + " because the person was already participating"); }else{ participation.setEvent(this); if(participations.add(participation)){ getLogService().log(Level.INFO, "Ended addPartipation, added participant: " + participation.getParticipant().getFirstName() + " " + participation.getParticipant().getLastName()); }else{ getLogService().log(Level.WARNING, "Ended addPartipation, not able to add participant: " + participation.getParticipant().getFirstName() + " " + participation.getParticipant().getLastName() + " because the person was already participating"); } } } public void addParticipations(Set<Participation> participations){ getLogService().log(Level.INFO, "About to add " + participations.size() + " participations to event: " + this.getStartDate()); for (Participation participation : participations){ this.addParticipation(participation); } } public void removeParticipation(Participation participation){ if(participation == null){ throw new IllegalArgumentException("Participation to be removed is null"); } boolean replace = false; HashSet<Participation> replaceHS = new HashSet<Participation>(); if(participation.getEvent() != null){ if(!getParticipations().remove(participation)){ for(Participation p : getParticipations()){ if(p.equals(participation)){ replace=true; }else{ replaceHS.add(p); } } if(replace){ getParticipations().clear(); getParticipations().addAll(replaceHS); } } } } public void removeParticipations(Set<Participation> participations){ if(participations == null){ throw new IllegalArgumentException("Participation to be removed is null"); } for(Participation part : participations){ removeParticipation(part); } } public void addInstruction(Instruction instruction){ if(instruction == null){ throw new IllegalArgumentException("Instruction to be added is null"); } if(instruction.getEvent() != null){ instruction.getEvent().getInstructions().remove(instruction); } instruction.setEvent(this); instructions.add(instruction); } // <editor-fold defaultstate="collapsed" desc=" Constructors "> public Event () { } // </editor-fold> public String getLabel() { return startDate.toString() + " - " + endDate.toString(); } public String getValue() { return Long.toString(id); } public Object getObject() { return this; } private boolean containParticipation(Participation participation) { Person participant = participation.getParticipant(); boolean returnVal = false; if(participant != null){ for(Participation prt : this.participations){ if(participant.equals(prt.getParticipant())){ returnVal = true; break; } } } return returnVal; } } <file_sep>/ksno3/src/java/ksno/ui/jsf/backing/Main.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.backing; /** * * @author halsnehauge */ public class Main { } <file_sep>/ksno3/src/java/ksno/model/OnDuty.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.model; import java.io.Serializable; import java.util.Calendar; /** * * @author HalsneHauge */ public class OnDuty implements Serializable { private Long id; private int version; private String comment; private Calendar fromDate; private Instructor instructor; public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public Calendar getFromDate() { return fromDate; } public void setFromDate(Calendar fromDate) { this.fromDate = fromDate; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Instructor getInstructor() { return instructor; } public void setInstructor(Instructor instructor) { this.instructor = instructor; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } } <file_sep>/ksno3/src/java/ksno/model/Text.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.model; import java.io.Serializable; import java.util.Date; import java.util.HashMap; import ksno.util.KSNOutil; /** * * @author tor.hauge */ public class Text implements Serializable { private Long id; private int version; private String name; private String body; private String subject; private Date createdDate; private Date lastUpdatedDate; private Person author; public Person getAuthor() { return author; } public void setAuthor(Person author) { this.author = author; } public String getBody() { return body; } public String getBody(HashMap<String, String> hm) { return KSNOutil.injectPlaceHolders(this.getBody(), hm); } public void setBody(String body) { this.body = body; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getLastUpdatedDate() { return lastUpdatedDate; } public void setLastUpdatedDate(Date lastUpdatedDate) { this.lastUpdatedDate = lastUpdatedDate; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSubject() { return subject; } public String getSubject(HashMap<String, String> hm) { return KSNOutil.injectPlaceHolders(this.getSubject(), hm); } public void setSubject(String subject) { this.subject = subject; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Text other = (Text) obj; if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) { return false; } if (this.subject != other.subject && (this.subject == null || !this.subject.equals(other.subject))) { return false; } if (this.createdDate != other.createdDate && (this.createdDate == null || !this.createdDate.equals(other.createdDate))) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 29 * hash + (this.id != null ? this.id.hashCode() : 0); hash = 29 * hash + (this.name != null ? this.name.hashCode() : 0); hash = 29 * hash + (this.subject != null ? this.subject.hashCode() : 0); hash = 29 * hash + (this.createdDate != null ? this.createdDate.hashCode() : 0); return hash; } } <file_sep>/ksno3/web/resources/js/logic.js var backgroundColor = 'transparent'; function setBackgroundColor(color){ backgroundColor = color; } function setBackground(event){ var srcEl = event.srcElement? event.srcElement : event.target; rowElement = findElement(srcEl,'tr') rowElement.style.background = backgroundColor; } function findElement(elem,tag){ if(elem.tagName.toLowerCase() == tag){ return elem } else{ var parent = elem.parentElement; if(parent == undefined){ parent = elem.parentNode; } return findElement(parent,'tr'); } } function openWindow(width,height,url,resize, scroll){ var rs = 'no' var scroll = 'no' if(resize){ rs = 'yes'; } if(scroll){ scroll = 'yes'; } var arguments = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=" + scroll + ",resizable=" + rs + ",copyhistory=yes,width="+width+",height=" + height; window.open(url,"my_new_window",arguments) } function setLanguage(language) { document.all.actionForm.language.value = language; document.all.actionForm.submit(); } function setContent(url) { document.getElementById("contentFrame").src = url; } function setThisContent(url) { location = url; } function changeMainMenu(id) { document.getElementById("menuId").value = id; setAnchors(id); if(id=='5'){ document.getElementById("contentHeading").innerHTML = "<div class='links'><h1>Links</h1><p>Beneath you will find a selection of kite links.</p><p>If you want to add one of your own, please send us a mail</p><a href='mailto:<EMAIL>' style='color:orange; font-size:10'><EMAIL></a><hr/></div>"; } } function setAnchors(id) { if (id.length == 1){ //temporary fix. does not support more than one level in menu if(document.getElementById("anchors"+id) != null) { document.getElementById("contentHeading").innerHTML = document.getElementById("anchors"+id).value; } else { document.getElementById("contentHeading").innerHTML = "&nbsp;"; } } } function goTo(id, page) {//TO DO remove this document.all.actionForm.menuId.value = id; document.all.actionForm.contentPage.value = page; document.all.actionForm.submit(); } function parentGoTo(id, page) {//TO DO remove this parent.document.all.actionForm.menuId.value = id; parent.document.all.actionForm.contentPage.value = page; parent.document.all.actionForm.submit(); } function goAnchor(url) { temp = url + "?language=EN" document.getElementById("contentFrame").src = url; } function ksnoImgageBorder(img,anc){ this.height = document.body.clientHeight; this.images = img; this.captions= new Array(); for(i=0; i<anc.length;i++){ this.captions[i] = new caption(anc[i]); } this.textHeight=19; this.imgBorderAndMargin=12; this.update(); } function caption(anchor){ this.anchor = anchor; this.haveText = false; if(this.anchor.innerText.length > 1){ this.haveText = true; } } ksnoImgageBorder.prototype.update = function(){ this.height = document.body.clientHeight; var tempH=0; for(i=0;i<this.images.length;i++){ tempH += parseInt(this.images[i].clientHeight) + this.imgBorderAndMargin; if(this.captions[i].haveText){ tempH += this.textHeight; } if(tempH<this.height){ this.images[i].style.display = 'block' this.captions[i].anchor.style.display = 'block' } else{ this.images[i].style.display = 'none' this.captions[i].anchor.style.display = 'none' } } } var doValidate = true; function disableValidate(){ if(doValidate){ doValidate = false; } } function validate(formElem){ if(doValidate){ var formElement = formElem; if(formElement == undefined){ if(window.event == undefined){ formElement = document.forms[0]; }else{ formElement = event.srcElement? event.srcElement : event.target; } } var validated = validateRequiredElements(formElement, "input"); if(validated){ validated = validateRequiredElements(formElement, "select"); } if(validated){ validated = validateRequiredElements(formElement, "textarea"); } if(!validated){ alert("De merkede elementene er obligatoriske."); return validated; } validated = validateFormatFields(formElement); return validated; }else{ return true; } } function validateFormatFields(form){ var hasCorrectFormat = true; var formElements = form.getElementsByTagName("input"); for(var i = 0; i<formElements.length; i++){ var formElement = formElements[i]; if(formElement.type != "hidden" && formElement.type != "submit"){ if(hasFormat(formElement, "email")){ if(!validateEmail(formElement)){ return false; } } if(hasFormat(formElement, "phone")){ if(!validatePhone(formElement)){ return false; } } } } return hasCorrectFormat; } function validatePhone(elem){ var str = elem.value; if(str != undefined && str != ""){ if(!checkInternationalPhone(str)){ elem.style.background = "orange"; elem.focus(); alert("Ugyldig telefonnummer. Det må være på format ########. Mellomrom er tillat, og man kan også ha retningsnummer på format +##"); return false; } } elem.style.background = "white"; return true; } function isRequired(field){ if(field.parentElement != undefined){ return field.required ||field.parentElement.required }else{ if(field.attributes.getNamedItem("required")!= undefined){ return field.attributes.getNamedItem("required").nodeValue == "true"; }else if(field.parentNode.attributes.getNamedItem("required")!= undefined){ return field.parentNode.attributes.getNamedItem("required").nodeValue == "true"; } } } function validateRequiredElements(form, tagName){ var allRequired = true; var formElements = form.getElementsByTagName(tagName); for(var i = 0; i<formElements.length; i++){ var formElement = formElements[i]; if(tagName.toLowerCase() == "select"){ if(isRequired(formElement) && (formElement.value == undefined || formElement.value == "" || formElement.value == "empty" || formElement.value == "Empty")){ formElement.style.background = "orange"; allRequired = false; }else{ formElement.style.background = "white"; } }else{ if(formElement.type != "hidden" && formElement.type != "submit"){ if(isRequired(formElement) && (formElement.value == undefined || formElement.value == "")){ formElement.style.background = "orange"; allRequired = false; }else{ formElement.style.background = "white"; } } } } return allRequired; } function hasFormat(field, format){ var fieldFormat; try{ fieldFormat = (field.format != undefined)?field.format:field.parentElement.format; }catch(err){} try{ if(field.attributes.getNamedItem("format")!= undefined){ fieldFormat = field.attributes.getNamedItem("format").nodeValue; } if(field.parentNode.attributes.getNamedItem("format")!= undefined){ fieldFormat = field.parentNode.attributes.getNamedItem("format").nodeValue; } }catch(err){} var returnVal =false; if(fieldFormat != undefined){ fieldFormat = fieldFormat.toLowerCase(); returnVal = fieldFormat.indexOf(format.toLowerCase()) > -1 } return returnVal; } // Declaring required variables var digits = "0123456789"; // non-digit characters which are allowed in phone numbers var phoneNumberDelimiters = " "; // characters which are allowed in international phone numbers // (a leading + is OK) var validWorldPhoneChars = phoneNumberDelimiters + "+"; // Minimum no of digits in an international phone no. var minDigitsInIPhoneNumber = 8; function isInteger(s) { var i; for (i = 0; i < s.length; i++) { // Check that current character is number. var c = s.charAt(i); if (((c < "0") || (c > "9"))) return false; } // All characters are numbers. return true; } function trim(s) { var i; var returnString = ""; // Search through string's characters one by one. // If character is not a whitespace, append to returnString. for (i = 0; i < s.length; i++) { // Check that current character isn't whitespace. var c = s.charAt(i); if (c != " ") returnString += c; } return returnString; } function stripCharsInBag(s, bag) { var i; var returnString = ""; // Search through string's characters one by one. // If character is not in bag, append to returnString. for (i = 0; i < s.length; i++) { // Check that current character isn't whitespace. var c = s.charAt(i); if (bag.indexOf(c) == -1) returnString += c; } return returnString; } function checkInternationalPhone(strPhone){ strPhone=trim(strPhone) if(strPhone.indexOf("+")>1) return false s=stripCharsInBag(strPhone,validWorldPhoneChars); return (isInteger(s) && s.length >= minDigitsInIPhoneNumber); } function validateEmail(elem) { var str = elem.value; if(str != undefined && str != ""){ var at="@" var dot="." var lat=str.indexOf(at) var lstr=str.length var ldot=str.indexOf(dot) if (str.indexOf(at)==-1){ alert("Invalid E-mail, it must contain the @ character"); elem.style.background = "orange"; elem.focus(); return false } if (str.indexOf(at)==0 || str.indexOf(at)==lstr){ alert("Invalid E-mail"); elem.style.background = "orange"; elem.focus(); return false } if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){ alert("Invalid E-mail"); elem.style.background = "orange"; elem.focus(); return false } if (str.indexOf(at,(lat+1))!=-1){ alert("Invalid E-mail"); elem.style.background = "orange"; elem.focus(); return false } if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){ alert("Invalid E-mail"); elem.style.background = "orange"; elem.focus(); return false } if (str.indexOf(dot,(lat+2))==-1){ alert("Invalid E-mail"); elem.style.background = "orange"; elem.focus(); return false } if (str.indexOf(" ")!=-1){ alert("Invalid E-mail"); elem.style.background = "orange"; elem.focus(); return false } } elem.style.background = "white"; return true } function getBaseId(srcElem){ alert(event.srcElement.id); debugger; /*id = src.id; lastColon = id.lastIndexOf(':'); if (lastColon == -1) { basePath = ""; } else { basePath = id.substring(0, lastColon + 1);*/ return false; } <file_sep>/ksno3/src/java/ksno/ui/jsf/converter/WorkCategoryConverter.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.converter; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import ksno.dao.hibernate.WorkCategoryDaoImpl; import ksno.model.Category; import ksno.model.Person; import ksno.model.WorkCategory; import ksno.service.WorkCategoryService; import ksno.service.WorkCategoryServiceImpl; import ksno.service.PersonService; import ksno.service.PersonServiceImpl; import ksno.util.JSFUtil; /** * * @author tor.hauge */ public class WorkCategoryConverter implements Converter { private Logger getLogService(){ return Logger.getLogger(WorkCategoryConverter.class.getName()); } private WorkCategoryService getWorkCategoryService(){ WorkCategoryService service = null; try { service = (WorkCategoryService) JSFUtil.getBeanValue("#{WorkCategoryService}", WorkCategoryService.class); //return (ArticleCategoryService)FacesContextUtils.getWebApplicationContext(context).getBean("articleCategoryService"); } catch (Exception ex) { Logger.getLogger(WorkCategoryConverter.class.getName()).log(Level.SEVERE, null, ex); } return service; } public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException { getLogService().log(Level.INFO,"About to convert " + value + " to a Category"); //ArticleCategoryDaoImpl dao = new ArticleCategoryDaoImpl(); //return dao.getArticleCategory(Long.parseLong(value)); return getWorkCategoryService().getWorkCategory(Long.parseLong(value)); } public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException { if(null == value){ return null; } getLogService().log(Level.INFO,"About to convert " + value.toString() + " to a string"); WorkCategory category = (WorkCategory)value; return category.getId().toString(); } } <file_sep>/ksno3/src/java/ksno/service/TransactionService.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.service; import java.util.List; import ksno.model.Transaction; /** * * @author tor.hauge */ public interface TransactionService { public Transaction getTransaction(Long id); public Long newTransaction(Transaction transaction); public void updateTransaction(Transaction transaction); public void deleteTransaction(Transaction transaction); public List getTransactions(); } <file_sep>/ksno3/src/java/ksno/ui/jsf/converter/PersonConverter.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.converter; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import ksno.model.Person; import ksno.service.PersonService; import ksno.service.PersonServiceImpl; import ksno.util.JSFUtil; /** * * @author tor.hauge */ public class PersonConverter implements Converter { private Logger getLogService(){ return Logger.getLogger(CategoryConverter.class.getName()); } private PersonService getPersonService(){ PersonService service = null; try { service = (PersonService) JSFUtil.getBeanValue("#{PersonService}", PersonService.class); } catch (Exception ex) { Logger.getLogger(CategoryConverter.class.getName()).log(Level.SEVERE, null, ex); } return service; } public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException { getLogService().log(Level.INFO,"About to convert " + value + " to a Category"); //ArticleCategoryDaoImpl dao = new ArticleCategoryDaoImpl(); //return dao.getArticleCategory(Long.parseLong(value)); return getPersonService().getPerson(Long.parseLong(value)); } public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException { if(null == value){ getLogService().log(Level.INFO,"Value is null, and null is returned"); return null; } getLogService().log(Level.INFO,"About to convert " + value.toString() + " to a string"); Person person = (Person)value; return person.getId().toString(); } } <file_sep>/ksno3/src/java/ksno/dao/EventDao.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.dao; import java.util.Calendar; import java.util.Date; import java.util.List; import ksno.model.BeginnerCourse; import ksno.model.Event; /** * * @author halsnehauge */ public interface EventDao { public Long newEvent(Event event); public void deleteEvent(Event event); public void updateEvent(Event event); public List getEvents(); public List getEvents(Calendar fromDate); public Event getEvent(Long id); public BeginnerCourse getBeginnerCourse(Long id); public BeginnerCourse getBeginnerCourse(String prettyPrintId); public List getBeginnerCourses(); public List<BeginnerCourse> getBeginnerCourses(Calendar fromDate); public List getBeginnerCourses(Date fromDate, Date toDate, String location); public List getOpenBeginnerCourses(); public List getOpenBeginnerCourses(Date fromDate, Date toDate, String location); } <file_sep>/ksno3/src/java/ksno/ui/jsf/converter/ExperienceLevelConverter.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.converter; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import ksno.model.ExperienceLevel; import ksno.service.ExperienceLevelService; import ksno.util.JSFUtil; /** * * @author tor.hauge */ public class ExperienceLevelConverter implements Converter { private Logger getLogService(){ return Logger.getLogger(ExperienceLevelConverter.class.getName()); } private ExperienceLevelService getExperienceLevelService(){ ExperienceLevelService service = null; try { service = (ExperienceLevelService) JSFUtil.getBeanValue("#{ExperienceLevelService}", ExperienceLevelService.class); //return (ArticleCategoryService)FacesContextUtils.getWebApplicationContext(context).getBean("articleCategoryService"); } catch (Exception ex) { Logger.getLogger(ExperienceLevelConverter.class.getName()).log(Level.SEVERE, null, ex); } return service; } public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException { getLogService().log(Level.INFO,"About to convert " + value + " to a Category"); //ArticleCategoryDaoImpl dao = new ArticleCategoryDaoImpl(); //return dao.getArticleCategory(Long.parseLong(value)); return getExperienceLevelService().getExperienceLevel(Long.parseLong(value)); } public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException { if(null == value){ return null; } getLogService().log(Level.INFO,"About to convert " + value.toString() + " to a string"); ExperienceLevel level = (ExperienceLevel)value; return level.getId().toString(); } } <file_sep>/ksno3/src/java/ksno/ui/jsf/backing/TransactionCreate.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.backing; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.model.SelectItem; import ksno.model.Image; import ksno.model.Person; import ksno.model.Transaction; import ksno.service.DocumentService; import ksno.service.ImageService; import ksno.service.PersonService; import ksno.service.TransactionService; import ksno.util.ImageMeta; import ksno.util.JSFUtil; import org.apache.myfaces.component.html.ext.HtmlInputText; import org.apache.myfaces.component.html.ext.HtmlOutputText; import org.apache.myfaces.component.html.ext.HtmlSelectOneMenu; import org.apache.myfaces.custom.fileupload.UploadedFile; /** * * @author tor.hauge */ public class TransactionCreate { private HtmlInputText comment; private HtmlInputText date; private HtmlInputText amount; private HtmlSelectOneMenu category; private HtmlSelectOneMenu customerSelect; private HtmlOutputText upAttachmentResult; private HtmlOutputText errorMsg; private UploadedFile upAttachment; private TransactionService transactionService; private PersonService personService; private ImageService imageService; private DocumentService documentService; // <editor-fold defaultstate="collapsed" desc=" getters and setters"> public HtmlSelectOneMenu getCustomerSelect() { return customerSelect; } public void setCustomerSelect(HtmlSelectOneMenu customerSelect) { this.customerSelect = customerSelect; } public DocumentService getDocumentService() { return documentService; } public void setDocumentService(DocumentService documentService) { this.documentService = documentService; } public HtmlInputText getAmount() { return amount; } public void setAmount(HtmlInputText amount) { this.amount = amount; } public ImageService getImageService() { return imageService; } public void setImageService(ImageService imageService) { this.imageService = imageService; } public UploadedFile getUpAttachment() { return upAttachment; } public void setUpAttachment(UploadedFile upAttachment) { this.upAttachment = upAttachment; } public HtmlOutputText getUpAttachmentResult() { return upAttachmentResult; } public void setUpAttachmentResult(HtmlOutputText upAttachmentResult) { this.upAttachmentResult = upAttachmentResult; } public PersonService getPersonService() { return personService; } public void setPersonService(PersonService personService) { this.personService = personService; } public HtmlInputText getDate() { return date; } public void setDate(HtmlInputText date) { this.date = date; } public HtmlSelectOneMenu getCategory() { return category; } public void setCategory(HtmlSelectOneMenu category) { this.category = category; } public HtmlInputText getComment() { return comment; } public void setComment(HtmlInputText comment) { this.comment = comment; } public HtmlOutputText getErrorMsg() { return errorMsg; } public void setErrorMsg(HtmlOutputText errorMsg) { this.errorMsg = errorMsg; } public TransactionService getTransactionService() { return transactionService; } public void setTransactionService(TransactionService transactionService) { this.transactionService = transactionService; } private Logger getLogService(){ return Logger.getLogger(this.getClass().getName()); } // </editor-fold> public SelectItem[] getCustomers(){ List persons = personService.getPersons(); return JSFUtil.toSelectItemArray(persons, true); } public String createTransaction(){ String returnVal = "success"; try{ Transaction transaction = new Transaction(); transaction.setComment(comment.getValue().toString()); transaction.setCategory(category.getValue().toString()); transaction.setDate((Calendar)date.getValue()); transaction.setAmount(Double.parseDouble(amount.getValue().toString())); String userName = JSFUtil.getRequest().getUserPrincipal().getName(); Person currentUser = personService.getPerson(userName); transaction.setOwner(currentUser); HashMap<ImageMeta,String> imageSize = imageService.uploadImage(upAttachment.getInputStream(), userName); Image image = new Image(); image.setOwner(currentUser); image.setName(imageSize.get(ImageMeta.sizeMAX)); image.setUrl(imageSize.get(ImageMeta.url)); transaction.setImage(image); transactionService.newTransaction(transaction); }catch(Exception e){ getLogService().log(Level.SEVERE,"Unable to create transaction", e); errorMsg.setValue("Transaksjonen ble ikke lagret, forsøk på nytt. Detaljert feilmelding: " + e.getMessage()); returnVal = "no"; } return returnVal; } } <file_sep>/ksno3/src/java/ksno3/ApplicationBean1.java /* * ApplicationBean1.java * * Created on 21.sep.2008, 21:10:07 */ package ksno3; import com.sun.rave.web.ui.appbase.AbstractApplicationBean; import java.util.Calendar; import java.util.List; import javax.faces.FacesException; import ksno.model.Article; import ksno.model.BeginnerCourse; import ksno.model.Category; import ksno.model.ExperienceLevel; import ksno.model.Video; import ksno.model.WorkCategory; import ksno.util.JSFUtil; /** * <p>Application scope data bean for your application. Create properties * here to represent cached data that should be made available to all users * and pages in the application.</p> * * <p>An instance of this class will be created for you automatically, * the first time your application evaluates a value binding expression * or method binding expression that references a managed bean using * this class.</p> * * @author halsnehauge */ public class ApplicationBean1 extends AbstractApplicationBean { // <editor-fold defaultstate="collapsed" desc="Managed Component Definition"> /** * <p>Automatically managed component initialization. <strong>WARNING:</strong> * This method is automatically generated, so any user-specified code inserted * here is subject to being replaced.</p> */ private void _init() throws Exception { } // </editor-fold> public String getPrettyURLHome(){ return JSFUtil.prettyURLHome; } public String getPrettyURLArticlesAndVideos(){ return JSFUtil.prettyURLArticlesAndVideos; } public String getPrettyURLArticle(){ return JSFUtil.prettyURLArticle; } public String getPrettyURLCourseSummer(){ return JSFUtil.prettyURLCourseSummer; } public String getPrettyURLCourseWinter(){ return JSFUtil.prettyURLCourseWinter; } public String getPrettyURLAboutUs(){ return JSFUtil.prettyURLAboutUs; } public String getContextPath(){ return JSFUtil.getRequest().getContextPath(); } /** * <p>Construct a new application data bean instance.</p> */ public ApplicationBean1() { } /** * <p>This method is called when this bean is initially added to * application scope. Typically, this occurs as a result of evaluating * a value binding or method binding expression, which utilizes the * managed bean facility to instantiate this bean and store it into * application scope.</p> * * <p>You may customize this method to initialize and cache application wide * data values (such as the lists of valid options for dropdown list * components), or to allocate resources that are required for the * lifetime of the application.</p> */ @Override public void init() { // Perform initializations inherited from our superclass super.init(); // Perform application initialization that must complete // *before* managed components are initialized // TODO - add your own initialiation code here // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization"> // Initialize automatically managed components // *Note* - this logic should NOT be modified try { _init(); } catch (Exception e) { log("ApplicationBean1 Initialization Failure", e); throw e instanceof FacesException ? (FacesException) e: new FacesException(e); } // </editor-fold> // Perform application initialization that must complete // *after* managed components are initialized // TODO - add your own initialization code here } /** * <p>This method is called when this bean is removed from * application scope. Typically, this occurs as a result of * the application being shut down by its owning container.</p> * * <p>You may customize this method to clean up resources allocated * during the execution of the <code>init()</code> method, or * at any later time during the lifetime of the application.</p> */ @Override public void destroy() { } /** * <p>Return an appropriate character encoding based on the * <code>Locale</code> defined for the current JavaServer Faces * view. If no more suitable encoding can be found, return * "UTF-8" as a general purpose default.</p> * * <p>The default implementation uses the implementation from * our superclass, <code>AbstractApplicationBean</code>.</p> */ @Override public String getLocaleCharacterEncoding() { return super.getLocaleCharacterEncoding(); } private List events; private List eventsFromThisYear; private List<BeginnerCourse> beginnerCoursesFromThisYear; private List<Article> articles; private List<Video> videos; private List onDutys; private List<ExperienceLevel> experienceLevels; public List<ExperienceLevel> getExperienceLevels() { return experienceLevels; } public void setExperienceLevels(List<ExperienceLevel> experienceLevels) { this.experienceLevels = experienceLevels; } private List<WorkCategory> workCategorys; public List<WorkCategory> getWorkCategorys() { return workCategorys; } public void setWorkCategorys(List<WorkCategory> workCategorys) { this.workCategorys = workCategorys; } public List getOnDutys() { return onDutys; } public void setOnDutys(List onDutys) { this.onDutys = onDutys; } public List<Video> getVideos() { return videos; } public void setVideos(List<Video> videos) { this.videos = videos; } private List<Category> articleCategorys; public List<BeginnerCourse> getBeginnerCoursesFromThisYear() { return beginnerCoursesFromThisYear; } public void setBeginnerCoursesFromThisYear(List<BeginnerCourse> beginnerCoursesFromThisYear) { this.beginnerCoursesFromThisYear = beginnerCoursesFromThisYear; } public List<Category> getArticleCategorys() { return articleCategorys; } public void setArticleCategorys(List<Category> articleCategorys) { this.articleCategorys = articleCategorys; } public List getEventsFromThisYear() { return eventsFromThisYear; } public void setEventsFromThisYear(List eventsFromThisYear) { this.eventsFromThisYear = eventsFromThisYear; } public List<Article> getArticles() { return articles; } public void setArticles(List<Article> articles) { this.articles = articles; } private List persons; private Calendar youTubeListLastScanned; private List instructors; public List getInstructors() { return instructors; } public void setInstructors(List instructors) { this.instructors = instructors; } public Calendar getYouTubeListLastScanned() { return youTubeListLastScanned; } public void setYouTubeListLastScanned(Calendar youTubeListLastScanned) { this.youTubeListLastScanned = youTubeListLastScanned; } public List getEvents() { return events; } public void setEvents(List events) { this.events = events; } public List getPersons() { return persons; } public void setPersons(List persons) { this.persons = persons; } } <file_sep>/ksno3/src/java/ksno/service/WorkCategoryServiceImpl.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.service; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import ksno.dao.WorkCategoryDao; import ksno.model.WorkCategory; import ksno.util.JSFUtil; /** * * @author tor.hauge */ public class WorkCategoryServiceImpl implements WorkCategoryService { private WorkCategoryDao workCategoryDao; private Logger getLogService(){ return Logger.getLogger(WorkCategoryServiceImpl.class.getName()); } public WorkCategoryDao getWorkCategoryDao() { return workCategoryDao; } public void setWorkCategoryDao(WorkCategoryDao WorkCategoryDao) { this.workCategoryDao = WorkCategoryDao; } public WorkCategory getWorkCategory(Long id) { return workCategoryDao.getWorkCategory(id); } public Long newWorkCategory(WorkCategory category) { JSFUtil.clearApplicationCache(JSFUtil.appCacheWorkCategories); return workCategoryDao.newWorkCategory(category); } public void updateWorkCategory(WorkCategory category) { JSFUtil.clearApplicationCache(JSFUtil.appCacheWorkCategories); workCategoryDao.updateWorkCategory(category); } public void deleteWorkCategory(WorkCategory category) { JSFUtil.clearApplicationCache(JSFUtil.appCacheWorkCategories); workCategoryDao.deleteWorkCategory(category); } public List<WorkCategory> getWorkCategorys() { Class c = null; try { c = Class.forName("java.util.List"); } catch (ClassNotFoundException ex) { getLogService().log(Level.SEVERE, null, ex); } List<WorkCategory> returnList = (List)JSFUtil.getValue("#{ApplicationBean1." + JSFUtil.appCacheWorkCategories + "}", c); if(returnList == null){ returnList = workCategoryDao.getWorkCategorys(); JSFUtil.setValue("#{ApplicationBean1." + JSFUtil.appCacheWorkCategories + "}", returnList, c); } return returnList; } } <file_sep>/ksno3/src/java/ksno/service/ExperienceLevelService.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.service; import java.util.List; import ksno.model.ExperienceLevel; /** * * @author tor.hauge */ public interface ExperienceLevelService { public ExperienceLevel getExperienceLevel(Long id); public Long newExperienceLevel(ExperienceLevel experienceLevel); public void updateExperienceLevel(ExperienceLevel experienceLevel); public void deleteExperienceLevel(ExperienceLevel experienceLevel); public List<ExperienceLevel> getExperienceLevels(); } <file_sep>/ksno3/src/java/ksno/service/ArticleService.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.service; import java.util.List; import ksno.model.Article; import ksno.model.Category; /** * * @author Tor-Erik */ public interface ArticleService { public Article getArticle(Long id); public Article getArticle(String prettyPrintId); public Long newArticle(Article article); public void updateArticle(Article article); public void deleteArticle(Article article); public List getArticles(); public Category getCategory(String name); public Category getCategory(Long id); public List<Category> getCategories(); public List<Article> getVisibleArticles(); public List<Article> getArticlesByCategory(Category category); } <file_sep>/ksno3/src/java/ksno/ui/jsf/backing/CoursesWinter.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.ui.jsf.backing; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.model.SelectItem; import ksno.model.Category; import ksno.model.Video; import ksno.service.ArticleService; import ksno.service.EventService; import ksno.service.VideoService; import ksno.util.JSFUtil; import org.apache.myfaces.component.html.ext.HtmlSelectOneMenu; /** * * @author tor.hauge */ public class CoursesWinter { private EventService eventService; private ArticleService articleService; private VideoService videoService; private HtmlSelectOneMenu coursesSelect; public HtmlSelectOneMenu getCoursesSelect() { return coursesSelect; } public boolean isHaveUpcomingActiveCourses(){ SelectItem[] arr = getCoursesSelectItems(); return arr != null && arr.length > 0; } public void setCoursesSelect(HtmlSelectOneMenu coursesSelect) { this.coursesSelect = coursesSelect; } public ArticleService getArticleService() { return articleService; } public void setArticleService(ArticleService articleService) { this.articleService = articleService; } public VideoService getVideoService() { return videoService; } public void setVideoService(VideoService videoService) { this.videoService = videoService; } public EventService getEventService() { return eventService; } public void setEventService(EventService eventService) { this.eventService = eventService; } public List getCourses(){ return eventService.getOpenUpcommingWinterBeginnerCourses(); } public SelectItem[] getCoursesSelectItems() { List events = eventService.getOpenUpcommingWinterBeginnerCourses(); return JSFUtil.toSelectItemArray(events); } public List<ksno.model.Article> getCourseArticles(){ getLogService().log(Level.INFO, "Start getCourseArticles()"); Category category = new Category(); category.setName("Vinterkurs"); List<ksno.model.Article> returnList = getArticleService().getArticlesByCategory(category); getLogService().log(Level.INFO, "Found a list of " + returnList.size() + " articles."); while(returnList.size() > 5){ returnList.remove(returnList.size()-1); } return returnList; } public List<Video> getCourseVideos(){ getLogService().log(Level.INFO, "Start getCourseVideos()"); Category category = new Category(); category.setName("Vinterkurs"); List<Video> returnList = getVideoService().getVideosByCategory(category); getLogService().log(Level.INFO, "Found a list of " + returnList.size() + " videos."); while(returnList.size() > 5){ returnList.remove(returnList.size()-1); } return returnList; } private Logger getLogService() { return Logger.getLogger(this.getClass().getName()); } public List getFiveNextCourses(){ getLogService().log(Level.INFO, "Start getting four next courses"); List<ksno.model.BeginnerCourse> courses = this.getCourses(); Iterator <ksno.model.BeginnerCourse> courseIterator = courses.iterator(); List<ksno.model.BeginnerCourse> returnList = new LinkedList<ksno.model.BeginnerCourse>(); while(courseIterator.hasNext() && returnList.size()<5){ ksno.model.BeginnerCourse course = courseIterator.next(); returnList.add(course); } getLogService().log(Level.INFO, "Finished getting four next courses, returning a list of " + returnList.size() + " courses."); return returnList; } public List getEightNextCourses(){ getLogService().log(Level.INFO, "Start getting four next courses"); List<ksno.model.BeginnerCourse> courses = this.getCourses(); Iterator <ksno.model.BeginnerCourse> courseIterator = courses.iterator(); List<ksno.model.BeginnerCourse> returnList = new LinkedList<ksno.model.BeginnerCourse>(); while(courseIterator.hasNext() && returnList.size()<8){ ksno.model.BeginnerCourse course = courseIterator.next(); returnList.add(course); } getLogService().log(Level.INFO, "Finished getting four next courses, returning a list of " + returnList.size() + " courses."); return returnList; } public boolean isMoreThanFourCourses(){ return this.getCourses().size() > 4; } } <file_sep>/ksno3/src/java/ksno/util/KSNOutil.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.util; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author tor.hauge */ public class KSNOutil { private static Logger getLogService(){ return Logger.getLogger(KSNOutil.class.getName()); } public static String injectPlaceHolders(String stringToBeInjected, HashMap<String, String> placeHolderValueMap) { getLogService().log(Level.INFO,"Start"); String temp = stringToBeInjected; if(stringToBeInjected != null && !"".equals(stringToBeInjected) && placeHolderValueMap != null){ Iterator iter = placeHolderValueMap.entrySet().iterator(); while(iter.hasNext()){ Entry<String, String> entry = (Entry<String, String>)iter.next(); temp = temp.replaceAll("~" + entry.getKey() + "~", entry.getValue()); } } getLogService().log(Level.INFO,"Return"); return temp; } public static String getPrettyPrintId(Date date, String title){ getLogService().log(Level.INFO,"Start"); Calendar cal = Calendar.getInstance(); cal.setTime(date); String toBeReturned = "/" + cal.get(Calendar.YEAR) + "/" + getWithLeadingZero(cal.get(Calendar.MONTH) + 1) + "/" + getWithLeadingZero(cal.get(Calendar.DAY_OF_MONTH)) + "/" + title.replace(" ", "-"); getLogService().log(Level.INFO,"Returning string " + toBeReturned); return toBeReturned; } public static String getPrettyPrintId(Date date){ getLogService().log(Level.INFO,"Start"); Calendar cal = Calendar.getInstance(); cal.setTime(date); String toBeReturned = "/" + cal.get(Calendar.YEAR) + "/" + getWithLeadingZero(cal.get(Calendar.MONTH) + 1) + "/" + getWithLeadingZero(cal.get(Calendar.DAY_OF_MONTH)); getLogService().log(Level.INFO,"Returning string " + toBeReturned); return toBeReturned; } public static String getWithLeadingZero(int number){ if(number < 10){ return "0" + number; }else{ return "" + number; } } } <file_sep>/ksno3/src/java/ksno/service/ImageService.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.service; import java.io.InputStream; import java.util.HashMap; import ksno.model.Image; import ksno.util.ImageMeta; /** * * @author halsnehauge */ public interface ImageService { public Long newImage(Image image); public HashMap<ImageMeta,String> uploadImage(InputStream stream, String userName) throws Exception; } <file_sep>/ksno3/src/java/ksno/model/ExperienceLevel.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.model; import java.io.Serializable; /** * * @author Roger */ public class ExperienceLevel implements LabelObjectValuePair, LabelValuePair, Serializable { private Long id; private int version; private String name; private int rank; // <editor-fold defaultstate="collapsed" desc=" Getters and setters"> public int getRank() { return rank; } public void setRank(int rank) { this.rank = rank; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getStringId(){ return this.id.toString(); } public void setStringId(String id){ this.id = Long.parseLong(id); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" equals and hashcode"> @Override public boolean equals(Object obj) { if (obj == null) { return false; } final ExperienceLevel other = (ExperienceLevel) obj; if ((this.getId() == null) ? (other.getId() != null) : !this.getId().equals(other.getId())) { return false; } return true; } @Override public String toString() { return "WorkCategory: " + this.getName(); } @Override public int hashCode() { int hash = 7; hash = 97 * hash + (this.name != null ? this.name.hashCode() : 0); return hash; } public String getLabel() { return this.getName(); } public Object getObject() { return this; } public String getValue() { return this.getId().toString(); } // </editor-fold> } <file_sep>/ksno3/src/java/ksno/model/UserRoles.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.model; /** * * @author tor.hauge */ public class UserRoles { private Person user; private String role; private Long id; private int version; // <editor-fold defaultstate="collapsed" desc=" getters and setters"> public Long getId() { return id; } public void setId(Long id) { this.id = id; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public Person getUser() { return user; } public void setUser(Person user) { this.user = user; } // </editor-fold> } <file_sep>/ksno3/src/java/ksno/dao/hibernate/WorkCategoryDaoImpl.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ksno.dao.hibernate; import java.util.List; import ksno.dao.WorkCategoryDao; import ksno.model.WorkCategory; import ksno.util.HibernateUtil; import org.hibernate.Query; import org.hibernate.Session; /** * * @author tor.hauge */ public class WorkCategoryDaoImpl implements WorkCategoryDao { public WorkCategory getWorkCategory(Long id) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); WorkCategory category = (WorkCategory)session.get(WorkCategory.class,id); return category; } public Long newWorkCategory(WorkCategory category) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Long l = (Long)session.save(category); return l; } public void updateWorkCategory(WorkCategory category) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); try{ session.saveOrUpdate(category); }catch(Exception e){ session.merge(category); } } public void deleteWorkCategory(WorkCategory category) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.delete(category); } public List<WorkCategory> getWorkCategorys() { Query q = null; List returnVal = null; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); q=session.createQuery("from WorkCategory c order by c.name desc"); returnVal = q.list(); return returnVal; } }
00caadb2aed3f066880fa0177911771b3aabd85b
[ "JavaScript", "Java" ]
62
Java
Torsi007/ksno3
d37fd07065fc524c79874d00bb4600aa752c4609
ee35cff726dc131220a3e1409000a522c57519a4
refs/heads/master
<file_sep><?php add_action('admin_menu', 'x_social_register_sub_menu_page_like'); function x_social_register_sub_menu_page_like(){ add_submenu_page( 'x-social', 'Social Like', 'Like', 'manage_options', 'social-like', 'x_social_register_options_like'); } function x_social_register_options_like() { }<file_sep><?php add_shortcode('x-social-login', 'x_social_login_form_render'); function x_social_login_form_render($params, $content = null) { global $current_user; extract(shortcode_atts(array( 'class' => '' ), $params)); ob_start(); ?> <div class="cs-login-form"> <?php if ( is_user_logged_in() ) : $user_ID = $current_user->ID; ?> <div class="bp-login-widget-user-avatar"> <a href="<?php echo get_edit_user_link( $user_ID ); ?>"> <?php if(get_user_meta( $user_ID,'_fbid' )){ $image = get_user_meta( $user_ID,'cs_user_picture'); echo '<img alt="'.$current_user->display_name.'" src="'.$image[0].'"/>'; } else { echo get_avatar( $user_ID, 128 ); } ?> </a> </div> <div class="bp-login-widget-user-links"> <div class="bp-login-widget-user-link"><a href="<?php echo get_edit_user_link( get_the_author_id() ); ?>"><?php echo $current_user->display_name; ?></a></div> <div class="bp-login-widget-user-logout"><a class="logout" href="<?php echo wp_logout_url(); ?>"><?php _e( 'Log Out', 'buddypress' ); ?></a></div> </div> <?php else : ?> <div class="social-login"> <?php if(get_option('x_facebook_login', 'off') == 'on'): ?> <button class="facebook-login btn btn-primary"><i class="<?php echo get_option('x_facebook_login_icon', 'fa fa-facebook') ?>"></i></button> <?php endif; ?> <?php if(get_option('x_google_login', 'off') == 'on'): ?> <button class="google-login btn btn-primary"><i class="<?php echo get_option('x_google_login_icon', 'fa fa-google-plus') ?>"></i></button> <?php endif; ?> <?php if(get_option('x_live_login', 'off') == 'on'): ?> <button class="live-login btn btn-primary"><i class="<?php echo get_option('x_live_login_icon', 'fa fa-windows') ?>"></i></button> <?php endif; ?> </div> <?php if(get_option('x_login_form', 'on') == 'on'): ?> <form name="bp-login-form" id="bp-login-widget-form" class="standard-form" action="<?php echo esc_url( site_url( 'wp-login.php', 'login_post' ) ); ?>" method="post"> <p><label for="bp-login-widget-user-login"><?php _e( 'Username', 'buddypress' ); ?></label> <input type="text" name="log" id="bp-login-widget-user-login" class="input" value="" /></p> <p><label for="bp-login-widget-user-pass"><?php _e( 'Password', '<PASSWORD>' ); ?></label> <input type="<PASSWORD>" name="pwd" id="bp-login-widget-user-pass" class="input" value="" /></p> <div class="forgetmenot"><label><input name="rememberme" type="checkbox" id="bp-login-widget-rememberme" value="forever" /> <?php _e( 'Remember Me', 'buddypress' ); ?></label></div> <input type="submit" class="btn btn-default-alt" name="wp-submit" id="bp-login-widget-submit" value="<?php esc_attr_e( 'Log In', 'buddypress' ); ?>" /> <span class="bp-login-widget-register-link"><?php printf( __( '<a href="%s" title="Register for a new account">Register</a>', 'buddypress' ),''); ?></span> </form> <?php endif; ?> <?php endif; ?> </div> <?php return ob_get_clean(); }<file_sep>// Additional JS functions here window.fbAsyncInit = function() { FB.init({ appId : facebook.api, cookie : true, // enable cookies to allow the server to access xfbml : true, // parse social plugins on this page version : 'v2.1' // use version 2.1 }); }; // Load the SDK asynchronously (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/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); // Login jQuery(document).ready(function($) { jQuery('.facebook-login').click(function() { FB.login(function(FB_response) { if (FB_response.status === 'connected') { fb_intialize(FB_response); } }, { scope : 'public_profile,email' }); }); function fb_intialize(FB_response) { FB.api('/me', 'GET', { 'fields' : 'id,email,verified,name' }, function(FB_userdata) { FB_userdata.image = 'https://graph.facebook.com/' + FB_userdata.id + '/picture'; $.post(facebook.ajaxurl, { "action" : "social_intialize", "FB_userdata" : FB_userdata, "FB_response" : FB_response }, function(user) { if(user.url != ''){ window.location(user.url); } else { location.reload(); } }); }); } ; });<file_sep><?php global $pagenow; add_action('admin_menu', 'x_social_register_menu_page'); add_action('admin_init', 'x_social_register_options' ); add_action( 'admin_enqueue_scripts', 'x_social_admin_scripts' ); function x_social_register_menu_page() { add_menu_page('X Social Setting', 'Setting', 'manage_options', 'x-social', 'x_social_menu_page', 'dashicons-share', 6); } function x_social_register_options() { } function x_social_admin_scripts(){ wp_enqueue_style('x-social-admin', X_PLUGIN_URL . 'assets/css/x.social.admin.css'); } function x_social_menu_page() { ob_start(); ?> <div class="wrap"> <form method="post" action="options.php"> <?php settings_fields( 'baw-settings-group' ); do_settings_sections( 'baw-settings-group' ); ?> <?php x_options(array( 'id'=>'images', 'label' => 'BG', 'type' => 'select', 'value' => '2', 'options' => array('1'=>'1','2'=>'2'), 'desc' => 'BG' )); ?> <?php submit_button(); ?> </form> </div> <?php echo '<div id="field_icon" style="display: none;"></div>'; echo ob_get_clean(); }<file_sep><?php require_once 'loginform/loginform.php';<file_sep><?php add_action('admin_menu', 'x_social_register_sub_menu_page_login'); add_action('admin_init', 'x_social_register_options_login' ); function x_social_register_sub_menu_page_login(){ add_submenu_page( 'x-social', 'Social Login', 'Login', 'manage_options', 'social-login', 'x_social_menu_page_login'); } function x_social_register_options_login() { register_setting( 'baw-settings-group', 'x_facebook_login' ); register_setting( 'baw-settings-group', 'x_facebook_api' ); register_setting( 'baw-settings-group', 'x_facebook_login_icon' ); register_setting( 'baw-settings-group', 'x_facebook_login_icon_color' ); register_setting( 'baw-settings-group', 'x_facebook_login_bt_color' ); register_setting( 'baw-settings-group', 'x_google_login' ); register_setting( 'baw-settings-group', 'x_google_api' ); register_setting( 'baw-settings-group', 'x_google_login_icon' ); register_setting( 'baw-settings-group', 'x_google_login_icon_color' ); register_setting( 'baw-settings-group', 'x_google_login_bt_color' ); register_setting( 'baw-settings-group', 'x_live_login' ); register_setting( 'baw-settings-group', 'x_live_api' ); register_setting( 'baw-settings-group', 'x_live_login_icon' ); register_setting( 'baw-settings-group', 'x_live_login_icon_color' ); register_setting( 'baw-settings-group', 'x_live_login_bt_color' ); register_setting( 'baw-settings-group', 'x_login_form' ); register_setting( 'baw-settings-group', 'x_login_redirect' ); register_setting( 'baw-settings-group', 'x_login_button_style' ); register_setting( 'baw-settings-group', 'x_login_redirect_page' ); } function x_social_menu_page_login() { ob_start(); ?> <div class="wrap"> <form method="post" action="options.php"> <?php settings_fields( 'baw-settings-group' ); do_settings_sections( 'baw-settings-group' ); ?> <div class="row"> <div class="x-box col-lg-6 col-md-6 col-sm-12 col-xs-12"> <h3><label><i class="dashicons dashicons-twitter"></i><?php _e(' Social Login', X_NAME); ?></label></h3> <div class="x-box-main"> <div class="row"> <?php x_options(array( 'id' => 'x_facebook_login', 'label' => 'Facebook', 'type' => 'switch', 'value' => 'off', 'follow'=> array( 'on' => array( 'x_facebook_api', 'x_facebook_login_icon', 'x_facebook_login_icon_color', 'x_facebook_login_bt_color' ) ), 'desc' => 'Login with Facebook account' )); ?> </div> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <?php x_options(array( 'id' => 'x_facebook_api', 'type' => 'text', 'icon' => 'fa fa-terminal', 'desc' => 'Facebook App ID' )); ?> </div> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <?php x_options(array( 'id' => 'x_facebook_login_icon', 'type' => 'icon', 'desc' => 'Select icon for button Facebook' )); ?> </div> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <?php x_options(array( 'id' => 'x_facebook_login_icon_color', 'type' => 'color', 'desc' => 'Set color for icon' )); ?> </div> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <?php x_options(array( 'id' => 'x_facebook_login_bt_color', 'type' => 'color', 'desc' => 'Set color for button' )); ?> </div> </div> <div class="row"> <?php x_options(array( 'id' => 'x_google_login', 'label' => 'Google+', 'type' => 'switch', 'value' => 'off', 'follow'=> array( 'on' => array( 'x_google_api', 'x_google_login_icon', 'x_google_login_icon_color', 'x_google_login_bt_color', ) ), 'desc' => 'Login with Google plus account' )); ?> </div> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <?php x_options(array( 'id' => 'x_google_api', 'type' => 'text', 'icon' => 'fa fa-terminal', 'desc' => 'Google App ID' )); ?> </div> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <?php x_options(array( 'id' => 'x_google_login_icon', 'type' => 'icon', 'desc' => 'Select icon for button Google+' )); ?> </div> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <?php x_options(array( 'id' => 'x_google_login_icon_color', 'type' => 'color', 'desc' => 'Set color for icon' )); ?> </div> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <?php x_options(array( 'id' => 'x_google_login_bt_color', 'type' => 'color', 'desc' => 'Set color for button' )); ?> </div> </div> <div class="row"> <?php x_options(array( 'id' => 'x_live_login', 'label' => 'Live', 'type' => 'switch', 'value' => 'off', 'follow'=> array( 'on' => array( 'x_live_api', 'x_live_login_icon', 'x_live_login_icon_color', 'x_live_login_bt_color', ) ), 'desc' => 'Login with Microsoft account' )); ?> </div> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <?php x_options(array( 'id' => 'x_live_api', 'type' => 'text', 'icon' => 'fa fa-terminal', 'desc' => 'Live App ID' )); ?> </div> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <?php x_options(array( 'id' => 'x_live_login_icon', 'type' => 'icon', 'desc' => 'Select icon for button Live' )); ?> </div> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <?php x_options(array( 'id' => 'x_live_login_icon_color', 'type' => 'color', 'desc' => 'Set color for icon' )); ?> </div> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <?php x_options(array( 'id' => 'x_live_login_bt_color', 'type' => 'color', 'desc' => 'Set color for button' )); ?> </div> </div> <?php ?> </div> </div> <div class="x-box col-lg-6 col-md-6 col-sm-12 col-xs-12"> <h3><label><i class="dashicons dashicons-admin-settings"></i><?php _e(' Setting', X_NAME); ?></label></h3> <div class="x-box-main"> <div class="row"> <?php x_options(array( 'id' => 'x_login_form', 'label' => 'Login Form', 'type' => 'switch', 'value' => 'on', 'desc' => 'Show Login Form' )); ?> </div> <div class="row"> <?php x_options(array( 'id' => 'x_login_redirect', 'label' => 'Login Redirect', 'type' => 'select', 'options' => array( '' => 'Current Page', '1' => 'Profile', '2' => 'Home', '3' => 'Post', '4' => 'Blog', '5' => 'Page', '6' => 'Custom Link', ), 'follow' => array( '3'=>array('x_login_redirect_post'), '5'=>array('x_login_redirect_page'), '6'=>array('x_login_redirect_custom') ), 'desc' => 'Select login redirect type' )); ?> </div> <div class="row"> <?php x_options(array( 'id' => 'x_login_redirect_post', 'label' => 'Post ID', 'type' => 'text', 'icon' => 'fa fa-pencil', 'desc' => 'Insert custom URL' )); ?> </div> <div class="row"> <?php x_options(array( 'id' => 'x_login_redirect_custom', 'label' => 'URL', 'type' => 'text', 'icon' => 'fa fa-code-fork', 'desc' => 'Insert custom URL' )); ?> </div> <div class="row"> <?php x_options(array( 'id' => 'x_login_redirect_page', 'label' => 'Page', 'type' => 'select', 'multiple' => false, 'data' => array('type'=> 'pages'), 'width' => '100%', 'desc' => 'Select a redirect page' )); ?> </div> <div class="row"> <?php x_options(array( 'id' => 'x_login_button_style', 'label' => 'Button Style', 'type' => 'select', 'width' => '100%', 'options' => array( '' => 'demo1', '1' => 'demo2', '2' => 'demo2', '3' => 'Flat', ), 'demo' => array( ''=>'#', '3'=>'<img width="100%" src="'.X_PLUGIN_URL.'assets/img/FlatSocialIcons.png">', ), 'desc' => 'Select style for button' )); ?> </div> <div class="row"> <?php x_options(array( 'id' => 'x_login_button_size', 'label' => 'Button Size', 'type' => 'number', 'value' => '40', 'format' => 'px' )); ?> </div> <div class="row"> <?php x_options(array( 'id' => 'x_login_button_margin', 'label' => 'Button Margin', 'type' => 'text', 'icon' => 'fa fa-arrows', 'placeholder' => '0px 0px 0px 0px' )); ?> </div> <div class="row"> <?php x_options(array( 'id' => 'x_login_button_margin', 'label' => 'Button Margin', 'type' => 'select', 'multiple' => true, 'data' => array( 'type'=> 'taxonomies', 'post_tag'=> 'category', 'options'=> array('hide_empty'=>true) ), )); ?> </div> <div class="row"> <?php x_options(array( 'id' => 'x_login_button_margin', 'label' => 'Button Margin', 'type' => 'select', 'multiple' => true, 'data' => array( 'type'=> 'postype' ), )); ?> </div> <div class="row"> <?php x_options(array( 'id' => 'x_login_button_margin1111', 'label' => 'Button Margin', 'google' => true, 'demo' => true, 'type' => 'fonts', )); ?> </div> <div class="row"> <?php x_options(array( 'id' => 'x_login_button_margin11113', 'label' => 'Button Margin', 'type' => 'tags', )); ?> </div> <div class="row"> <?php x_options(array( 'id' => 'x_login_button_margin11113', 'label' => 'Button Margin', 'type' => 'slider', 'value' => '0', 'max' => '100', 'min' => '0', )); ?> </div> <div class="row"> <?php x_options(array( 'id' => 'values', 'value' => '0', 'type' => 'values' )); ?> </div> </div> </div> </div> <button type="button" onclick="XOptionsGetAllValues()">TEST ALL VALUES</button> <?php submit_button(); ?> </form> </div> <?php echo '<div id="field_icon" style="display: none;"></div>'; echo ob_get_clean(); }<file_sep><?php add_action('admin_menu', 'x_social_register_sub_menu_page_comment'); function x_social_register_sub_menu_page_comment(){ add_submenu_page( 'x-social', 'Social Comment', 'Comment', 'manage_options', 'social-comment', 'x_social_register_options_comment'); } function x_social_register_options_comment() { }<file_sep><?php add_action('wp_head', 'cs_facebook_login_head'); function cs_facebook_login_head() { $ajaxurl = admin_url('admin-ajax.php'); wp_register_script('google-login', X_PLUGIN_URL . 'sociallogin/google.login.js'); wp_register_script('facebook-login', X_PLUGIN_URL . 'sociallogin/facebook.login.js'); wp_register_script('live-login', X_PLUGIN_URL . 'sociallogin/live.login.js'); //wp_register_script('linkedin-login', get_template_directory_uri() . '/framework/plugins/sociallogin/linkedin.login.js'); $data = array( 'api' => '564183186994005', 'ajaxurl' => $ajaxurl ); wp_localize_script('google-login', 'google', $data); wp_localize_script('facebook-login', 'facebook', $data); wp_localize_script('live-login', 'live', $data); //wp_localize_script('linkedin-login', 'linkedin', $data); wp_enqueue_script('google-login'); wp_enqueue_script('facebook-login'); wp_enqueue_script('live-login'); //wp_enqueue_script('linkedin-login'); } add_action('wp_ajax_nopriv_social_intialize', 'cs_ajax_social_intialize'); function cs_ajax_social_intialize() { @error_reporting(0); // Don't break the JSON result header('Content-type: application/json'); if (! isset($_REQUEST['FB_response']) || ! isset($_REQUEST['FB_userdata'])) die(json_encode(array( 'error' => __('Authenication required.', THEMENAME) ))); $response = $_REQUEST['FB_response']; $userdata = $_REQUEST['FB_userdata']; $userid = $userdata['id']; if (! $userid) die(json_encode(array( 'error' => __('Please connect your facebook account.', THEMENAME) ))); global $wpdb; // check if we already have matched our facebook account $user_ID = $wpdb->get_var("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '_fbid' AND meta_value = '$userid'"); // if facebook is not connected extract($userdata); if (! $user_ID) { $user_email = $userdata['email']; $user_ID = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE user_email = '" . $wpdb->escape($user_email) . "'"); $redirect = ''; // Register user if (! $user_ID) { // Check admin options if (! get_option('users_can_register')) { die(json_encode(array( 'error' => __('Registration is not open at this time. Please come back later.', THEMENAME) ))); } // Get first,last,display name $display_name = $name; $first_name = ''; $last_name = ''; $name_array = explode(' ', $name, 2); $first_name = $name_array[0]; if (isset($name_array[1])) { $last_name = $name_array[1]; } // Check facebook account if (empty($verified) || ! $verified) die(json_encode(array( 'error' => __('Your facebook account is not verified. You have to verify your account before proceed login or registering on this site.', THEMENAME) ))); $user_email = $email; if (empty($user_email)) die(json_encode(array( 'error' => __('Please re-connect your facebook account as we couldn\'t find your email address.', THEMENAME) ))); if (empty($name)) die(json_encode(array( 'error' => 'empty_name', __('We didn\'t find your name. Please complete your facebook account before proceeding.', THEMENAME) ))); // Create user login $user_login = sanitize_title_with_dashes(sanitize_user($display_name, true)); if (username_exists($user_login)) { $user_login = $user_login . time(); } // Create pass $user_pass = wp_generate_password(12, false); $userdata = compact('user_login', 'user_email', 'user_pass', 'display_name', 'first_name', 'last_name'); // Insert user $user_ID = wp_insert_user($userdata); if (is_wp_error($user_ID)) { die(json_encode(array( 'error' => $user_ID->get_error_message() ))); } // Send email with password wp_new_user_notification($user_ID, wp_unslash($user_pass)); add_user_meta( $user_ID, '_fbid', $id ); // Add Facebook image add_user_meta($user_ID, 'cs_user_picture', $image); die(json_encode(array( 'error' => __($user_ID, THEMENAME) ))); $logintype = 'register'; } else { wp_update_user(array( 'display_name' => $name )); update_user_meta( $user_ID, '_fbid', (int) $id ); // Add Facebook image update_user_meta($user_ID, 'cs_user_picture', $image); $logintype = 'login'; } } else { $logintype = 'login'; } wp_set_auth_cookie( $user_ID, false, false ); switch (get_option('x_login_redirect')){ case '1': $redirect = get_edit_user_link($user_ID); break; case '2': $redirect = home_url(); break; case '3': break; case '4': break; case '5': break; case '6': $redirect = '#'; break; default: $redirect = ''; break; } die( json_encode( array( 'loggedin' => true, 'type' => $logintype, 'url' => $redirect, 'siteUrl' => home_url() ))); }<file_sep><?php add_action('admin_menu', 'x_social_register_sub_menu_page_share'); function x_social_register_sub_menu_page_share(){ add_submenu_page( 'x-social', 'Social Share', 'Share', 'manage_options', 'social-share', 'x_social_register_options_share'); } function x_social_register_options_share() { }<file_sep>x-codes-social ============== <file_sep><?php /** * @package X-Social */ /* * Plugin Name: X-Social * Plugin URI: http://x-codes.net/ * Description: Login WP Facebook, Google+, Live, ... * Version: 1.0.0 * Author: x-codes * Author URI: http://x-codes.net/ * License: GPLv2 or later * Text Domain: x-social */ define('X_NAME', 'X-Social'); define('X_VERSION', '1.0.0'); define('X_MINIMUM_WP_VERSION', '3.9'); define('X_PLUGIN_URL', plugin_dir_url(__FILE__)); define('X_PLUGIN_DIR', plugin_dir_path(__FILE__)); if (is_admin()) { require_once 'core/index.php'; require_once 'options.admin.php'; require_once 'admin/options.login.php'; require_once 'admin/options.like.php'; require_once 'admin/options.share.php'; require_once 'admin/options.comment.php'; } else { require_once 'sociallogin/sociallogin.php'; require_once 'shortcodes/load.php'; }
bf9dd60e6cc49cb6c577304bb898c955b0407339
[ "JavaScript", "Markdown", "PHP" ]
11
PHP
vianhtu/x-codes-social
5e5bd2f10bc093e458e3820b6dd964b53f692568
6f2668de998710bf2f9634b01ad4bb7ce9122fed
refs/heads/master
<repo_name>donal-davies/GeometricEfficiency<file_sep>/GeometricEfficiency.cpp #include <bits/stdc++.h> #define PI 3.141592653589793238463 #define STEP_SIZE 0.1 #define STEP_LIMIT 100 #define DETECTOR_SIZE 2 #define inch 2.54 using namespace std; static default_random_engine generator; static uniform_real_distribution<double> dist(0, 1.0); struct coordinate{ double x; double y; double z; coordinate(double posX, double posY, double posZ) : x(posX), y(posY), z(posZ) {} coordinate operator+=(coordinate c){ x+=c.x; y+=c.y; z+=c.z; } }; struct ray{ coordinate* source; coordinate* direction; ray(coordinate* start, coordinate* dir) : source(start), direction(dir) {} ~ray() { delete source; delete direction; } }; struct cylinder{ coordinate* position; double length; double rad; cylinder(double posX, double posY, double posZ, double len, double r) : position(new coordinate(posX, posY, posZ)), length(len), rad(r) {} double zMin(){ return position->z - length; } double zMax(){ return position->z + length; } double distFromCenter(double posX, double posY){ return sqrt( pow((posX - position->x),2) + pow((posY - position->y),2) ); } }; struct cube{ coordinate* position; double dimX; double dimY; double dimZ; cube(double posX, double posY, double posZ, double x, double y, double z) : position(new coordinate(posX, posY, posZ)), dimX(x), dimY(y), dimZ(z) {} double xMin(){ return position->x - dimX; } double xMax(){ return position->x + dimX; } double yMin(){ return position->y - dimY; } double yMax(){ return position->y + dimY; } double zMin(){ return position->z - dimZ; } double zMax(){ return position->z + dimZ; } }; ray* generateRay(cube* source){ double posX; double posY; double posZ; double angleTheta; double anglePhi; posX = (source->xMin()) + dist(generator) * 2 * source->dimX; posY = (source->yMin()) + dist(generator) * 2 * source->dimY; posZ = (source->zMin()) + dist(generator) * 2 * source->dimZ; angleTheta = dist(generator) * PI; anglePhi = dist(generator) * 2 * PI; double dirX, dirY, dirZ; dirX = STEP_SIZE * sin(angleTheta) * cos(anglePhi); dirY = STEP_SIZE * sin(angleTheta) * sin(anglePhi); dirZ = STEP_SIZE * cos(angleTheta); return new ray(new coordinate(posX,posY,posZ),new coordinate(dirX,dirY,dirZ)); } //CHANGE THIS TO A FAST RAY-TRACING ALGORITHM!! bool stepRay(ray* track, cylinder* target){ coordinate* source = track->source; coordinate position(source->x, source->y, source->z); for(int i=0;i < STEP_LIMIT; ++i){ position += *(track->direction); if(position.z > target->zMin() && position.z < target->zMax()){ if(target->distFromCenter(position.x, position.y) <= target->rad){ return true; } } } return false; } double doSim(cube* source, cylinder* detector, int N){ int counts = 0; for(int i=0; i < N; ++i){ ray* genRay = generateRay(source); if(stepRay(genRay, detector))++counts; delete genRay; } return (double)counts / N; } int main(){ //Foil Dims: 2 x 2 x 0.1 cm //Detector Dims: 2" x 2" x ??" //Detector pos: 2cm from detector cube source(0., 0., 0., 1.0, 1.0, 0.1); cylinder detector(0., 0., 3.0, DETECTOR_SIZE*inch/2, DETECTOR_SIZE*inch/2); int N; cin >> N; vector<double> counts; for(int i=0;i < 50;++i){ cout << "Run " << i << endl; counts.push_back(doSim(&source, &detector, N)); } double mean = 0; for(auto iter = counts.begin(); iter!=counts.end(); ++iter){ mean += *iter; } mean /= 50; double var = 0; for(auto iter = counts.begin(); iter!=counts.end(); ++iter){ var += ( pow(*iter - mean, 2) ); } var /= 49; var = sqrt(var); cout << "Mean Efficiency: " << mean << endl; cout << "1 sigma: " << var << endl; }
2966e1bc08e1a5434b9045a3154b08e77e43ed24
[ "C++" ]
1
C++
donal-davies/GeometricEfficiency
e7c6301a4b389aac208e3ed798e44f5fc5974146
9865ef9fc3c28baac1178c9ac37547df368b9e75
refs/heads/master
<file_sep><?php $con=mysqli_connect("localhost","root","","quiz"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $sql = "CREATE TABLE IF NOT EXISTS registration ( SNo INT NOT NULL AUTO_INCREMENT, Student_ID CHAR(20) NOT NULL, PRIMARY KEY(SNo,Student_ID), Name CHAR(30), Password CHAR(5) )"; if (mysqli_query($con,$sql)) { } else { echo "Error creating table: " . mysqli_error($con); } $con=mysqli_connect("localhost","root","","quiz"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $Student_ID = $_GET["RollNumber"]; $Student_ID = strtolower($Student_ID); $Name = $_GET["Name"]; $Password = rand(1<PASSWORD>,<PASSWORD>); $result = mysqli_query($con, "SELECT COUNT(Student_ID) FROM quiz.registration WHERE Student_ID = $Student_ID"); while($row = mysqli_fetch_array($result)) { $exists = $row['COUNT(Student_ID)']; } if( $exists == '0') { $sql = "INSERT INTO `registration`(`SNo`, `Student_ID`, `Name`, `Password`) VALUES (NULL, $Student_ID, $Name, $Password)"; mysqli_query($con, $sql); echo "1"; require_once 'swift/lib/swift_required.php'; $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl") ->setUsername('<EMAIL>') ->setPassword('<PASSWORD>'); $mailer = Swift_Mailer::newInstance($transport); /////// EDIT THIS INFO /////// $user = str_replace("'", "", $Name); $pass=$<PASSWORD>; $email=$Student_ID.'<EMAIL>'; //$email = '<EMAIL>'; $email = str_replace("'", "", $email); ////////////////////////////// $body="Hi ".$user." ,\n\nYou have successfully registered into the placement mock test database. Your password is \b".$pass."\b. Use this in the settings page in your moblie application. \n\nThis is a one time authentication process. Your mobile, on successful authentication, will remember the password for you. \n\nThis mail has been automatically generated. Please do not reply to it. For assistance, ping <EMAIL>.\n\nHave a pleasant day. \n\nCheers,\nPlacement Team"; $message = Swift_Message::newInstance('Successful Registration') ->setFrom(array('<EMAIL>' => 'Quiz Admin')) ->setTo(array($email)) ->setBody($body); $result = $mailer->send($message); } else if ($exists != 0) { echo "2"; } else { echo "0"; } mysqli_close($con); ?><file_sep><html> <body> <h1>Scores</h1> <p>database</p> </body> </html> <?php $connection = mysqli_connect("localhost", "root", "", "quiz"); //The Blank string is the password //mysql_select_db('hrmwaitrose'); $QuizName = $_GET["QuizName"]; $query = "SELECT Student_ID, Name, Quiz_Name, Score FROM score where Quiz_Name = ($QuizName)"; //You don't need a ; like you do in SQL $result = mysqli_query($connection,$query); echo "<table>"; // start a table tag in the HTML echo "<tr><td>Student ID</td><td>Name</td><td>Quiz Name</td><td>Score</td>"; while($row = mysqli_fetch_array($result)) { //Creates a loop to loop through results echo "<tr><td>" . $row['Student_ID'] . "</td><td>" . $row['Name'] . "</td><td>" . $row['Quiz_Name'] . "</td><td>" . $row['Score'] . "</td></tr>"; //$row['index'] the index here is a field name } echo "</table>"; //Close the table in HTML mysqli_close($connection); //Make sure to close out the database connection ?><file_sep>package com.example.quiz; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.channels.FileChannel; import android.app.Activity; import android.os.Environment; import android.util.Log; public class DBhandling extends Activity{ public String dirpath=""; public String dirname="/NABquiz"; public String chkdir() { dirpath=Environment.getExternalStorageDirectory() + dirname; File direct = new File(dirpath); if(!direct.exists()) { if(direct.mkdir()) { Log.d("Debug_dbhandling","Created the directory"); //directory is created; } } else { Log.d("Debug_dbhandling","Directory exists"); } return dirpath; } @SuppressWarnings("resource") public boolean importDB(String DatabaseName,String newpath) { // TODO Auto-generated method stub File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); String PackageName="com.example.quiz"; if (sd.canWrite()) { String currentDBPath = "//data//" + PackageName + "//databases//" + DatabaseName; String backupDBPath = newpath; String exten=""; if(newpath.length()>4) exten=newpath.substring(newpath.length()-3, newpath.length()); else return false; Log.d("Debug_dbhandling_import", "Got path as "+newpath+" "+exten); if(exten.equals("nab")) { File backupDB= new File(data, currentDBPath); File currentDB = new File(backupDBPath); try { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); Log.d("Debug_dbhandling_import", backupDB.toString()); return true; } catch (Exception e) { Log.d("Debug_dbhandling_import", "Exception => "+e.toString()); } } else { Log.d("Debug_dbhandling_import", "Unrecognized format"); } } return false; } //exporting database @SuppressWarnings("resource") public void exportDB(String DatabaseName,String QuizName) { // TODO Auto-generated method stub try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); String PackageName="com.example.quiz"; chkdir(); if (sd.canWrite()) { String currentDBPath= "//data//" + PackageName + "//databases//" + DatabaseName; String backupDBPath = dirname +"/"+ QuizName; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); Log.d("Debug_dbhandling_export", "Exported the DB to "+backupDB.toString()); } } catch (Exception e) { Log.d("Debug_dbhandling_export", "Exception => "+e.toString()); } } }<file_sep>package com.example.quiz; import java.util.Timer; import java.util.TimerTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Handler.Callback; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.database.Cursor; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.TextView; import android.widget.Toast; public class Mainquiz extends Activity { Context context = this; //Timer TextView time; int Tottime; long starttime = 0; Timer timer = new Timer(); Button submit,prev,cimg; private Integer qno,qmax; private String answ; private Integer totq; private String timeleft; private boolean Must_answer=false; private boolean prev_flag=false; CheckBox chka; CheckBox chkb; CheckBox chkc; CheckBox chkd; TextView Q; TextView opta; TextView optb; TextView optc; TextView optd; MyDBAdapter ad; scoresDBAdapter ads; SettingsDBAdapter set; final Handler h = new Handler(new Callback() { @Override public boolean handleMessage(Message msg) { long millis = System.currentTimeMillis() - starttime; int seconds = (int) (millis / 1000); int minutes = seconds / 60; seconds = seconds % 60; int seconds_left = 59 - seconds; int minutes_left = Tottime - minutes - 1; if(minutes_left==0 && seconds_left==0){ timer.cancel(); timer.purge(); Toast.makeText(getApplicationContext(), "Time up", Toast.LENGTH_SHORT).show(); Intent j=new Intent(getApplicationContext(), User_publish.class); startActivity(j); finish(); } if(set.ShowTimer==true) time.setText(String.format("%d:%02d", minutes_left, seconds_left)); else time.setText("Timer running. <Set to invisible>"); return false; } }); class firstTask extends TimerTask { @Override public void run() { h.sendEmptyMessage(0); } }; private void updateactivity() { Cursor c1=ad.getQno(qno); if(c1==null) { Toast.makeText(getApplicationContext(), "Invalid question no", Toast.LENGTH_SHORT).show(); } else { Log.d("Debug_Mainquiz","Updating Question"); Q.setText(c1.getString(1)+". "+c1.getString(2)); opta.setText(c1.getString(3)); optb.setText(c1.getString(4)); optc.setText(c1.getString(5)); optd.setText(c1.getString(6)); answ=c1.getString(7).toString(); Integer imagethere=c1.getInt(8); c1.close(); // Integer imagethere=0; if(imagethere==0) { cimg.setVisibility(4); //Invisible } else { cimg.setVisibility(0); //Visible } // Clearing all checkboxes chka.setChecked(false); chkb.setChecked(false); chkc.setChecked(false); chkd.setChecked(false); if(prev_flag==true) { Cursor c=ads.getQno(qno); String mans=c.getString(2);//Marked ans c.close(); Log.d("Debug_Mainquiz","Have to decipher => "+mans); if(mans.contains("A")==true) chka.setChecked(true); if(mans.contains("B")==true) chkb.setChecked(true); if(mans.contains("C")==true) chkc.setChecked(true); if(mans.contains("D")==true) chkd.setChecked(true); Log.d("Debug_Mainquiz","Checkboxes Corrected"); } Log.d("Debug","Updated"); } if(ad.N==qno) { submit.setText("Finish"); } else { submit.setText("Next"); } if(qno>1) { prev.setVisibility(0);//Visible } else { prev.setVisibility(4);//Invisible } Log.d("Debug_Mainquiz","Question updated"); } private void Initialize() { Q=(TextView) findViewById(R.id.textView1); opta=(TextView) findViewById(R.id.textView2); optb=(TextView) findViewById(R.id.textView3); optc=(TextView) findViewById(R.id.textView4); optd=(TextView) findViewById(R.id.textView5); chka = (CheckBox)findViewById(R.id.checkBox1); chkb = (CheckBox)findViewById(R.id.checkBox2); chkc = (CheckBox)findViewById(R.id.checkBox3); chkd = (CheckBox)findViewById(R.id.checkBox4); ad=new MyDBAdapter(context); ads=new scoresDBAdapter(context); ads.dropsheet(); //Drop the scoresheet qno=1; //Initialise the question number answ=""; //Initialise the answ string set=new SettingsDBAdapter(context); set.updatemem(); //Update the settings prev.setVisibility(4); //Invisible int currentOrientation = getResources().getConfiguration().orientation; if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); } } private Boolean isquizover() { if(qno>totq) { Log.d("Debug","Quiz Over."); return true; } else { Log.d("Debug","Continue to next question"); return false; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mainquiz); Bundle b = getIntent().getExtras(); totq=b.getInt("totq"); timeleft=b.getString("timeleft"); Tottime = Integer.parseInt(timeleft); time = (TextView)findViewById(R.id.textView6); starttime = System.currentTimeMillis(); timer = new Timer(); timer.schedule(new firstTask(), 0,500); submit=(Button) findViewById(R.id.button1); prev=(Button) findViewById(R.id.button2); cimg=(Button) findViewById(R.id.button3); Initialize(); updateactivity(); prev.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { if(prev_flag==false) { qmax=qno; prev_flag=true; } Log.d("Debug_Mainquiz","Previous button pressed. Prev_flag " + "=> "+prev_flag+" qno =>"+qno+" qmax => "+qmax); String option = ""; if(chka.isChecked()) { option=option.concat("A"); } if(chkb.isChecked()) { option=option.concat("B"); } if(chkc.isChecked()) { option=option.concat("C"); } if(chkd.isChecked()) { option=option.concat("D"); } //Inserts a String value into the mapping of this Bundle Log.d("Debug","Your answer"); Log.d("Debug",option); Log.d("Debug","Correct answer"); Log.d("Debug",answ); // Now, even if answers are unchecked Next key will work if // Must_answer is set to false. if(!option.equals("")||(Must_answer==false)) { Log.d("Debug_Mainquiz","Scoring the answer (prev)"); Cursor c=ads.getQno(qno); if(c!=null) // Qno can't be null...and if it is not null update { if(option.equals(answ)) // Always the order will be A-B-C-D. :) { ads.updateans(qno,option,answ,1); Log.d("Debug_Mainquiz","Corrected a previous question"); } else { ads.updateans(qno,option,answ,0); Log.d("Debug_Mainquiz","Wronged a previous question"); } c.close(); // Close only if null Log.d("Debug_Mainquiz","Closed it"); } else//The first previous button press..updating the answers in the current question { if(option.equals(answ)) // Always the order will be A-B-C-D. :) { ads.insertans(qno,option,answ,1); Log.d("Debug_Mainquiz","Going to a previous question but this question is correct"); } else { ads.insertans(qno,option,answ,0); Log.d("Debug_Mainquiz","Going to a previous question but this question is wrong"); } } qno=qno-1; updateactivity(); Log.d("Debug","Question Updated"); // We will never hit quiz over from here. } else { Toast.makeText(getApplicationContext(), "You forgot to enter answer.", Toast.LENGTH_SHORT).show(); } } }); submit.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Log.d("Debug_Mainquiz","Prev_flag => "+prev_flag+" qno =>"+qno+" qmax => "+qmax); String option = ""; if(chka.isChecked()) { option=option.concat("A"); } if(chkb.isChecked()) { option=option.concat("B"); } if(chkc.isChecked()) { option=option.concat("C"); } if(chkd.isChecked()) { option=option.concat("D"); } //Inserts a String value into the mapping of this Bundle Log.d("Debug","Your answer"); Log.d("Debug",option); Log.d("Debug","Correct answer"); Log.d("Debug",answ); // Now, even if answers are unchecked Next key will work if // Must_answer is set to false. if(!option.equals("")||(Must_answer==false)) { Cursor c=ads.getQno(qno); Log.d("Debug_Mainquiz","Scoring the answer (next)"); if(c!=null) // Cursor is empty { if(option.equals(answ)) // Always the order will be A-B-C-D. :) { ads.updateans(qno,option,answ,1); Log.d("Debug_Mainquiz","In a previous question and made it correct"); } else { ads.updateans(qno,option,answ,0); Log.d("Debug_Mainquiz","In a previous question and made it wrong"); } if(qno==qmax) { prev_flag=false; //Now whatever you will face is new //So don't have to check for checkboxes } c.close(); Log.d("Debug_Mainquiz","Closed it"); } else { if(option.equals(answ)) // Always the order will be A-B-C-D. :) { ads.insertans(qno,option,answ,1); Log.d("Debug_Mainquiz","In a new question and made it correct"); } else { ads.insertans(qno,option,answ,0); Log.d("Debug_Mainquiz","In a new question and made it wrong"); } } qno=qno+1; if(!isquizover()) { updateactivity(); Log.d("Debug","Question Answered"); } else { // Toast.makeText(getApplicationContext(), "Quiz Over", Toast.LENGTH_SHORT).show(); Log.d("Debug","Quiz Over! Congrats"); timer.cancel(); timer.purge(); Intent i=new Intent(getApplicationContext(), User_publish.class); startActivity(i); finish(); } } else { Toast.makeText(getApplicationContext(), "You forgot to enter answer.", Toast.LENGTH_SHORT).show(); } } }); cimg.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), FullscreenActivity.class); //Create a bundle object Bundle b = new Bundle(); b.putInt("qno",qno); //Add the bundle to the intent. intent.putExtras(b); //Toast.makeText(getApplicationContext(), "Done.", Toast.LENGTH_SHORT).show(); //start the DisplayActivity startActivity(intent); } }); } } <file_sep><?PHP session_start(); if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) { header ("Location: login.php"); } ?> <?php $con=mysqli_connect("localhost","root","","quiz"); $Quiz_Name = "'".$_POST["QuizName"]."'"; $StartTime = date("YmdHis"); $StartTime = $StartTime - 100000; if($Quiz_Name != "''") { mysqli_query($con,"UPDATE `quiz`.`tests` SET Deadline=$StartTime WHERE Quiz_Name=$Quiz_Name"); echo $Quiz_Name." has been stopped"; } else { echo "The field Quiz name cannot be empty."; } ?><file_sep><?php $con=mysqli_connect("localhost","root","","quiz"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $sql = "CREATE TABLE IF NOT EXISTS scores ( SNo INT NOT NULL AUTO_INCREMENT, Student_ID CHAR(20) NOT NULL, PRIMARY KEY(SNo,Student_ID), Name CHAR(30), StartingTime BIGINT, Quiz_Name CHAR(40), Score INT )"; if (mysqli_query($con,$sql)) { } else { echo "Error creating table: " . mysqli_error($con); } $con=mysqli_connect("localhost","root","","quiz"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $StartTime = date("YmdHis"); $Quiz_Name = $_GET["Quiz_Name"]; $Student_ID = $_GET["Student_ID"]; $Name = $_GET["Name"]; $Deadline = $_GET["Deadline"]; $result = mysqli_query($con, "SELECT COUNT(Student_ID) FROM quiz.scores WHERE Student_ID = $Student_ID AND Quiz_Name = $Quiz_Name"); while($row = mysqli_fetch_array($result)) { $exists = $row['COUNT(Student_ID)']; } $Deadline = str_replace("'", "", $Deadline); $timestamp = strtotime($Deadline); $Deads = date('YmdHis', $timestamp); $Deads = $Deads+235959; if($Quiz_Name == "'DefaultTest'") { echo "1"; } else if( $exists == '0' && $Deads>$StartTime) { $sql = "INSERT INTO `scores`(`SNo`, `Student_ID`, `Name`, `StartingTime`, `Quiz_Name`, `Score`) VALUES (NULL, $Student_ID, $Name, $StartTime, $Quiz_Name, NULL)"; mysqli_query($con, $sql); echo "1"; } else if ($exists != 0) { echo "2"; } else if ($Deads<$StartTime) { echo "3"; } else { echo "0"; } mysqli_close($con); ?><file_sep><?PHP session_start(); if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) { header ("Location: login.php"); } ?> <?php $con=mysqli_connect("localhost","root","","quiz"); $Quiz_Name = "'".$_POST['QuizName']."'"; $Deadline = $_POST['Deadline']; $timestamp = strtotime($Deadline); $Deads = date('YmdHis', $timestamp); $Deads = $Deads+235959; $StartTime = date("YmdHis"); if($StartTime<$Deads) { if($Quiz_Name != "''") { mysqli_query($con,"UPDATE `quiz`.`tests` SET Deadline=$Deads WHERE Quiz_Name=$Quiz_Name"); echo $Quiz_Name." has been extended to ".$Deads; } else { echo "The field Quiz name cannot be empty."; } } else { echo "Please give a future date/ Use the Stop Test option."; } ?> <file_sep>package com.example.quiz; import java.io.File; import java.util.ArrayList; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; public class EditQActivity extends Activity { Context context=this; String imgpath="",option=""; Boolean imagethere=true; private static final int REQUEST_PICK_FILE = 1; CheckBox chka; CheckBox chkb; CheckBox chkc; CheckBox chkd; EditText Q; EditText opta; EditText optb; EditText optc; EditText optd; MyDBAdapter ad; Integer qno=0,imagethereint=0; boolean suc=false; private void updateactivity(Integer qno) { Cursor c1=ad.getQno(qno); if(c1==null) { Toast.makeText(getApplicationContext(), "Invalid question no", Toast.LENGTH_SHORT).show(); } else { Log.d("Debug_EditQ","Updating Question "+c1.getString(1)); Toast.makeText(context, "Question no. "+c1.getString(1), Toast.LENGTH_SHORT).show(); Q.setText(c1.getString(2)); opta.setText(c1.getString(3)); optb.setText(c1.getString(4)); optc.setText(c1.getString(5)); optd.setText(c1.getString(6)); imagethereint=c1.getInt(8); String mans=c1.getString(7).toString(); c1.close(); Log.d("Debug_EditQ","Have to decipher => "+mans); if(mans.contains("A")==true) chka.setChecked(true); if(mans.contains("B")==true) chkb.setChecked(true); if(mans.contains("C")==true) chkc.setChecked(true); if(mans.contains("D")==true) chkd.setChecked(true); Log.d("Debug_EditQ","Checkboxes Corrected"); } } private void Initialize() { Q=(EditText) findViewById(R.id.editText1); opta=(EditText) findViewById(R.id.editText2); optb=(EditText) findViewById(R.id.editText3); optc=(EditText) findViewById(R.id.editText4); optd=(EditText) findViewById(R.id.editText5); chka = (CheckBox)findViewById(R.id.checkBox1); chkb = (CheckBox)findViewById(R.id.checkBox2); chkc = (CheckBox)findViewById(R.id.checkBox3); chkd = (CheckBox)findViewById(R.id.checkBox4); ad=new MyDBAdapter(context); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_q); Initialize(); Bundle b = getIntent().getExtras(); qno=b.getInt("Qno"); Log.d("Debug_editq","Asked to fetch =>"+qno); updateactivity(qno); Log.d("Debug_EditQ","Updated"); Button submit=(Button) findViewById(R.id.button1); Button back=(Button) findViewById(R.id.button2); final AlertDialog.Builder builder= new AlertDialog.Builder(context); submit.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { option=""; //Necessary as now we have to start afresh. :) if(chka.isChecked()) { option=option.concat("A"); } if(chkb.isChecked()) { option=option.concat("B"); } if(chkc.isChecked()) { option=option.concat("C"); } if(chkd.isChecked()) { option=option.concat("D"); } //Inserts a String value into the mapping of this Bundle if(!option.equals("")) { Log.d("Debug_editq","What about the image?"); builder.setTitle("What about the image?"); builder.setMessage("Press back to go back to editing question."); builder.setIcon(android.R.drawable.ic_dialog_alert); if(imagethereint==1) { builder.setPositiveButton("Modify Image", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { newimg(); } }); builder.setNeutralButton("Retain Image", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { retainimg(); } }); builder.setNegativeButton("Remove Image", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { confirm(); } }); } else { builder.setPositiveButton("Add Image", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { newimg(); } });builder.setNegativeButton("No Image", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { confirm(); } }); } builder.show(); } else { Toast.makeText(getApplicationContext(), "You forgot to enter answer.", Toast.LENGTH_SHORT).show(); } } }); back.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent i=new Intent(context,Admin_chkq.class); startActivity(i); finish(); } }); } public void confirm() { imagethere=false; imgpath=""; Log.d("Debug_editq","Updating the question without image"); // Could have used updateQ but didn't put fight for that :P It works na. :P ad.updateQprev(qno,Q.getText().toString(),opta.getText().toString(),optb.getText().toString(),optc.getText().toString(),optd.getText().toString(),option,imagethere,imgpath); Toast.makeText(context, "Question updated", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(context, Admin_chkq.class); startActivity(intent); finish(); } public void retainimg() { Cursor c=ad.getQno(qno); ad.updateQ(qno,qno,Q.getText().toString(),opta.getText().toString(),optb.getText().toString(),optc.getText().toString(),optd.getText().toString(),option,c.getInt(8),c.getBlob(9)); Toast.makeText(getApplicationContext(), "Question updated", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(getApplicationContext(), Admin_chkq.class); startActivity(intent); finish(); } public void newimg() { Intent intent = new Intent(context, FilePickerActivity.class); //Proceeding with image selection // Set the initial directory to be the sdcard DBhandling db=new DBhandling(); db.chkdir(); Log.d("Debug_dbhandling",db.dirpath); intent.putExtra(FilePickerActivity.EXTRA_FILE_PATH,db.dirpath); // Only make .png files visible ArrayList<String> extensions = new ArrayList<String>(); extensions.add(".png"); extensions.add(".jpg"); intent.putExtra(FilePickerActivity.EXTRA_ACCEPTED_FILE_EXTENSIONS, extensions); // Start the activity startActivityForResult(intent, REQUEST_PICK_FILE); Log.d("Debug_dbhandling","Triggered File picker"); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d("Debug_dbhandling","Result"); if(resultCode == RESULT_OK) { switch(requestCode) { case REQUEST_PICK_FILE: { if(data.hasExtra(FilePickerActivity.EXTRA_FILE_PATH)) { // Get the file path File f = new File(data.getStringExtra(FilePickerActivity.EXTRA_FILE_PATH)); imgpath=f.getPath(); Log.d("Debug_admin_qu",imgpath); suc=ad.updateQprev(qno,Q.getText().toString(),opta.getText().toString(),optb.getText().toString(),optc.getText().toString(),optd.getText().toString(),option,imagethere,imgpath); if(suc==false) { Toast.makeText(getApplicationContext(), "Question updated without adding image because the image was larger than 850 kB.", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "Question updated", Toast.LENGTH_SHORT).show(); } Intent intent = new Intent(getApplicationContext(), Admin_chkq.class); startActivity(intent); finish(); } else { Toast.makeText(getApplicationContext(), "Aborted", Toast.LENGTH_SHORT).show(); } break; } } } } } <file_sep>/* * Copyright 2011 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.quiz; import java.io.File; import java.util.ArrayList; import com.example.quiz.R; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class Filepicker extends Activity implements OnClickListener { private static final int REQUEST_PICK_FILE = 1; private TextView mFilePathTextView; private Button mStartActivityButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Set the views mFilePathTextView = (TextView)findViewById(R.id.file_path_text_view); mStartActivityButton = (Button)findViewById(R.id.start_file_picker_button); mStartActivityButton.setOnClickListener(this); } @Override public void onClick(View v) { switch(v.getId()) { case R.id.start_file_picker_button: // Create a new Intent for the file picker activity Intent intent = new Intent(this, FilePickerActivity.class); // Set the initial directory to be the sdcard DBhandling db=new DBhandling(); db.chkdir(); Log.d("Debug",db.dirpath); intent.putExtra(FilePickerActivity.EXTRA_FILE_PATH,db.dirpath); // Show hidden files //intent.putExtra(FilePickerActivity.EXTRA_SHOW_HIDDEN_FILES, true); // Only make .png files visible ArrayList<String> extensions = new ArrayList<String>(); extensions.add(".png"); extensions.add(".jpg"); extensions.add(".nab"); intent.putExtra(FilePickerActivity.EXTRA_ACCEPTED_FILE_EXTENSIONS, extensions); // Start the activity startActivityForResult(intent, REQUEST_PICK_FILE); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode == RESULT_OK) { switch(requestCode) { case REQUEST_PICK_FILE: if(data.hasExtra(FilePickerActivity.EXTRA_FILE_PATH)) { // Get the file path File f = new File(data.getStringExtra(FilePickerActivity.EXTRA_FILE_PATH)); // Set the file path text view mFilePathTextView.setText(f.getPath()); } } } } }<file_sep>package com.example.quiz; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.database.Cursor; import android.graphics.Point; import android.util.Log; import android.view.Display; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; public class User_score extends Activity { Context context=this; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Getting the window sizes Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int width = size.x; int fonts = 40; TableRow.LayoutParams params = new TableRow.LayoutParams(width,fonts); TableLayout table = new TableLayout(this); //TableLayout table = (TableLayout) findViewById(R.id.table1); TableRow row = new TableRow(this); TextView text = new TextView(this); params.gravity=Gravity.CENTER; text.setLayoutParams(params); text.setText("Your Marksheet (Most Recent on top)"); Log.d("Debug","Tablelayout1"); row.addView(text); Log.d("Debug","Tablelayout11"); table.addView(row); Log.d("Debug","Tablelayout2"); fonts = 50; TableRow.LayoutParams params0 = new TableRow.LayoutParams(0,fonts,.1f); TableRow.LayoutParams params1 = new TableRow.LayoutParams(0,fonts,.35f); TableRow.LayoutParams params2 = new TableRow.LayoutParams(0,fonts,.27f); TableRow.LayoutParams params3 = new TableRow.LayoutParams(0,fonts,.14f); TableRow.LayoutParams params4 = new TableRow.LayoutParams(0,fonts,.14f); // The table headers TableRow rowi = new TableRow(this); TextView text0 = new TextView(this); text0.setText("#"); params0.gravity=Gravity.CENTER; text0.setLayoutParams(params0); TextView text1 = new TextView(this); text1.setText("Quiz Name"); params1.gravity=Gravity.CENTER; text1.setLayoutParams(params1); TextView text2 = new TextView(this); text2.setText("Date taken"); params2.gravity=Gravity.CENTER; text2.setLayoutParams(params2); TextView text3 = new TextView(this); text3.setText("Score"); params3.gravity=Gravity.CENTER; text3.setLayoutParams(params3); TextView text4 = new TextView(this); text4.setText("Out of"); params4.gravity=Gravity.CENTER; text4.setLayoutParams(params4); rowi.addView(text0); rowi.addView(text1); rowi.addView(text2); rowi.addView(text3); rowi.addView(text4); table.addView(rowi); final markDBAdapter md=new markDBAdapter(getApplicationContext()); Cursor c=md.getAllperf(); c.moveToLast(); Integer slno; do { rowi = new TableRow(this); text0 = new TextView(this); slno=md.N-Integer.parseInt(c.getString(1))+1; text0.setText(slno.toString()); params0.gravity=Gravity.CENTER; text0.setLayoutParams(params0); text1 = new TextView(this); text1.setText(c.getString(2)); params1.gravity=Gravity.CENTER; text1.setLayoutParams(params1); text2 = new TextView(this); text2.setText(c.getString(3)); params2.gravity=Gravity.CENTER; text2.setLayoutParams(params2); text3 = new TextView(this); text3.setText(c.getString(4)); params3.gravity=Gravity.CENTER; text3.setLayoutParams(params3); text4 = new TextView(this); text4.setText(c.getString(5)); params4.gravity=Gravity.CENTER; text4.setLayoutParams(params4); rowi.addView(text0); rowi.addView(text1); rowi.addView(text2); rowi.addView(text3); rowi.addView(text4); table.addView(rowi); }while(c.moveToPrevious() && (slno<5)); c.close(); rowi = new TableRow(this); Button clr= new Button(context); fonts=80; TableRow.LayoutParams paramsb=new TableRow.LayoutParams(200,fonts); paramsb.gravity=Gravity.CENTER; clr.setLayoutParams(paramsb); clr.setText("Clear All"); rowi.addView(clr); table.addView(rowi); setContentView(table); final AlertDialog.Builder builder = new AlertDialog.Builder(context); clr.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.d("Debug_admin_review","Deleting the records"); builder.setTitle("Remove all scores?"); builder.setMessage("Are you sure?"); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { //Yes button clicked, do something md.dropsheet(); Toast.makeText(context,"Deleted the records", Toast.LENGTH_SHORT).show(); Log.d("Debug_admin_review","Deleted the paper"); finish(); // No point staying back here. :) } }); builder.setNegativeButton("No", null); builder.show(); } }); } } <file_sep><?php $str = '21-JUN-2013'; echo $str; // previous to PHP 5.1.0 you would compare with -1, instead of false if (($timestamp = strtotime($str)) === false) { echo "The string ($str) is bogus"; } else { echo "$str == " . date('YmdHis', $timestamp); } echo "<br>"; echo $timestamp; ?><file_sep><?php $con=mysqli_connect("localhost","root","","quiz"); $StartTime = date("YmdHis"); $result=mysqli_query($con,"SELECT * FROM `quiz`.`tests` WHERE Deadline>$StartTime"); while($row = mysqli_fetch_array($result)) { $entry = $row['File_Name']; echo "$entry\n"; } /*if ($handle = opendir('./uploads')) { while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { echo "$entry\n"; } } closedir($handle); }*/ ?><file_sep><?php $con=mysqli_connect("localhost","root","","quiz"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $Student_ID = $_GET["RollNumber"]; $Name = $_GET["Name"]; $Password = $_GET["Password"]; $Password = str_replace("'", "", $Password); $result = mysqli_query($con, "SELECT Password FROM quiz.registration WHERE Student_ID = $Student_ID"); while($row = mysqli_fetch_array($result)) { $exists = $row['Password']; } //echo $exists; if( $exists == $Password) { echo "1"; } else if ($exists != $Password) { echo "2"; } else { echo "0"; } mysqli_close($con); ?><file_sep><!-- <html> <head> <title> Login page </title> </head> <body> <h1 style="font-family:Comic Sans Ms;text-align="center";font-size:20pt; color:#00FF00;"> Simple Login Page </h1> <form name="login"> Username<input type="text" name="userid"/> Password<input type="<PASSWORD>" name="pswrd"/> <input type="button" onclick="check(this.form)" value="Login"/> <input type="reset" value="Cancel"/> </form> <script language="javascript"> function check(form)/*function to check userid & password*/ { /*the following code checkes whether the entered userid and password are matching*/ if(form.userid.value == "user" && form.pswrd.value == "<PASSWORD>") { window.open('landing.html',"_self")/*opens the target page while Id & password matches*/ } else { alert("Error Password or Username")/*displays error message*/ } } </script> </body> </html> --> <?PHP $uname = ""; $pword = ""; $errorMessage = ""; //========================================== // ESCAPE DANGEROUS SQL CHARACTERS //========================================== if ($_SERVER['REQUEST_METHOD'] == 'POST'){ $uname = $_POST['username']; $pword = $_POST['<PASSWORD>']; $uname = htmlspecialchars($uname); $pword = htmlspecialchars($pword); if ($uname == 'admin' && $pword == 'password') { session_start(); $_SESSION['login'] = "1"; header ("Location: landing.php"); } else { $errorMessage = "Error logging on"; } } ?> <html> <head> <title>Basic Login Script</title> </head> <body> <FORM NAME ="form1" METHOD ="POST" ACTION ="login.php"> Username: <INPUT TYPE = 'TEXT' Name ='username' value="<?PHP print $uname;?>" maxlength="20"> Password: <INPUT TYPE = 'PASSWORD' Name ='password' value="<?PHP print $pword;?>" maxlength="16"> <P align = center> <INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login"> </P> </FORM> <P> <?PHP print $errorMessage;?> </body> </html><file_sep>package com.example.quiz; import java.io.ByteArrayOutputStream; import java.io.File; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; public class MyDBAdapter { // Calls public void onCreate(SQLiteDatabase db) MyDBHelper db_helper; // Database naming String DB_NAME="Quiz"; String TAB_NAME="qbank"; // Do most of the communication // db_helper is just to do the upper-level SQLiteDatabase db=null; String Q_Name,Admin_ID; byte[] filepickedimg={}; boolean filepickflag=false; long MAX_IMG_SIZE=850; // 850 kB max public Integer N=1; //The total count public MyDBAdapter(Context context) { db_helper = new MyDBHelper(context, DB_NAME, null, 1); Cursor c1=getAllQs(); N=c1.getCount()-1; // N now has the count Log.d("Debug_mydbadapter","Total no. of elements =>"+N); c1.close(); close(); // Closing the link for Qs(); } public void open() throws SQLException { //open database in reading/writing mode db = db_helper.getWritableDatabase(); } public void close() { if (db != null) db.close(); } public boolean isfilesizebad(String path) { File file = new File(path); long length = file.length()/1024; Log.d("Debug_myadapter","Image size is "+length); if(length<MAX_IMG_SIZE) return false; else return true; } public boolean insertQ(String quest,String opta,String optb,String optc,String optd,String option,Boolean imgthere,String photoPath) { boolean result=true; byte[] img={}; Integer imagethere; if(imgthere==true) { if(isfilesizebad(photoPath)) { imagethere=0; Log.d("Debug_myadapter","No image added as too big an image provided"); result=false; } else { BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; Bitmap icon = BitmapFactory.decodeFile(photoPath, options); ByteArrayOutputStream bos = new ByteArrayOutputStream(); icon.compress(Bitmap.CompressFormat.PNG, 100, bos); img = bos.toByteArray(); imagethere=1; } } else { imagethere=0; Log.d("Debug_myadapter","No image added"); } // ContentValues which is like bundle ContentValues bag = new ContentValues(); // Order matters. It should be as same as the columns // Contents of the bag will increase with every put statement bag.put("Qno", N+1); bag.put("quest", quest); bag.put("opta", opta); bag.put("optb", optb); bag.put("optc", optc); bag.put("optd", optd); bag.put("option",option); bag.put("imagethere",imagethere); bag.put("img",img); open(); //Insert into the table qbank the contents of the bag. long row=db.insert("qbank", null, bag); if(row!=-1) Log.d("Debug_mydbadapter","Inserted an entry => "+row); else Log.d("Debug_mydbadapter","Error while inserting"); close(); N=N+1; // Update N return result; } public boolean updateQprev(Integer qno,String quest,String opta,String optb,String optc,String optd,String option,Boolean imgthere,String photoPath) { boolean result=true; byte[] img={}; Integer imagethere; if(imgthere==true) { if(isfilesizebad(photoPath)) { imagethere=0; Log.d("Debug_myadapter","No image added as too big an image provided"); result=false; } else { BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; Bitmap icon = BitmapFactory.decodeFile(photoPath, options); Log.d("Debug_myadapter","Converted into bitmap file"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); icon.compress(Bitmap.CompressFormat.PNG, 100, bos); img = bos.toByteArray(); imagethere=1; } } else { imagethere=0; Log.d("Debug_myadapter","No image added"); } // ContentValues which is like bundle ContentValues bag = new ContentValues(); // Order matters. It should be as same as the columns // Contents of the bag will increase with every put statement bag.put("Qno", qno); bag.put("quest", quest); bag.put("opta", opta); bag.put("optb", optb); bag.put("optc", optc); bag.put("optd", optd); bag.put("option",option); bag.put("imagethere",imagethere); bag.put("img",img); open(); //Insert into the table qbank the contents of the bag. long row=db.update(TAB_NAME,bag,"Qno=?",new String []{qno.toString()}); if(row!=-1) Log.d("Debug_mydbadapter","Inserted an entry => "+row); else Log.d("Debug_mydbadapter","Error while inserting"); close(); return result; } public void updateQ(Integer Qprev, Integer Qno, String quest,String opta,String optb,String optc,String optd,String option,Integer imagethere,byte[] img) { // ContentValues which is like bundle ContentValues bag = new ContentValues(); // Order matters. It should be as same as the columns // Contents of the bag will increase with every put statement bag.put("Qno", Qno); bag.put("quest", quest); bag.put("opta", opta); bag.put("optb", optb); bag.put("optc", optc); bag.put("optd", optd); bag.put("option",option); bag.put("imagethere",imagethere); bag.put("img",img); open(); //Insert into the table qbank the contents of the bag. long row=db.update(TAB_NAME,bag,"Qno=?",new String []{Qprev.toString()}); if(row==1) Log.d("Debug_mydbadapter","Updated "+Qprev+" to "+Qno); else Log.d("Debug_mydbadapter","Error as rows updated are "+row+" in no."); close(); } public void deleteEntry(Integer QN) { open(); //Insert into the table fruits the contents of the bag. Log.d("Debug_mydbadapter","Deleting an entry"); db.delete(TAB_NAME,"qno = ?", new String[]{QN.toString()}); preparedel(QN); Log.d("Debug_mydbadapter",QN.toString()); N=N-1; close(); } void preparedel(Integer QN) { open(); Cursor c=getAllQs(); Integer qtemp=0; while(c.moveToNext()) { qtemp=c.getInt(1); if(qtemp>QN) { updateQ(qtemp,qtemp-1, c.getString(2), c.getString(3), c.getString(4), c.getString(5), c.getString(6), c.getString(7), c.getInt(8), c.getBlob(9)); } } c.close(); } public void deleteall() { open(); String query="DELETE FROM "; query=query.concat(TAB_NAME); db.execSQL(query); Log.d("Debug_settings","Dropped the question paper"); close(); } public Cursor getAllQs() { open(); Log.d("Debug_mydbadapter","Asked to fetch the entire question bank"); String query="SELECT * FROM "; query=query.concat(TAB_NAME); Cursor c1 = db.rawQuery(query, null); Log.d("Debug_mydbadapter","Fetched the entire question bank"); return c1; } public Cursor getQBset() { open(); Log.d("Debug_mydbadapter","Got to fetch the settings"); String query="SELECT * FROM "+TAB_NAME+" WHERE Qno=0"; Cursor c=null; if ( N >= 0 ) { c=db.rawQuery(query,null); c.moveToNext(); // Moving the cursor forward Log.d("Debug_mydbadapter","Got the settings"); Q_Name=c.getString(2); Admin_ID=c.getString(7); } else { Log.d("Debug_mydbadapter","No question bank"); } close(); return c; // Returns null if failed } public Cursor getQno(Integer QN) { open(); Log.d("Debug_scoredbadapter","Got to fetch "+QN.toString()); String query="SELECT * FROM "+TAB_NAME+" WHERE Qno=?"; Cursor c=null; if ( (QN <= N) && (QN > 0) ) { c=db.rawQuery(query, new String[]{QN.toString()}); c.moveToNext(); // Moving the cursor forward Log.d("Debug_mydbadapter","Got it"); } else { Log.d("Debug_mydbadapter","Bad luck"); } close(); return c; // Returns null if failed } } <file_sep><?php $con=mysqli_connect("localhost","root","","quiz"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } //mysql_select_db("quiz"); $Quiz_Name = $_GET["Quiz_Name"]; $Score = $_GET["Score"]; $Time_Limit = $_GET["TimeLimit"]; $currTime = date("YmdHis"); $Student_ID = $_GET["Student_ID"];//echo "<br>"; echo $Student_ID; $result = mysqli_query($con,"SELECT * FROM scores WHERE Student_ID = $Student_ID"); if($Quiz_Name=="'DefaultTest'") { echo "1"; } else if(mysqli_num_rows($result)=='0') { echo "Trying to upload score without authenticating"; } else { while($row = mysqli_fetch_array($result)) { $StartTime = $row['StartingTime']; //echo $StartTime; //echo "<br>"; } //echo $Score; //echo "<br>"; //echo $Time_Limit; //echo "<br>"; //echo ($currTime - $StartTime); if( $currTime - $StartTime < $Time_Limit) { mysqli_query($con,"UPDATE scores SET Score=$Score WHERE Student_ID = $Student_ID AND Quiz_Name = $Quiz_Name "); echo "1"; } else { echo "0"; } } mysqli_close($con); ?><file_sep>Quiz (An Android App for Mock Test-taking) ========================================== This Android application for conducting mock tests on Android smartphones was built by a team of 3 students from the Dept. of Electrical Engineering, IIT Madras. The primary objective of the app is to enable students to take their placement mock tests at the ease of their Android smartphones, thereby solving the problem of slow rendering of questions, when the tests are hosted on external websites. The app has been designed to supports devices of all sizes operating on Android OS 2.3 (Gingerbread) and above. **Overview of the Application**: The app can be used to create MCQ questions with multiple options correct and the question can have one image attachment (For example: The circuits). These questions as a bundle can be exported as a database, which then can be uploaded onto an official website. The app can then access this website and download the database. The user can then take the timed test. The app meanwhile will authenticate the user on to the server and register the start of the test and end of the test and the score. The app has two parts, the Admin app, and the User app. **Admin app**: The Admin app, (the master app) will be only with the Branch Councillors and Placement coordinators, who need to create the questions. They can create questions on this app, export the data base and then check the test. It is hosted in the *master* branch of the repository. A video demonstrating the Admin app: http://youtu.be/UlSCEk_oq00 **User app**: The User app is basically a scaled down version of the Admin app. It will not have the capabilities of creating questions and exporting. This app will authenticate users on to the website, download the question database and begin the quiz for the user. Once the user is done with the quiz, the app will automatically log the marks in to the server. It is hosted in the *User* branch of the repository. **Current Status**: With a great deal of help from the EE Branch Councillor, Chaitra, we were given space on the students server (students.iitm.ac.in) to test the application, and we have successfully tested the app and shown it her. We are now ready to share the application with the students, and the best way of doing it would be through the Google Play Store. We will be uploading it on Play Store soon. **Future**: Depending on the demand and interest, we intend to make the application SCORM compliant helping us expand the usability of the application. <file_sep><?PHP session_start(); if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) { header ("Location: login.php"); } ?> <?php $con=mysqli_connect("localhost","root","","quiz"); $Quiz_Name=$_GET["QuizName"]; echo $Quiz_Name."<br>"; $QuizName = "'".$Quiz_Name."'"; echo $QuizName; $query = "SELECT Student_ID,Name,Score FROM quiz.scores WHERE Quiz_Name = $QuizName ORDER BY DESC"; $result = mysqli_query($con, "SELECT Student_ID,Name,Score FROM quiz.scores WHERE Quiz_Name = $QuizName ORDER BY Score DESC"); echo $query; echo "<table border='1'> <tr> <th>Student ID</th> <th>Name</th> <th>Score</th> </tr>"; while($row = mysqli_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['Student_ID'] . "</td>"; echo "<td>" . $row['Name'] . "</td>"; echo "<td>" . $row['Score'] . "</td>"; echo "</tr>"; } echo "</table>"; mysqli_close($con); ?><file_sep><?PHP session_start(); if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) { header ("Location: login.php"); } ?> <html> <head> <title>Title of the document</title> </head> </body> </html> <a href="upload_landing.php"> <button type="button" >Upload</button> </a> <br> <br> <a href="query_landing.php"> <button type="button" >Query</button> </a> <br> <br> <a href="extend_landing.php"> <button type="button" >Extend Deadline</button> </a> <br> <br> <a href="stop_landing.php"> <button type="button" >Stop Test</button> </a> </html> <file_sep>package com.example.quiz; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.os.AsyncTask; import android.os.Bundle; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class User_landing extends Activity { Context context=this; Integer totq; String timeleft; String url1; SettingsDBAdapter set; String datef=""; @SuppressLint("SimpleDateFormat") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_landing); Log.d("DEBUG","User Landing"); Button b=(Button) findViewById(R.id.button1); TextView t=(TextView) findViewById(R.id.textView1); final MyDBAdapter ad=new MyDBAdapter(context); set=new SettingsDBAdapter(context); set.updatemem(); Cursor c = ad.getQBset(); String dates=c.getString(6); Date expiry=null; try { SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); expiry = formatter.parse(dates); Log.d("DEBUG","Reached before datef"); datef=new SimpleDateFormat("dd-MMM-yyyy").format(expiry.getTime()); Log.d("DEBUG","Cleared datef"); } catch (Exception e) { e.printStackTrace(); Log.d("DEBUG","Shit!"); Toast.makeText(context, "Invalid database as date not set correctly", Toast.LENGTH_LONG).show(); finish(); } String details="Hi. The following are the details of " + "the quiz you are about to take."; details=details.concat("\n\n Quiz Name: "+c.getString(2)); details=details.concat("\n\n # of Qs: "+c.getString(3)); details=details.concat("\n\n Duration: "+c.getString(4)+" mins"); details=details.concat("\n\n Deadline: "+datef); details=details.concat("\n\n Syllabus:\n"+c.getString(5)); t.setText(details); totq= Integer.parseInt(c.getString(3)); timeleft=c.getString(4); b.setText("Authenticate & Continue"); c.close(); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.d("DEBUG","button click"); DownloadWebPageTask task = new DownloadWebPageTask(); String studentID = set.ID; String name = set.Name; MyDBAdapter ad=new MyDBAdapter(context); Cursor c=ad.getQBset(); String QuizName = c.getString(2); c.close(); String Deadline = datef; QuizName= QuizName.replace(" ", ""); name=name.replace(" ",""); studentID=studentID.replace(" ",""); Log.d("DEBUG", "SpaceRemoved:"+QuizName); String Student_ID = "Student_ID='"+studentID+"'"; String Name = "Name='"+name+"'"; String Deads= "Deadline='"+Deadline+"'"; String Quiz_Name = "Quiz_Name='"+QuizName+"'"; Log.d("DEBUG", "Deadline:"+Deads); url1= set.URL+"Authenticate.php"; String url = set.URL+"Authenticate.php?"+Student_ID+"&"+Name+"&"+Quiz_Name+"&"+Deads; Log.d("debug", url); scoresDBAdapter ads=new scoresDBAdapter(context); ads.dropsheet(); // Clear the sheet if(set.disablehttp==true) { Toast.makeText(getApplicationContext(), "Working in HTTP Disabled mode | Orientation Locked", Toast.LENGTH_LONG).show(); Log.d("Debug_user_landing","Bypassing the http authentication"); proceed(); } else { Toast.makeText(getApplicationContext(), "Orientation Locked", Toast.LENGTH_LONG).show(); task.execute(url); } } }); } private class DownloadWebPageTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { Log.d("DEBUG", "Inside dwp"); String response = ""; for (String url : urls) { DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { HttpResponse execute = client.execute(httpGet); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader( new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { response += s; } } catch (Exception e) { e.printStackTrace(); Log.d("DEBUG", "Exception"); } } Log.d("DEBUG", "Done dwp"); return response; } @Override protected void onPostExecute(String result) { Log.d("DEBUG", "onPostExecute"+result); if(result.equals("1")) { proceed(); } else if(result.equals("2")) { Toast.makeText(context, "You have already taken the test. You being sent back to the previous page", Toast.LENGTH_LONG).show(); // Calling finish will take you back to admin.java } else if(result.equals("3")) { Toast.makeText(context, "The test is past the deadline. You being sent back to the previous page", Toast.LENGTH_LONG).show(); // Calling finish will take you back to admin.java } else { Toast.makeText(context, "The website "+url1+" cannot be reached", Toast.LENGTH_LONG).show(); } finish(); } } protected void proceed() { final Bundle bund = new Bundle(); // Bundle containing // Total Questions stored as totq (int) // Time as timeleft (String) bund.putInt("totq",totq); bund.putString("timeleft",timeleft); //Toast.makeText(context, "The test will start now. All the best!!!", Toast.LENGTH_SHORT).show(); Intent i= new Intent(getApplicationContext(),Mainquiz.class); i.putExtras(bund); startActivity(i); finish(); } } <file_sep><?PHP session_start(); if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) { header ("Location: login.php"); } ?> <?php $allowedExts = array("nab"); $extension = end(explode(".", $_FILES["file"]["name"])); if ( in_array($extension, $allowedExts) ) { if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br>"; } else { $target_path = getcwd()."/uploads/"; $target_path = $target_path . basename( $_FILES['file']['name']); if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) { $sql = "CREATE TABLE IF NOT EXISTS Tests ( SNo INT NOT NULL AUTO_INCREMENT, Quiz_Name CHAR(20) NOT NULL, PRIMARY KEY(SNo,Quiz_Name), Deadline BIGINT, File_Name CHAR(20) )"; $con=mysqli_connect("https://students.iitm.ac.in","placementmt","PMockTest13-14","PlacementMockTest"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } if (mysqli_query($con,$sql)) { } else { echo "Error creating table: " . mysqli_error($con); } $Quiz_Name = "'".$_POST["QuizName"]."'"; $Deadline = $_POST["Deadline"]; $timestamp = strtotime($Deadline); $Deads = date('YmdHis', $timestamp); $Deads = $Deads+235959; $File_Name = "'".$_FILES["file"]["name"]."'"; $StartTime = date("YmdHis"); if($StartTime<$Deads && $Quiz_Name!="''") { $con=mysqli_connect("students.iitm.ac.in","placementmt","PMockTest13-14","PlacementMockTest"); mysqli_query($con,"INSERT INTO `PlacementMockTest`.`tests` (`SNo`, `Quiz_Name`, `Deadline`, `File_Name`) VALUES (NULL, $Quiz_Name, $Deads, $File_Name)"); echo "The file ". basename( $_FILES['file']['name']). " has been uploaded"; echo '<script type="text/javascript" language="javascript"> window.open("/app/uploads"); </script>'; } else { echo "Cannot upload file without proper Deadline or Quiz Name."; } //echo "The file ". basename( $_FILES['file']['name']). //" has been uploaded"; } else{ echo "There was an error uploading the file, please try again!"; } /*$result = mysqli_query($con, "SELECT Quiz_Name,Deadline,File_Name FROM quiz.tests"); echo "<table border='1'> <tr> <th>Quiz Name</th> <th>Deadline</th> <th>File Name</th> </tr>"; while($row = mysqli_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['Quiz_Name'] . "</td>"; echo "<td>" . $row['Deadline'] . "</td>"; echo "<td>" . $row['File_Name'] . "</td>"; echo "</tr>"; } echo "</table>"; */ // echo "Upload: " . $_FILES["file"]["name"] . "<br>"; // echo "Type: " . $_FILES["file"]["type"] . "<br>"; // echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>"; // echo "Stored in: " . $_FILES["file"]["tmp_name"]; } } else { echo "Invalid file"; } //window.open('/uploads'); ?>
82d79597c41882715b14e19d46b5aa7e83144d3b
[ "Markdown", "Java", "PHP" ]
21
PHP
abyvinod/Quiz_app
107b7d211ea444920a8f70114956e2905f54cdde
53cd02bbd4860083f3e413be43b4630f1dde331b
refs/heads/master
<file_sep># echo-in-rust <file_sep>#![feature(io)] #![feature(rustc_private)] #![feature(core)] #![feature(env)] #![feature(collections)] extern crate getopts; use std::env; use std::old_io::{print, println}; use std::old_io::stdio; static VERSION: &'static str = "1.0.0"; fn main() { let args: Vec<String> = env::args().map(|x| x.to_string()) .collect(); let ref program = args[0]; let opts = [ getopts::optflag("n", "", "do not output the trding newline"), getopts::optflag("h", "help", "display this help and exit"), getopts::optflag("V", "version", "output version information and exet"), ]; let matches = match getopts::getopts(args.tail(), &opts) { Ok(m) => m, Err(f) => { println!("{}", f); env::set_exit_status(1); return; } } if matches.opt_present("help") { println!("echo {} - display a line of text", VERSION); println!(""); println!("Usage:"); println!(" {} [SHORT-OPTION]... [STRING]...", program); println!(""); println!(""); println(getopts::usage("Echo the STRING(s) to standard output.", &opts) .as_slice()); return; } if matches.opt_present("version") { let string = matches.free.connect(" "); print!(string.as_slice()); } if !matches.opt_present("n") { print!("") } else { stdio::flush(); } }
e147d7d93f462edb638ebe80daef9e447aaeb1be
[ "Markdown", "Rust" ]
2
Markdown
11Takanori/echo-in-rust
f143acc40b1fa08b72b4e8758dd3146eadf6ac8d
f1730e5b5ddf9971e8510dc498da0788243f9f0e
refs/heads/master
<file_sep>from numpy import genfromtxt import math from datetime import datetime import matplotlib.pyplot as plt from datetime import date import calendar import csv #Array of dates holidays in the dataset: holidays = [] def TypeOfDay(timestamp): day_of_week = calendar.day_name[datetime.fromtimestamp(timestamp).weekday()] if ((day_of_week == 'Saturday') or (day_of_week == 'Sunday')): return 0 else: return 1 #import data: gps_data = genfromtxt('gps.csv', delimiter=',') tmp = [] #Clean data: for row in gps_data: if ((not math.isnan(row[1])) and (not math.isnan(row[2])) and (not math.isnan(row[3]))): tmp.append([row[1], round(row[2],4), round(row[3],4)]) #Agregate data by days: dataset = [[]] dataset_day_type = [] day_num = 0 date = datetime.fromtimestamp(tmp[0][0]).day dataset_day_type = [TypeOfDay(tmp[0][0])] for row in tmp: if (datetime.fromtimestamp(row[0]).day == date): dataset[day_num].append([row[1], row[2]]) else: date = datetime.fromtimestamp(row[0]).day day_num = day_num + 1 dataset.append([]) dataset[day_num].append([row[1], row[2]]) dataset_day_type.append(TypeOfDay(row[0])) print dataset[0] print "Number of days in dataset: " + str(len(dataset)) #Write aggregated data to CSV file: with open('aggregated_data.csv', 'wb') as csvfile: coorwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) day_counter = 0 coorwriter.writerow(['Day number', 'Longitude', 'Latitude', 'Type of day']) for row in dataset: for coor in row: coorwriter.writerow([day_counter, coor[0], coor[1], dataset_day_type[day_counter]]) day_counter = day_counter + 1 <file_sep>from numpy import genfromtxt import sys import matplotlib.pyplot as plt #Import aggregated data, day numbering need to start from zero: gps_data = genfromtxt('aggregated_data.csv', delimiter=',', skip_header=1) #Create dataset dataset: x=[[[],[]]] #coordinates per day y=[] #day type first_time = True for row in gps_data: if (first_time): #first row if (row[0] == 0): day_num = row[0] sequence_num = 0 x[sequence_num][0].append(round(row[1], 4)) x[sequence_num][1].append(round(row[2], 4)) y.append(row[3]) first_time = False else: print "[ERROR] Day numbering in CSV file need to start from 0." sys.exit() else: if (day_num == row[0]): x[sequence_num][0].append(round(row[1], 4)) x[sequence_num][1].append(round(row[2], 4)) else: day_num = row[0] sequence_num = sequence_num + 1 x.append([[],[]]) x[sequence_num][0].append(round(row[1], 4)) x[sequence_num][1].append(round(row[2], 4)) y.append(row[3]) #Working days: plt.subplot(2, 1, 1) for day in range(len(y)): if (y[day] == 1): plt.plot(x[day][0], x[day][1], 'r*') #Free days: plt.subplot(2, 1, 2) for day in range(len(y)): if (y[day] == 0): plt.plot(x[day][0], x[day][1], 'g*') plt.show() <file_sep>from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.callbacks import EarlyStopping from keras.callbacks import Callback from numpy import genfromtxt import numpy as np import sys import matplotlib.pyplot as plt # fix random seed for reproducibility np.random.seed(7) #Import aggregated data, day numbering need to start from zero: gps_data = genfromtxt('aggregated_data.csv', delimiter=',', skip_header=1) #Create dataset dataset: x=[[]] #coordinates per day y=[] #day type first_time = True for row in gps_data: if (first_time): #first row if (row[0] == 0): day_num = row[0] sequence_num = 0 x[sequence_num].append([round(row[1], 4), round(row[2], 4)]) y.append(row[3]) first_time = False else: print "[ERROR] Day numbering in CSV file need to start from 0." sys.exit() else: if (day_num == row[0]): x[sequence_num].append([round(row[1], 4), round(row[2], 4)]) else: day_num = row[0] sequence_num = sequence_num + 1 x.append([]) x[sequence_num].append([round(row[1], 4), round(row[2], 4)]) y.append(row[3]) #Find out max number of coordinates per day: max_value = 0 for day in x: if (len(day) > max_value): max_value = len(day) #if number of coordinat per day is less then max then append zero coordinats: for day in x: if (len(day) > max_value): day = day[0:max_value] else: for j in range((max_value - len(day))): day.append([0.0,0.0]) x = np.array(x) #convert to numpy array y = np.array(y) #convert to numpy array x = np.reshape(x, (x.shape[0], 2, x.shape[1])) #Callbacks: class My_Callback(Callback): def on_epoch_end(self, epoch, logs={}): if logs.get('acc') > 0.85: self.model.stop_training = True callbacks = [My_Callback()] #Create sequential neural network model three layers: model1 = Sequential() model1.add(LSTM(60, input_shape=(2,max_value))) model1.add(Dense(1, activation='sigmoid')) model1.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy']) history1 = model1.fit(x, y, validation_split=0.1, epochs=1000, batch_size=10, verbose=0, callbacks=callbacks) #Create sequential neural network model three layers: model2 = Sequential() model2.add(LSTM(60, input_shape=(2,max_value))) model2.add(Dense(40, activation='relu')) model2.add(Dense(1, activation='sigmoid')) model2.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy']) history2 = model2.fit(x, y, validation_split=0.1, epochs=1000, batch_size=10, verbose=0, callbacks=callbacks) #Create sequential neural network model two layers and smaller number of elements: model3 = Sequential() model3.add(LSTM(30, input_shape=(2,max_value))) model3.add(Dense(1, activation='sigmoid')) model3.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy']) history3 = model3.fit(x, y, validation_split=0.1, epochs=1000, batch_size=10, verbose=0, callbacks=callbacks) #Create sequential neural network model three layers and smaller number of elements: model4 = Sequential() model4.add(LSTM(30, input_shape=(2,max_value))) model4.add(Dense(5, activation='relu')) model4.add(Dense(1, activation='sigmoid')) model4.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy']) history4 = model4.fit(x, y, validation_split=0.1, epochs=1000, batch_size=10, verbose=0, callbacks=callbacks) #Plot results: plt.subplot(2, 2, 1) plt.plot(history1.history['acc'], 'r', label = 'Accuracy') plt.plot(history1.history['loss'], 'g', label = 'Loss') plt.plot(history1.history['val_acc'], 'b', label = 'Validation accuracy') plt.subplot(2, 2, 2) plt.plot(history2.history['acc'], 'r', label = 'Accuracy') plt.plot(history2.history['loss'], 'g', label = 'Loss') plt.plot(history2.history['val_acc'], 'b', label = 'Validation accuracy') plt.subplot(2, 2, 3) plt.plot(history3.history['acc'], 'r', label = 'Accuracy') plt.plot(history3.history['loss'], 'g', label = 'Loss') plt.plot(history3.history['val_acc'], 'b', label = 'Validation accuracy') plt.subplot(2, 2, 4) plt.plot(history4.history['acc'], 'r', label = 'Accuracy') plt.plot(history4.history['loss'], 'g', label = 'Loss') plt.plot(history4.history['val_acc'], 'b', label = 'Validation accuracy') plt.show()
d922fae6ccefc0dd85d6a575143504ee382a0291
[ "Python" ]
3
Python
sabreatom/course_work_route
33ff23dab0e0de5f0157325c823aea018043d73a
dd36ab7df1f5b85a0ca8a5b68a5b686cce40b590
refs/heads/master
<file_sep>require 'csv' puts "============波動分析============" mondays_with_end_prices = Hash.new() tuesdays_with_end_prices = Hash.new() wednesdays_with_end_prices = Hash.new() thursdays_with_end_prices = Hash.new() fridays_with_end_prices = Hash.new() mondays_with_waves = Hash.new() tuesdays_with_waves = Hash.new() wednesdays_with_waves = Hash.new() thursdays_with_waves = Hash.new() fridays_with_waves = Hash.new() closingdays_with_waves = Array.new() period_month = (Date.new(2015,06)..Date.new(2019,11)).select {|d| d.day == 1} period_month_csv = period_month.map do |ele| "./data/" + ele.strftime("%Y%m") + ".csv" end period_month_csv.each do |file| if File.file?(file) CSV.foreach(file) do |row| row0 = row[0].strip begin date = Date.strptime(row0,"%Y/%m/%d").next_year(1911) cwday = date.cwday end_price = row[4].delete(',').to_f case cwday when 1 mondays_with_end_prices[date] = end_price when 2 tuesdays_with_end_prices[date] = end_price when 3 wednesdays_with_end_prices[date] = end_price when 4 thursdays_with_end_prices[date] = end_price when 5 fridays_with_end_prices[date] = end_price end rescue Exception => e # puts e end end end end mondays = mondays_with_end_prices.keys tuesdays = tuesdays_with_end_prices.keys wednesdays = wednesdays_with_end_prices.keys thursdays = thursdays_with_end_prices.keys fridays = fridays_with_end_prices.keys # 禮拜一波動 mondays.each do |date| yesterday = date.prev_day.prev_day.prev_day if fridays.include? yesterday mondays_with_waves[date.strftime("%Y/%m/%d")] = (mondays_with_end_prices[date] - fridays_with_end_prices[yesterday]).round(2) end end # mondays_with_waves mondays_waves = mondays_with_waves.values mondays_positive_waves = mondays_with_waves.values.select { |e| e > 0 } mondays_negative_waves = mondays_with_waves.values.select { |e| e < 0 } mondays_waves_sort = mondays_waves.sort mondays_positive_waves_sort = mondays_positive_waves.sort mondays_negative_waves_sort = mondays_negative_waves.sort monday_avg_wave = (mondays_waves.inject(0, :+)/mondays_waves.size).round(2) monday_avg_positive_wave = (mondays_positive_waves.inject(0, :+)/mondays_positive_waves.size).round(2) monday_avg_negative_wave = (mondays_negative_waves.inject(0, :+)/mondays_negative_waves.size).round(2) monday_median_wave = mondays_waves_sort[mondays_waves_sort.size/2] monday_median_positive_wave = mondays_positive_waves_sort[mondays_positive_waves_sort.size/2] monday_median_negative_wave = mondays_negative_waves_sort[mondays_negative_waves_sort.size/2] monday_positive_odds = (mondays_positive_waves.size.to_f/mondays_waves.size.to_f).round(2) monday_negative_odds = (mondays_negative_waves.size.to_f/mondays_waves.size.to_f).round(2) monday_max = mondays_waves.max monday_min = mondays_waves.min puts "============禮拜一============" puts "禮拜一波動中位數#{monday_median_wave}點" puts "禮拜一波動平均數#{monday_avg_wave}點" puts "禮拜一上漲機率#{monday_positive_odds}" puts "禮拜一上漲中位數#{monday_median_positive_wave}點" puts "禮拜一上漲平均數#{monday_avg_positive_wave}點" puts "禮拜一最大上漲#{monday_max}點" puts "禮拜一下跌機率#{monday_negative_odds}" puts "禮拜一下跌中位數#{monday_median_negative_wave}點" puts "禮拜一下跌平均數#{monday_avg_negative_wave}點" puts "禮拜一最大下跌#{monday_min}點" # 禮拜二波動 tuesdays.each do |date| yesterday = date.prev_day if mondays.include? yesterday tuesdays_with_waves[date.strftime("%Y/%m/%d")] = (tuesdays_with_end_prices[date] - mondays_with_end_prices[yesterday]).round(2) end end # tuesdays_with_waves tuesdays_waves = tuesdays_with_waves.values tuesdays_positive_waves = tuesdays_with_waves.values.select { |e| e > 0 } tuesdays_negative_waves = tuesdays_with_waves.values.select { |e| e < 0 } tuesdays_waves_sort = tuesdays_waves.sort tuesdays_positive_waves_sort = tuesdays_positive_waves.sort tuesdays_negative_waves_sort = tuesdays_negative_waves.sort tuesday_avg_wave = (tuesdays_waves.inject(0, :+)/tuesdays_waves.size).round(2) tuesday_avg_positive_wave = (tuesdays_positive_waves.inject(0, :+)/tuesdays_positive_waves.size).round(2) tuesday_avg_negative_wave = (tuesdays_negative_waves.inject(0, :+)/tuesdays_negative_waves.size).round(2) tuesday_median_wave = tuesdays_waves_sort[tuesdays_waves_sort.size/2] tuesday_median_positive_wave = tuesdays_positive_waves_sort[tuesdays_positive_waves_sort.size/2] tuesday_median_negative_wave = tuesdays_negative_waves_sort[tuesdays_negative_waves_sort.size/2] tuesday_positive_odds = (tuesdays_positive_waves.size.to_f/tuesdays_waves.size.to_f).round(2) tuesday_negative_odds = (tuesdays_negative_waves.size.to_f/tuesdays_waves.size.to_f).round(2) tuesday_max = tuesdays_waves.max tuesday_min = tuesdays_waves.min puts "============禮拜二============" puts "禮拜二波動中位數#{tuesday_median_wave}點" puts "禮拜二波動平均數#{tuesday_avg_wave}點" puts "禮拜二上漲機率#{tuesday_positive_odds}" puts "禮拜二上漲中位數#{tuesday_median_positive_wave}點" puts "禮拜二上漲平均數#{tuesday_avg_positive_wave}點" puts "禮拜二最大上漲#{tuesday_max}點" puts "禮拜二下跌機率#{tuesday_negative_odds}" puts "禮拜二下跌中位數#{tuesday_median_negative_wave}點" puts "禮拜二下跌平均數#{tuesday_avg_negative_wave}點" puts "禮拜二最大下跌#{tuesday_min}點" # 禮拜三波動 wednesdays.each do |date| yesterday = date.prev_day if tuesdays.include? yesterday wednesdays_with_waves[date.strftime("%Y/%m/%d")] = (wednesdays_with_end_prices[date] - tuesdays_with_end_prices[yesterday]).round(2) end end # wednesdays_with_waves wednesdays_waves = wednesdays_with_waves.values wednesdays_positive_waves = wednesdays_with_waves.values.select { |e| e > 0 } wednesdays_negative_waves = wednesdays_with_waves.values.select { |e| e < 0 } wednesdays_waves_sort = wednesdays_waves.sort wednesdays_positive_waves_sort = wednesdays_positive_waves.sort wednesdays_negative_waves_sort = wednesdays_negative_waves.sort wednesday_avg_wave = (wednesdays_waves.inject(0, :+)/wednesdays_waves.size).round(2) wednesday_avg_positive_wave = (wednesdays_positive_waves.inject(0, :+)/wednesdays_positive_waves.size).round(2) wednesday_avg_negative_wave = (wednesdays_negative_waves.inject(0, :+)/wednesdays_negative_waves.size).round(2) wednesday_median_wave = wednesdays_waves_sort[wednesdays_waves_sort.size/2] wednesday_median_positive_wave = wednesdays_positive_waves_sort[wednesdays_positive_waves_sort.size/2] wednesday_median_negative_wave = wednesdays_negative_waves_sort[wednesdays_negative_waves_sort.size/2] wednesday_positive_odds = (wednesdays_positive_waves.size.to_f/wednesdays_waves.size.to_f).round(2) wednesday_negative_odds = (wednesdays_negative_waves.size.to_f/wednesdays_waves.size.to_f).round(2) wednesday_max = wednesdays_waves.max wednesday_min = wednesdays_waves.min puts "============禮拜三============" puts "禮拜三波動中位數#{wednesday_median_wave}點" puts "禮拜三波動平均數#{wednesday_avg_wave}點" puts "禮拜三上漲機率#{wednesday_positive_odds}" puts "禮拜三上漲中位數#{wednesday_median_positive_wave}點" puts "禮拜三上漲平均數#{wednesday_avg_positive_wave}點" puts "禮拜三最大上漲#{wednesday_max}點" puts "禮拜三下跌機率#{wednesday_negative_odds}" puts "禮拜三下跌中位數#{wednesday_median_negative_wave}點" puts "禮拜三下跌平均數#{wednesday_avg_negative_wave}點" puts "禮拜三最大下跌#{wednesday_min}點" # 禮拜四波動 thursdays.each do |date| yesterday = date.prev_day if wednesdays.include? yesterday thursdays_with_waves[date.strftime("%Y/%m/%d")] = (thursdays_with_end_prices[date] - wednesdays_with_end_prices[yesterday]).round(2) end end # thursdays_with_waves thursdays_waves = thursdays_with_waves.values thursdays_positive_waves = thursdays_with_waves.values.select { |e| e > 0 } thursdays_negative_waves = thursdays_with_waves.values.select { |e| e < 0 } thursdays_waves_sort = thursdays_waves.sort thursdays_positive_waves_sort = thursdays_positive_waves.sort thursdays_negative_waves_sort = thursdays_negative_waves.sort thursday_avg_wave = (thursdays_waves.inject(0, :+)/thursdays_waves.size).round(2) thursday_avg_positive_wave = (thursdays_positive_waves.inject(0, :+)/thursdays_positive_waves.size).round(2) thursday_avg_negative_wave = (thursdays_negative_waves.inject(0, :+)/thursdays_negative_waves.size).round(2) thursday_median_wave = thursdays_waves_sort[thursdays_waves_sort.size/2] thursday_median_positive_wave = thursdays_positive_waves_sort[thursdays_positive_waves_sort.size/2] thursday_median_negative_wave = thursdays_negative_waves_sort[thursdays_negative_waves_sort.size/2] thursday_positive_odds = (thursdays_positive_waves.size.to_f/thursdays_waves.size.to_f).round(2) thursday_negative_odds = (thursdays_negative_waves.size.to_f/thursdays_waves.size.to_f).round(2) thursday_max = thursdays_waves.max thursday_min = thursdays_waves.min puts "============禮拜四============" puts "禮拜四波動中位數#{thursday_median_wave}點" puts "禮拜四波動平均數#{thursday_avg_wave}點" puts "禮拜四上漲機率#{thursday_positive_odds}" puts "禮拜四上漲中位數#{thursday_median_positive_wave}點" puts "禮拜四上漲平均數#{thursday_avg_positive_wave}點" puts "禮拜四最大上漲#{thursday_max}點" puts "禮拜四下跌機率#{thursday_negative_odds}" puts "禮拜四下跌中位數#{thursday_median_negative_wave}點" puts "禮拜四下跌平均數#{thursday_avg_negative_wave}點" puts "禮拜四最大下跌#{thursday_min}點" # 禮拜五波動 fridays.each do |date| yesterday = date.prev_day if thursdays.include? yesterday fridays_with_waves[date.strftime("%Y/%m/%d")] = (fridays_with_end_prices[date] - thursdays_with_end_prices[yesterday]).round(2) end end # fridays_with_waves fridays_waves = fridays_with_waves.values fridays_positive_waves = fridays_with_waves.values.select { |e| e > 0 } fridays_negative_waves = fridays_with_waves.values.select { |e| e < 0 } fridays_waves_sort = fridays_waves.sort fridays_positive_waves_sort = fridays_positive_waves.sort fridays_negative_waves_sort = fridays_negative_waves.sort friday_avg_wave = (fridays_waves.inject(0, :+)/fridays_waves.size).round(2) friday_avg_positive_wave = (fridays_positive_waves.inject(0, :+)/fridays_positive_waves.size).round(2) friday_avg_negative_wave = (fridays_negative_waves.inject(0, :+)/fridays_negative_waves.size).round(2) friday_median_wave = fridays_waves_sort[fridays_waves_sort.size/2] friday_median_positive_wave = fridays_positive_waves_sort[fridays_positive_waves_sort.size/2] friday_median_negative_wave = fridays_negative_waves_sort[fridays_negative_waves_sort.size/2] friday_positive_odds = (fridays_positive_waves.size.to_f/fridays_waves.size.to_f).round(2) friday_negative_odds = (fridays_negative_waves.size.to_f/fridays_waves.size.to_f).round(2) friday_max = fridays_waves.max friday_min = fridays_waves.min puts "============禮拜五============" puts "禮拜五波動中位數#{friday_median_wave}點" puts "禮拜五波動平均數#{friday_avg_wave}點" puts "禮拜五上漲機率#{friday_positive_odds}" puts "禮拜五上漲中位數#{friday_median_positive_wave}點" puts "禮拜五上漲平均數#{friday_avg_positive_wave}點" puts "禮拜五最大上漲#{friday_max}點" puts "禮拜五下跌機率#{friday_negative_odds}" puts "禮拜五下跌中位數#{friday_median_negative_wave}點" puts "禮拜五下跌平均數#{friday_avg_negative_wave}點" puts "禮拜五最大下跌#{friday_min}點" total_positive_odds = ((mondays_positive_waves.size + tuesdays_positive_waves.size + wednesdays_positive_waves.size + thursdays_positive_waves.size + fridays_positive_waves.size).to_f/ (mondays_waves.size + tuesdays_waves.size + wednesdays_waves.size + thursdays_waves.size + fridays_waves.size ).to_f).round(2) total_negative_odds = ((mondays_negative_waves.size + tuesdays_negative_waves.size + wednesdays_negative_waves.size + thursdays_negative_waves.size + fridays_negative_waves.size).to_f/ (mondays_waves.size + tuesdays_waves.size + wednesdays_waves.size + thursdays_waves.size + fridays_waves.size ).to_f).round(2) total_positive_waves = mondays_positive_waves + tuesdays_positive_waves + wednesdays_positive_waves + thursdays_positive_waves + fridays_positive_waves total_negative_waves = mondays_negative_waves + tuesdays_negative_waves + wednesdays_negative_waves + thursdays_negative_waves + fridays_negative_waves total_avg_positive_wave = (total_positive_waves.inject(0, :+)/total_positive_waves.size).round(2) total_avg_negative_wave = (total_negative_waves.inject(0, :+)/total_negative_waves.size).round(2) total_positive_waves_sort = total_positive_waves.sort total_negative_waves_sort = total_negative_waves.sort total_median_positive_wave = total_positive_waves_sort[total_positive_waves_sort.size/2] total_median_negative_wave = total_negative_waves_sort[total_negative_waves_sort.size/2] total_waves = mondays_waves + tuesdays_waves + wednesdays_waves + thursdays_waves + fridays_waves total_waves_sort = total_waves.sort total_avg_wave = (total_waves.inject(0, :+)/total_waves.size).round(2) total_median_wave = total_waves_sort[total_waves_sort.size/2] total_max = total_waves.max total_min = total_waves.min puts "============總計============" puts "波動中位數#{total_median_wave}點" puts "波動平均數#{total_avg_wave}點" puts "上漲機率#{total_positive_odds}" puts "上漲中位數#{total_median_positive_wave}點" puts "上漲平均數#{total_avg_positive_wave}點" puts "最大上漲#{total_max}" puts "下跌機率#{total_negative_odds}" puts "下跌中位數#{total_median_negative_wave}點" puts "下跌平均數#{total_avg_negative_wave}點" puts "最大下跌#{total_min}" wednesdays.each do |day| yesterday = day.prev_day before_yesterday = yesterday.prev_day if ((tuesdays.include? yesterday) && (mondays.include? before_yesterday)) tuesday_wave = (tuesdays_with_end_prices[yesterday] - mondays_with_end_prices[before_yesterday]).round(2) wednesday_wave = (wednesdays_with_end_prices[day] - tuesdays_with_end_prices[yesterday]).round(2) closingdays_with_waves << [tuesday_wave,wednesday_wave] else #puts day end end closingdays_positive_waves = closingdays_with_waves.select { |e| e.last > 0 } closingdays_negative_waves = closingdays_with_waves.select { |e| e.last < 0 } closingday_call = (closingdays_positive_waves.map { |e| e.last }.inject(0, :+)/closingdays_with_waves.size).round(2) closingday_put = (closingdays_negative_waves.map { |e| e.last }.inject(0, :+)/closingdays_with_waves.size).round(2) over = 50 closingdays_yesterday_over_positive = closingdays_with_waves.select { |e| e.first >= over } closingdays_yesterday_over_negative = closingdays_with_waves.select { |e| e.first <= -over } closingdays_yesterday_small_positive = closingdays_with_waves.select { |e| e.first > 0 && e.first < over } closingdays_yesterday_small_negative = closingdays_with_waves.select { |e| e.first < 0 && e.first > -over } closingdays_yesterday_small_positive_call = (closingdays_yesterday_small_positive.select { |e| e.last > 0 }.map { |e| e.last }.inject(0, :+)/closingdays_yesterday_small_positive.size).round(2) closingdays_yesterday_small_positive_put = (closingdays_yesterday_small_positive.select { |e| e.last < 0 }.map { |e| e.last }.inject(0, :+)/closingdays_yesterday_small_positive.size).round(2) closingdays_yesterday_small_negative_call = (closingdays_yesterday_small_negative.select { |e| e.last > 0 }.map { |e| e.last }.inject(0, :+)/closingdays_yesterday_small_negative.size).round(2) closingdays_yesterday_small_negative_put = (closingdays_yesterday_small_negative.select { |e| e.last < 0 }.map { |e| e.last }.inject(0, :+)/closingdays_yesterday_small_negative.size).round(2) closingdays_yesterday_over_positive_call = (closingdays_yesterday_over_positive.select { |e| e.last > 0 }.map { |e| e.last }.inject(0, :+)/closingdays_yesterday_over_positive.size).round(2) closingdays_yesterday_over_positive_put = (closingdays_yesterday_over_positive.select { |e| e.last < 0 }.map { |e| e.last }.inject(0, :+)/closingdays_yesterday_over_positive.size).round(2) closingdays_yesterday_over_negative_call = (closingdays_yesterday_over_negative.select { |e| e.last > 0 }.map { |e| e.last }.inject(0, :+)/closingdays_yesterday_over_negative.size).round(2) closingdays_yesterday_over_negative_put = (closingdays_yesterday_over_negative.select { |e| e.last < 0 }.map { |e| e.last }.inject(0, :+)/closingdays_yesterday_over_negative.size).round(2) closingdays_yesterday_small_positive_max = closingdays_yesterday_small_positive.map { |e| e.last }.max closingdays_yesterday_small_positive_min = closingdays_yesterday_small_positive.map { |e| e.last }.min closingdays_yesterday_small_negative_max = closingdays_yesterday_small_negative.map { |e| e.last }.max closingdays_yesterday_small_negative_min = closingdays_yesterday_small_negative.map { |e| e.last }.min closingdays_yesterday_over_positive_max = closingdays_yesterday_over_positive.map { |e| e.last }.max closingdays_yesterday_over_positive_min = closingdays_yesterday_over_positive.map { |e| e.last }.min closingdays_yesterday_over_negative_max = closingdays_yesterday_over_negative.map { |e| e.last }.max closingdays_yesterday_over_negative_min = closingdays_yesterday_over_negative.map { |e| e.last }.min puts "============週選結算日============" #puts "Call平均收在#{closingday_call}點" #puts "Put平均收在#{closingday_put}點" puts "當結算日前一天大漲超過#{over}點,Call平均收在#{closingdays_yesterday_over_positive_call},Call最大收在#{closingdays_yesterday_over_positive_max},Put平均收在#{closingdays_yesterday_over_positive_put},Put最大收在#{closingdays_yesterday_over_positive_min}" puts "當結算日前一天小漲在#{over}點以內,Call平均收在#{closingdays_yesterday_small_positive_call},Call最大收在#{closingdays_yesterday_small_positive_max},Put平均收在#{closingdays_yesterday_small_positive_put},Put最大收在#{closingdays_yesterday_small_positive_min}" puts "當結算日前一天大跌超過#{over}點,Put平均收在#{closingdays_yesterday_over_negative_put},Put最大收在#{closingdays_yesterday_over_negative_min},Call平均收在#{closingdays_yesterday_over_negative_call},Call最大收在#{closingdays_yesterday_over_negative_max}" puts "當結算日前一天小跌在#{over}點以內,Put平均收在#{closingdays_yesterday_small_negative_put},Put最大收在#{closingdays_yesterday_small_negative_min},Call平均收在#{closingdays_yesterday_small_negative_call},Call最大收在#{closingdays_yesterday_small_negative_max}" <file_sep>require 'csv' datas = Array.new() date_gap = Hash.new() date_highestGap = Hash.new() date_lowestGap = Hash.new() date_usingday = Hash.new() date_highestPrice = Hash.new() date_lowestPrice = Hash.new() period_month = (Date.new(2012,01)..Date.new(2020,02)).select {|d| d.day == 1} period_month_csv = period_month.map do |ele| "./data/" + ele.strftime("%Y%m") + ".csv" end period_month_csv.each do |file| if File.file?(file) CSV.foreach(file) do |data| begin date = Date.strptime(data[0].strip,"%Y/%m/%d").next_year(1911) date_highestPrice[date.strftime("%Y/%m/%d")] = data[2].delete(',').to_f date_lowestPrice[date.strftime("%Y/%m/%d")] = data[3].delete(',').to_f rescue => exception # puts exception end end end end CSV.foreach("option.csv") do |data| datas.unshift(data) end datas.each_cons(2) do |data,next_data| gap = next_data[2].to_f - data[2].to_f usingday = Date.parse(next_data[0]).mjd - Date.parse(data[0]).mjd date = "#{next_data[1]}(#{next_data[0]})" date_gap[date] = gap date_usingday[date] = usingday rangeDates = ((Date.parse(data[0]).next_day)..Date.parse(next_data[0])).to_a date_highestGap[date] = (rangeDates.map { |date| date_highestPrice[date.strftime("%Y/%m/%d")] }.compact << data[2].to_f << next_data[2].to_f).max - data[2].to_f date_lowestGap[date] = (rangeDates.map { |date| date_lowestPrice[date.strftime("%Y/%m/%d")] }.compact << data[2].to_f << next_data[2].to_f).min - data[2].to_f end midValue = 0.9 gaps = date_gap.values gapTotalCount = gaps.count gapUpCount = gaps.select {|gap| gap > 0}.count gapDownCount = gaps.select {|gap| gap < 0}.count gapMaxs = date_gap.max_by(3){|k,v| v} gapMaxs1 = gapMaxs[0] gapMaxs2 = gapMaxs[1] gapMaxs3 = gapMaxs[2] #gapUpTotalValue = gaps.select {|gap| gap > 0}.inject(0, :+) gapUpMid = gaps.select {|gap| gap > 0}.sort[gapUpCount*midValue] gapUpTotalMid = gaps.sort[gapTotalCount*midValue] gapMins = date_gap.min_by(3){|k,v| v} gapMins1 = gapMins[0] gapMins2 = gapMins[1] gapMins3 = gapMins[2] #gapDownTotalValue = gaps.select {|gap| gap < 0}.inject(0, :+) gapDownMid = gaps.select {|gap| gap < 0}.sort.reverse[gapDownCount*midValue] gapDownTotalMid = gaps.sort.reverse[gapTotalCount*midValue] gapUp4s = gaps.select {|gap| gap > 400 && gap <= 500} gapUp3s = gaps.select {|gap| gap > 300 && gap <= 400} gapUp2s = gaps.select {|gap| gap > 200 && gap <= 300} gapUp1s = gaps.select {|gap| gap > 100 && gap <= 200} gapUp0s = gaps.select {|gap| gap > 0 && gap <= 100} gapZero = gaps.select {|gap| gap == 0 } gapDown0s = gaps.select {|gap| gap < 0 && gap >= -100} gapDown1s = gaps.select {|gap| gap < -100 && gap >= -200} gapDown2s = gaps.select {|gap| gap < -200 && gap >= -300} gapDown3s = gaps.select {|gap| gap < -300 && gap >= -400} gapDown4s = gaps.select {|gap| gap < -400 && gap >= -500} gapDown5s = gaps.select {|gap| gap < -500 && gap >= -600} gapDown6s = gaps.select {|gap| gap < -600 && gap >= -700} gapDown7s = gaps.select {|gap| gap < -700 && gap >= -800} gapDown8s = gaps.select {|gap| gap < -800 && gap >= -900} gapDown9s = gaps.select {|gap| gap < -900 && gap >= -1000} gapDown10s = gaps.select {|gap| gap < -1000 && gap >= -1100} gapDown11s = gaps.select {|gap| gap < -1100 && gap >= -1200} gapDown12s = gaps.select {|gap| gap < -1200 && gap >= -1300} gapDown13s = gaps.select {|gap| gap < -1300 && gap >= -1400} gapDown14s = gaps.select {|gap| gap < -1400 && gap >= -1500} gapDown15s = gaps.select {|gap| gap < -1500 && gap >= -1600} gapDown16s = gaps.select {|gap| gap < -1600 && gap >= -1700} sc100WinCount = gapUp0s.count sc200WinCount = sc100WinCount + gapUp1s.count sc300WinCount = sc200WinCount + gapUp2s.count sc400WinCount = sc300WinCount + gapUp3s.count sc500WinCount = sc400WinCount + gapUp4s.count allWinCount = gapZero.count sp100WinCount = gapDown0s.count sp200WinCount = sp100WinCount + gapDown1s.count sp300WinCount = sp200WinCount + gapDown2s.count sp400WinCount = sp300WinCount + gapDown3s.count sp500WinCount = sp400WinCount + gapDown4s.count sp600WinCount = sp500WinCount + gapDown5s.count sp700WinCount = sp600WinCount + gapDown6s.count sp800WinCount = sp700WinCount + gapDown7s.count sp900WinCount = sp800WinCount + gapDown8s.count sp1000WinCount = sp900WinCount + gapDown9s.count sp1100WinCount = sp1000WinCount + gapDown10s.count sp1200WinCount = sp1100WinCount + gapDown11s.count sp1300WinCount = sp1200WinCount + gapDown12s.count sp1400WinCount = sp1300WinCount + gapDown13s.count sp1500WinCount = sp1400WinCount + gapDown14s.count sp1600WinCount = sp1500WinCount + gapDown15s.count sp1700WinCount = sp1600WinCount + gapDown16s.count sc100TotalWinRate = (((sc100WinCount.to_f + allWinCount.to_f + gapDownCount.to_f)/(gapTotalCount.to_f))*100).round(4) sc200TotalWinRate = (((sc200WinCount.to_f + allWinCount.to_f + gapDownCount.to_f)/(gapTotalCount.to_f))*100).round(4) sc300TotalWinRate = (((sc300WinCount.to_f + allWinCount.to_f + gapDownCount.to_f)/(gapTotalCount.to_f))*100).round(4) sc400TotalWinRate = (((sc400WinCount.to_f + allWinCount.to_f + gapDownCount.to_f)/(gapTotalCount.to_f))*100).round(4) sc500TotalWinRate = (((sc500WinCount.to_f + allWinCount.to_f + gapDownCount.to_f)/(gapTotalCount.to_f))*100).round(4) # ================== # sp100TotalWinRate = (((sp100WinCount.to_f + allWinCount.to_f + gapUpCount.to_f)/(gapTotalCount.to_f))*100).round(4) sp200TotalWinRate = (((sp200WinCount.to_f + allWinCount.to_f + gapUpCount.to_f)/(gapTotalCount.to_f))*100).round(4) sp300TotalWinRate = (((sp300WinCount.to_f + allWinCount.to_f + gapUpCount.to_f)/(gapTotalCount.to_f))*100).round(4) sp400TotalWinRate = (((sp400WinCount.to_f + allWinCount.to_f + gapUpCount.to_f)/(gapTotalCount.to_f))*100).round(4) sp500TotalWinRate = (((sp500WinCount.to_f + allWinCount.to_f + gapUpCount.to_f)/(gapTotalCount.to_f))*100).round(4) sp600TotalWinRate = (((sp600WinCount.to_f + allWinCount.to_f + gapUpCount.to_f)/(gapTotalCount.to_f))*100).round(4) sp700TotalWinRate = (((sp700WinCount.to_f + allWinCount.to_f + gapUpCount.to_f)/(gapTotalCount.to_f))*100).round(4) sp800TotalWinRate = (((sp800WinCount.to_f + allWinCount.to_f + gapUpCount.to_f)/(gapTotalCount.to_f))*100).round(4) sp900TotalWinRate = (((sp900WinCount.to_f + allWinCount.to_f + gapUpCount.to_f)/(gapTotalCount.to_f))*100).round(4) sp1000TotalWinRate = (((sp1000WinCount.to_f + allWinCount.to_f + gapUpCount.to_f)/(gapTotalCount.to_f))*100).round(4) sp1100TotalWinRate = (((sp1100WinCount.to_f + allWinCount.to_f + gapUpCount.to_f)/(gapTotalCount.to_f))*100).round(4) sp1200TotalWinRate = (((sp1200WinCount.to_f + allWinCount.to_f + gapUpCount.to_f)/(gapTotalCount.to_f))*100).round(4) sp1300TotalWinRate = (((sp1300WinCount.to_f + allWinCount.to_f + gapUpCount.to_f)/(gapTotalCount.to_f))*100).round(4) sp1400TotalWinRate = (((sp1400WinCount.to_f + allWinCount.to_f + gapUpCount.to_f)/(gapTotalCount.to_f))*100).round(4) sp1500TotalWinRate = (((sp1500WinCount.to_f + allWinCount.to_f + gapUpCount.to_f)/(gapTotalCount.to_f))*100).round(4) sp1600TotalWinRate = (((sp1600WinCount.to_f + allWinCount.to_f + gapUpCount.to_f)/(gapTotalCount.to_f))*100).round(4) sp1700TotalWinRate = (((sp1700WinCount.to_f + allWinCount.to_f + gapUpCount.to_f)/(gapTotalCount.to_f))*100).round(4) sc100WinRate = (((sc100WinCount.to_f)/(gapUpCount.to_f))*100).round(4) sc200WinRate = (((sc200WinCount.to_f)/(gapUpCount.to_f))*100).round(4) sc300WinRate = (((sc300WinCount.to_f)/(gapUpCount.to_f))*100).round(4) sc400WinRate = (((sc400WinCount.to_f)/(gapUpCount.to_f))*100).round(4) sc500WinRate = (((sc500WinCount.to_f)/(gapUpCount.to_f))*100).round(4) # ================== # sp100WinRate = (((sp100WinCount.to_f)/(gapDownCount.to_f))*100).round(4) sp200WinRate = (((sp200WinCount.to_f)/(gapDownCount.to_f))*100).round(4) sp300WinRate = (((sp300WinCount.to_f)/(gapDownCount.to_f))*100).round(4) sp400WinRate = (((sp400WinCount.to_f)/(gapDownCount.to_f))*100).round(4) sp500WinRate = (((sp500WinCount.to_f)/(gapDownCount.to_f))*100).round(4) sp600WinRate = (((sp600WinCount.to_f)/(gapDownCount.to_f))*100).round(4) sp700WinRate = (((sp700WinCount.to_f)/(gapDownCount.to_f))*100).round(4) sp800WinRate = (((sp800WinCount.to_f)/(gapDownCount.to_f))*100).round(4) sp900WinRate = (((sp900WinCount.to_f)/(gapDownCount.to_f))*100).round(4) sp1000WinRate = (((sp1000WinCount.to_f)/(gapDownCount.to_f))*100).round(4) sp1100WinRate = (((sp1100WinCount.to_f)/(gapDownCount.to_f))*100).round(4) sp1200WinRate = (((sp1200WinCount.to_f)/(gapDownCount.to_f))*100).round(4) sp1300WinRate = (((sp1300WinCount.to_f)/(gapDownCount.to_f))*100).round(4) sp1400WinRate = (((sp1400WinCount.to_f)/(gapDownCount.to_f))*100).round(4) sp1500WinRate = (((sp1500WinCount.to_f)/(gapDownCount.to_f))*100).round(4) sp1600WinRate = (((sp1600WinCount.to_f)/(gapDownCount.to_f))*100).round(4) sp1700WinRate = (((sp1700WinCount.to_f)/(gapDownCount.to_f))*100).round(4) # highest lowest highestGaps = date_highestGap.values lowestGaps = date_lowestGap.values highestGapMaxs = date_highestGap.max_by(3){|k,v| v} highestGapMaxs1 = highestGapMaxs[0] highestGapMaxs2 = highestGapMaxs[1] highestGapMaxs3 = highestGapMaxs[2] lowestGapMaxs = date_lowestGap.min_by(3){|k,v| v} lowestGapMaxs1 = lowestGapMaxs[0] lowestGapMaxs2 = lowestGapMaxs[1] lowestGapMaxs3 = lowestGapMaxs[2] highestGapUp5s = highestGaps.select {|gap| gap >= 500 } highestGapUp4s = highestGaps.select {|gap| gap >= 400 } highestGapUp3s = highestGaps.select {|gap| gap >= 300 } highestGapUp2s = highestGaps.select {|gap| gap >= 200 } highestGapUp1s = highestGaps.select {|gap| gap >= 100} highestGapUp0s = highestGaps.select {|gap| gap > 0} lowestGapDown0s = lowestGaps.select {|gap| gap < 0 } lowestGapDown1s = lowestGaps.select {|gap| gap <= -100 } lowestGapDown2s = lowestGaps.select {|gap| gap <= -200 } lowestGapDown3s = lowestGaps.select {|gap| gap <= -300 } lowestGapDown4s = lowestGaps.select {|gap| gap <= -400 } lowestGapDown5s = lowestGaps.select {|gap| gap <= -500 } lowestGapDown6s = lowestGaps.select {|gap| gap <= -600 } lowestGapDown7s = lowestGaps.select {|gap| gap <= -700 } lowestGapDown8s = lowestGaps.select {|gap| gap <= -800 } lowestGapDown9s = lowestGaps.select {|gap| gap <= -900 } lowestGapDown10s = lowestGaps.select {|gap| gap <= -1000 } lowestGapDown11s = lowestGaps.select {|gap| gap <= -1100 } lowestGapDown12s = lowestGaps.select {|gap| gap <= -1200 } lowestGapDown13s = lowestGaps.select {|gap| gap <= -1300 } lowestGapDown14s = lowestGaps.select {|gap| gap <= -1400 } lowestGapDown15s = lowestGaps.select {|gap| gap <= -1500 } lowestGapDown16s = lowestGaps.select {|gap| gap <= -1600 } lowestGapDown17s = lowestGaps.select {|gap| gap <= -1700 } highestGapUp5Odd = (((highestGapUp5s.count.to_f)/(gapTotalCount.to_f))*100).round(4) highestGapUp4Odd = (((highestGapUp4s.count.to_f)/(gapTotalCount.to_f))*100).round(4) highestGapUp3Odd = (((highestGapUp3s.count.to_f)/(gapTotalCount.to_f))*100).round(4) highestGapUp2Odd = (((highestGapUp2s.count.to_f)/(gapTotalCount.to_f))*100).round(4) highestGapUp1Odd = (((highestGapUp1s.count.to_f)/(gapTotalCount.to_f))*100).round(4) highestGapUp0Odd = (((highestGapUp0s.count.to_f)/(gapTotalCount.to_f))*100).round(4) lowestGapDown0Odd = ((lowestGapDown0s.count.to_f/gapTotalCount.to_f)*100).round(4) lowestGapDown1Odd = ((lowestGapDown1s.count.to_f/gapTotalCount.to_f)*100).round(4) lowestGapDown2Odd = ((lowestGapDown2s.count.to_f/gapTotalCount.to_f)*100).round(4) lowestGapDown3Odd = ((lowestGapDown3s.count.to_f/gapTotalCount.to_f)*100).round(4) lowestGapDown4Odd = ((lowestGapDown4s.count.to_f/gapTotalCount.to_f)*100).round(4) lowestGapDown5Odd = ((lowestGapDown5s.count.to_f/gapTotalCount.to_f)*100).round(4) lowestGapDown6Odd = ((lowestGapDown6s.count.to_f/gapTotalCount.to_f)*100).round(4) lowestGapDown7Odd = ((lowestGapDown7s.count.to_f/gapTotalCount.to_f)*100).round(4) lowestGapDown8Odd = ((lowestGapDown8s.count.to_f/gapTotalCount.to_f)*100).round(4) lowestGapDown9Odd = ((lowestGapDown9s.count.to_f/gapTotalCount.to_f)*100).round(4) lowestGapDown10Odd = ((lowestGapDown10s.count.to_f/gapTotalCount.to_f)*100).round(4) lowestGapDown11Odd = ((lowestGapDown11s.count.to_f/gapTotalCount.to_f)*100).round(4) lowestGapDown12Odd = ((lowestGapDown12s.count.to_f/gapTotalCount.to_f)*100).round(4) lowestGapDown13Odd = ((lowestGapDown13s.count.to_f/gapTotalCount.to_f)*100).round(4) lowestGapDown14Odd = ((lowestGapDown14s.count.to_f/gapTotalCount.to_f)*100).round(4) lowestGapDown15Odd = ((lowestGapDown15s.count.to_f/gapTotalCount.to_f)*100).round(4) lowestGapDown16Odd = ((lowestGapDown16s.count.to_f/gapTotalCount.to_f)*100).round(4) lowestGapDown17Odd = ((lowestGapDown17s.count.to_f/gapTotalCount.to_f)*100).round(4) # puts puts "==================================最大結算==================================" puts "#{gapMaxs1[0]}發生結算最大漲幅`#{gapMaxs1[1]}`,週期#{date_usingday[gapMaxs1[0]]}天" puts "#{gapMaxs2[0]}發生結算第二大漲幅`#{gapMaxs2[1]}`,週期#{date_usingday[gapMaxs2[0]]}天" puts "#{gapMaxs3[0]}發生結算第三大漲幅`#{gapMaxs3[1]}`,週期#{date_usingday[gapMaxs3[0]]}天" puts "============================================================================" puts "#{gapMins1[0]}發生結算最大跌幅`#{gapMins1[1]}`,週期#{date_usingday[gapMins1[0]]}天" puts "#{gapMins2[0]}發生結算第二大跌幅`#{gapMins2[1]}`,週期#{date_usingday[gapMins2[0]]}天" puts "#{gapMins3[0]}發生結算第三大跌幅`#{gapMins3[1]}`,週期#{date_usingday[gapMins3[0]]}天" puts "==================================正結算裡==================================" puts "-> #{midValue*100}%勝率中位數#{gapUpMid} <-" puts "sc500點勝率#{sc500WinRate}%" puts "sc400點勝率#{sc400WinRate}%" puts "sc300點勝率#{sc300WinRate}%" puts "sc200點勝率#{sc200WinRate}%" puts "sc100點勝率#{sc100WinRate}%" puts "==================================負結算裡==================================" puts "sp100點勝率#{sp100WinRate}%" puts "sp200點勝率#{sp200WinRate}%" puts "sp300點勝率#{sp300WinRate}%" puts "sp400點勝率#{sp400WinRate}%" puts "sp500點勝率#{sp500WinRate}%" puts "sp600點勝率#{sp600WinRate}%" puts "sp700點勝率#{sp700WinRate}%" puts "sp800點勝率#{sp800WinRate}%" puts "sp900點勝率#{sp900WinRate}%" puts "sp1000點勝率#{sp1000WinRate}%" puts "sp1100點勝率#{sp1100WinRate}%" puts "sp1200點勝率#{sp1200WinRate}%" puts "sp1300點勝率#{sp1300WinRate}%" puts "sp1400點勝率#{sp1400WinRate}%" puts "sp1500點勝率#{sp1500WinRate}%" puts "sp1600點勝率#{sp1600WinRate}%" puts "sp1700點勝率#{sp1700WinRate}%" puts "-> #{midValue*100}%勝率中位數#{gapDownMid} <-" puts "==================================所有總合==================================" puts "-> #{midValue*100}%勝率中位數#{gapUpTotalMid} <-" puts "sc500點勝率#{sc500TotalWinRate}%" puts "sc400點勝率#{sc400TotalWinRate}%" puts "sc300點勝率#{sc300TotalWinRate}%" puts "sc200點勝率#{sc200TotalWinRate}%" puts "sc100點勝率#{sc100TotalWinRate}%" puts "============================================================================" puts "sp100點勝率#{sp100TotalWinRate}%" puts "sp200點勝率#{sp200TotalWinRate}%" puts "sp300點勝率#{sp300TotalWinRate}%" puts "sp400點勝率#{sp400TotalWinRate}%" puts "sp500點勝率#{sp500TotalWinRate}%" puts "sp600點勝率#{sp600TotalWinRate}%" puts "sp700點勝率#{sp700TotalWinRate}%" puts "sp800點勝率#{sp800TotalWinRate}%" puts "sp900點勝率#{sp900TotalWinRate}%" puts "sp1000點勝率#{sp1000TotalWinRate}%" puts "sp1100點勝率#{sp1100TotalWinRate}%" puts "sp1200點勝率#{sp1200TotalWinRate}%" puts "sp1300點勝率#{sp1300TotalWinRate}%" puts "sp1400點勝率#{sp1400TotalWinRate}%" puts "sp1500點勝率#{sp1500TotalWinRate}%" puts "sp1600點勝率#{sp1600TotalWinRate}%" puts "sp1700點勝率#{sp1700TotalWinRate}%" puts "-> #{midValue*100}%勝率中位數#{gapDownTotalMid} <-" puts "==================================最大波動==================================" puts "#{highestGapMaxs1[0]}發生中間最大漲幅`#{highestGapMaxs1[1].to_i}`,週期#{date_usingday[highestGapMaxs1[0]]}天" puts "#{highestGapMaxs2[0]}發生中間第二大漲幅`#{highestGapMaxs2[1].to_i}`,週期#{date_usingday[highestGapMaxs2[0]]}天" puts "#{highestGapMaxs3[0]}發生中間第三大漲幅`#{highestGapMaxs3[1].to_i}`,週期#{date_usingday[highestGapMaxs3[0]]}天" puts "============================================================================" puts "#{lowestGapMaxs1[0]}發生中間最大跌幅`#{lowestGapMaxs1[1].to_i}`,週期#{date_usingday[lowestGapMaxs1[0]]}天" puts "#{lowestGapMaxs2[0]}發生中間最大跌幅`#{lowestGapMaxs2[1].to_i}`,週期#{date_usingday[lowestGapMaxs2[0]]}天" puts "#{lowestGapMaxs3[0]}發生中間最大跌幅`#{lowestGapMaxs3[1].to_i}`,週期#{date_usingday[lowestGapMaxs3[0]]}天" puts "==================================中間波動==================================" puts "正波動500點機率#{highestGapUp5Odd}%" puts "正波動400點機率#{highestGapUp4Odd}%" puts "正波動300點機率#{highestGapUp3Odd}%" puts "正波動200點機率#{highestGapUp2Odd}%" puts "正波動100點機率#{highestGapUp1Odd}%" puts "正波動機率#{highestGapUp0Odd}%" puts "============================================================================" puts "負波動機率#{lowestGapDown0Odd}%" puts "負波動100點機率#{lowestGapDown1Odd}%" puts "負波動200點機率#{lowestGapDown2Odd}%" puts "負波動300點機率#{lowestGapDown3Odd}%" puts "負波動400點機率#{lowestGapDown4Odd}%" puts "負波動500點機率#{lowestGapDown5Odd}%" puts "負波動600點機率#{lowestGapDown6Odd}%" puts "負波動700點機率#{lowestGapDown7Odd}%" puts "負波動800點機率#{lowestGapDown8Odd}%" puts "負波動900點機率#{lowestGapDown9Odd}%" puts "負波動1000點機率#{lowestGapDown10Odd}%" puts "負波動1100點機率#{lowestGapDown11Odd}%" puts "負波動1200點機率#{lowestGapDown12Odd}%" puts "負波動1300點機率#{lowestGapDown13Odd}%" puts "負波動1400點機率#{lowestGapDown14Odd}%" puts "負波動1500點機率#{lowestGapDown15Odd}%" puts "負波動1600點機率#{lowestGapDown16Odd}%" puts "負波動1700點機率#{lowestGapDown17Odd}%"<file_sep>require 'csv' wednesdays_with_end_prices = Hash.new() otherdays_with_high_prices = Hash.new() otherdays_with_low_prices = Hash.new() week_with_high_low_wave = Hash.new() period_month = (Date.new(2008,01)..Date.new(2020,02)).select {|d| d.day == 1} period_month_csv = period_month.map do |ele| "./data/" + ele.strftime("%Y%m") + ".csv" end period_month_csv.each do |file| if File.file?(file) CSV.foreach(file) do |row| row0 = row[0].strip begin date = Date.strptime(row0,"%Y/%m/%d").next_year(1911) cwday = date.cwday end_price = row[4].delete(',').to_f high_prices = row[2].delete(',').to_f low_prices = row[3].delete(',').to_f if cwday == 3 wednesdays_with_end_prices[date] = end_price end otherdays_with_high_prices[date] = high_prices otherdays_with_low_prices[date] = low_prices rescue Exception => e # puts e end end end end wednesdays = wednesdays_with_end_prices.keys wednesdays.each_with_index do |date,index| if date.next_day.next_day.next_day.next_day.next_day.next_day.next_day == wednesdays[index + 1] start_prices = wednesdays_with_end_prices[date] end_prices = wednesdays_with_end_prices[wednesdays[index + 1]] high_prices = {} low_prices = {} high_prices[date] = start_prices high_prices[date.next_day] = otherdays_with_high_prices[date.next_day] high_prices[date.next_day.next_day] = otherdays_with_high_prices[date.next_day.next_day] high_prices[date.next_day.next_day.next_day.next_day.next_day] = otherdays_with_high_prices[date.next_day.next_day.next_day.next_day.next_day] high_prices[date.next_day.next_day.next_day.next_day.next_day.next_day] = otherdays_with_high_prices[date.next_day.next_day.next_day.next_day.next_day.next_day] high_prices[date.next_day.next_day.next_day.next_day.next_day.next_day.next_day] = otherdays_with_high_prices[date.next_day.next_day.next_day.next_day.next_day.next_day.next_day] low_prices[date] = start_prices low_prices[date.next_day] = otherdays_with_low_prices[date.next_day] low_prices[date.next_day.next_day] = otherdays_with_low_prices[date.next_day.next_day] low_prices[date.next_day.next_day.next_day.next_day.next_day] = otherdays_with_low_prices[date.next_day.next_day.next_day.next_day.next_day] low_prices[date.next_day.next_day.next_day.next_day.next_day.next_day] = otherdays_with_low_prices[date.next_day.next_day.next_day.next_day.next_day.next_day] low_prices[date.next_day.next_day.next_day.next_day.next_day.next_day.next_day] = otherdays_with_low_prices[date.next_day.next_day.next_day.next_day.next_day.next_day.next_day] high_prices_max = high_prices.values.compact.max high_prices_day = high_prices.key(high_prices_max) high_wave = high_prices_max - start_prices low_prices_min = low_prices.values.compact.min low_prices_day = low_prices.key(low_prices_min) low_wave = low_prices_min - start_prices high_prices_cwday = 0 low_prices_cwday = 0 if high_prices_day == date high_prices_cwday = 0 low_prices_cwday = 0 else high_prices_cwday = high_prices_day.cwday low_prices_cwday = low_prices_day.cwday end week_with_high_low_wave[date] = { wave: (end_prices - start_prices).round(2), high_prices_cwday: high_prices_cwday, low_prices_cwday: low_prices_cwday, high_wave: high_wave, low_wave: low_wave } else #puts date end end waves = [] got_high_prices_waves = [] got_low_prices_waves = [] high_prices_open = 0 high_prices_monday = 0 high_prices_tuesday = 0 high_prices_wednesday = 0 high_prices_thursday = 0 high_prices_friday = 0 low_prices_open = 0 low_prices_monday = 0 low_prices_tuesday = 0 low_prices_wednesday = 0 low_prices_thursday = 0 low_prices_friday = 0 week_with_high_low_wave.each do |k,v| waves << v[:wave] high_prices_cwday = v[:high_prices_cwday] low_prices_cwday = v[:low_prices_cwday] case high_prices_cwday when 0 high_prices_open += 1 when 1 high_prices_monday += 1 when 2 high_prices_tuesday += 1 when 3 high_prices_wednesday += 1 when 4 high_prices_thursday += 1 when 5 high_prices_friday += 1 end case low_prices_cwday when 0 low_prices_open += 1 when 1 low_prices_monday += 1 when 2 low_prices_tuesday += 1 when 3 low_prices_wednesday += 1 when 4 low_prices_thursday += 1 when 5 low_prices_friday += 1 end end wave_level = 570 wave_level_2 = 100 rise_buy_win = 0 rise_sell_win = 0 decline_buy_win = 0 decline_sell_win = 0 buy_win = 0 sell_win = 0 got_high_prices_rise_buy_win = 0 got_high_prices_rise_sell_win = 0 got_low_prices_decline_buy_win = 0 got_low_prices_decline_sell_win = 0 week_with_high_low_wave.each do |k,v| if v[:high_wave] >= wave_level_2 got_high_prices_waves << v[:wave] end end week_with_high_low_wave.each do |k,v| if v[:low_wave] <= -wave_level_2 got_low_prices_waves << v[:wave] end end waves.each do |wave| if wave >= wave_level rise_buy_win += 1 else rise_sell_win += 1 end end waves.each do |wave| if wave <= -wave_level decline_buy_win += 1 else decline_sell_win += 1 end end waves.each do |wave| if wave.abs <= wave_level sell_win += 1 else buy_win += 1 end end got_high_prices_waves.each do |wave| if wave >= wave_level got_high_prices_rise_buy_win += 1 else got_high_prices_rise_sell_win += 1 end end got_low_prices_waves.each do |wave| if wave <= -wave_level got_low_prices_decline_buy_win += 1 else got_low_prices_decline_sell_win += 1 end end rise_sell_win_rate = (rise_sell_win.to_f/(rise_sell_win.to_f+rise_buy_win.to_f)).round(2) decline_sell_win_rate = (decline_sell_win.to_f/(decline_sell_win.to_f+decline_buy_win.to_f)).round(2) sell_win_rate = (sell_win.to_f/(sell_win.to_f+buy_win.to_f)).round(2) got_high_prices_rise_sell_win_rate = (got_high_prices_rise_sell_win.to_f/(got_high_prices_rise_sell_win.to_f+got_high_prices_rise_buy_win.to_f)).round(2) got_low_prices_decline_sell_win_rate = (got_low_prices_decline_sell_win.to_f/(got_low_prices_decline_sell_win.to_f+got_low_prices_decline_buy_win.to_f)).round(2) high_prices_open_rate = (high_prices_open.to_f/(high_prices_open.to_f + high_prices_monday.to_f + high_prices_tuesday.to_f + high_prices_wednesday.to_f + high_prices_thursday.to_f + high_prices_friday.to_f)).round(2) high_prices_monday_rate = (high_prices_monday.to_f/(high_prices_open.to_f + high_prices_monday.to_f + high_prices_tuesday.to_f + high_prices_wednesday.to_f + high_prices_thursday.to_f + high_prices_friday.to_f)).round(2) high_prices_tuesday_rate = (high_prices_tuesday.to_f/(high_prices_open.to_f + high_prices_monday.to_f + high_prices_tuesday.to_f + high_prices_wednesday.to_f + high_prices_thursday.to_f + high_prices_friday.to_f)).round(2) high_prices_wednesday_rate = (high_prices_wednesday.to_f/(high_prices_open.to_f + high_prices_monday.to_f + high_prices_tuesday.to_f + high_prices_wednesday.to_f + high_prices_thursday.to_f + high_prices_friday.to_f)).round(2) high_prices_thursday_rate = (high_prices_thursday.to_f/(high_prices_open.to_f + high_prices_monday.to_f + high_prices_tuesday.to_f + high_prices_wednesday.to_f + high_prices_thursday.to_f + high_prices_friday.to_f)).round(2) high_prices_friday_rate = (high_prices_friday.to_f/(high_prices_open.to_f + high_prices_monday.to_f + high_prices_tuesday.to_f + high_prices_wednesday.to_f + high_prices_thursday.to_f + high_prices_friday.to_f)).round(2) low_prices_open_rate = (low_prices_open.to_f/(low_prices_open.to_f + low_prices_monday.to_f + low_prices_tuesday.to_f + low_prices_wednesday.to_f + low_prices_thursday.to_f + low_prices_friday.to_f)).round(2) low_prices_monday_rate = (low_prices_monday.to_f/(low_prices_open.to_f + low_prices_monday.to_f + low_prices_tuesday.to_f + low_prices_wednesday.to_f + low_prices_thursday.to_f + low_prices_friday.to_f)).round(2) low_prices_tuesday_rate = (low_prices_tuesday.to_f/(low_prices_open.to_f + low_prices_monday.to_f + low_prices_tuesday.to_f + low_prices_wednesday.to_f + low_prices_thursday.to_f + low_prices_friday.to_f)).round(2) low_prices_wednesday_rate = (low_prices_wednesday.to_f/(low_prices_open.to_f + low_prices_monday.to_f + low_prices_tuesday.to_f + low_prices_wednesday.to_f + low_prices_thursday.to_f + low_prices_friday.to_f)).round(2) low_prices_thursday_rate = (low_prices_thursday.to_f/(low_prices_open.to_f + low_prices_monday.to_f + low_prices_tuesday.to_f + low_prices_wednesday.to_f + low_prices_thursday.to_f + low_prices_friday.to_f)).round(2) low_prices_friday_rate = (low_prices_friday.to_f/(low_prices_open.to_f + low_prices_monday.to_f + low_prices_tuesday.to_f + low_prices_wednesday.to_f + low_prices_thursday.to_f + low_prices_friday.to_f)).round(2) puts "==============================" puts "漲不超過#{wave_level}點機率 : #{rise_sell_win_rate}" puts "跌不超過#{wave_level}點機率 : #{decline_sell_win_rate}" #puts "漲跌不超過#{wave_level}點擊率 : #{sell_win_rate}" puts "==============================" puts "當發生最高點#{wave_level_2},最後漲不超過#{wave_level}點機率 : #{got_high_prices_rise_sell_win_rate}" puts "當發生最低點#{wave_level_2},最後跌不超過#{wave_level}點機率 : #{got_low_prices_decline_sell_win_rate}" puts "==============================" puts "最高點發生在開盤天機率 : #{high_prices_open_rate}" puts "最高點發生在禮拜四機率 : #{high_prices_thursday_rate}" puts "最高點發生在禮拜五機率 : #{high_prices_friday_rate}" puts "最高點發生在禮拜一機率 : #{high_prices_monday_rate}" puts "最高點發生在禮拜二機率 : #{high_prices_tuesday_rate}" puts "最高點發生在結算機率 : #{high_prices_wednesday_rate}" puts "==============================" puts "最低點發生在開盤天機率 : #{low_prices_open_rate}" puts "最低點發生在禮拜四機率 : #{low_prices_thursday_rate}" puts "最低點發生在禮拜五機率 : #{low_prices_friday_rate}" puts "最低點發生在禮拜一機率 : #{low_prices_monday_rate}" puts "最低點發生在禮拜二機率 : #{low_prices_tuesday_rate}" puts "最低點發生在結算機率 : #{low_prices_wednesday_rate}"
a578d002b7b011010abab12558f45071d3f2b0b5
[ "Ruby" ]
3
Ruby
tsaohucn/option
ad44add5abd5f95fa1325838453a57ba31f51f66
c63dd6fe27666baac5fa51ec76038903e05be204
refs/heads/master
<file_sep>require 'test_helper' class RegistroMaestrosControllerTest < ActionDispatch::IntegrationTest setup do @registro_maestro = registro_maestros(:one) end test "should get index" do get registro_maestros_url assert_response :success end test "should get new" do get new_registro_maestro_url assert_response :success end test "should create registro_maestro" do assert_difference('RegistroMaestro.count') do post registro_maestros_url, params: { registro_maestro: { area: @registro_maestro.area, cuenta: @registro_maestro.cuenta, nombre: @registro_maestro.nombre } } end assert_redirected_to registro_maestro_url(RegistroMaestro.last) end test "should show registro_maestro" do get registro_maestro_url(@registro_maestro) assert_response :success end test "should get edit" do get edit_registro_maestro_url(@registro_maestro) assert_response :success end test "should update registro_maestro" do patch registro_maestro_url(@registro_maestro), params: { registro_maestro: { area: @registro_maestro.area, cuenta: @registro_maestro.cuenta, nombre: @registro_maestro.nombre } } assert_redirected_to registro_maestro_url(@registro_maestro) end test "should destroy registro_maestro" do assert_difference('RegistroMaestro.count', -1) do delete registro_maestro_url(@registro_maestro) end assert_redirected_to registro_maestros_url end end <file_sep>class RegistroMaestro < ApplicationRecord end <file_sep>json.partial! "registro_maestros/registro_maestro", registro_maestro: @registro_maestro <file_sep>json.extract! registro_maestro, :id, :nombre, :cuenta, :area, :created_at, :updated_at json.url registro_maestro_url(registro_maestro, format: :json) <file_sep>json.array! @registro_maestros, partial: 'registro_maestros/registro_maestro', as: :registro_maestro <file_sep>class RegistroMaestrosController < ApplicationController before_action :set_registro_maestro, only: [:show, :edit, :update, :destroy] # GET /registro_maestros # GET /registro_maestros.json def index @registro_maestros = RegistroMaestro.all end # GET /registro_maestros/1 # GET /registro_maestros/1.json def show end # GET /registro_maestros/new def new @registro_maestro = RegistroMaestro.new end # GET /registro_maestros/1/edit def edit end # POST /registro_maestros # POST /registro_maestros.json def create @registro_maestro = RegistroMaestro.new(registro_maestro_params) respond_to do |format| if @registro_maestro.save format.html { redirect_to @registro_maestro, notice: 'Registro maestro was successfully created.' } format.json { render :show, status: :created, location: @registro_maestro } else format.html { render :new } format.json { render json: @registro_maestro.errors, status: :unprocessable_entity } end end end # PATCH/PUT /registro_maestros/1 # PATCH/PUT /registro_maestros/1.json def update respond_to do |format| if @registro_maestro.update(registro_maestro_params) format.html { redirect_to @registro_maestro, notice: 'Registro maestro was successfully updated.' } format.json { render :show, status: :ok, location: @registro_maestro } else format.html { render :edit } format.json { render json: @registro_maestro.errors, status: :unprocessable_entity } end end end # DELETE /registro_maestros/1 # DELETE /registro_maestros/1.json def destroy @registro_maestro.destroy respond_to do |format| format.html { redirect_to registro_maestros_url, notice: 'Registro maestro was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_registro_maestro @registro_maestro = RegistroMaestro.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def registro_maestro_params params.require(:registro_maestro).permit(:nombre, :cuenta, :area) end end <file_sep>require "application_system_test_case" class RegistroMaestrosTest < ApplicationSystemTestCase # test "visiting the index" do # visit registro_maestros_url # # assert_selector "h1", text: "RegistroMaestro" # end end
dd6ca625cf473a6c8fcac1f729e43f05b4be1f49
[ "Ruby" ]
7
Ruby
GermanHN/Tarea2_Ing_Software
55c6b2bed07323c73a8ed7a434bbbe2a62df6ec9
7854ee82ee6f6e25db0860032ffeda8c974c065d
refs/heads/main
<repo_name>nomadkode/sekilas13-ssr<file_sep>/components/Navigasi/memoized/NavLink.js import { useRouter } from "next/router"; import { memo, useMemo, useState } from "react"; import Nav from "react-bootstrap/Nav"; import Link from "next/link"; const List = { "/": [ { nama: "Deskripsi", to: ".deskripsi" }, { nama: "Pandangan Orang", to: ".KataOrang" }, { nama: "Gambar", to: ".gambar" } ], "/covid": [ { nama: "Kondisi Terkini", to: "#all" }, { nama: "Data Provinsi", to: "#provinsi" } ] }; function NavLink({ getHeight, expanded, setExpandClose }) { const { pathname } = useRouter(); const [key, setActiveKey] = useState(); const renderer = useMemo(() => List[pathname], [pathname]); const to = useMemo(() => (pathname === "/" ? "/covid" : "/"), [pathname]); return ( <Nav className="ml-auto text-center" activeKey={key}> {renderer && ( <> <Link href={to} passHref> <Nav.Link> {pathname === "/" ? "Informasi Covid 19" : "Halaman Utama"} </Nav.Link> </Link> <Link href="/blog" passHref> <Nav.Link>Blog</Nav.Link> </Link> {renderer.map((link, i) => { const [href] = useState( pathname === "/" ? link.to.replace(".", "") : link.to.replace("#", "") ); const handleLink = (e) => { e.preventDefault(); setExpandClose(); const height = getHeight(); const selector = "section" + link.to; if (height) { const el = document.querySelector(selector); if (expanded) { setTimeout(() => { const tujuan = el.offsetTop - height; window.scrollTo(0, tujuan); }, 150); } else { const tujuan = el.offsetTop - height; window.scrollTo(0, tujuan); } } setActiveKey(); }; return ( <Nav.Link href={href} key={i} onClick={handleLink}> {link.nama} </Nav.Link> ); })} </> )} </Nav> ); } export default memo(NavLink); <file_sep>/posts/mxlinux-telegram.md --- Judul: Instalasi Telegram Desktop di MX Linux 19.3 Deskripsi: Tutorial bagaimana cara menginstall Telegram di MX Linux 19.3 Patito Feo dengan benar. Penulis: <NAME> TanggalDibuat: 5-1-2021 21:55 TanggalDiubah: 7-1-2021 10:43 --- # Apa itu Telegram [Telegram](https://telegram.org/) adalah aplikasi berkirim pesan yang cukup cepat dan juga aman. Aplikasi ini bisa mengirim pesan, foto, video dan file dengan tipe apapun hingga 1,5 Gigabyte. Aplikasi ini bersifat multiplatform, bisa digunakan di perangkat selular ([Android](<https://id.wikipedia.org/wiki/Android_(operating_system)>), [IOS](https://id.wikipedia.org/wiki/IOS)) dan juga perangkat komputer ([Windows](https://id.wikipedia.org/wiki/Microsoft_Windows), [OS X](https://id.wikipedia.org/wiki/OS_X), [Linux](https://id.wikipedia.org/wiki/Linux)). Aplikasi ini berbasis awan, artinya kamu bisa mengakses telegram dari perangkat manapun tanpa harus perangkat utama yang mendaftarkan terhubung ke internet. ## Instalasi di MX Linux 1. ### Unduh File Tar Telegram Buka [https://desktop.telegram.org/](https://desktop.telegram.org/) dan dapatkan File `.tar.xz` yang nanti digunakan. 2. ### Buka Terminal Buka terminal dengan kombinasi tombol `Ctrl+Alt+T` atau `Cmd+Alt+T` untuk pengguna Mac. 3. ### Ekstrak File Ekstrak file yang tadi sudah didownload, arahkan ke folder file berada dan lakukan ```sh tar xvf tsetup*.tar.xz -C /tmp/ ``` 4. ### Set Folder Telegram Sebagai SuperUser (sudo) Telegram yang sudah tadi diekstrak akan berada di folder `/tmp/Telegram`. Supaya bisa diinstall ke sistem, ubah usernya menjadi sudo. ```sh sudo chown -R root:root /tmp/Telegram ``` 5. ### Pindahkan ke Folder `/opt` Tujuan file dipindah ke folder `opt` supaya file asli dari Telegram tidak mudah diubah-ubah dan tidak mengganggu symbolic link ke file instance telegram. Jalankan perintah ini. ```sh sudo mv /tmp/Telegram /opt/ ``` 6. ### Tambahkan Telegram ke System Path Supaya bisa diakses, tambahkan symbolic link ke `/usr/local/bin`. Jalankan perintah ini. ```sh sudo ln -s /opt/Telegram/Telegram /usr/local/bin/Telegram ``` ## Sumber Tulisan - [https://tutorialforlinux.com/2019/07/29/how-to-install-telegram-on-mx-linux-easy-guide/](https://tutorialforlinux.com/2019/07/29/how-to-install-telegram-on-mx-linux-easy-guide/) - [https://id.wikipedia.org/wiki/Telegram\_(aplikasi)](<https://id.wikipedia.org/wiki/Telegram_(aplikasi)>) ## Pranala Menarik - [https://www.centerklik.com/apa-aplikasi-telegram-cara-menggunakan-telegram/](https://www.centerklik.com/apa-aplikasi-telegram-cara-menggunakan-telegram/) - [https://www.brilio.net/gadget/10-keunggulan-telegram-dibandingkan-whatsapp-yang-jarang-orang-tahu-1605055.html](https://www.brilio.net/gadget/10-keunggulan-telegram-dibandingkan-whatsapp-yang-jarang-orang-tahu-1605055.html) - [https://kirim.email/aplikasi-telegram-dan-5-kelebihannya/](https://kirim.email/aplikasi-telegram-dan-5-kelebihannya/) <file_sep>/components/main/lazy/Gambar.js import { Row, Container, Col } from "react-bootstrap"; import gambar from "../../../assets/data/Gambar"; import dynamic from "next/dynamic"; import Wrapper from "./WrapperImg"; const DynamicSRL = dynamic(() => import("simple-react-lightbox"), { loading: ({ children: Child }) => <Child /> }); const DynamicSRLWrapper = dynamic( () => import("simple-react-lightbox").then((module) => module.SRLWrapper), { loading: ({ children: Child }) => <Child /> } ); export default function Gambar() { return ( <DynamicSRL> <DynamicSRLWrapper> <Container className="pt-4"> <Row> {gambar.map((g, i) => ( <Col md={4} key={i}> <Wrapper src={g.src} alt={g.alt} placeholder={g.placeholder} /> </Col> ))} </Row> </Container> </DynamicSRLWrapper> </DynamicSRL> ); } <file_sep>/components/main/lazy/KataOrang.js import { useState } from "react"; import data from "../../../assets/data/KataOrang"; import Carousel from "react-bootstrap/Carousel"; export default function KataOrang({ ukuran, theme }) { const [index, setIndex] = useState(3); const handleSelect = (selectedIndex) => void setIndex(selectedIndex); return ( <Carousel activeIndex={index} onSelect={handleSelect}> {data.map((key, i) => ( <Carousel.Item key={i}> <img className="d-block w-100" src={`${process.env.PUBLIC_URL}/api/image/${ukuran.width}/${ ukuran.height }/${theme ? "373940" : "f1faee"}`} alt={key.alt} width={ukuran.width} height={ukuran.height} /> <Carousel.Caption> <h3 style={{ color: theme ? "fff" : "000" }}>{key.capt[0]}</h3> <p style={{ color: theme ? "fff" : "000" }}>{key.capt[1]}</p> </Carousel.Caption> </Carousel.Item> ))} </Carousel> ); } <file_sep>/assets/data/KataOrang.js const Pandangan = [ { alt: "Gambar background Edwin 1", capt: [ "Edwin", '"Bagus, karna mereka slalu membuat penemuan yang mengejutkan"' ] }, { alt: "Gambar background Miko 2", capt: [ "<NAME>", '"Eskulnya santai sih, bercanda juga iya. Bukannya ga serius tapi biar nyaman aja"' ] }, { alt: "Gambar background Kenzie 3", capt: ["<NAME>", '"Ya seru lah dapet banyak pengalaman"'] }, { alt: "Gambar background Djilan 4", capt: [ "Djilan", '"Eskulnya santai sih,selama di KIR ga terlalu ketat banget buat nugas, tapi bebas eksperimen"' ] }, { alt: "Gambar background Muflih 5", capt: [ "<NAME>", '"Eskulnya fleksibel, bisa maen biasa aja, ga terlalu banyak duit keluar"' ] }, { alt: "Gambar background Fathur 6", capt: [ "<NAME>", '"KIR sih sama aja kayak eskul kebanyakan, bedanya disini eksperimennya unik sama seru"' ] }, { alt: "Gambar background Michelle 7", capt: [ "<NAME>", '"Ekskul KIR itu ekskul yg berbeda,karena disini fleksibel,gak terikat sama waktu, eksperimen nya asik dan kita tidak dipaksa berhasil dalam mencoba eksperimen nya"' ] } ]; export default Pandangan; <file_sep>/components/Navigasi/memoized/Switcher.js import { memo, useContext } from "react"; import Check from "react-bootstrap/FormCheck"; import { DarkModeContext } from "../../../context/darkMode"; function Switcher() { const { isDark, themeToggler } = useContext(DarkModeContext); return ( <Check type="switch" id="custom-switch" checked={isDark} onChange={themeToggler} label="&zwnj;" /> ); } export default memo(Switcher); <file_sep>/components/covid/Card.js import { konversiBulan, updateTime } from "../../utils/konversiWaktu"; import CardWrapper from "./Custom/CardWrapper"; import { faVirus, faHospital, faHandHoldingMedical, faSkullCrossbones } from "@fortawesome/free-solid-svg-icons"; import { Row, Col } from "react-bootstrap"; import { useCallback } from "react"; import useSWR from "swr"; const TampilWaktu = ({ data, error }) => { if (!error) { if (data) { const time = new Date(data.lastUpdate); return ( <> {time.getDate()} {konversiBulan(time.getMonth())} {time.getFullYear()}{" "} Pukul {updateTime(time.getHours())}:{updateTime(time.getMinutes())}: {updateTime(time.getSeconds())}. </> ); } else { return <></>; } } else { return <></>; } }; export default function Card() { const { data, error } = useSWR( "https://apicovid19indonesia-v2.vercel.app/api/indonesia" ); const labelGenerator = useCallback((label, index) => { if (error) { return label; } else { if (!data) return label; return data[index].toLocaleString(); } }); return ( <section id="all"> <Row className="mt-4 justify-content-center"> <Col lg={3} sm={5}> <CardWrapper data={labelGenerator("=,===,===", "positif")} label="Positif" icon={faVirus} /> </Col> <Col lg={3} sm={5}> <CardWrapper data={labelGenerator("===,===", "dirawat")} label="Dirawat" icon={faHospital} /> </Col> <Col lg={3} sm={5}> <CardWrapper data={labelGenerator("===,===", "sembuh")} label="Sembuh" icon={faHandHoldingMedical} /> </Col> <Col lg={3} sm={5}> <CardWrapper data={labelGenerator("==,===", "meninggal")} label="Meninggal" icon={faSkullCrossbones} /> </Col> </Row> <Row className="mt-2"> <Col> <p> {!error && data && data.lastUpdate && "Terakhir data diperbarui tanggal" + " "} {error && "Mohon maaf, data tidak dapat ditampilkan. " + "Error: " + error.message} <TampilWaktu data={data} error={error} /> </p> </Col> </Row> </section> ); } <file_sep>/components/covid/Custom/CardWrapper.js import { Card, Row, Col } from "react-bootstrap"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import styles from "../../../styles/covid/Card.module.css"; export default function CardWrapper({ label, data, icon }) { return ( <Card className={styles.card}> <Card.Body> <Row className="justify-content-center h-100 d-flex"> <Col md={4} className="text-center align-self-center"> <FontAwesomeIcon icon={icon} size="6x" className={styles.svg} /> </Col> <Col md={8} className="text-center align-self-center"> <h4>{label}</h4> <h3>{data} Orang</h3> </Col> </Row> </Card.Body> </Card> ); } <file_sep>/next.config.js const withPWA = require("next-pwa"); const withPlugins = require("next-compose-plugins"); const optimizedImages = require("next-optimized-images"); const whitelist = require("./config/whitelist.config"); const NODE_ENV = process.env.NODE_ENV; const dualENV = { production: { PUBLIC_URL: process.env.DEPLOYMENT_BASE_URL }, development: { PUBLIC_URL: "http://localhost:3000" } }; const env = { ...dualENV[NODE_ENV], isProduction: NODE_ENV === "production" }; module.exports = withPlugins( [ [ optimizedImages, { inlineImageLimit: 8192, imagesFolder: "images", imagesName: "[name]-[hash].[ext]", handleImages: ["jpeg", "png", "webp"], removeOriginalExtension: false, optimizeImages: true, optimizeImagesInDev: false, mozjpeg: { quality: 80 }, optipng: { optimizationLevel: 3 }, pngquant: false, webp: { preset: "default", quality: 75 }, responsive: { adapter: require("responsive-loader/sharp") } } ], [ withPWA, { pwa: { disable: process.env.NODE_ENV === "development", register: true, scope: "/", sw: "service-worker.js", dest: "public" } } ] ], { webpack: (config, { isServer }) => { if (isServer) { require("./scripts/sitemap-robots-generator")(env.PUBLIC_URL); require("./scripts/noflash.minimizer")(); } config.module.rules.push({ test: /\.md$/, use: "raw-loader" }); return config; }, env } ); <file_sep>/components/Navigasi/memoized/FormSwitcher.js import { memo } from "react"; import dynamic from "next/dynamic"; import Form from "react-bootstrap/Form"; import styles from "../../../styles/navigasi/Switcher.module.css"; const Sun = dynamic(() => import("./Sun")); const Moona = dynamic(() => import("./Moona")); const Switcher = dynamic(() => import("./Switcher")); function FormSwitcher() { return ( <Form id={styles.switcher}> <Form.Row className="justify-content-center"> <small className={styles.sun}> <Sun /> </small> <Switcher /> <small className={styles.moona}> <Moona /> </small> </Form.Row> </Form> ); } export default memo(FormSwitcher); <file_sep>/posts/README.markdown # Panduan Kontribusi Tulisan ## Aturan Anda bebas berkontribusi untuk blog web ini, tetapi dengan catatan : 1. **Dilarang keras** menyebarkan informasi hoax, SARA, konten NSFW, atau apapun yang tidak pantas berada di ruang publik. 2. Informasi yang diberikan bisa dipertanggung-jawabkan kebenarannya. Jika tidak postingan bisa dihapus. 3. Jika tulisan anda juga bersumber dari tulisan orang lain, Cantumkan link ke tulisan yang bersangkutan di akhir tulisan anda. ## Penulisan ### Metadata Tulisan Metadata adalah informasi tulisan yang wajib anda cantumkan. Format metadata seperti berikut : ``` --- Judul: <Judul> Deskripsi: <Deskripsi singkat tulisan> Penulis: <Nama anda> TanggalDibuat: <Tanggal>-<Bulan>-<Tahun> <Jam>:<Menit> TanggalDiubah: <Tanggal>-<Bulan>-<Tahun> <Jam>:<Menit> --- ``` Format penanggalan : ``` TanggalDibuat: DD-MM-YYYY HH:MM TanggalDiubah: DD-MM-YYYY HH:MM ``` Keterangan: - `DD` Date (tanggal) - `MM` Month (Bulan) - `YYYY` Year (Tahun) - `HH` Hour (Jam) - `MM` Minute (Menit) Sebagai contoh seperti ini : ``` --- Judul: Postingan Kedua Deskripsi: Postingan kedua dimana ini cuman contoh Penulis: <NAME> TanggalBuat: 2-1-2021 14:42 TanggalDiubah: 7-1-2021 10:43 --- ``` Properti `TanggalDiubah` ditambahkan jika ada perubahan pada konten, jika tulisan tersebut tulisan baru, tidak usah menambahkan `TanggalDiubah`. Judul dan deskripsi nantinya akan digunakan di website, Jadi usahakan Judul singkat tetapi langsung ke Topik dari tulisan tersebut. > Waktu yang digunakan adalah [Waktu Indonesia Barat UTC+07:00](https://id.wikipedia.org/wiki/UTC%2B07:00) ### Ektensi dan Penamaan File File yang digunakan dalam penulisan blog adalah [Markdown](https://id.wikipedia.org/wiki/Markdown) dengan ekstensi `.md` di akhir file. Berikan nama file yang relevan dengan judul metadata file dengan pengganti spasi yaitu `-` dengan contoh : ``` reactjs-hook.md ``` Tambahkan file `.md` ke folder saat ini. Jangan menggunakan spasi dalam penamaan file, tulisan anda tidak bisa dibaca oleh sistem. ### Draft Jika belum yakin dengan tulisan anda, bisa dibuat sebagai draft. Tambahkan prefix `DRAFT-` supaya bisa di-ignore oleh git. ## Preview Jika anda mengerti cara menjalankan aplikasi [Node.JS](https://nodejs.org/), lakukan instalasi seperti biasa dan jalankan `npm run dev`. Buka website di http://localhost:3000/blog/ dan anda bisa langsung melihat hasilnya di web. <file_sep>/components/main/lazy/FooterInfo.js import { InView } from "react-intersection-observer"; import { Transition } from "react-spring/renderprops"; const From = { transform: "translate3d(20px,0,0)", opacity: 0 }; const Enter = { transform: "translate3d(0px,0,0)", opacity: 1 }; const Leave = { opacity: 0 }; export default function FooterInfo() { return ( <InView> {({ inView, ref }) => ( <div ref={ref}> <Transition items={inView} from={From} enter={Enter} leave={Leave} config={{ duration: 750 }} > {(show) => show && ((props) => ( <p style={props}> Dibuat oleh{" "} <a href="https://github.com/sekilas13" target="_blank" rel="noopener noreferrer" > <NAME> </a>{" "} SMP Negeri 13 Bekasi | {new Date().getFullYear()} </p> )) } </Transition> </div> )} </InView> ); } <file_sep>/components/main/Gambar.js import styles from "../../styles/main/Gambar.module.css"; import dynamic from "next/dynamic"; const Content = dynamic(() => import("./lazy/Gambar")); export default function Gambar() { return ( <section className="gambar" id={styles.gambar}> <Content /> </section> ); } <file_sep>/utils/konversiWaktu.js export const konversiBulan = (number) => { switch (number) { case 0: return "Januari"; case 1: return "Februari"; case 2: return "Maret"; case 3: return "April"; case 4: return "Mei"; case 5: return "Juni"; case 6: return "Juli"; case 7: return "Agustus"; case 8: return "September"; case 9: return "Oktober"; case 10: return "November"; case 11: return "Desember"; default: break; } }; export const updateTime = (t) => (t < 10 ? "0" + t : t); <file_sep>/components/covid/Tabel.js import { DarkModeContext } from "../../context/darkMode"; import { Table, Row, Col } from "react-bootstrap"; import { useState, useContext, useEffect } from "react"; import dynamic from "next/dynamic"; import useSWR from "swr"; const Tbody = dynamic(() => import("./lazy/Tbody"), { loading: ({ error, data }) => !error && !data && ( <> <tr> <td>1</td> <td colSpan={4} className="text-center"> Sedang mengambil data.... </td> </tr> <tr> <td>2</td> <td colSpan={4} className="text-center"> Mohon tunggu.... </td> </tr> </> ), ssr: false }); export default function Tabel() { const { data, error } = useSWR( "https://apicovid19indonesia-v2.vercel.app/api/indonesia/provinsi" ); const { isDark } = useContext(DarkModeContext); return ( <section id="provinsi"> <Row className="justify-content-center mt-4 mb-2"> <Col md={6}> <h1 className="text-center">Data Provinsi</h1> </Col> </Row> <Table striped bordered hover responsive variant={isDark ? "dark" : "light"} > <thead> <tr> <th>#</th> <th>Provinsi</th> <th>Positif</th> <th>Sembuh</th> <th>Meninggal</th> </tr> </thead> <tbody> <Tbody data={data} error={error} /> </tbody> </Table> </section> ); } <file_sep>/.env.example GA_TRACKING_ID= GOOGLE_VERIF= DEPLOYMENT_BASE_URL= <file_sep>/components/main/GlobalStyles.js import { createGlobalStyle } from "styled-components"; const GlobalStyles = createGlobalStyle` .jumbotron { background: ${({ theme }) => theme.jumbotron.bg} !important; color: ${({ theme }) => theme.jumbotron.color}; transition: all 0.20s linear; } .deskripsi { background: ${({ theme }) => theme.deskripsi.bg} !important; transition: all 0.50s linear; } .deskripsi h2 { color: ${({ theme }) => theme.deskripsi.h2}; transition: all 0.50s linear; } .deskripsi p { color: ${({ theme }) => theme.deskripsi.p}; transition: all 0.50s linear; } .KataOrang { background-color: ${({ theme }) => theme.kataOrang}; } .carousel-caption { color: ${({ theme }) => theme.carousel.color}; transition: all 0.50s linear; } .carousel-indicators li { background-color: ${({ theme }) => theme.carousel.indicator}; transition: all 0.50s linear; } .carousel-control-prev-icon { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23${({ theme }) => theme.carousel .arrow}' viewBox='0 0 8 8'%3E%3Cpath d='M5.25 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3E%3C/svg%3E") !important; transition: all 0.50s linear; } .carousel-control-next-icon { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23${({ theme }) => theme.carousel .arrow}' viewBox='0 0 8 8'%3E%3Cpath d='M2.75 0l-1.5 1.5 2.5 2.5-2.5 2.5 1.5 1.5 4-4-4-4z'/%3E%3C/svg%3E") !important; transition: all 0.50s linear; } .gambar { background: linear-gradient( to bottom, #${({ theme }) => theme.carousel.arrow !== "fff" ? "f1faee" : "373940"} 0%, #${({ theme }) => theme.carousel.arrow !== "fff" ? "f1faee" : "373940"} 13.5%, ${({ theme }) => theme.gambar.bg} 35%, ${({ theme }) => theme.gambar.bg} 100% ); transition: all 0.50s linear; } `; export default GlobalStyles; <file_sep>/pages/blog/[post].js import fs from "fs"; import dynamic from "next/dynamic"; import { BlogJsonLd, NextSeo } from "next-seo"; import { useContext, useMemo } from "react"; import ReactMarkdown from "react-markdown"; import moment from "moment-timezone"; import matter from "gray-matter"; import Head from "next/head"; import "github-markdown-css"; const Code = dynamic(() => import("../../components/blog/Code"), { ssr: false, loading: () => ( <pre style={{ background: "rgb(245, 242, 240)", minHeight: "1.25em", margin: "0.5em 0px", lineHeight: "1.5", padding: "1em", width: "100%" }} > <span>&zwnj;</span> </pre> ) }); const ISOString = (tanggal) => moment(tanggal, "DD-MMM-YYYY HH:mm").tz("Asia/Jakarta").toISOString(true); export default function Read({ content, data, url, tanggalDibuat, tanggalDiubah }) { const { Judul, Deskripsi, Penulis } = data; const fullUrl = useMemo(() => process.env.PUBLIC_URL + "/blog/" + url); return ( <> <Head> <meta name="author" content={Penulis} /> </Head> <NextSeo title={Judul} description={Deskripsi} canonical={fullUrl} openGraph={{ url: fullUrl, title: Judul, description: Deskripsi, type: "article", images: [ { url: `${process.env.PUBLIC_URL}/ogp-img.png`, width: 256, height: 256, alt: "KIR Open Graph" } ], site_name: "Sekilas 13" }} /> <BlogJsonLd url={fullUrl} title={Judul} description={Deskripsi} authorName={Penulis} datePublished={tanggalDibuat} dateModified={tanggalDiubah !== null ? tanggalDiubah : undefined} /> <article className="markdown-body"> <ReactMarkdown escapeHtml={true} source={content} renderers={{ code: Code }} /> </article> <style jsx scoped>{` .markdown-body { box-sizing: border-box; min-width: 200px; max-width: 980px; margin: 0 auto; padding: 45px; } @media (max-width: 767px) { .markdown-body { padding: 15px; } } `}</style> </> ); } export async function getStaticPaths() { const files = fs.readdirSync(`${process.cwd()}/posts`, "utf-8"); const paths = files .filter((fn) => fn.endsWith(".md")) .map((filename) => ({ params: { post: filename.replace(".md", "") } })); return { paths, fallback: false }; } export async function getStaticProps({ params: { post } }) { const path = `${process.cwd()}/posts/${post}.md`; const md = fs.readFileSync(path, { encoding: "utf-8" }); const parsed = matter(md); const tanggalDibuat = ISOString(parsed.data.TanggalDibuat); const tanggalDiubah = parsed.data.TanggalDiubah ? ISOString(parsed.data.TanggalDiubah) : null; return { props: { content: parsed.content, data: parsed.data, url: post, tanggalDibuat, tanggalDiubah } }; } <file_sep>/posts/palapa-desktop-app.md --- Judul: Instalasi Palapa versi Desktop Deskripsi: Penjelasan tentang cara bagaimana melakukan instalasi Palapa Chat App versi desktop, terkhusus untuk sistem operasi linux. Penulis: <NAME> TanggalDibuat: 12-1-2021 22:09 TanggalDiubah: 26-1-2021 08:56 --- # Palapa, apa itu ? [Palapa](https://landing.xecure.world/) adalah aplikasi perpesanan lokal buatan asli Indonesia yang dikembangkan oleh start up local [XecureIT](https://xecureit.com/). Aplikasi ini memiliki sederet fitur yang memiliki keamanan yang tinggi seperti Enkripsi Chat, Relay panggilan telepon, Keamanan Layar, Pin Anti pembajakan, dan lain-lain. Aplikasi ini sudah support diberbagai platform, dari di perangkat mobile maupun komputer. ## Instalasi Palapa Jika anda mengunjungi website resmi [palapa](https://landing.xecure.world/), anda akan mendapatkan tiga pilihan menu instalasi yaitu Android, iPhone, dan Desktop. Untuk mendapatkan file desktop, kunjungi [https://landing.xecure.world/palapa/](https://landing.xecure.world/palapa/). - Jika sistem operasi anda Windows, klik `windows`, dan klik file `exe` di browser - Jika sistem operasi anda Windows, klik `mac`, dan klik file `dmg` di browser Untuk sistem operasi Windows dan OS X (mac), instalasi tergolong cukup mudah. Tinggal klik-klik, selesai. ### Linux Untuk sistem operasi linux umum, proses ini agak berbeda dengan yang lain, karena ini sepertinya versi `linux-unpacked` dari aplikasi [ElectronJS](https://www.electronjs.org/) yang sudah di build (dilihat dari hasil extract download, ada sebuah file lisensi `LICENSE.electron.txt`, dimana electron sendiri dibuat oleh github). Ikuti langkah instalasi berikut ini. 1. #### Buka Terminal Buka terminal dengan kombinasi tombol `Ctrl+Alt+T` atau `Cmd+Alt+T` untuk pengguna Mac. 2. #### Unduh file .tar.gz Anda bisa mendownload file dengan klik file langsung di browser, tapi saya merekomendasikan dengan `wget`. Lakukan : ```sh wget https://landing.xecure.world/palapa/linux/palapa-desktop-release-2.1.2-756079983-24-Sep-2020-17-41.tar.gz ``` > Catatan: Cek kembali ke link unduhan, sewaktu-waktu nama file akan berubah. 3. #### Extract file .tar.gz Extract file .tar.gz ke folder `/tmp` untuk menyimpan sementara folder extract. Lakukan : ```sh tar -zxvf palapa-desktop-release-2.1.2-756079983-24-Sep-2020-17-41.tar.gz -C /tmp ``` 4. #### Ubah nama folder release menjadi Palapa File hasil extract akan memiliki output folder `release`, nama folder seharusnya diubah. Lakukan : ```sh mv /tmp/release /tmp/Palapa ``` 5. #### Set Folder Palapa Menjadi SuperUser (sudo) Palapa yang sudah tadi diekstrak akan berada di folder `/tmp/Palapa`. Supaya bisa diinstall ke sistem, ubah usernya menjadi sudo. Lakukan : ```sh sudo chown -R root:root /tmp/Palapa ``` 6. ### Pindahkan ke Folder `/opt` Tujuan file dipindah ke folder `opt` supaya folder asli dari Palapa tidak mudah diubah-ubah dan tidak mengganggu symbolic link ke file instance palapa. Lakukan : ```sh sudo mv /tmp/Palapa /opt/ ``` 7. ### Tambahkan Palapa ke System Path Supaya bisa diakses, tambahkan symbolic link ke `/usr/bin`. Jalankan perintah ini. ```sh sudo ln -s /opt/Palapa/linux-unpacked/palapa-desktop /usr/bin/palapa ``` ### Menjalankannya Karena sudah ditambahkan ke system path, file ini sudah bisa diakses dari terminal dengan menjalankan : ```sh palapa ``` ## Sumber Tulisan - [https://www.pendrivelinux.com/how-to-open-a-tar-file-in-unix-or-linux/](https://www.pendrivelinux.com/how-to-open-a-tar-file-in-unix-or-linux/) - [https://tekno.tempo.co/read/1389942/songsong-sumpah-pemuda-aplikasi-palapa-siap-menantang-whatsapp/full&view=ok](https://tekno.tempo.co/read/1389942/songsong-sumpah-pemuda-aplikasi-palapa-siap-menantang-whatsapp/full&view=ok) - [https://sekilas13.vercel.app/blog/mxlinux-telegram](https://sekilas13.vercel.app/blog/mxlinux-telegram) => Sumber Utama ## Pranala Menarik - [https://www.youtube.com/watch?v=u134QX3ZKg8](https://www.youtube.com/watch?v=u134QX3ZKg8) - [https://www.youtube.com/watch?v=QVrhtoVQHko](https://www.youtube.com/watch?v=QVrhtoVQHko) - [http://onnocenter.or.id/wiki/index.php/Palapa:\_Perbandingan_WA_Telegram_Signal_Palapa](http://onnocenter.or.id/wiki/index.php/Palapa:_Perbandingan_WA_Telegram_Signal_Palapa) <file_sep>/scripts/noflash.minimizer.js const fs = require("fs"); const { resolve } = require("path"); const { minify } = require("terser"); module.exports = async function () { const txt = fs.readFileSync(resolve("./scripts/noflash.js.txt"), "utf8"); const result = await minify(txt); fs.writeFileSync("public/noflash.min.js", result.code); }; <file_sep>/assets/data/ThemeBlog.js export const darkBlog = { article: { all: { color: "#dee3ea" }, anchor: { color: "#3d8bfd" } }, card: { center: { bg: "#0b0e11" }, lighter: { bg: "#151a21" }, textColor: "#dee3ea", border: "rgb(11,14,17)" } }; export const lightBlog = { article: { all: { color: "#24292e" }, anchor: { color: "#0355d6" } }, card: { center: { bg: "#fff" }, lighter: { bg: "rgba(0,0,0,.03)" }, textColor: "#212529", border: "rgba(0,0,0, .125)" } }; <file_sep>/components/main/JumbotronTop.js import dynamic from "next/dynamic"; import { useSpring } from "react-spring"; import { Jumbotron, Container, Row } from "react-bootstrap"; import styles from "../../styles/main/Jumbotron.module.css"; import { memo, useRef, useCallback, useEffect } from "react"; import useProgressiveImage from "./hooks/useProgressiveImage"; import { source, placeholder } from "../../assets/data/GambarJumbotron"; const Img = dynamic(() => import("./lazy/JumbonImg"), { loading: ({ src, loading }) => ( <img src={src} style={{ filter: loading ? "blur(10px)" : "none", transition: "all 0.40s linear" }} className={`${styles.gambar} img-fluid text-center rounded`} alt="Logo KIR" /> ) }); const Hasatu = dynamic(() => import("./lazy/JumbonHasatu"), { loading: () => <h1 className={styles.hasatu}>Sekilas !</h1> }); const Paragrap = dynamic(() => import("./lazy/JumbonParagrap"), { loading: () => <p className={styles.paragrap}>Semangat KIR Tiga Belas !</p> }); function JumbotronTop() { const ref = useRef(); const { src, loading, onChangeVisible } = useProgressiveImage({ srcTujuan: source, placeholder }); const [{ offset }, setOffset] = useSpring(() => ({ offset: 0 })); const handleScroll = useCallback(() => { if (ref.current) { const posY = ref.current.getBoundingClientRect().top; const offset = window.pageYOffset - posY; setOffset({ offset }); } }, [ref]); useEffect(() => { onChangeVisible(true); window.addEventListener("scroll", handleScroll); return () => { window.removeEventListener("scroll", handleScroll); }; }, []); return ( <Jumbotron fluid className={styles.jumbotron} ref={ref}> <Container className={styles.container}> <Row className="justify-content-center"> <Img src={src} loading={loading} offset={offset} /> </Row> <Row className="justify-content-center"> <Hasatu offset={offset} /> </Row> <Row className="justify-content-center"> <Paragrap offset={offset} /> </Row> </Container> </Jumbotron> ); } export default memo(JumbotronTop); <file_sep>/components/main/KataOrang.js import { useEffect, useState, useContext, useRef } from "react"; import styles from "../../styles/main/KataOrang.module.css"; import { DarkModeContext } from "../../context/darkMode"; import LazyLoad from "react-lazyload"; import dynamic from "next/dynamic"; const Content = dynamic(() => import("./lazy/KataOrang"), { ssr: false }); export default function KataOrang() { const ref = useRef(); const [ukuran, setUkuran] = useState({ width: window.innerWidth, height: window.innerHeight }); const { isDark } = useContext(DarkModeContext); useEffect(() => { const curr = ref.current; const Ubah = { width: curr.offsetWidth, height: curr.offsetHeight }; setUkuran(Object.assign({}, Ubah)); function resize() { const forUbah = { width: curr.offsetWidth, height: curr.offsetHeight }; setUkuran(Object.assign({}, forUbah)); } window.addEventListener("resize", resize); return () => { window.removeEventListener("resize", resize); }; }, []); return ( <section className="KataOrang" id={styles.KataOrang} ref={ref}> <LazyLoad once> <Content ukuran={ukuran} theme={isDark} /> </LazyLoad> </section> ); } <file_sep>/components/covid/lazy/Tbody.js import Pascalize from "../../../utils/Pascalize"; export default function Tbody({ data, error }) { return ( <> {!error && !data && ( <> <tr> <td>1</td> <td colSpan={4} className="text-center"> Sedang mengambil data.... </td> </tr> <tr> <td>2</td> <td colSpan={4} className="text-center"> Mohon tunggu.... </td> </tr> </> )} {typeof data === "object" && data.map((d, i) => ( <tr key={i}> <td>{i + 1}</td> <td>{Pascalize(d.provinsi).replace("Dki", "DKI")}</td> <td>{Number(d.kasus).toLocaleString()}</td> <td>{Number(d.sembuh).toLocaleString()}</td> <td>{Number(d.meninggal).toLocaleString()}</td> </tr> ))} {error && !data && ( <> <tr> <td colSpan={5} className="text-center"> Mohon maaf, data tidak dapat ditampilkan. </td> </tr> <tr> <td colSpan={5} className="text-center"> Error: {error.message} </td> </tr> </> )} </> ); } <file_sep>/pages/covid.js import { useContext } from "react"; import dynamic from "next/dynamic"; import Content from "../components/covid"; import { exception } from "../utils/gtag"; import { NextSeo } from "next-seo"; import { SWRConfig } from "swr"; import Head from "next/head"; import fetch from "axios"; import DEF_SEO from "../config/seo.config"; import "bootstrap/dist/css/bootstrap.min.css"; const PageSEO = DEF_SEO.pages.covid; const Navigasi = dynamic(() => import("../components/Navigasi"), { loading: () => ( <nav className="navbar navbar-expand-lg navbar-light bg-light sticky-top" style={{ height: "56px" }} /> ), ssr: false }); const PRELOAD_CSS = [ "b337d7e4fd55d8158c57.css", // Statistik.module.css "bff4e0b56d744a9baaee.css" // Navigasi.module.css ]; const fetcher = (...args) => fetch(...args).then((res) => res.data); export default function Covid() { return ( <> <Head> {process.env.isProduction && PRELOAD_CSS.map((css) => ( <link rel="preload" href={"/_next/static/css/" + css} as="style" key={css} /> ))} <link rel="preconnect" href="https://apicovid19indonesia-v2.vercel.app" /> </Head> <NextSeo title={PageSEO.title} description={PageSEO.description} canonical={PageSEO.canonical} openGraph={PageSEO.opg} /> <Navigasi /> <SWRConfig value={{ fetcher, onError: (error) => { exception({ error: error.message, fatal: false }); } }} > <Content /> </SWRConfig> </> ); } <file_sep>/README.md ## sekilas13-ssr | Server Side Rendering Ini adalah repositori refactor dari website client side rendering. Diubah ke versi server side rendering menggunakan [Next.js](https://nextjs.org/) karena kebutuhan search engine optimization. ### Local Development Cloning repositori ini ke perangkat lokal. ```sh git clone https://github.com/sekilas13/sekilas13-ssr.git # atau versi ssh git clone git@github.com:sekilas13/sekilas13-ssr.git ``` Masuk ke folder clone tadi dan install development dependencies. ```sh cd sekilas13-ssr && npm i -D ``` Copy file `.env.example` menjadi `.env.local` dan isi variabel-variabelnya. Contoh : ``` GA_TRACKING_ID=G-XXXX GOOGLE_VERIF=XXX_XXX-XXX DEPLOYMENT_BASE_URL=https://sekilas13.vercel.app ``` Jalankan development mode ```sh npm run dev ``` Bisa dibuka di http://localhost:3000 untuk melihatnya langsung di peramban. <file_sep>/config/whitelist.config.js const dummy = [...new Array(12)]; const col = (type) => dummy.map((_, idx) => `col${type !== "" ? `-${type}-` : "-"}${++idx}`); const table = [ "table-responsive", "table-light", "table-dark", "table-striped", "table-bordered", "table-hover" ]; const satuan = [ "show", "hide", "slide", "active", "carousel", "container-fluid", "collapsing", "collapsed", "navbar-nav", "navbar-dark", "navbar-toggler-icon", ...col("md"), ...col("sm"), ...col("lg"), ...table ]; module.exports = [/^carousel-/, ...satuan]; <file_sep>/utils/isSupportWebp.js const isSupportWebp = (() => { const elem = document.createElement("canvas"); if (!!(elem.getContext && elem.getContext("2d"))) { return elem.toDataURL("image/webp").indexOf("data:image/webp") === 0; } else { return false; } })(); export default isSupportWebp; <file_sep>/config/seo.config.js const PUBLIC_URL = process.env.PUBLIC_URL; const config = { pages: { index: { title: "Karya Ilmiah Remaja SMP Negeri 13 Bekasi", description: "Website resmi Karya Il<NAME> SMPN 13 Bekasi. K<NAME> ini adalah ekskul yang bertemakan tentang Sains dan Ilmu Pengetahuan Umum", canonical: PUBLIC_URL }, covid: { title: "Informasi Covid 19 | Sekilas 13", description: "Informasi penyebaran virus corona di Indonesia dengan tampilan web dari K<NAME> SMPN 13 Bekasi", canonical: PUBLIC_URL + "/covid" } } }; const pages = Object.keys(config.pages); pages.forEach((page) => { const conf = config.pages[page]; const opg = { url: conf.canonical, title: conf.title, description: conf.description, type: "website", images: [ { url: `${PUBLIC_URL}/ogp-img.png`, width: 256, height: 256, alt: "KIR Open Graph" } ], site_name: "Sekilas 13" }; config.pages[page].opg = opg; }); export default config; <file_sep>/pages/_document.js import Document, { Html, Head, Main, NextScript } from "next/document"; import { GA_TRACKING_ID } from "../utils/gtag"; import { minify } from "terser"; const getScript = async () => { const code = ` window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '${GA_TRACKING_ID}', { page_path: window.location.pathname, }); `; if (process.env.NODE_ENV === "development") return code; const minified = await minify(code); return minified.code; }; export default class Root extends Document { static async getInitialProps(ctx) { const initialProps = await Document.getInitialProps(ctx); const gtagScript = await getScript(); return { ...initialProps, gtagScript }; } render() { return ( <Html lang="id"> <Head> <link rel="icon" href={process.env.PUBLIC_URL + "/favicon.ico"} /> <link rel="apple-touch-icon" href={process.env.PUBLIC_URL + "/logo192-apple-touch.png"} /> <link rel="manifest" href={process.env.PUBLIC_URL + "/manifest.json"} /> <script async src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`} /> <script dangerouslySetInnerHTML={{ __html: this.props.gtagScript }} /> </Head> <body> {process.env.isProduction && <script src="noflash.min.js" />} <Main /> <NextScript /> </body> </Html> ); } } <file_sep>/components/Navigasi/memoized/Sun.js import { memo, useMemo, useContext } from "react"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faSun as SunSolid } from "@fortawesome/free-solid-svg-icons"; import { faSun as SunRegular } from "@fortawesome/free-regular-svg-icons"; import { DarkModeContext } from "../../../context/darkMode"; function Sun() { const { isDark } = useContext(DarkModeContext); const icon = useMemo(() => (isDark ? SunRegular : SunSolid), [isDark]); return <FontAwesomeIcon icon={icon} />; } export default memo(Sun); <file_sep>/utils/Pascalize.js export default function Pascalize(str) { return str.replace( /(\w)(\w*)/g, (g0, g1, g2) => g1.toUpperCase() + g2.toLowerCase() ); } <file_sep>/components/main/Footer.js import dynamic from "next/dynamic"; import LazyLoad from "react-lazyload"; import { Container, Row, Col } from "react-bootstrap"; import styles from "../../styles/main/Footer.module.css"; const Email = dynamic(() => import("./lazy/FooterEmail"), { ssr: false }); const Info = dynamic(() => import("./lazy/FooterInfo"), { ssr: false }); export default function Footer() { return ( <footer id={styles.footer} className="bg-dark text-white"> <Container> <Row className="pt-3 justify-content-center text-center"> <Col md={4}> <LazyLoad once> <Email /> </LazyLoad> </Col> <Col md={4}> <LazyLoad once> <Info /> </LazyLoad> </Col> </Row> </Container> </footer> ); } <file_sep>/pages/index.js import Content from "../components/main"; import { NextSeo } from "next-seo"; import dynamic from "next/dynamic"; import { useContext } from "react"; import Head from "next/head"; import DEF_SEO from "../config/seo.config"; import "bootstrap/dist/css/bootstrap.min.css"; const PageSEO = DEF_SEO.pages.index; const Navigasi = dynamic(() => import("../components/Navigasi"), { loading: () => ( <nav className="navbar navbar-expand-lg navbar-light bg-light sticky-top" style={{ height: "56px" }} /> ), ssr: false }); const PRELOAD_CSS = [ "b337d7e4fd55d8158c57.css", // Statistik.module.css "bff4e0b56d744a9baaee.css", // Navigasi.module.css "83a97b3f0d7136785509.css" // KataOrang.module.css ]; const PRELOAD_LCP_IMG = "KIR-228-c7ad9295d87ea5f047a2312222929797.webp"; // KIR.png export default function Home() { return ( <> <Head> {process.env.isProduction && PRELOAD_CSS.map((css) => ( <link rel="preload" href={"/_next/static/css/" + css} as="style" key={css} /> ))} <link rel="preload" href="https://fonts.googleapis.com/css2?family=Eczar:wght@600&family=Roboto&family=Kufam&display=swap" as="style" onLoad="this.onload=null;this.rel='stylesheet'" /> {process.env.isProduction && ( <link rel="preload" as="image" href={"/_next/static/images/" + PRELOAD_LCP_IMG} /> )} <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Eczar:wght@600&family=Roboto&family=Kufam&display=swap" /> <link rel="preconnect" href="https://fonts.gstatic.com" /> <link rel="preconnect" href="https://fonts.googleapis.com" /> </Head> <NextSeo title={PageSEO.title} description={PageSEO.description} canonical={PageSEO.canonical} openGraph={PageSEO.opg} /> <Navigasi /> <Content /> </> ); } <file_sep>/components/Navigasi/memoized/Moona.js import { memo, useMemo, useContext } from "react"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faMoon as MoonSolid } from "@fortawesome/free-solid-svg-icons"; import { faMoon as MoonRegular } from "@fortawesome/free-regular-svg-icons"; import { DarkModeContext } from "../../../context/darkMode"; function Moon({ theme }) { const { isDark } = useContext(DarkModeContext); const icon = useMemo(() => (isDark ? MoonSolid : MoonRegular), [isDark]); return <FontAwesomeIcon icon={icon} />; } export default memo(Moon); <file_sep>/components/blog/ArticleStyles.js import { createGlobalStyle } from "styled-components"; const GlobalStyles = createGlobalStyle` article.markdown-body h1,h2,h3,h4,h5,h6,p,ol,li,ul, .container .row .col h1 { color: ${({ theme }) => theme.article.all.color}; transition: all 0.20s linear; } article.markdown-body a, .card .card-footer a { color: ${({ theme }) => theme.article.anchor.color}; transition: all 0.20s linear; } .card { border-color: ${({ theme }) => theme.card.border}; transition: all 0.20s linear; border-radius: 0.30em; } .card .card-header,.card .card-body { color: ${({ theme }) => theme.card.textColor}; transition: all 0.20s linear; } .card .card-header,.card-footer { background-color: ${({ theme }) => theme.card.lighter.bg}; transition: all 0.20s linear; border-top-right-radius: 0.25em; border-top-left-radius: 0.25em; } .card-body { background-color: ${({ theme }) => theme.card.center.bg}; transition: all 0.20s linear; } `; export default GlobalStyles; <file_sep>/components/main/lazy/JumbonParagrap.js import { animated } from "react-spring"; import styles from "../../../styles/main/Jumbotron.module.css"; const calc3 = (o) => `translateY(${o * 0.08}px)`; export default function JumbonImg({ offset }) { return ( <animated.p style={{ transform: offset.interpolate(calc3), overflow: "hidden" }} className={styles.paragrap} > Semangat KIR Tiga Belas ! </animated.p> ); } <file_sep>/components/main/lazy/JumbonHasatu.js import { animated } from "react-spring"; import styles from "../../../styles/main/Jumbotron.module.css"; const calc2 = (o) => `translateY(${o * 0.1}px)`; export default function JumbonImg({ offset }) { return ( <animated.h1 style={{ transform: offset.interpolate(calc2), overflow: "hidden" }} className={styles.hasatu} > Sekilas ! </animated.h1> ); } <file_sep>/pages/blog/index.js import { Container, Row, Col, Card } from "react-bootstrap"; import moment from "moment-timezone"; import { useContext } from "react"; import { NextSeo } from "next-seo"; import matter from "gray-matter"; import Link from "next/link"; import style from "../../styles/blog/Posts.module.css"; import "bootstrap/dist/css/bootstrap.min.css"; const title = "Our Blog | Sekilas 13"; const description = "Daftar tulisan blog Karya <NAME> SMP Negeri 13 Bekasi"; const timeParser = (tanggal) => moment(tanggal, "DD-MMM-YYYY HH:mm").tz("Asia/Jakarta"); export default function Blog({ data }) { return ( <> <NextSeo title={title} description={description} canonical={`${process.env.PUBLIC_URL}/blog`} openGraph={{ url: `${process.env.PUBLIC_URL}/blog`, title, description, type: "article", images: [ { url: `${process.env.PUBLIC_URL}/ogp-img.png`, width: 256, height: 256, alt: "KIR Open Graph" } ], site_name: "Sekilas 13" }} /> <Container className="mt-4"> <Row> <Col> <h1>Daftar Postingan</h1> </Col> </Row> <Row className="mt-2"> {data.map(({ content, redirect }) => ( <Col md={3} sm={6} key={content.Judul}> <Card className={style.cardResponsive}> <Card.Header>{content.Judul}</Card.Header> <Card.Body>{content.Deskripsi}</Card.Body> <Card.Footer> <Link href={process.env.PUBLIC_URL + "/blog/" + redirect}> <a>Baca &raquo;</a> </Link> </Card.Footer> </Card> </Col> ))} </Row> </Container> </> ); } export async function getStaticProps() { const fs = require("fs"); const files = fs.readdirSync(`${process.cwd()}/posts`, "utf-8"); const blogs = files.filter((fn) => fn.endsWith(".md")); const data = blogs .map((blog) => { const path = `${process.cwd()}/posts/${blog}`; const rawContent = fs.readFileSync(path, { encoding: "utf-8" }); const content = matter(rawContent).data; const redirect = blog.replace(".md", ""); return { content, redirect }; }) .sort((a, b) => { const aTime = timeParser(a.content.TanggalDibuat); const bTime = timeParser(b.content.TanggalDibuat); return aTime - bTime; }); return { props: { data } }; } <file_sep>/context/darkMode.js import { createContext, useEffect, useMemo, useCallback } from "react"; import { darkBlog, lightBlog } from "../assets/data/ThemeBlog"; import { darkTheme, lightTheme } from "../assets/data/Theme"; import { ThemeProvider } from "styled-components"; import { useRouter } from "next/router"; import useDarkMode from "use-dark-mode"; import * as gtag from "../utils/gtag"; import dynamic from "next/dynamic"; const GlobalStylesMain = dynamic( () => import("../components/main/GlobalStyles"), { ssr: false } ); const GlobalStylesCovid = dynamic( () => import("../components/covid/GlobalStyles"), { ssr: false } ); const ArticleStyles = dynamic( () => import("../components/blog/ArticleStyles"), { ssr: false } ); export const DarkModeContext = createContext({ value: false }); export default function Provider({ children }) { const router = useRouter(); const dark = useDarkMode(false); const isDark = useMemo(() => dark.value, [dark]); const themeNonBlog = useMemo(() => (isDark ? darkTheme : lightTheme), [ isDark ]); const themeBlog = useMemo(() => (isDark ? darkBlog : lightBlog), [isDark]); const themeToggler = useCallback(() => void dark.toggle(), [dark]); const theme = useMemo(() => { switch (router.pathname) { case "/covid": case "/": return themeNonBlog; case "/blog": default: return themeBlog; } }, [router, isDark]); const GlobalStyles = useMemo(() => { switch (router.pathname) { case "/": return GlobalStylesMain; case "/covid": return GlobalStylesCovid; case "/blog": default: return ArticleStyles; } }, [router]); const providerValue = useMemo( () => ({ dark, isDark, themeToggler }), [dark, isDark, themeToggler] ); useEffect(() => { const handleRouteChange = (url) => { gtag.pageview(url); }; router.events.on("routeChangeComplete", handleRouteChange); return () => { router.events.off("routeChangeComplete", handleRouteChange); }; }, [router.events]); return ( <DarkModeContext.Provider value={providerValue}> <ThemeProvider theme={theme} prefetch={false}> <GlobalStyles /> {children} </ThemeProvider> </DarkModeContext.Provider> ); } <file_sep>/components/main/lazy/FooterEmail.js import { InView } from "react-intersection-observer"; import { Transition } from "react-spring/renderprops"; const From = { transform: "translate3d(-20px,0,0)", opacity: 0 }; const Enter = { transform: "translate3d(0px,0,0)", opacity: 1 }; const Leave = { opacity: 0 }; export default function FooterEmail() { return ( <InView> {({ inView, ref }) => ( <div ref={ref}> <Transition items={inView} from={From} enter={Enter} leave={Leave}> {(show) => show && ((props) => ( <p style={props}> Ada pertanyaan ? Tanyakan lewat email{" "} <a href="mailto:<EMAIL>"><EMAIL></a> </p> )) } </Transition> </div> )} </InView> ); } <file_sep>/assets/data/GambarJumbotron.js const source = require("../Img/KIR/KIR.png?resize&size=228&format=webp"); const placeholder = require("../Img/KIR/KIR.png?resize&size=15&format=webp"); module.exports = { source, placeholder }; <file_sep>/pages/_app.js import Head from "next/head"; import { memo, useContext } from "react"; import * as gtag from "../utils/gtag"; import ProgressLoad from "../components/ProgressLoad"; import DarkModeProvider, { DarkModeContext } from "../context/darkMode"; function MyApp(props) { return ( <DarkModeProvider> <Head> <meta name="viewport" content="width=device-width,initial-scale=1" /> <meta name="google-site-verification" content={gtag.GOOGLE_VERIF} /> <meta name="theme-color" content="#f0efeb" /> </Head> <ProgressLoad /> <ThemeColorSetter {...props} /> <style jsx global>{` html { font-family: "Roboto", sans-serif; scroll-behavior: smooth; } body.light-mode { background: #fff !important; transition: all 0.2s linear; } body.dark-mode { background: #242423 !important; transition: all 0.2s linear; } `}</style> </DarkModeProvider> ); } function ThemeColorSetter({ Component, pageProps }) { const { isDark } = useContext(DarkModeContext); return ( <> <Head> <meta name="theme-color" content={isDark ? "#323234" : "#f0efeb"} /> </Head> <Component {...pageProps} /> </> ); } export default memo(MyApp); export function reportWebVitals({ id, name, label, value }) { window.gtag("event", name, { event_category: label === "web-vital" ? "Web Vitals" : "Next.js metric", value: Math.round(name === "CLS" ? value * 1000 : value), event_label: id, non_interaction: true }); }
292251141dde249483ec76014e9c60b46e01d4d2
[ "JavaScript", "TypeScript", "Markdown", "Shell" ]
43
JavaScript
nomadkode/sekilas13-ssr
ac3b5f6e6585d69bbbb920840e79bfe30eb9305a
27aba588b206d4e88b8e23446ca3308209db1c13
refs/heads/master
<file_sep>import React from 'react' import { Link } from 'react-router-dom'; export const Info = (props) => { console.log(props) const infoArr = props.state.filter(function(i) { return i.title === props.info; }); console.log(infoArr) if(infoArr[0] !== undefined){ const titleInfo= infoArr[0].title const genresInfo = infoArr[0].genres.join(' ') const overviewInfo = infoArr[0].overview const release_dateInfo = infoArr[0].release_date const vote_averageInfo =infoArr[0].vote_average return ( <nav> <Link to = '/'> <div className = 'wrap_info'> <div className ='wrap_info2'> <div className = 'info'> <h2>{titleInfo}</h2> <h3>{genresInfo}</h3> <p>{overviewInfo}</p> <p>Release date: {release_dateInfo}</p> <p>Rating: {vote_averageInfo}</p> </div> </div> </div> </Link> </nav> ) } return ( <></> ) }<file_sep>import React, { useState } from 'react' import { ListMovies } from '../../components/ListMovies' export const BtnSearch = (props) =>{ const [films, setFilms] = useState([]); const loadData = (event) => { event.preventDefault(); fetch(props.url) .then(results => { return results.json() }).then(data => { setFilms (() =>data.data.map(item => item)) }).catch(() => { alert('Ведите название фильма!'); }); } const BtnSortReting = () => { setFilms(() => films.sort((a,b) => b.vote_count - a.vote_count)) } const BtnSortDate = () => { setFilms(() => films.sort((a,b) =>b.release_date.split('-')[0] - a.release_date.split('-')[0])) } return ( <> <input type="button" value="SEARCH" className='BtnSearch' onClick = {loadData} /> <div className = 'Sort'> <h3>Sort by</h3> <button className = 'BtnSort' onClick = {BtnSortReting}>Reting</button> <button className = 'BtnSort' onClick = {BtnSortDate}>Release date</button> </div> <ListMovies films = {films}/> </> ) } <file_sep>import React, { useState } from 'react' import { Route, Link } from 'react-router-dom'; import { Info } from '../state-manager/action/Info' export const ListMovies = (props) => { const [info, setInfo] = useState([]); const state = props.films; const BtnInfo = (e) =>{ e.preventDefault(); setInfo (e.currentTarget.innerText) } return ( <> <div className = 'wrap' > {props.films.map(el => { return( <div className = 'wrap_movies' onClick = {BtnInfo} key ={el.id}> <nav> <Link to = 'info'> <img src ={el.poster_path} alt = ""/> <h4 className = 'title'> {el.title}</h4> </Link> </nav> </div> )}) } </div> <Route exact path = '/' Component = {ListMovies}/> <Route exact path='/info' render={(props) => ( <Info {...props} state = {state} info = {info}/> )}/> </> ) }
60fe9921104775b44415ea0f45e0d9691afa1106
[ "JavaScript" ]
3
JavaScript
VitaliKarpuk/Movie-App
2166b92c15c49518e9e51833e03b2d312c43f4f7
3aefd7467e94b8fe9544c5944c190c7dd2ec1a02
refs/heads/master
<repo_name>Maneesha24/Twitter-analysis-for-social-unrest<file_sep>/client/src/app/modules/notifications/notifications/notifications.component.ts import { Component, OnInit } from '@angular/core'; import * as echarts from 'echarts'; import * as $ from 'jquery'; import { AuthService } from 'src/app/services/data.service.ts'; // import { outputdata } from '../../../data/output.js'; import { outputdata } from '../../../../../../tweetsdata/output.js'; @Component({ selector: 'app-notifications', templateUrl: './notifications.component.html', styleUrls: ['./notifications.component.scss'] }) export class NotificationsComponent implements OnInit { myMap: any; option: any; outputdata = outputdata; data = [ {name: 'Alabama', value: 4822023}, {name: 'Alaska', value: 731449}, {name: 'Arizona', value: 6553255}, {name: 'Arkansas', value: 2949131}, {name: 'California', value: 38041430}, {name: 'Colorado', value: 5187582}, {name: 'Connecticut', value: 3590347}, {name: 'Delaware', value: 917092}, {name: 'District of Columbia', value: 632323}, {name: 'Florida', value: 19317568}, {name: 'Georgia', value: 9919945}, {name: 'Hawaii', value: 1392313}, {name: 'Idaho', value: 1595728}, {name: 'Illinois', value: 12875255}, {name: 'Indiana', value: 6537334}, {name: 'Iowa', value: 3074186}, {name: 'Kansas', value: 2885905}, {name: 'Kentucky', value: 4380415}, {name: 'Louisiana', value: 4601893}, {name: 'Maine', value: 1329192}, {name: 'Maryland', value: 5884563}, {name: 'Massachusetts', value: 6646144}, {name: 'Michigan', value: 9883360}, {name: 'Minnesota', value: 5379139}, {name: 'Mississippi', value: 2984926}, {name: 'Missouri', value: 6021988}, {name: 'Montana', value: 1005141}, {name: 'Nebraska', value: 1855525}, {name: 'Nevada', value: 2758931}, {name: 'New Hampshire', value: 1320718}, {name: 'New Jersey', value: 8864590}, {name: 'New Mexico', value: 2085538}, {name: 'New York', value: 19570261}, {name: 'North Carolina', value: 9752073}, {name: 'North Dakota', value: 699628}, {name: 'Ohio', value: 11544225}, {name: 'Oklahoma', value: 3814820}, {name: 'Oregon', value: 3899353}, {name: 'Pennsylvania', value: 12763536}, {name: 'Rhode Island', value: 1050292}, {name: 'South Carolina', value: 4723723}, {name: 'South Dakota', value: 833354}, {name: 'Tennessee', value: 6456243}, {name: 'Texas', value: 26059203}, {name: 'Utah', value: 2855287}, {name: 'Vermont', value: 626011}, {name: 'Virginia', value: 8185867}, {name: 'Washington', value: 6897012}, {name: 'West Virginia', value: 1855413}, {name: 'Wisconsin', value: 5726398}, {name: 'Wyoming', value: 576412}, {name: '<NAME>', value: 3667084} ] mapXData: any = {}; threshold: any = 500; email: any = '<EMAIL>'; finalData = []; emailSent = false; constructor(private authService: AuthService) { } ngOnInit(): void { Object.values(this.data).map(val => { if (val && val.name) { this.mapXData[val.name] = 0 } }); this.outputdata.map(data => { if (data.location in this.mapXData) { this.mapXData[data.location] += 1 } else { this.mapXData[data.location] = 1 } }); Object.keys(this.mapXData).map (value => { this.finalData.push({ 'name': value, 'value': this.mapXData[value] }) }); if(this.finalData && this.finalData.length) { $.get('https://s3-us-west-2.amazonaws.com/s.cdpn.io/95368/USA_geo.json', (usaJson) => { const myMap = echarts.init((document.getElementById('map')) as any); echarts.registerMap('USA', usaJson, { Alaska: { // 把阿拉斯加移到美国主大陆左下方 left: -131, top: 25, width: 15 }, Hawaii: { left: -110, // 夏威夷 top: 28, width: 5 }, 'Puerto Rico': { // 波多黎各 left: -76, top: 26, width: 2 } }); const option = { // title: { // text: 'USA Protest data' // }, tooltip: { trigger: 'item', showDelay: 0, transitionDuration: 0.2, formatter: function (params) { let value = (params.value + '').split('.'); value = value[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,'); return params.seriesName + '<br/>' + params.name + ': ' + value; } }, visualMap: { left: 'right', min: 0, max: 25, inRange: { color: ['#ffcdd2', '#ef9a9a', '#e57373', '#ef5350', '#f44336', '#e53935', '#d32f2f', '#c62828', '#b71c1c'] }, text: ['High', 'Low'], // 文本,默认为数值文本 calculable: true, // borderWidth: 5 }, toolbox: { show: true, left: 'left', top: 'top', feature: { dataView: {readOnly: false}, restore: {}, saveAsImage: {} } }, series: [ { name: 'USA Protest data', type: 'map', roam: true, map: 'USA', emphasis: { label: { show: true } }, darkMode: "auto", textFixed: { Alaska: [20, -20] }, data: this.finalData } ] }; myMap.setOption(option); }); } } sendMail() { this.authService.sendEmail().subscribe(value => { if(value && value.success) { this.emailSent = true; setTimeout(() => { this.emailSent = false; }, 3000) } }) } } <file_sep>/client/src/app/modules/statistics/statistics/statistics.component.ts import { Component, OnInit } from '@angular/core'; import * as echarts from 'echarts'; import { data } from '../../../data/result.js'; import { outputdata } from '../../../../../../tweetsdata/output.js'; @Component({ selector: 'app-statistics', templateUrl: './statistics.component.html', styleUrls: ['./statistics.component.scss'] }) export class StatisticsComponent implements OnInit { result = data; outputdata = outputdata; private myChart: any = null; private myBarChart: any = null; protestTweets = 0; nonProtestTweets = 0; sentimentScoreObj = { '1': 0, '2': 0, '3': 0, '4': 0, '5': 0 } hashtags = {}; hashtagsXData = [] hashtagsYData = [] retweetData = {}; followerData = {}; retweetXData = []; followerXData = []; constructor() { } ngOnInit(): void { this.outputdata.map(data => { this.sentimentScoreObj[data.sentiment_class] += 1 data.hashtags.map(tag => { if (tag in this.hashtags) { this.hashtags[tag] += 1 } else { this.hashtags[tag] = 1 } }) }); this.hashtags = Object.entries(this.hashtags).sort((a, b) => b[1] - a[1]) this.hashtagsXData = Object.values(this.hashtags.slice(0, 5)).map(val => val[0]); this.hashtagsYData = Object.values(this.hashtags.slice(0, 5)).map(val => val[1]); this.hashtagsXData.map(tag => { this.retweetData[tag] = 0 this.followerData[tag] = 0 }); console.log('data', this.hashtags) this.outputdata.map(data => { if(data.hashtags.includes('#maga')) { this.retweetData['#maga'] += data?.retweetcount; this.followerData['#maga'] += data?.followers; } if(data.hashtags.includes('#trump')) { this.retweetData['#trump'] += data?.retweetcount; this.followerData['#trump'] += data?.followers; } if(data.hashtags.includes('#capitolattack')) { this.retweetData['#capitolattack'] += data?.retweetcount; this.followerData['#capitolattack'] += data?.followers; } if(data.hashtags.includes('#terrorism')) { this.retweetData['#terrorism'] += data?.retweetcount; this.followerData['#terrorism'] += data?.followers; } if(data.hashtags.includes('#biden')) { this.retweetData['#biden'] += data?.retweetcount this.followerData['#biden'] += data?.followers; } }); this.retweetXData = Object.values(this.retweetData) this.followerXData = Object.values(this.followerData) for (let i = 0; i < this.result.length; i++) { if (this.result[i].target == 1) { this.protestTweets += 1 } else { this.nonProtestTweets += 1 } } this.InitPipe(); this.BarPipe(); } private BarPipe() { this.myBarChart = echarts.init((document.getElementById('bar')) as any); const baroption = { tooltip: { trigger: 'axis' }, legend: { data: ['Retweet', 'Followers'] }, toolbox: { show: true, feature: { dataView: { show: true, readOnly: false }, magicType: { show: true, type: ['line', 'bar'] }, restore: { show: true }, saveAsImage: { show: true } } }, calculable: true, xAxis: [ { type: 'category', data: this.hashtagsXData } ], yAxis: [ { type: 'value' } ], series: [ { name: 'Retweets', type: 'bar', data: this.retweetXData, markPoint: { data: [ { type: 'max', name: 'Retweets'}, { type: 'min', name: '最小值' } ] }, markLine: { data: [ { type: 'average', name: 'Retweets' } ] }, color: ['#14557b'], }, { name: 'Followers', type: 'bar', data: this.followerXData, markPoint: { data: [ { type: 'max', name: 'Followers'}, { type: 'min', name: 'Followers' } // data: [ // { name: 'Retweets', value: 182.2, xAxis: 7, yAxis: 183 }, // { name: 'Followers', value: 2.3, xAxis: 11, yAxis: 3 } ] }, markLine: { data: [ { type: 'average', name: 'Followers' } ] }, color: ['#7fcec5'] }, { name: 'Hashtags', type: 'bar', data: this.hashtagsYData, markPoint: { data: [ { type: 'max', name: 'Hashtags'}, { type: 'min', name: 'Hashtags' } ] }, color: ['#d6f48b'] } ] } this.myBarChart.setOption(baroption); } private InitPipe() { this.myChart = echarts.init((document.getElementById('pipe')) as any); const option = { tooltip: { trigger: 'item' }, legend: { top: '5%', left: 'center' }, series: [ { type: 'pie', radius: ['40%', '70%'], color: ['#14557b', '#1779b3', 'rgb(22, 200, 224)', 'rgb(22, 224, 204)', '#7fcec5'], avoidLabelOverlap: false, itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 }, label: { show: false, position: 'center' }, emphasis: { label: { show: true, fontSize: '20', fontWeight: 'bold' } }, labelLine: { show: false }, data: [ { value: this.sentimentScoreObj['5'], name: 'Score 5' }, { value: this.sentimentScoreObj['4'], name: 'Score 4' }, { value: this.sentimentScoreObj['3'], name: 'Score 3' }, { value: this.sentimentScoreObj['2'], name: 'Score 2' }, { value: this.sentimentScoreObj['1'], name: 'Score 1' }, ] } ] }; this.myChart.setOption(option); } } <file_sep>/client/src/app/modules/home/home/home.component.ts import { Component, OnInit } from '@angular/core'; import { data } from '../../../data/result.js'; import { outputdata } from '../../../../../../tweetsdata/output.js'; import * as echarts from 'echarts'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { constructor() { } result = data outputdata = outputdata protestTweets: any = []; hashtags: any = {}; result_arr: any = []; private myChart: any = null; xAxisData: any = ['2:30PM', '2:45PM', '3:00 PM', '3:15 PM']; yAxisObj = { '2:30PM': 0, '2:45PM': 0, '3:00PM': 0, '3:15PM': 0 } yAxisData: any = []; sentimentScoreColorObj = { '1': 'border-low-violent', '2': 'border-lowly-violent', '3': 'border-neutral-violent', '4': 'border-high-violent', '5': 'border-highly-violent' } ngOnInit(): void { for (let i = 0;i < outputdata.length; i++) { console.log('date', outputdata[i] && outputdata[i].tweetcreatedts) if(outputdata[i] && outputdata[i].tweetcreatedts.includes('14:30')) { this.yAxisObj['2:30PM'] += 1 } else if(outputdata[i] && outputdata[i].tweetcreatedts.includes('14:45')) { this.yAxisObj['2:45PM'] += 1 } else if(outputdata[i] && outputdata[i].tweetcreatedts.includes('15:00')) { this.yAxisObj['3:00PM'] += 1 } else { this.yAxisObj['3:15PM'] += 1 } } this.yAxisData = Object.values(this.yAxisObj); this.InitPipe(); } private InitPipe(): void { this.myChart = echarts.init((document.getElementById('main')) as any); const option = { xAxis: { type: 'category', data: this.xAxisData }, yAxis: { type: 'value' }, series: [{ data: this.yAxisData, type: 'line', smooth: true, color: 'black' }] }; this.myChart.setOption(option); } getBorder(score) { return this.sentimentScoreColorObj[score] } }<file_sep>/client/src/app/services/data.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; // https://job-board-maneesha.herokuapp.com @Injectable() export class AuthService { constructor(private http: HttpClient) { } /** * Register user with name, email & password */ sendEmail(): Observable<any> { return this.http.get<any>(`http://localhost:5000/twitter/sendMail`); } }
7e93a2fdf4a2727112433c044435619a2b86537f
[ "TypeScript" ]
4
TypeScript
Maneesha24/Twitter-analysis-for-social-unrest
9945aa8b92bb72ed7f12983545b394420eed6041
8e3d34ed5b78086b643f63e3dfd4bbf6bda370b7
refs/heads/master
<file_sep>$(document).ready(function () { new WOW().init(); $('.bxslider').bxSlider({ pager: false, controls: true, nextText: '', prevText: '', responsive: true }); });<file_sep><h1>Autoservice39</h1> <p> Сайт компании, предоставляющей услуги автосервиса, автостоянки и продаже запчастей. </p> <p>Bootstrap 4, JQuery, Animate.css, Bxslider, Sass, Gulp</p>
8df5037fdb025506391b93c09b8a1f412ecc5cd4
[ "JavaScript", "Markdown" ]
2
JavaScript
Vonasur/autoservice39
90281bb67d2e18106d06ed852bb0d3bc44c912c1
b9ddefa2562d4514c66ec1af9c16fb295a210045
refs/heads/master
<repo_name>vijaygehlot987/Sem6<file_sep>/jaccardsimilarity.py from nltk.tokenize import word_tokenize file1 =open("C:/Users/admin/Desktop/stopword1.txt",'r') s1=word_tokenize(file1.read()) print(s1) file2 =open("C:/Users/admin/Desktop/stopword2.txt",'r') s2=word_tokenize(file2.read()) print(s2) a=0 def intersection(s1,s2): return list(set(s1) & set(s2)) print(intersection(s1, s2)) print(len(intersection(s1, s2))) def Union(s1, s2): unionlist= list(set(s1)|set(s2)) return unionlist print(Union(s1,s2)) print(len(Union(s1,s2))) jaccard=float(len(intersection(s1, s2))/len(Union(s1,s2))) print(jaccard)<file_sep>/cosine.py from nltk.corpus import stopwords from nltk.tokenize import word_tokenize file1=open("C:/Users/Admin/Documents/a1.txt",'r') file2=open("C:/Users/Admin/Documents/a2.txt",'r') # tokenization x = word_tokenize(file1.read()) y = word_tokenize(file2.read()) # sw contains the list of stopwords sw = stopwords.words('english') l1 =[] l2 =[] # remove stop words from string a = {w for w in x if not w in sw} b = {w for w in y if not w in sw} # form a set containing keywords of both strings rvector = a.union(b) for w in rvector: if w in a: l1.append(1) # create a vector else: l1.append(0) if w in b: l2.append(1) else: l2.append(0) c=0 # cosine formula for i in range(len(rvector)): c+= l1[i]*l2[i] cosine = c / float((sum(l1)*sum(l2))**0.5) print("Cosine similarity: ", cosine)<file_sep>/pagerank.py import numpy as np from fractions import Fraction def display(vector, decimal): return np.round((vector).astype(np.float), decimals=decimal) x = Fraction(1,3) Mat = np.matrix([[0,0,1], [Fraction(1,2),0,0], [Fraction(1,2),1,0]]) Ex = np.zeros((3,3)) Ex[:] = x beta = 0.7 Al = beta * Mat + ((1-beta) * Ex) r = np.matrix([x,x,x]) r = np.transpose(r) previous = r for i in range(1,100): r = Al * r print (display(r,3)) if (previous==r).all(): break previous = r print ("Final:\n", display(r,3)) print ("sum", np.sum(r))
4f083ad1b89419b30fb77fc7190c3343a4edec7a
[ "Python" ]
3
Python
vijaygehlot987/Sem6
2662b549b39dfe08debc2720bf47b01cce64a203
639c7ee326127b514ce0ba1043a48a9f5ad42f48
refs/heads/master
<file_sep>/** * Bot * * Credits * CreaturePhil - Lead Development (https://github.com/CreaturePhil) * TalkTakesTime - Parser (https://github.com/TalkTakesTime) * Stevoduhhero - Battling AI (https://github.com/stevoduhhero) * * @license MIT license */ var config = { name: '<NAME>', userid: function () { return toId(this.name); }, group: '#', customavatars: 'hispanobot.gif', rooms: ['lobby'], punishvals: { 1: 'warn', 2: 'mute', }, privaterooms: ['staff'], hosting: {}, laddering: true, ladderPercentage: 70 }; /** * On server start, this sets up fake user connection for bot and uses a fake ip. * It gets a the fake user from the users list and modifies it properties. In addition, * it sets up rooms that bot will join and adding the bot user to Users list and * removing the fake user created which already filled its purpose * of easily filling in the gaps of all the user's property. */ function joinServer() { if (process.uptime() > 5) return; // to avoid running this function again when reloading var worker = new(require('./fake-process.js').FakeProcess)(); Users.socketConnect(worker.server, undefined, '1', 'bot'); for (var i in Users.users) { if (Users.users[i].connections[0].ip === 'bot') { var bot = Users.users[i]; bot.name = config.name; bot.named = true; bot.renamePending = config.name; bot.authenticated = true; bot.userid = config.userid(); bot.group = config.group; bot.avatar = config.customavatars; if (config.join === true) { Users.users[bot.userid] = bot; for (var room in Rooms.rooms) { if (room != 'global') { bot.roomCount[room] = 1; Rooms.rooms[room].users[Users.users[bot.userid]] = Users.users[bot.userid]; } } } else { Users.users[bot.userid] = bot; for (var index in config.rooms) { bot.roomCount[config.rooms[index]] = 1; Rooms.rooms[config.rooms[index]].users[Users.users[bot.userid]] = Users.users[bot.userid]; } } delete Users.users[i]; } } } const ACTION_COOLDOWN = 3 * 1000; const FLOOD_MESSAGE_NUM = 4; const FLOOD_PER_MSG_MIN = 500; // this is the minimum time between messages for legitimate spam. It's used to determine what "flooding" is caused by lag const FLOOD_MESSAGE_TIME = 6 * 1000; const MIN_CAPS_LENGTH = 18; const MIN_CAPS_PROPORTION = 0.8; var parse = { chatData: {}, processChatData: function (user, room, connection, message) { if (user.userid === config.userid() || !room.users[config.userid()]) return true; var cmds = this.processBotCommands(user, room, connection, message); if (cmds) return false; message = message.trim().replace(/ +/g, " "); // removes extra spaces so it doesn't trigger stretching this.updateSeen(user.userid, 'c', room.title); var time = Date.now(); if (!this.chatData[user]) this.chatData[user] = { zeroTol: 0, lastSeen: '', seenAt: time }; if (!this.chatData[user][room]) this.chatData[user][room] = { times: [], points: 0, lastAction: 0 }; this.chatData[user][room].times.push(time); var pointVal = 0; var muteMessage = ''; // moderation for flooding (more than x lines in y seconds) var isFlooding = (this.chatData[user][room].times.length >= FLOOD_MESSAGE_NUM && (time - this.chatData[user][room].times[this.chatData[user][room].times.length - FLOOD_MESSAGE_NUM]) < FLOOD_MESSAGE_TIME && (time - this.chatData[user][room].times[this.chatData[user][room].times.length - FLOOD_MESSAGE_NUM]) > (FLOOD_PER_MSG_MIN * FLOOD_MESSAGE_NUM)); if (isFlooding) { if (pointVal < 2) { pointVal = 2; muteMessage = ', Flood'; } } // moderation for caps (over x% of the letters in a line of y characters are capital) var capsMatch = message.replace(/[^A-Za-z]/g, '').match(/[A-Z]/g); if (capsMatch && toId(message).length > MIN_CAPS_LENGTH && (capsMatch.length >= Math.floor(toId(message).length * MIN_CAPS_PROPORTION))) { if (pointVal < 1) { pointVal = 1; muteMessage = ', Caps'; } } // moderation for stretching (over x consecutive characters in the message are the same) var stretchMatch = message.toLowerCase().match(/(.)\1{7,}/g) || message.toLowerCase().match(/(..+)\1{4,}/g); // matches the same character (or group of characters) 8 (or 5) or more times in a row if (stretchMatch) { if (pointVal < 1) { pointVal = 1; muteMessage = ', Alargar Palabras'; } } if (pointVal > 0 && !(time - this.chatData[user][room].lastAction < ACTION_COOLDOWN)) { var cmd = 'mute'; // defaults to the next punishment in config.punishVals instead of repeating the same action (so a second warn-worthy // offence would result in a mute instead of a warn, and the third an hourmute, etc) if (this.chatData[user][room].points >= pointVal && pointVal < 4) { this.chatData[user][room].points++; cmd = config.punishvals[this.chatData[user][room].points] || cmd; } else { // if the action hasn't been done before (is worth more points) it will be the one picked cmd = config.punishvals[pointVal] || cmd; this.chatData[user][room].points = pointVal; // next action will be one level higher than this one (in most cases) } if (config.privaterooms.indexOf(room) >= 0 && cmd === 'warn') cmd = 'mute'; // can't warn in private rooms // if the bot has % and not @, it will default to hourmuting as its highest level of punishment instead of roombanning if (this.chatData[user][room].points >= 4 && config.group === '%') cmd = 'hourmute'; if (this.chatData[user].zeroTol > 4) { // if zero tolerance users break a rule they get an instant roomban or hourmute muteMessage = ', zero tolerance user'; cmd = config.group !== '%' ? 'roomban' : 'hourmute'; } if (this.chatData[user][room].points >= 2) this.chatData[user].zeroTol++; // getting muted or higher increases your zero tolerance level (warns do not) this.chatData[user][room].lastAction = time; room.add('|c|' + user.group + user.name + '|' + message); CommandParser.parse(('/' + cmd + ' ' + user.userid + muteMessage), room, Users.get(config.name), Users.get(config.name).connections[0]); return false; } return true; }, updateSeen: function (user, type, detail) { user = toId(user); type = toId(type); if (type in {j: 1, l: 1, c: 1} && (config.rooms.indexOf(toId(detail)) === -1 || config.privaterooms.indexOf(toId(detail)) > -1)) return; var time = Date.now(); if (!this.chatData[user]) this.chatData[user] = { zeroTol: 0, lastSeen: '', seenAt: time }; if (!detail) return; var msg = ''; if (type in {j: 1, l: 1, c: 1}) { msg += (type === 'j' ? 'joining' : (type === 'l' ? 'leaving' : 'chatting in')) + ' ' + detail.trim() + '.'; } else if (type === 'n') { msg += 'changing nick to ' + ('+%@&#~'.indexOf(detail.trim().charAt(0)) === -1 ? detail.trim() : detail.trim().substr(1)) + '.'; } if (msg) { this.chatData[user].lastSeen = msg; this.chatData[user].seenAt = time; } }, processBotCommands: function (user, room, connection, message) { if (room.type !== 'chat' || message.charAt(0) !== '.') return; var cmd = '', target = '', spaceIndex = message.indexOf(' '), botDelay = (Math.floor(Math.random() * 6) * 1000), now = Date.now(); if (spaceIndex > 0) { cmd = message.substr(1, spaceIndex - 1); target = message.substr(spaceIndex + 1); } else { cmd = message.substr(1); target = ''; } cmd = cmd.toLowerCase(); if (message.charAt(0) === '.' && Object.keys(Bot.commands).join(' ').toString().indexOf(cmd) >= 0 && message.substr(1) !== '') { if ((now - user.lastBotCmd) * 0.001 < 30) { connection.sendTo(room, 'Please wait ' + Math.floor((30 - (now - user.lastBotCmd) * 0.001)) + ' seconds until the next command.'); return true; } user.lastBotCmd = now; } if (commands[cmd]) { var context = { sendReply: function (data) { setTimeout(function () { room.add('|c|' + config.group + config.name + '|' + data); }, botDelay); }, sendPm: function (data) { var message = '|pm|' + config.group + config.name + '|' + user.group + user.name + '|' + data; user.send(message); }, can: function (permission) { if (!user.can(permission)) { setTimeout(function () { connection.sendTo(room, '.' + cmd + ' - Access denied.'); }, botDelay); return false; } return true; }, parse: function (target) { CommandParser.parse(target, room, Users.get(Bot.config.name), Users.get(Bot.config.name).connections[0]); }, }; if (typeof commands[cmd] === 'function') { commands[cmd].call(context, target, room, user, connection, cmd, message); } } }, getTimeAgo: function (time) { time = Date.now() - time; time = Math.round(time / 1000); // rounds to nearest second var seconds = time % 60; var times = []; if (seconds) times.push(String(seconds) + (seconds === 1 ? ' second' : ' seconds')); var minutes, hours, days; if (time >= 60) { time = (time - seconds) / 60; // converts to minutes minutes = time % 60; if (minutes) times = [String(minutes) + (minutes === 1 ? ' minute' : ' minutes')].concat(times); if (time >= 60) { time = (time - minutes) / 60; // converts to hours hours = time % 24; if (hours) times = [String(hours) + (hours === 1 ? ' hour' : ' hours')].concat(times); if (time >= 24) { days = (time - hours) / 24; // you can probably guess this one if (days) times = [String(days) + (days === 1 ? ' day' : ' days')].concat(times); } } } if (!times.length) times.push('0 seconds'); return times.join(', '); } }; var commands = { guide: function (target, room, user) { var commands = Object.keys(Bot.commands); commands = commands.join(', ').toString(); this.sendReply('List of bot commands: ' + commands); }, say: function (target, room, user) { if (!this.can('say')) return; this.sendReply(target); }, tell: function (target, room, user) { if (!this.can('bottell')) return; var parts = target.split(','); if (parts.length < 2) return; this.parse('/tell ' + toId(parts[0]) + ', ' + Tools.escapeHTML(parts[1])); this.sendReply('Mensaje enviado a: ' + parts[0] + '.'); }, penislength: function (target, room, user) { this.sendReply('8.5 inches from the base. Perv.'); }, seen: function (target, room, user, connection) { if (!target) return; if (!toId(target) || toId(target).length > 18) return connection.sendTo(room, 'Invalid username.'); if (!parse.chatData[toId(target)] || !parse.chatData[toId(target)].lastSeen) { return this.sendPm('The user ' + target.trim() + ' nunca ha sido visto en las salas.'); } return this.sendPm(target.trim() + ' fue visto por última vez ' + parse.getTimeAgo(parse.chatData[toId(target)].seenAt) + ' ago, ' + parse.chatData[toId(target)].lastSeen); }, arena: function (target, room, user) { if (!global.salt) global.salt = 0; salt++; this.sendReply(salt + '% Arenoso.'); }, whois: (function () { var reply = [ "Un usuario más de Pokémon Hispano", "Un entrenador Pokémon muy competitivo", "Este si vale la pena, retalo", "Normalmente, es malo... BaleBergaLaBida", "El es bastante bueno jugando~", "Alguien mucho mejor que tú", "Una persona cúl", "Una persona Kawaii", "Olvidalo, es virgen", "Un Líder", "Un amigo de Smiler 1313", "Que? Donde está?... *Se esconde bajo la cama*", "Alguien muy, pero muy arenoso :(", "Un Seguidor muy leal a RamirOP", "MMM a veces juega bien, a veces mal~", ]; return function (target, room, user) { if (!target) return; var message = reply[Math.floor(Math.random() * reply.length)]; target = toId(target); if (target === 'Shake') message = 'Administrador de este server, actualmente uno de los jugadores mas experimentados que he conocido; líder indiscutible del clan End Game'; if (target === config.userid()) message = 'Ese Soy YO! soy mucho mejor que los admins, no les digas porque se pondran arenosos <w<'; if (target === 'Neon') message = 'Administrador de este server, persona bastante dedicada y seria, no lo molestes, te puede salir de mal humor...'; if (target === 'stevoduhhero') message = 'STEVO DUH GOD DAMN HERO! Respect him!'; if (target === 'Kizzu') message = 'Random, Random Everywhere~ Administrador de este servidor, actualmente retirado de Pokémon, aunque llego a su puesto muy rápido <_<'; if (target === 'Billy') message = 'Yugi Cabrera, haxero, haxero!!! D= corran que vino billy trampas locas x_x'; if (target === 'Osco') message = 'Leader del server, especialista en la tier Ubers. Poco paciente, mejor evitar la desesperación de este hombre:'; this.sendReply(message); }; })(), helix: (function () { var reply = [ "Signs point to yes.", "Yes.", "Reply hazy, try again.", "Without a doubt.", "My sources say no.", "As I see it, yes.", "You may rely on it.", "Concentrate and ask again.", "Outlook not so good.", "It is decidedly so.", "Better not tell you now.", "Very doubtful.", "Yes - definitely.", "It is certain.", "Cannot predict now.", "Most likely.", "Ask again later.", "My reply is no.", "Outlook good.", "Don't count on it." ]; return function (target, room, user) { if (!target) return; var message = reply[Math.floor(Math.random() * reply.length)]; this.sendPm(message); }; })(), maketournament: function (target, room, user) { if (!this.can('maketournament')) return; if (Tournaments.tournaments[room.id]) return this.sendReply('A tournament is already running in the room.'); var parts = target.split(','), self = this, counter = 1; if (parts.length < 2 || Tools.getFormat(parts[0]).effectType !== 'Format' || !/[0-9]/.test(parts[1])) return this.sendPm('Correct Syntax: !maketournament [tier], [time/amount of players]'); if (parts[1].indexOf('minute') >= 0) { var time = Number(parts[1].split('minute')[0]); this.parse('/tour create ' + parts[0] + ', elimination'); this.sendReply('**You have ' + time + ' minute' + parts[1].split('minute')[1] + ' to join the tournament.**'); var loop = function () { setTimeout(function () { if (!Tournaments.tournaments[room.id]) return; if (counter === time) { if (Tournaments.tournaments[room.id].generator.users.size < 2) { self.parse('/tour end'); return self.sendReply('**The tournament was canceled because of lack of players.**'); } return self.parse('/tour start'); } if ((time - counter) === 1) { self.sendReply('**You have ' + (time - counter) + ' minute to sign up for the tournament.**'); } else { self.sendReply('**You have ' + (time - counter) + ' minutes to sign up for the tournament.**'); } counter++; if (!Tournaments.tournaments[room.id].isTournamentStarted) loop(); }, 1000 * 60); }; loop(); return; } if (Number(parts[1]) < 2) return; parts[1] = parts[1].replace(/[^0-9 ]+/g, ''); this.parse('/tour create ' + parts[0] + ', elimination'); this.sendReply('**The tournament will begin when ' + parts[1] + ' players join.**'); var playerLoop = function () { setTimeout(function () { if (!Tournaments.tournaments[room.id]) return; if (Tournaments.tournaments[room.id].generator.users.size === Number(parts[1])) { self.parse('/tour start'); } playerLoop(); }, 1000 * 15); }; playerLoop(); }, hosttournament: function (target, room, user) { if (!this.can('hosttournament')) return; if (target.toLowerCase() === 'end') { if (!Bot.config.hosting[room.id]) return this.sendPm('I\'m not hosting tournaments.'); Bot.config.hosting[room.id] = false; return this.sendReply('I will now stop hosting tournaments.'); } if (Bot.config.hosting[room.id]) return this.sendReply('I\'m already hosting tournaments.'); Bot.config.hosting[room.id] = true this.sendReply('**I will now be hosting tournaments.**'); var self = this, _room = room, _user = user; var poll = function () { if (!Bot.config.hosting[_room.id]) return; setTimeout(function () { if (Poll[_room.id].question) self.parse('/endpoll'); self.parse('/poll Tournament tier?, ' + Object.keys(Tools.data.Formats).filter(function (f) { return Tools.data.Formats[f].effectType === 'Format'; }).join(", ")); setTimeout(function () { self.parse('/endpoll'); Bot.commands.maketournament.call(self, (Poll[_room.id].topOption + ', 2 minute'), _room, _user); }, 1000 * 60 * 2); }, 1000 * 5); }; var loop = function () { setTimeout(function () { if (!Tournaments.tournaments[_room.id] && !Poll[_room.id].question) poll(); if (Bot.config.hosting[_room.id]) loop(); }, 1000 * 60); }; poll(); loop(); }, join: function (target, room, user, connection) { if (!user.can('kick')) return; if (!target || !Rooms.get(target.toLowerCase())) return; if (Rooms.get(target.toLowerCase()).users[Bot.config.name]) return this.sendPm('I\'m already in this room.'); Users.get(Bot.config.name).joinRoom(Rooms.get(target.toLowerCase())); var botDelay = (Math.floor(Math.random() * 6) * 1000) setTimeout(function() { connection.sendTo(room, Bot.config.name + ' has join ' + target + ' room.'); }, botDelay); }, leave: function (target, room, user, connection) { if (!user.can('kick')) return; if (!target || !Rooms.get(target.toLowerCase())) return; Users.get(Bot.config.name).leaveRoom(Rooms.get(target.toLowerCase())); var botDelay = (Math.floor(Math.random() * 6) * 1000) setTimeout(function() { connection.sendTo(room, Bot.config.name + ' has left ' + target + ' room.'); }, botDelay); }, rps: function (target, room, user) { if (!target) return; var options = ['rock', 'paper', 'scissors'], rng = options[Math.floor(Math.random() * options.length)], target = toId(target); if (rng === target) return this.sendReply('Tie!'); if (rng === options[0]) if (target === options[1]) return this.sendReply(user.name + ' wins! I had ' + rng + '.'); if (target === options[2]) return this.sendReply('I win! I had ' + rng + '.'); if (rng === options[1]) if (target === options[2]) return this.sendReply(user.name + ' wins! I had ' + rng + '.'); if (target === options[0]) return this.sendReply('I win! I had ' + rng + '.'); if (rng === options[2]) if (target === options[0]) return this.sendReply(user.name + ' wins! I had ' + rng + '.'); if (target === options[1]) return this.sendReply('I win! I had ' + rng + '.'); }, }; exports.joinServer = joinServer; exports.config = config; exports.parse = parse; exports.commands = commands; joinServer(); <file_sep>/** * Core * Created by CreaturePhil - https://github.com/CreaturePhil * * This is where essential core infrastructure of * Pokemon Showdown extensions for private servers. * Core contains standard streams, profile infrastructure, * elo rating calculations, and polls infrastructure. * * @license MIT license */ var fs = require("fs"); var path = require("path"); var core = exports.core = { stdin: function (file, name) { var data = fs.readFileSync('config/' + file + '.csv', 'utf8').split('\n'); var len = data.length; while (len--) { if (!data[len]) continue; var parts = data[len].split(','); if (parts[0].toLowerCase() === name) { return parts[1]; } } return 0; }, stdout: function (file, name, info, callback) { var data = fs.readFileSync('config/' + file + '.csv', 'utf8').split('\n'); var match = false; var len = data.length; while (len--) { if (!data[len]) continue; var parts = data[len].split(','); if (parts[0] === name) { data = data[len]; match = true; break; } } if (match === true) { var re = new RegExp(data, 'g'); fs.readFile('config/' + file + '.csv', 'utf8', function (err, data) { if (err) return console.log(err); var result = data.replace(re, name + ',' + info); fs.writeFile('config/' + file + '.csv', result, 'utf8', function (err) { if (err) return console.log(err); typeof callback === 'function' && callback(); }); }); } else { var log = fs.createWriteStream('config/' + file + '.csv', { 'flags': 'a' }); log.write('\n' + name + ',' + info); typeof callback === 'function' && callback(); } }, atm: { name: function (online, user) { if (online === true) { return '<strong>' + user.name + '</strong>'; } return '<strong>' + user + '</strong>'; }, money: function (user) { return Core.stdin('money', user); }, display: function (args, info, option) { if (args === 'money') return '&nbsp;tiene ' + info + '&nbsp;PokeDolares.'; }, }, shop: function (showDisplay) { var shop = [ ['Simbolo', 'Un simbolo personalizado junto a tu nick.', 15], ['Declare', 'Puedes hacer un declare en el server', 30], ['Cambio', 'Compras la capacidad de cambiar tu avatar personalizado o tarjeta de entrenador.', 50], ['Avatar', 'Un avatar personalizado.', 75], ['Trainer', 'Tarjeta de entrenador.', 80], ['Chatroom', 'Una sala de chat.', 125] ]; if (showDisplay === false) { return shop; } var shopName = '<center><img src="http://i.imgur.com/xA7ruKZ.png" /><div class="shop">'; var s = shopName; s += '<table border="0" cellspacing="0" cellpadding="5" width="100%"><tbody><tr><th>Nombre</th><th>Descripción</th><th>Precio</th></tr>'; var start = 0; while (start < shop.length) { s = s + '<tr><td><button name="send" value="/buy ' + shop[start][0] + '">' + shop[start][0] + '</button></td><td>' + shop[start][1] + '</td><td>' + shop[start][2] + '</td></tr>'; start++; } s += '</tbody></table><br /><center>Para comprar un producto de la tienda, usa el comando /buy [nombre].</center><br /></div><img src="http://i.imgur.com/fyLaZTn.png" /></center>'; return s; }, };
82fe8e02a09336e3f20a59a7ba34f41dbe136e0f
[ "JavaScript" ]
2
JavaScript
BasedGod7/PH
951301a4728e5a1e6117c9e8b6cc3687bb19ebcc
bf17c5baa40360335dc14ae360c05f69d9de4ccb
refs/heads/master
<file_sep>rootProject.name = 'catStream' include ':app' <file_sep>// Sample app showcasing ListView and Navigator. // Scroll to get more cats, tap the cat to view in fullscreen import React, { AppRegistry, Component, StyleSheet, Text, View, Image, ListView, Navigator, TouchableHighlight } from 'react-native'; import _ from 'lodash'; function cats() { // Parsing XML with RegEx is not recommended, // but I wasn't able to load 'xmldom' package in RN playground return fetch('http://thecatapi.com/api/images/get?format=xml&results_per_page=10&size=small', {method: 'GET'}) .then(response => response.text()) .then(text => { var images = text.split("<image>"); var urlRegex = new RegExp("<url>(.*)<\/url>"); var idRegex = new RegExp("<id>(.*)<\/id>"); return _.chain(images) .map(img => { var url = img.match(urlRegex); var id = img.match(idRegex); if(url != null && id != null) { return { url: url[1], id: id[1] } } else { return null; } }) .filter(x => x!=null) .value(); }); } var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1.id !== r2.id}); var Overview = React.createClass({ _fetchData: function () { cats().then(result=> { var newData = this.state.data.concat(result); this.setState({ data: newData, loading: false, dataSource: ds.cloneWithRows(newData) }) }) }, getInitialState: function () { return { data: [], loading: true } }, componentDidMount: function () { this._fetchData() }, render: function () { if (this.state.loading) { return ( <View style={styles.container}> <Text style={styles.welcome}> Loading... </Text> </View>) } else { return ( <View style={styles.container}> <ListView onEndReached={()=>this._fetchData()} onEndReachedThreshold={600} dataSource={this.state.dataSource} renderRow={(pic) => <TouchableHighlight onPress={()=>this.props.navigator.push({id: 2, url: pic.url})}> <Image key={pic.id} style={{height: 200}} source={{uri: pic.url}}/> </TouchableHighlight> } /> </View> ); } } }); var ImageView = React.createClass({ render: function () { return ( <View style={styles.container}> <TouchableHighlight style={{flex: 1}} onPress={()=>this.props.navigator.pop()}> <Image style={{flex: 1}} source={{uri: this.props.url}}/> </TouchableHighlight> </View>) } }); var App = React.createClass({ _renderScene: function (route, navigator) { if (route.id == 1) { return <Overview navigator={navigator}/> } else if (route.id == 2) { return <ImageView navigator={navigator} url={route.url}/> } }, render: function () { return <Navigator initialRoute={{id: 1}} renderScene={this._renderScene} /> } }); const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'stretch', backgroundColor: '#F5FCFF', } }); AppRegistry.registerComponent('SampleApp', () => App);<file_sep>'use strict'; import React, { Component, StyleSheet, Text, View, Image, ListView, Navigator, TouchableHighlight } from 'react-native'; import cats from './Cats'; import _ from 'lodash'; var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1.id !== r2.id}); var Overview = React.createClass({ _fetchData: function () { cats().then(result=> { var newData = this.state.data.concat(result); this.setState({ data: newData, loading: false, dataSource: ds.cloneWithRows(newData) }) }) }, getInitialState: function () { return { data: [], loading: true } }, componentDidMount: function () { this._fetchData() }, render: function () { if (this.state.loading) { return ( <View style={styles.container}> <Text style={styles.welcome}> Loading... </Text> </View>) } else { return ( <View style={styles.container}> <ListView onEndReached={()=>this._fetchData()} onEndReachedThreshold={600} dataSource={this.state.dataSource} renderRow={(pic) => <TouchableHighlight onPress={()=>this.props.navigator.push({id: 2, url: pic.url})}> <Image key={pic.id} style={{height: 200}} source={{uri: pic.url}}/> </TouchableHighlight> } /> </View> ); } } }); var ImageView = React.createClass({ render: function () { return ( <View style={styles.container}> <TouchableHighlight style={{flex: 1}} onPress={()=>this.props.navigator.pop()}> <Image style={{flex: 1}} source={{uri: this.props.url}}/> </TouchableHighlight> </View>) } }); var App = React.createClass({ _renderScene: function (route, navigator) { if (route.id == 1) { return <Overview navigator={navigator}/> } else if (route.id == 2) { return <ImageView navigator={navigator} url={route.url}/> } }, render: function () { return <Navigator initialRoute={{id: 1}} renderScene={this._renderScene} /> } }); const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'stretch', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); module.exports = App; <file_sep># JSNN2: React Native Source code from live-coding presentation performed at [<NAME> JS meetup #2](http://www.it52.info/events/2016-02-27-js-nn-2) [Slides](http://slides.com/sergeysmyshlyaev/deck/) [Video](https://www.youtube.com/watch?v=FLSrZwPYWeg) You can see the code in action at [React Native playground](https://rnplay.org/apps/x_g_ew) ## To run the code locally Install prerequisites for React Native development: [official instruction](https://facebook.github.io/react-native/docs/getting-started.html#Requirements) ```bash cd source npm install react-native run-ios react-native run-android ``` <file_sep>var _ = require('lodash'); var DOMParser = require('xmldom').DOMParser; function cats() { return fetch('http://thecatapi.com/api/images/get?format=xml&results_per_page=10&size=small', {method: 'GET'}) .then(response => response.text()) .then(text => { var parser = new DOMParser(); var images = parser .parseFromString(text, "text/xml").documentElement .getElementsByTagName("data")[0] .getElementsByTagName("images")[0] .getElementsByTagName("image"); return _.map(images, image => { return { url: image.getElementsByTagName('url')[0].childNodes[0].nodeValue, id: image.getElementsByTagName('id')[0].childNodes[0].nodeValue } }); }); } module.exports = cats;
d7d04c0bdce00db4a337f22f444025f4e3ca06d4
[ "JavaScript", "Markdown", "Gradle" ]
5
Gradle
sesm/JSNN2_React_Native
94fcf313fa1db9ec81930bd4270aa61f27f2e818
47387c537e2a498dcb9312f3079dd7edaba18070
refs/heads/master
<file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import './CreateCard.css'; //Material UI import PropTypes from 'prop-types'; import Fade from '@material-ui/core/Fade'; import Button from '@material-ui/core/Button'; import { withStyles } from '@material-ui/core/styles'; import CircularProgress from '@material-ui/core/CircularProgress'; import Typography from '@material-ui/core/Typography'; import TextField from '@material-ui/core/TextField'; const styles = theme => ({ root: { display: 'flex', flexDirection: 'column', alignItems: 'center', }, button: { margin: theme.spacing.unit * 2, }, placeholder: { height: 40, }, }); class CreateCard extends Component { state = { loading: false, query: 'idle', word_en: '', word_ru: '', image: '', deck_category: Number(this.props.match.params.id), user_id: this.props.state.user.id }; handleChange = (event) => { console.log('in handleChange'); if (event.target.name === 'word_en') { this.setState({ word_en: event.target.value }) } else if (event.target.name === 'word_ru') { this.setState({ word_ru: event.target.value }) } else { this.setState({ image: event.target.value }) } } componentWillUnmount() { clearTimeout(this.timer); } handleClickLoading = () => { this.setState(state => ({ loading: !state.loading, })); }; studyDeck = (event) => { console.log('in studyDeck'); this.props.history.push(`/practice/${this.props.match.params.id}`); } handleClick = () => { clearTimeout(this.timer); if (this.state.query !== 'idle') { this.setState({ query: 'idle', }); return; } this.setState({ query: 'progress', }); this.timer = setTimeout(() => { this.setState({ query: 'success', }); }, 2000); console.log(this.state) this.props.dispatch({ type: 'CREATE_CARD', payload: this.state }); }; render() { const { classes } = this.props; const { loading, query } = this.state; return ( <div className={classes.root}> <h1>Create a Card</h1> <h4><i>To type in Russian, use a keyboard overlay.</i></h4> <form align='center'> <TextField onChange={this.handleChange} name='word_en' required id="standard-required" label="English" className={classes.textField} margin="normal" /> <TextField onChange={this.handleChange} name='word_ru' required id="standard-required" label="Russian" className={classes.textField} margin="normal" /> {/* <TextField onChange={this.handleChange} name='image' required id="standard-required" label="Image URL" className={classes.textField} margin="normal" /> */} <div className={classes.placeholder}> {query === 'success' ? ( <Typography>Success!</Typography> ) : ( <Fade in={query === 'progress'} style={{ transitionDelay: query === 'progress' ? '800ms' : '0ms', }} unmountOnExit > <CircularProgress /> </Fade> )} </div> <Button onClick={this.handleClick} className={classes.button}> {query !== 'idle' ? 'Creating...' : 'Create Card'} </Button> <button onClick={this.studyDeck}> Study Deck </button> </form> {/* <button onClick={this.studyDeck}> Study Deck </button> */} </div> ); } } CreateCard.propTypes = { classes: PropTypes.object.isRequired, }; const mapStateToProps = (state) => ({ state }); // export default withStyles(styles)(CreateCard); export default connect(mapStateToProps)(withStyles(styles)(CreateCard)); // export default connect((mapStateToProps)(CreateCard), withStyles(styles)(CreateCard));<file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import LogOutButton from '../LogOutButton/LogOutButton'; import axios from 'axios'; import DeckItem from '../DeckItem/DeckItem'; // this could also be written with destructuring parameters as: // const UserPage = ({ user }) => ( // and then instead of `props.user.username` you could use `user.username` class YourDecks extends Component { state = { categories: [], } //When the component mounts, immediately GET's the deck info //from the database and assigns response.data to state.categories. //This gets passed down via props to DeckItem.js. componentDidMount() { axios.get('/api/cards/your-decks') .then((response) => { this.setState({ categories: response.data }) }).catch((error) => { console.log(`error in UserPage get request: ${error}`); }) } render() { return ( <div> <h1 align='center'>Your Decks</h1> <h4 align='center'><i>Choose which deck you'd like to review</i></h4> <br/> <br/> <table className="user-decks"> <thead> <tr><th>Examine Deck</th><th>Theme</th><th>Number of Cards</th></tr> </thead> <tbody> {this.state.categories.map((deck, i) => { return <DeckItem history={this.props.history} key={i} id={deck.id} category={deck.name} count={deck.count} /> })} </tbody> </table> <br/> <br/> <br/> </div> ) } } // Instead of taking everything from state, we just want the user info. // if you wanted you could write this code like this: // const mapStateToProps = ({user}) => ({ user }); const mapStateToProps = state => ({ user: state.user, }); // this allows us to use <App /> in index.js export default connect(mapStateToProps)(YourDecks); <file_sep>self.__precacheManifest = [ { "revision": "89a8f2cbfc588d7937b0", "url": "/static/css/main.5f3d7323.chunk.css" }, { "revision": "89a8f2cbfc588d7937b0", "url": "/static/js/main.89a8f2cb.chunk.js" }, { "revision": "fdfcfda2d9b1bf31db52", "url": "/static/js/runtime~main.fdfcfda2.js" }, { "revision": "31ccd8f<PASSWORD>", "url": "/static/js/2.31ccd8f1.chunk.js" }, { "revision": "d518047f3f8c2576f8208fc64b95cc8c", "url": "/index.html" } ];<file_sep>import { put, takeLatest } from 'redux-saga/effects'; import axios from 'axios'; //This saga exists to let other components access deck id's function* getDeck(action) { try { //action.payload = id of category in DB console.log(action.payload) const serverResponse = yield axios.get(`/api/cards/${action.payload}`, action.payload); yield put({type: 'SET_CARDS', payload: serverResponse.data}); } catch(error) { console.log('error in getDeck saga: ', error); } } //this will allow the user to add a new card to the database function* createCard(action) { try { yield axios.post('/api/cards', action.payload) } catch(error) { console.log('error in createCard saga: ', error); } } function* deleteCard(action) { try { console.log(`action.payload: ${action.payload}`); yield axios.delete(`api/cards/${action.payload.id}`, action.payload.id) const nextAction = {type: 'GET_CARDS', payload: action.payload.category}; yield put(nextAction); } catch(error) { console.log(`error in deleteCard saga: ${error}`); } } function* getUserStats(action) { console.log(`in getUserStats: ${action.payload.deck_id}`); try { const serverResponse = yield axios.get(`api/cards/stats/${action.payload.deck_id}`, action.payload); yield put({type: 'SET_STATS', payload: serverResponse.data}); } catch(error) { console.log(`error in getUserStats saga: ${error}`); } } function* postGuess(action) { try { yield axios.post(`api/cards/guess/${action.payload.card_id}`, action.payload); } catch(error) { console.log(`error in postGuess saga: ${error}`); } } function* decksSaga() { yield takeLatest('GET_CARDS', getDeck); yield takeLatest('GET_USER_STATS', getUserStats); yield takeLatest('CREATE_CARD', createCard); yield takeLatest('DELETE_CARD', deleteCard) yield takeLatest('POST_GUESS', postGuess); } export default decksSaga;<file_sep># Learn Russian ## Prerequisites Before you get started, make sure you have the following software installed on your computer: - [Node.js](https://nodejs.org/en/) - [PostrgeSQL](https://www.postgresql.org/) - [Nodemon](https://nodemon.io/) ## Create database and table Create a new database called `prime_app` and create a `person` table: ```SQL CREATE TABLE "person" ( "id" SERIAL PRIMARY KEY, "username" VARCHAR (80) UNIQUE NOT NULL, "password" VARCHAR (1000) NOT NULL ); ``` ## Development Setup Instructions * `npm install` * `npm run server` * `npm run client` ## How to Use Log in as me: ``` Username: Dion Password: <PASSWORD> ``` Or register as a new user. When logged in, the user will be presented with thematically organized decks of cards. This is where the user will choose which deck to study. Upon clicking on a deck, the user is presented with each of the cards in that deck. From there, cards can be created or deleted from the deck. When ready, click “Study Deck”. Then, to study the deck, click “Start”. The four images which render will be randomly pulled from the deck. The Russian word you at the top is the word in question which the user will try to connect to the corresponding image. If the image is correctly guessed, four new cards will render on the screen. If the guess is incorrect, an alert will appear at the top of the page prompting the user to guess again. <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; class CardItem extends Component { state = { category: this.props.category, id: this.props.id } deleteCard = (event) => { this.props.dispatch({ type: 'DELETE_CARD', payload: this.state}); // alert('successfully deleted card'); } render() { return( <tr> <td> {this.props.russian} </td> <td> {this.props.english} </td> <td> <button onClick={this.deleteCard}>Delete</button> </td> </tr> ) } } const mapStateToProps = (state) => ({ state }); export default connect(mapStateToProps)(CardItem);<file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import PracticePageItem from './../PracticePageItem/PracticePageItem'; import './PracticePage.css' class PracticePage extends Component { state = { domCards: [], guessCard: undefined } seeStats = (event) => { this.props.history.push(`/stats/${this.props.match.params.id}`); } returnHome = (event) => { this.props.history.push('/home'); } componentDidMount() { this.props.dispatch({ type: 'GET_CARDS', payload: this.props.match.params.id }); } randomElement = (array) => { //array.length represents the maximum acceptable number in the range let randomNum = Math.floor(Math.random() * Math.floor(array.length)); return array[randomNum]; } //without this function the guessCard would always be the first card to append, //making studying predictable and therefore disfunctional shuffleDomCards = (array) => { let i, j, x; for (i = array.length - 1; i > 0; i--) { j = Math.floor(Math.random() * (i + 1)); x = array[i]; array[i] = array[j]; array[j] = x; } return array; } selectACard = () => { //assign an empty array let newDomCards = []; //completly random card from the deck const guessCard = this.randomElement(this.props.state.deckReducers); this.setState({ guessCard: guessCard, }) //newDomCards now has a length of one newDomCards.push(guessCard); //if the deck has less than 4 items, this if statement // will prevent an infinite loop if (this.props.state.deckReducers.length < 4) { return; } //three times we pull a random card from the entire deck for (let i = 0; i < 3; i += 1) { let allCardsFromDeck = this.props.state.deckReducers; const randomCard = allCardsFromDeck[Math.floor(Math.random() * allCardsFromDeck.length)]; //checks to see if the new random card is already in newDomCards const foundCard = newDomCards.find((element) => { return element.word_en === randomCard.word_en }) //if the card is not already in the deck, we push to newDomCards, //if the card is already in the deck, pull a new random card if (foundCard) { i = i - 1; } else { newDomCards.push(randomCard); } } this.setState({ domCards: newDomCards, }) } render() { return ( <div id='container'> <h1 align='center'>Practice Page</h1> {/* this line will conditionally render a random card */} <h2>{this.state.guessCard !== undefined ? this.state.guessCard.word_ru : null}</h2> {this.state.guessCard !== undefined ? this.shuffleDomCards(this.state.domCards).map((card, i) => { return ( <div class="row" align='center'> <div class='column' align='center'> <PracticePageItem history={this.props.history} key={i} english={card.word_en} russian={card.word_ru} category={card.name} categoryId={card.category} guessCard={this.state.guessCard} selectACard={this.selectACard} image={card.image} id={card.id} /> </div> </div> ) }) : <h4 align='center'><i>Click <button onClick={this.selectACard}>Start</button> when ready to begin</i></h4> } <br/> <br/> {/* <button onClick={this.seeStats}>See Stats</button> */} <button id='home-btn' onClick={this.returnHome}>Home</button> </div> ) } } const mapStateToProps = (state) => ({ state }); export default connect(mapStateToProps)(PracticePage); <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import CardItem from './../CardItem/CardItem'; import DeckDetailTheme from './../DeckDetailTheme/DeckDetailTheme'; import axios from 'axios'; class DeckDetail extends Component { goHome = (event) => { this.props.history.push('/home'); } handleAddNew = (event) => { //this.props.match.params is {"id": whatever the deck id is} this.props.history.push(`/create/${this.props.match.params.id}`); } studyDeck = (event) => { this.props.history.push(`/practice/${this.props.match.params.id}`); } //https://via.placeholder.com/200 //When the component mounts, an action will dispatch //action of type "GET_CARDS" to the decksSaga componentDidMount() { this.props.dispatch({ type: 'GET_CARDS', payload: this.props.match.params.id}); } render() { return ( <div align='center'> <h1 align='center'>Deck Detail</h1> <h4 align='center'><i>Here are all the cards in the deck</i></h4> <br/> <button onClick={this.goHome}>Home</button> <button onClick={this.handleAddNew}>Add New Card</button> <button onClick={this.studyDeck}>Study Deck</button> <br/> <br/> <br/> <table> <thead> <tr><th>Russian Word</th><th>English Translation</th><th>Remove Card</th></tr> </thead> <tbody> {this.props.state.deckReducers.map((card, i) => { return <CardItem history={this.props.history} key={i} english={card.word_en} russian={card.word_ru} category={card.category} id={card.id}/> })} </tbody> </table> <br/> <br/> <br/> </div> ) } } const mapStateToProps = (state) => ({ state }); export default connect(mapStateToProps)(DeckDetail);<file_sep>//cards is the name of the reducer import cards from '../../src/redux/reducers/deckReducers.js'; test('cards should return initially be an empty array', () => { const action = []; const returnedState = cards(undefined, action); expect(Array.isArray(returnedState)).toBe(true); expect(returnedState.length).toBe(0); }); test('cards should be able to add a card', () => { const action = {type: 'SET_CARDS', payload: {word_en: 'Dog'}}; const returnedState = cards(undefined, action); expect(returnedState).toEqual({word_en: 'Dog'}); }); test(`cards should ignore actions it doesn't care about`, () => { const action = {type: 'IGNORE_ME'}; const returnedState = cards(undefined, action); expect (returnedState).toEqual([]); });<file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import './DeckItem.css'; class DeckItem extends Component { //When the user clicks on an individul deck, //push to history the individual deck URL handleClick = (event) => { console.log(this.props.id); this.props.history.push(`/deck/${this.props.id}`); } //end handleClick render() { return( <tr> <td onClick={this.handleClick}> <button>View Cards</button> </td> <td> {this.props.category} </td> <td> {this.props.count} </td> </tr> ) } } const mapStateToProps = (state) => ({ state }); export default connect(mapStateToProps)(DeckItem);<file_sep>const express = require('express'); const pool = require('../modules/pool'); const router = express.Router(); //This GET request runs when the user is on the YourDecks page //It is reponsible for displaying each of the user's decks from the DB router.get('/your-decks', (req, res) => { console.log(`req.body: ${req.body}`); if (req.isAuthenticated()) { console.log(`req.user: ${req.user}`); const queryText = `select "category".*, count("card"."category") as "count" from "category" join "card" on "category"."id" = "card"."category" group by "category"."id";`; pool.query(queryText) .then((results) => { res.send(results.rows); }).catch((error) => { console.log(`Error in GET /decks: ${error}`); res.sendStatus(500); }) } else {res.sendStatus(403);} }) //this request allows the user to click on a particular deck and only see //the cards from that deck from the database, regardless of whether the cards are learned or not router.get('/:id', (req, res) => { console.log('req.params: ', req.params); //JOIN query joins cards table and category table to select //only the cards of a particular category const queryText = `select "word_en", "word_ru", "image", "category", "name", "card"."id" from "card" join "category" on "card"."category" = "category"."id" where "category" = $1;`; pool.query(queryText, [req.params.id]) .then((sqlResult) => { //sqlResults refers to the joined card and category tables //We will send this data to the saga when we call router.get('/cards'); res.send(sqlResult.rows); res.sendStatus(200); }).catch((sqlError) => { console.log(`Error in completing /cards query: ${sqlError}`); res.sendStatus(500); }) }) router.get('/stats/:id', (req, res) => { console.log(`in stats router: ${req.body}`); const queryText = `select * from "guesses" where "time_stamp" < $1;`; pool.query(queryText, [today.getDate()]) .then((sqlResult) => { res.send(sqlResult.rows); res.sendStatus(200); }).catch((error) => { console.log(`error in stats router: ${error}`); res.sendStatus(500) }) }) //this request POSTs a new card to the database router.post('/', (req, res) => { console.log(req.body) const newCard = req.body; const queryText = `insert into "card" ("word_en", "word_ru", "image", "user_id", "category") values ($1, $2, $3, $4, $5);`; // req.user.id is created by passport for logged in users const queryValues = [ newCard.word_en, newCard.word_ru, newCard.image, req.user.id, newCard.deck_category ]; pool.query(queryText, queryValues) .then((response) => { console.log('response: ', response) res.sendStatus(201); }) .catch((error) => { console.log('Error completing INSERT card query', error); res.sendStatus(500); }); }); //this will update the 'guesses' table on whether the user guessed a cards correctly or not router.post('/guess/:id', (req, res) => { console.log('in guess post router'); const newGuess = req.body; const queryText = `insert into guesses ("user_id", "card_id", "guessed_correctly") values ($1, $2, $3);`; const queryValues = [ newGuess.user_id, newGuess.card_id, 'true' ]; pool.query(queryText, queryValues) .then((response) => { console.log('response', response); res.sendStatus(201); }).catch((error) => { console.log(`error in guess post router: ${error}`); }) }); //this router deletes individual cards router.delete('/:id', (req, res) => { console.log(`req.params: ${req.params}`); const queryText = `delete from "card" where "id" = $1;`; pool.query(queryText, [req.params.id]) .then(() => { res.sendStatus(200); }).catch((error) => { console.log(`Error in deleting card: ${error}`); res.sendStatus(500); }) }) module.exports = router;<file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; class StatsPage extends Component { state = { user_id: this.props.state.user.id, deck_id: this.props.match.params.id } componentDidMount() { this.props.dispatch({type: 'GET_USER_STATS', payload: this.state}); // this.props.dispatch({type: 'GET_CARDS', payload: this.props.match.params.id}); } render() { return( <div> <p>User id: {JSON.stringify(this.props.state.user.username)}</p> <p>deck id: {JSON.stringify(this.props.match.params.id)}</p> {JSON.stringify(this.props.state.deckReducers)} </div> ) } } const mapStateToProps = (state) => ({ state }); export default connect(mapStateToProps)(StatsPage);<file_sep>const testServer = require('supertest'); const app = require('../server'); test('It should respond 200 to logout route', () => { return testServer(app).post('api/user/logout').then( (response) => { expect (response.statusCode).toBe(200) }) });<file_sep>CREATE TABLE "person" ( "id" SERIAL PRIMARY KEY, "username" VARCHAR (80) UNIQUE NOT NULL, "password" VARCHAR (1000) NOT NULL ); CREATE TABLE "user" ( "id" SERIAL PRIMARY KEY, "username" varchar(40) NOT NULL, "password" varchar(40) NOT NULL ); CREATE TABLE "card" ( "id" SERIAL PRIMARY KEY, "word_en" varchar(40) NOT NULL, "word_ru" varchar(40), "image" VARCHAR(255), "user_id" INT NOT NULL, "date" DATE NOT NULL DEFAULT CURRENT_DATE, "category" INT NOT NULL ); CREATE TABLE "guesses" ( "user_id" INT NOT NULL, "card_id" INT NOT NULL, "guessed_correctly" BOOLEAN NOT NULL DEFAULT 'false', "date" DATE NOT NULL DEFAULT CURRENT_DATE, ); CREATE TABLE "category" ( "id" SERIAL PRIMARY KEY, "name" varchar(40) NOT NULL ); ALTER TABLE "card" ADD CONSTRAINT "card_fk0" FOREIGN KEY ("user_id") REFERENCES "user"("id"); ALTER TABLE "card" ADD CONSTRAINT "card_fk1" FOREIGN KEY ("category") REFERENCES "category"("id"); ALTER TABLE "guesses" ADD CONSTRAINT "guesses_fk0" FOREIGN KEY ("user_id") REFERENCES "user"("id"); ALTER TABLE "guesses" ADD CONSTRAINT "guesses_fk1" FOREIGN KEY ("card_id") REFERENCES "card"("id");<file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import './PracticePageItem.css'; class PracticePageItem extends Component { state = { deck_id: this.props.categoryId, card_id: this.props.id, user_id: this.props.state.user.id } // componentDidMount() { // this.compare(); // } //this component will let the user know if their guess //was correct or incorrect on click. If the guess is correct, the cards re-render compare = () => { console.log('clicked', this.props); if (this.props.english === this.props.guessCard.word_en && this.props.english !== '') { // console.log('correct', this.props.id); this.props.dispatch({type: 'POST_GUESS', payload: this.state}) this.props.selectACard(); } else { alert('Try Again.'); } } //end compare render() { return ( <div class='container'> <img src={this.props.image} onClick={this.compare}/> </div> ) } } const mapStateToProps = (state) => ({ state }); export default connect(mapStateToProps)(PracticePageItem);
fb0f1d26675a188681c00ebcba91fd948d507f0a
[ "JavaScript", "SQL", "Markdown" ]
15
JavaScript
dionroloff/LearnRussian
dcec465134ba70ed77560e595407a5c710930ad6
5c6c546b5accda7f841c01f8fba81064004d274b
refs/heads/master
<repo_name>inaki-ba/GettingCleaningData<file_sep>/run_analysis.R run_analysis <- function() { ## Sets up vectors, including activity lables, and subsets of variables: means and stds l_activities <-read.table("activity_labels.txt") t_activities<-read.table("features.txt") i_activities<-grep("mean|std", t_activities$V2) s_activities<-grep("mean|std", t_activities$V2, value = TRUE) ## Shapes train sets, including column nanes, activity names for the activiy variable t_train<-read.table("train/X_train.txt") t_train_lab<-read.table("train/y_train.txt") t_train_sub<-read.table("train/subject_train.txt") d_train<-data.frame(t_train_sub, t_train_lab, t_train[,i_activities]) colnames(d_train) <- c("Subject", "Activity", c(s_activities)) d_train$Activity<-l_activities$V2[d_train$Activity] ## Shapes test sets, including column nanes, activity names for the activiy variable t_test<-read.table("test/X_test.txt") t_test_lab<-read.table("test/y_test.txt") t_test_sub<-read.table("test/subject_test.txt") d_test<-data.frame(t_test_sub, t_test_lab, t_test[,i_activities]) colnames(d_test) <- c("Subject", "Activity", c(s_activities)) d_test$Activity<-l_activities$V2[d_test$Activity] ## Merges the two sets, and calculates the summary set with averages per activity/subject final_frame<-rbind("Train"=d_train, "Test"=d_test) k<-1 final_frame2<-final_frame[1,] for( i in 1:nrow(l_activities)) { for(j in 1:30) { subs<-final_frame$Subject==j & final_frame$Activity==l_activities[i,2] sub_frame <- sapply( final_frame[subs,3:ncol(final_frame)], function(x) mean(x)) final_frame2[k,] = c(j, as.character(l_activities[i,2]), sub_frame) k<-k+1 } } ## Returns the summary set: 180 rows, 81 columns final_frame2 }<file_sep>/README.md # GettingCleaningData ================================== Getting and Cleaning Data Assignment Version 1.0 ====================================== <NAME> ====================================== R Script called run_analysis.R that retrieves data stored in several txt files, corresponding to information collected from the accelerometers of the Samsung Galaxy S smartphone. The script manipulates the source information to achieve the following assignment objectives: 1. Merges the training and the test sets to create one data set. 2. Extracts only the measurements on the mean and standard deviation for each measurement. 3. Uses descriptive activity names to name the activities in the data set 4. Appropriately labels the data set with descriptive variable names. 5. From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject. The dataset includes the following files: ========================================= - 'Summary_set.txt': A file containing the data generated by the R script: a tidy data set with the average of each variable for each activity and each subject: 30 subjects x 6 activities: 180 rows.
7dfe705ed77477819e491a882a4eedb239184d5d
[ "Markdown", "R" ]
2
R
inaki-ba/GettingCleaningData
9bb305aed3b20ba3987781b4148f749bd3e89475
d229361b7a2d48a650bb8a21c331386c80694b0e
refs/heads/master
<repo_name>SimonSaid1996/goPractice<file_sep>/socket_server.go package main //note that the code source is from ://note that the code source is from :https://blog.csdn.net/caileigood/article/details/84661746 //the code is only used for learning pursose, not for bussinesses import ( "fmt" "log" "net" "time" ) func startServer(){ listener, err := net.Listen("tcp", "127.0.0.1:12031") //use the same ip address to do the handshake defer listener.Close() //defer must be used for a following function call, enable to auto close the file after reading and working on the files, can also be used in mutex lock if err != nil{ //print error if error occurs fmt.Println(err) } for { //blocks until connected with client conn, err := listener.Accept() //accept the connection, listening to the client request if err != nil{ fmt.Println(err) continue } go receiveAndSendMsg(conn) //working properly so that can send messages //when one goroutine ends, it will not affect other goroutine's functionality //time.Sleep(1*time.Second) //to sleep in order to separte user connecting } } func receiveAndSendMsg(conn net.Conn){ defer conn.Close() log.Println(conn.RemoteAddr().String()) buffer := make([]byte, 50) //can connect with maximum of 50 users for{ conn.Write([]byte("hi, client, this is server:"+ time.Now().Format("10:04:05"))) _, err := conn.Read(buffer) if err!= nil{ //have error, have to break the connection return } log.Printf("msg is : %v\n", string(buffer)) //read stringfied byte message //time.Sleep(1 * time.Second) } } func main() { startServer() }<file_sep>/channelPractice.go package main import "fmt" //note that the code source is :https://blog.csdn.net/caileigood/article/details/84766188 //please don't use the code for purposes other than self-educating func testGoroutine(ch chan string, param string){ //means that the channel pass strings fmt.Println("testing") ch <- param //passing the parameter into channel } func main() { ch := make(chan string, 3) //making a string that can hold 3 elements at once go testGoroutine(ch, "1") go testGoroutine(ch, "2") go testGoroutine(ch, "3") //for some reasons, channel will be printing from the back? read channel more for i :=0; i< cap(ch); i++{ //will be deadlocked if not filling out all the blank spaces fmt.Println(<-ch) //print out info from channel } }<file_sep>/socket_client.go package main //note that the code source is from ://note that the code source is from :https://blog.csdn.net/caileigood/article/details/84661746 //the code is only used for learning pursose, not for bussinesses import ( "fmt" "net" "os" "time" ) func startClient(){ conn,err := net.Dial("tcp", "127.0.0.1:12031") //the conn here is the connection, tcp three way handshake defer conn.Close() if err != nil{ fmt.Println(err) } receiveAndSendMsg(conn) } func receiveAndSendMsg(conn net.Conn){ for{ buffer := make([]byte, 50) _, err := conn.Read(buffer) //because the server is writing first, client side read first if err != nil{ //stop the program os.Exit(-1) } fmt.Println(string(buffer)) str := "hello, i am client:"+time.Now().Format("10:04:05") conn.Write([]byte(str)) time.Sleep(1 * time.Second) } } func main() { startClient() }<file_sep>/README.md # goPractice 3 go practice codes inspired from online, just to learn how to write go code note that below are three small go programs, socket_client and socket_server works together. i didn't create those code myself, those code are inspired from the corresponding web sources listed on the top of the codes. i am only using the code as a way of self-practice and self-learning purpose <file_sep>/practiceGo.go package main //note that this practice is inspired by https://blog.csdn.net/caileigood/article/details/84107879, most of the functions are trying to solve the problems in the beginnning part of the pracitce //this is just a small practice for golang, hopefully will have some better projects in go in the future import( "fmt" "math" "strings" ) //1. get ride of space and change line in a string func modifyString(){ test_string := "what\n is in your shose?\n i don't know!" test_string = strings.Replace(test_string, "\n", "", -1) test_string = strings.Replace(test_string, " ", "", -1) fmt.Println(test_string) } //2.finding if the num is even or odd func judgeEven(num int){ if num%2 == 0{ fmt.Println("it is even") }else{ fmt.Println(" it is odd") } } //3. finding the prime number withing 100, note that prime numbers can only be divided by 1 or itself //probably have to try finding the number one by one, just need to check nums less than itself, for loop func printPrime(){ isPrime := true for i := 1; i < 100; i++{ for j := 1; j < i; j++{ if i != j && j != 1 && i%j == 0 { isPrime = false break } } if isPrime{ fmt.Println(" %d is a prime", i) } isPrime = true //reset the boolean } } //4. multiplication talbe withing 9*9 func multiplication(){ for i := 1; i <= 9; i++{ for j := 1; j <= i; j++{ fmt.Printf(" %d*%d=%d\t", i, j, i*j)//if wanting to print multiple numbers, must do the c style printing line } fmt.Println() //for formating } } //5.hui yang's triangle, will print out the number of lines with the triangle depending on the num of the rows func triangleNum(rows int){ numbers := make([]int, rows) //making an array length of rows, the difference between make and new is that make can give the uninitialized first element the correct type, not nill for i := 0; i < rows; i++{ for j:= 0; j < (i + 1); j++{ //if it is the first row, first column, print 1 //if it is the first column or the last column, print out 1 //if not, it equals to the previous line's above 2 value's sum // the number row here is used to recode numbers var num int var numLen = len(numbers) if j ==0 || j == i{ num = 1 }else{ num = numbers[numLen - i] + numbers[ numLen - i - 1] } numbers = append(numbers, num) //the way of appending requires the original array and the new elements fmt.Print(num, " ") } fmt.Println("") }//if using new to initialize, it will tell you it is nill and can't add more, also, new can't be initialized with a size } //6. to separate the students' scores by a switch statement, depending on the score value func separate_scores(score int) string{ var letter_grade string switch{ case score >= 90: letter_grade = "A" case score < 90 && score >= 60: letter_grade = "B" case score < 60: letter_grade = "C" default: letter_grade = "D" } return letter_grade } //7. define a structure, including x and y axis, finding the 2d distance between those two points type loc struct{ x float64 y float64 } func distance_calculator(p1, p2 loc)float64{ return math.Pow(p1.x-p2.x, 2) + math.Pow(p1.y-p2.y, 2) } //8.using iota to form a week, using 1-7 to represent the week //iota can only be used in the const expression, can't be used separately //also note that const need to use small bracket const( start = iota //not sure in the original version it uses "_ int = iota" monday tuesday wednesday thursday friday saturday sunday ) //9. define 2 slices, compare those two slice, can compare the lenth and the elements inside of the two slices //the compared type will be set as strings //not sure how to use generic in go, seems like the documentation is missing or i didn't find them func sliceComparator(ar1, ar2 []string) bool{ if len(ar1) != len(ar2){ return false }else{ for i,_ := range ar1{ //only need the index here, didn't use the value, well, can also use value if u really want if ar1[i] != ar2[i]{ return false } } return true } } //10. define a map, use student name as the key and the score as the value, find the value by keys and delete the index in which the corresponding key is not found //need to use pointer here in order to change the actual data from outside the function func stuSearch(stuN *[]string, name_score map[string]int){ for i, name := range *stuN{ score, exist := name_score[name] if !exist && score <= 60{ remove(stuN, i) } } } func remove(stuN *[]string, i int){ //basically shift everything behind the index i to the previous one position var temp []string = *stuN //copy the same content for j := i; j < len(temp)-1; j++{ temp[j] = temp[j+1] } *stuN = temp[:len(temp)-1] //copy everything down to the original array } func main(){ //modifyString() //judgeEven(2) //printPrime() //multiplication() //triangleNum(10) /*var score string= separate_scores(88) fmt.Println(score)*/ /*p1 := loc{-2, 3} //need to put loc in front to specify the data type p2 := loc{1, 2} result := distance_calculator(p1, p2) fmt.Println(result)*/ //fmt.Println(monday, tuesday, sunday) /*ar1 := []string{"a", "b", "c"} ar2 := make([]string, 3) copy(ar2, ar1) //or according to the websiteonline, u can use ar2 := ar1[:] result := sliceComparator(ar1, ar2) fmt.Println(result)*/ stu_arr := []string{"pierogie", "dumpling", "bum", "general tzuo's chicken", "taco"} score_map := map[string]int{"pierogie":70, "dumpling":90, "rosted duck":65} stuSearch(&stu_arr, score_map) //sending the address of the stu_arr to the fuction fmt.Println(stu_arr) }
46a5f60c2f377b5855700882f95bea35290b3b8a
[ "Markdown", "Go" ]
5
Go
SimonSaid1996/goPractice
936730d8954e1ae0f7e754f81e1b14dcd4d686f0
990ea317bd85dd3c1d20d3aa702d3d3dd5c87102
refs/heads/master
<file_sep># Ruby-Asteroids <file_sep>require 'ray' #Define Window Title Ray.game "Asteroids", :size => [800, 600] do register { add_hook :quit, method(:exit!) } scene :square do #Create Ship and Define parmeters @ship = Ray::Polygon.new @ship.pos = [400,290] @ship.add_point([-8,10]) @ship.add_point([8,10]) @ship.add_point([0,-10]) @ship.filled = false @ship.outlined = true @vel_x = 0.0 @vel_y = 0.0 @bullets = [] @abullets = [] @bull_vel_x = 0.0 @bull_vel_y = 0.0 @lives = 3 @score = 0 @level = 1 @flame = Ray::Polygon.new # @flame.pos = [400,290] @flame.add_point([-4, 10]) @flame.add_point([0, 20]) @flame.add_point([-4, 10]) @flame.filled = true @ast_vel= [rand(-3...3),rand(-3...3)] @al_vel = [rand(-3...3),rand(-3...3)] @aliens=[] @asteroids = 3.times.map do a = Ray::Polygon.rectangle([0, 0, 50, 50], Ray::Color.white) a.pos = [rand(600..800), rand(0..600)] a.filled = false a.outlined = true a.outline = Ray::Color.white a end @asteroids += 3.times.map do a = Ray::Polygon.rectangle([0, 0, 50, 50], Ray::Color.white) a.pos = [rand(0..300), rand(0..600)] a.filled = false a.outlined = true a.outline = Ray::Color.white a end always do puts @flame[1].pos puts @ship[1].pos puts "" if holding? key(:up) @vel_x += Math::sin(@ship.angle / (180 / Math::PI)) * 0.5 @vel_y -= Math::cos(@ship.angle / (180 / Math::PI)) * 0.5 if @flame[1].pos.y < @flame[0].pos.y+20 @flame[1].pos += [0,0.3] end end if holding? key(:left) @ship.angle -= 4.5 end if holding? key(:right) @ship.angle += 4.5 end @ship.pos += [@vel_x, @vel_y] @flame.pos = @ship.pos @flame.angle = @ship.angle @vel_x *= 0.97 @vel_y *= 0.97 #pass through screen if @ship.pos.x > 800 @ship.pos -= [800, 0] elsif @ship.pos.x < 0 @ship.pos += [800, 0] elsif @ship.pos.y < 0 @ship.pos += [0, 600] elsif @ship.pos.y > 600 @ship.pos -= [0, 600] end if holding? key(:space) if rand(5) == 1 @bullets += 1.times.map do b = Ray::Polygon.rectangle([0,0,2,2], Ray::Color.white) b.pos = [@ship.pos.x, @ship.pos.y] @bull_vel_x = 0.0 @bull_vel_y = 0.0 @bull_vel_x += Math::sin(@ship.angle / (180 / Math::PI)) * 20 @bull_vel_y -= Math::cos(@ship.angle / (180 / Math::PI)) * 20 b end end end if rand(200)==100 @ast_vel = [rand(-5...5), rand(-5...5)] end if rand(100)==50 @al_vel = [rand(-5...5), rand(-5...5)] end if @asteroids.empty? && @aliens.empty? @level += 1 @aliens = @level.times.map do a = Ray::Polygon.circle([0, 0], 10, Ray::Color.red) a.pos = [rand(0..800), rand(0..600)] a.filled = false a.outlined = true a.outline = Ray::Color.red a end end @asteroids.each do |a| a.pos += @ast_vel if a.pos.x > 800 a.pos -= [800, 0] elsif a.pos.x < 0 a.pos += [800, 0] elsif a.pos.y < 0 a.pos += [0, 600] elsif a.pos.y > 600 a.pos -= [0, 600] end end @bullets.each do |b| if b.pos.x > 800 @bullets.delete(b) elsif b.pos.x < 0 @bullets.delete(b) elsif b.pos.y < 0 @bullets.delete(b) elsif b.pos.y > 600 @bullets.delete(b) end @asteroids.each do |a| if [b.pos.x, b.pos.y, 2, 2].to_rect.collide?([a.pos.x, a.pos.y, 50, 50]) @bullets.delete(b) @score += 100 if a.scale == [0.6, 0.6] @asteroids.delete(a) else a.scale = [0.6, 0.6] end end end @aliens.each do |a| if [b.pos.x, b.pos.y, 2, 2].to_rect.collide?([a.pos.x, a.pos.y, 20, 20]) @bullets.delete(b) @score += 400 @aliens.delete(a) end end #elsif condition b.pos += [@bull_vel_x, @bull_vel_y] b end @asteroids.each do |a| if [@ship.pos.x, @ship.pos.y, 16, 20].to_rect.collide?([a.pos.x, a.pos.y, 50, 50]) @lives -= 1 @asteroids.delete(a) end end @aliens.each do |al| if al.pos.x > 800 al.pos -= [800, 0] elsif al.pos.x < 0 al.pos += [800, 0] elsif al.pos.y < 0 al.pos += [0, 600] elsif al.pos.y > 600 al.pos -= [0, 600] end al.pos += @al_vel al.angle = @ship.angle + 180 if rand(30) == 15 @abullets += 1.times.map do b = Ray::Polygon.rectangle([0,0,2,2], Ray::Color.red) b.pos = [al.pos.x, al.pos.y] @abull_vel_x = 0.0 @abull_vel_y = 0.0 @abull_vel_x += Math::sin(al.angle / (180 / Math::PI)) * 10 * rand(0.5...1.5) @abull_vel_y -= Math::cos(al.angle / (180 / Math::PI)) * 10 * rand(0.5...1.5) b end end end @abullets.each do |ab| if ab.pos.x > 800 @abullets.delete(ab) elsif ab.pos.x < 0 @abullets.delete(ab) elsif ab.pos.y < 0 @abullets.delete(ab) elsif ab.pos.y > 600 @abullets.delete(ab) end if [@ship.pos.x, @ship.pos.y, 16, 20].to_rect.collide?([ab.pos.x, ab.pos.y, 2, 2]) @abullets.delete(ab) @lives -= 1 end #elsif condition ab.pos += [@abull_vel_x, @abull_vel_y] ab end if @flame[1].pos.y > @flame[0].pos.y @flame[1].pos -= [0, 0.1] end end render do |win| # if @game_over #win.draw text("YOU LOST", :at => [180,180], :size => 60) if @lives <= 0 win.draw text("YOU LOST", :at => [180,180], :size => 60) win.draw text("Score:" + @score.to_s, :at => [0,0], :size => 20) else win.draw @ship win.draw text("Lives:" + @lives.to_s, :at => [0,0], :size => 20) win.draw text("Score:" + @score.to_s, :at => [100,0], :size => 20) win.draw @flame @bullets.each do |b| win.draw b end @asteroids.each do |a| win.draw a end @aliens.each do |al| win.draw al end @abullets.each do |ab| win.draw ab end end end end scenes << :square end =begin Can't get flame to work??????????????????????? Tommorow: Finish Missle game outline snake game breakout game =end
7e91ea3ff1fd6172c8a9ddf4d13b3c60623122d4
[ "Markdown", "Ruby" ]
2
Markdown
paulurbano/Ruby-Asteroids
69aea68ca3d39d67a88b27c71188046761e6b0e2
66a21f6c3c779c57c96352364a1cd98dbe2cff5e
refs/heads/master
<file_sep># Command-Search ## 概要 CとWindows APIを使って作成したコマンドプロンプトのコマンドライン上でweb検索を行えるよう機能を補完するツールです。 ## 動作環境 動作確認済み * Windows10 動作環境がWindowsで動作するはずです。 ## ダウンロード/やり方 releaseより最新バージョンをダウンロードし、好きなところに解答し、cmds.exeを好きなフォルダへ保存してください(保存場所がインストール場所になります)。 インストールしたフォルダのPathを通し、どこの場所からでもcmds.exeを起動できるように設定します。 Pathの通し方は検索するとわかりやすく解説してくれているサイトが多数あるため、ここでは割愛させて頂きます。 **ファイル名を変更するとその名前でコマンドを使えます(cmds.exeをopen.exeに変更してPathを通すと /open 〇〇 〇〇 のようにコマンドを変更できます)。** ## 使用方法 コマンドライン上で操作を行います。   cmds -list [-list]は登録されているコマンドリストを表示します。 cmds -add [command] [URL] コマンドを登録します。コマンドはURLを打ちやすいよう省略したもので、自分で好きなよう設定することができます。 URLは検索した際のURLの**キーワードを抜いた部分**を登録してください。 (例:https://www.google.com/search?q=) cmds -del [command] 登録したコマンドの削除を行います。 cmds [command] [Words] 登録したコマンドで検索を行います。Wordsの部分に検索ワードを入れることで、コマンドのサイトでワード検索を行います。 ## バージョン履歴 **v1.00(2020/08/30)** 初期バージョンです。 (2020/09/20)コミットされた日付けとReleasesされた日で時間差がありますが、これはReleasesのみを先に行っていたためです。時間差はありますがv1.00よりソースファイルの変更点はありません。 <file_sep>#include <stdio.h> #include <strings.h> #include <Windows.h> #define S 64 #define M 124 #define L 256 void readcommands(); void readlinks(); void viewlists(); void addcommand(char *a); void addlink(char *a); void delcommand(char *a); char commands[S][S]; char links[S][M]; char path[L]; char drive[MAX_PATH+1],dir [MAX_PATH+1],fname[MAX_PATH+1],ext [MAX_PATH+1]; char commandspath[L]; char linkspath[L]; int main(int argc, char *argv[]) { //pathの読み込み(read PATH) if(0!=GetModuleFileName( NULL, path, MAX_PATH )){// 実行ファイルの完全パスを取得 _splitpath(path,drive,dir,fname,ext);//パス名を構成要素に分解します } sprintf(commandspath,"%s\\commands.txt",dir); sprintf(linkspath,"%s\\links.txt",dir); //command処理(get command) if(!strcmp(argv[1],"-add")){ if(strlen(argv[3]) == 0){ printf(" Error : Can't found link.\n"); printf(" C:\\>open [-add] [sitecommand] [weblink]\n"); printf(" ex: >open -add g https://www.google.com/search?q="); printf(" WORNIG : [weblink] is removed keyword from searching URL"); return -2; } printf("Added : [ %s ] | [ %s ]\n",argv[2],argv[3]); addcommand(argv[2]); addlink(argv[3]); return 1; } readcommands(); //commands.txt読み込み(read commands.txt) readlinks(); //links.txt読み込み(read links.txt) if(!strcmp(argv[1],"-list")){ viewlists(); return 2; } if(!strcmp(argv[1],"-del")){ printf("DELETE : [ %s ]\n",argv[2]); delcommand(argv[2]); return 3; } int i=0; char *site; //commnads.txtを参照(seach cmd to commands.txt) while(strlen(commands[i]) != 0){ char cmd[S]; sprintf(cmd,"%s\n",argv[1]); if(!strcmp(cmd,commands[i])){ site = links[i]; break; } i+=1; } //エラー表示(display 'Error') if(strlen(commands[i]) == 0){ printf(" Error : No such thing as \"%s\" site\n",argv[1]); printf("By use command'open -list',You can view commands list.\n"); printf(" C:\\>open [sitecommand] [word]\n"); return -1; } //検索ワードの結合(join word) char word[M]; sprintf(word, "%s",argv[2]); if(2 < argc){ for (int i=3;i<argc;i+=1){ strcat(word," "); strcat(word,argv[i]); } } //url作成(make URL) char url[L]; sprintf(url, "%s%s", site, word); printf(" Open : %s ",word); //url実行(open URL) ShellExecute(NULL,"open",url,NULL,NULL,SW_SHOWNORMAL); return 0; } //command.txt読み込み(read command.txt) void readcommands(){ int i=0; FILE *fp; char a[S]; fp = fopen(commandspath,"r"); while(fgets(a,S,fp) != NULL){ sprintf(commands[i],"%s",a); i+=1; } fclose(fp); } //links.txt読み込み(read links.txt) void readlinks(){ int i=0; FILE *fp; char a[M]; fp = fopen(linkspath,"r"); while(fgets(a,S,fp) != NULL){ sprintf(links[i],"%s",a); i+=1; } fclose(fp); } //-listされたときにコマンドを表示する(view filelists when '-list') void viewlists(){ int i=0; while(strlen(commands[i]) != 0){ printf("%s|- %s\n",commands[i],links[i]); i+=1; } } //-addされたときにコマンドをファイルに追加(add command to commands.txt when '-add') void addcommand(char *a){ FILE *fp; fp = fopen(commandspath,"a"); fprintf(fp,"%s\n",a); fclose(fp); } //-addされたときにリンクをファイルに追加(add link to links.txt when '-add') void addlink(char *a){ FILE *fp; fp = fopen(linkspath,"a"); fprintf(fp,"%s\n",a); fclose(fp); } //-delされたときに対象コマンドを削除(deleate command when '-del') void delcommand(char *a){ int i=0,n; //commands.txtを参照(seach cmd to commands.txt) while(strlen(commands[i]) != 0){ char cmd[S]; sprintf(cmd,"%s\n",a); if(!strcmp(cmd,commands[i])){ n=i; break; } i+=1; } //エラー表示(display 'Error') if(strlen(commands[i]) == 0){ printf(" Error : No such thing as \"%s\"\n",a); printf("By use command'open -list',You can view commands list.\n"); return; } i=0; FILE *fp1; FILE *fp2; fp1 = fopen(commandspath,"w"); fp2 = fopen(linkspath,"w"); //delしたファイルで作り直す while(strlen(commands[i]) != 0){ if(i == n) i+=1; fprintf(fp1,"%s",commands[i]); fprintf(fp2,"%s",links[i]); i+=1; } printf(" SUCCESS\n"); fclose(fp1); fclose(fp2); }
cfca4bdc89d13febd0b71e41c6e674e7508b5a79
[ "Markdown", "C" ]
2
Markdown
N-Kazu/command-search
e267c9e69b14409855b7477fa0bcc099bb91a2e3
ee1f1cca15635141faaf2cd8cbdced9a4e1a259b
refs/heads/master
<file_sep><div class="ui container grid"> <div class="five wide column"> <div class="ui piled secondary segment"> <div class="ui header"> This seems cool... <div class="sub header">how do I test it?</div> </div> <p>The app works by loading html pages that are found inside a <strong>folder</strong>, like <em>slideshow</em> that you've seen in the previous page. You also need to specify the <strong>number</strong> of slides that you want to load.</p> </div> </div> <div class="eight wide column"> <div class="ui piled secondary segment"> <div class="ui header">Ok... but how do I create slides?</div> <p>Slides are just <code>html</code> files with just a <code>div</code> container inside.</p> <p>Inside that div you can do whatever you want. You can use <a href="http://semantic.ui.com" target="_blank">semantic-ui</a> to style the content too, which is awesome. Remember that the slides get <code>flexbox</code> from css, so you can use and experiment with that.</p> <p>Also remember that the slides can be in any folder you want to (so you can have multiple slideshows to load) but <strong>must</strong> have predetermined name, as in numeric, starting from <code>0.html</code>, without missing any.</p> </div> </div> <div class="thirteen wide column"> <div class="ui stacked secondary segment"> <div class="ui header">And what about events and script?</div> Since the slides are just <code>html</code>, you can add a <code>script</code> tag anywhere and the content will load and execute. The suggestion is to use the first slide to load everything, or split each slide functionalities for each slide, if there is lots to do...Since the pages will be loaded together, though, this is just a design preference. <div class="ui block header"> <i class="info icon"></i> <div class="content">hooks and app events</div> </div> You can also access and utilize app events and methods while writing down your slides, but <strong>there is a catch</strong>. If you want to access hooks you have to create an object inside a <code>script</code> tag that needs to be called <code>_slidesEvents</code>. inside that you have to nest an object for every slide you want to access the hooks, and define the callbacks functions for those events. <div class="ui block header"> <i class="help icon"></i> <div class="content">...uh?</div> </div> If you didn't understand what I mean, you can take a look at <code>0.html</code> inside the <code>slideshow</code> folder and check the script tag... </div> </div> </div> <file_sep> /** * This script tag contains all the functionality and event listeners for the * content of the slides. Functions and events can access the App methods to * execute events like moving through slides directly. * Event listeners will activate immediately. * * @var {object} _slidesEvents contains the onEnter and onLeave events for the * single slides. the object will be loaded and used by the app * and every method will be called when needed. i.e.: _slidesEvents.1.onLeave will be called when leaving the second slide (index starts from 0) */ var $s1Btn = $('#s1_btn') $s1Btn.on('click', function () { console.log('You triggered an App event from a slide!') $s1Btn.transition('remove looping') /** accessing App methods to control the slides */ App.go('next'); }); /** * this object will be automatically loaded inside Slides.config.events and * contains user defined callbacks for the slides onEnter and onLeave events */ _slidesEvents = { 0: { onEnter: function () { // console.log('entering slide 0') /** * hook is called in the first load too, so it can activate stuff */ setTimeout(function () { $s1Btn.transition('set looping').transition('jiggle', '1000ms') }, 800); }, onLeave: function () { /** removing the button looping */ $s1Btn.transition('remove looping') // console.log('exiting slide 0') }, }, 1: { // onEnter: function () { console.log('entering slide 1') }, onLeave: "I'm not a function so I don't count :(", } }; <file_sep>// selectors for DOM elements $helpIcon = $('[data-role="helpIcon"]'), $counter = $('[data-role="counter"]'), $authorAccordion = $('[data-role="authorAccordion"]'), $slideContainer = $('[data-role="slides"]'); $dimmer = $('[data-role="dimmer"]') $button = { // wrapper for slide movement buttons wrapper: $('[data-role="buttons"]'), // slide movement first: $('[data-role="btnFirst"]'), prev: $('[data-role="btnPrev"]'), black: $('[data-role="blackScreen"]'), jump: $('[data-role="jumpToSlide"]'), next: $('[data-role="btnNext"]'), last: $('[data-role="btnLast"]'), // ui toggler toggle: $('[data-role="toggle"]') }; about = { authorEmail: $('[data-role="authorEmail"]'), authorGitHub: $('[data-role="authorGitHub"]'), appVersion: $('[data-role="appVersion"]') }; <file_sep>> #Preface > Project is still work in progress, so this readme **DO NOT** mirror the actual code, functionalities etc... For example there is no need for manual configuration anymore. I'll leave it there but as far as this version all (basic) functionalities can be easily handled from the UI. > ## Last update to v. 0.9.3b # Simple slide presentational app I needed to create a little presentation and I told myself: _why should I use powerpoint and do it easily, when I can create an app to do the job?_ I think this is my first real project I've developed on my own, so due this and the fact that surely is an alpha version, code can look... well, could look better :D If you have any suggestions, find bugs etc feel free to contact me or fork your own to expand it. ## Intro The app is fairly simple, relies on `jQuery` and `semantic-ui` and `flexbox properties`, and uses `jQuery.load()` method to get progressively indexed `.html` files from `slides/` (_default_) folder inside the project, So you may want to have any kind of webserver where to run this application. ## Installation Just put the folder in a working web server (I'm using `wamp` for windows for this project) and decompress `semantic.zip` into the `semantic/` folder. I added semantic locally because I needed the app to be able to run without internet connection too, so this is safe and faster. ## How it works Pretty straightforward: Create one `html` file for each slide you want to show and give them a number as a name, starting from `0`. For example, if you want to show 3 slides, you will have `0.html`, `1.html` and `2.html` inside the `slides/` folder or the one that you want to use (see `config` below). Open `index.html` in a browser, follow the instructions and enjoy. See below for advanced usage. ## Creating the slides Every file will be loaded inside index.html, so there is no need to add all the `html`, `body` etc tags. What you'll need to set the content correctly is one container where to nest everything to allow flexbox to do its job correctly. You can always experiment freely how to design the content and change css properties as you may like. Since the app relies on semantic-ui to render the interface, you can also use it for your slide content, giving you a fairly complete set of components and modules to use for your slides. ## Config Basic configuration is handled from the UI, such as deciding the folder for the slideshow and the number of slides, so it wouldn't be necessary to know this, but still... Slideshow can be manually loaded calling `App.loadSlideshow([totalSlides], {config})` telling it how many slides it has to load so, if you have your 4 slides, you will tell it `App.loadSlideshow(4)` You can also pass an optional `config object` to customize your presentation: ```javascript var config = { folder: 'myPresentation', hash: 'awesomePresentation' }; App.init(4, config) ``` | property | type | default | description | |--------|------|---------|----------|-------------| | `folder` |`string` | `slides` |folder path that contains the slides (without final `/`)| | `hash` |`string` | `slide` |the hash that will be in the address bar.| | `showButtons` |`bool` | `true` |shows or hides the buttons at start.| | `showCounter` |`bool` | `true` |renders the counter of the slides.| | `debug` |`bool` | `false` |enable verbose mode in console| ## Advanced config and usage The app can handle custom events and call. Since the slides are just html files that are loaded inside index.html, you can add a `script` tag inside one of the pages (the last one, maybe?) and use all the javascript you want to handle special functionalities. You can also define a custom `script.js` file inside your slideshow folder that the app will try to get, using `jQuery.getScript()`, after loading all the slides into the slideshow. You can access `event hooks` from the app, such as `onEnter` and `onLeave` in and from a slide. To do so you have to manually create a events object with all the methods inside one of the slides. This object **MUST BE GLOBALLY DECLARED** so **NO** var in front of it and must be called `_slidesEvents`. inside that you can put nested objects, one for each slide you need to access, with that slide index as name, setting the callbacks as properties. if a slide index is missing or a property is not a function it gets ignored by the hook. ### Example ```javascript _slidesEvents = { 0: { onEnter: function () { console.log('We are about to enter slide one!')}, onLeave: 'I am an engine... string, not a function, captain! ignore me!' }, // we don't have anything for slide 1 2: { // we don't need onEnter here onLeave: function () { alert('don\'t leave me alone please!') } } } ``` Keep in mind that events are triggered just before the animation starts moving the slides. If there are events for the first slide (slide 0.html) they will trigger immediately after loading. ### hooks and event handlers #### Hooks * `onEnter` callback called when entering a slide * `onLeave` callback called when leaving a slide #### Handlers With these you can actually handle the slideshow programmatically, for example by having a button to go to the next or previous slide from a element (I will try to add a _go to slide number_ later on). * App * `.go(direction {string})` accepts one of `first`, `last`, `next`, `prev` and handles the movement of the slides * `.loadSlideshow(slides# {number}, config {object})` **requires** at least the first argument (min = 1). there is a default config stored already * `updateConfig(config {object})` manually update the config stored in Slides.config * `render()` re-render and assign styling to the slides. used when window changes sizes and at initialization * Interface * `toggle()` toggles on or off the interface * `toggleButtons()` refresh directional buttons classes. handles `disabled` class To see an example usage with all (?) the functionalities, check the `slideshow/` folder files. ## Controls You can control the app using the UI buttons to go to the first, previous, next or last slide of the presentation, or hide the controls. You can also control the slide using your keyboard or a remote presenter. * **first slide** `home` key * **prev slide** `left` key or presenter * **next slide** `right` key or presenter or `space` key * **last slide** `end` key * **toggle UI** `T` key You can always see the controls shortcuts using the `?` button on the bottom left of the UI. #What's next More events hooks, customization and tuning for sure. Option to jump to a slide directly, maybe. slides attributes like title (using config or data attributes, more probably) One thing I will most probably do in a not so late future is convert everything in `ES6` and create a small `react` application as standalone and as reusable component since I might need it for a couple of other big projects I'm working. I don't know if and when I'll do these steps, as I want to tune this as much as possible, but still... <file_sep> $(document).ready(function () { var $slides_loader // callback for the success of load 'config.html' // will activate the submit button, allowing the loading of slideshows function _enableSlideLoader () { $slides_loader.on('click', function (e) { e.preventDefault(); var folder = $('input[name="folderName"]').val(), hash = $('input[name="pageHash"]').val(), counter = $('input[name="counterToggle"]').is(':checked'), controls = $('input[name="controlsToggle"]').is(':checked'); // set the config object to load the slides var config = { folder: folder, hash: hash, showButtons: controls, showCounter: counter } function validateSuccess () { App.loadSlideshow(config) }; function validateFailure () { var message = $('[data-role="loadingErrorBox"]'), icon = $(message).children('.icon'); $(message).transition({ animation: 'fade up', onComplete: function () { $(icon).transition('tada') } }) }; App.validateSlideshowFolder(folder, validateSuccess, validateFailure); }); } function _loadApp () { // fetch the UI and load it into the page $('[data-role="ui"]').load("app/ui.html", function () { // fetch the config file $.getScript('app/config.js', function () { // fetch app.js $.getScript('js/app.js', function () { // initialize the app App.init(); }) }); }); } // load the configuration interface into the page $( '[data-role="slides"]').load("app/config.html", function () { // get the element for the load button $slides_loader = $('#load_slideshow_btn'); // initialization for loading screen $('.ui.checkbox').checkbox() $('[data-role="configSettingsAccordion"]').accordion() _enableSlideLoader() // load the rest of the UI and _loadApp() }); });
81a36df09b0ce98fea9336410b86df8f02056b2e
[ "JavaScript", "HTML", "Markdown" ]
5
HTML
dinghino/semantic-slideshow
1af4f1b718b141d0e529497fd9a9fca1bc30a465
9516b90d653099d9868bbe88174117815d6cc8f4
refs/heads/master
<file_sep># dokka-tests some tests and/or samples of Dokka <file_sep>set -e cd "$(dirname $0)" ./gradlew jefflib2:dokka <file_sep>settings.include(":jefflib1") settings.include(":jefflib2") settings.include(":jefflib3") <file_sep>settings.include(":jefflibA") settings.include(":jefflibB") <file_sep>set -e cd "$(dirname $0)" find -name build | xargs --no-run-if-empty rm -rf echo Project differences: diff -r jefflib-with-kotlin-android-plugin jefflib-without-kotlin-android-plugin || true echo ./gradlew dokka echo echo index-outline.html sizes: find -name index-outline.html | xargs wc -l | sort -n echo Notice that the two projects produce different results <file_sep>buildscript { project.ext.dokka_version = '0.9.16-eap-3' project.ext.kotlin_version = '1.2.20' repositories { jcenter() google() maven { url "https://dl.bintray.com/kotlin/kotlin-eap/" } } dependencies { classpath "org.jetbrains.dokka:dokka-android-gradle-plugin:${dokka_version}" classpath 'com.android.tools.build:gradle:3.0.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlin_version}" } } apply plugin: 'java' <file_sep>set -e cd "$(dirname $0)" find -name build | xargs --no-run-if-empty rm -rf echo Project differences: diff -r jefflibA jefflibB || true echo ./gradlew dokka echo echo Some output differences: diff jefflibA/build/dokka/jefflib-a/com.jeffclass2/-jeff-class2/index.html jefflibB/build/dokka/jefflib-b/com.jeffclass2/-jeff-class2/index.html | grep "Sample method" | grep --color 'href="[^"]*"' || true echo Notice that the reference from the jefflibB project fails to link to com.jeffclass.JeffClass#STATIC_FIELD or to com.jeffclass.JeffClass#memberField <file_sep>package com.jeffclass2; import static com.jeffclass.JeffClass.STATIC_FIELD; import com.jeffclass.JeffClass; /** * Sample Class */ public class JeffClass2 { /** * Sample method. See also {@link com.jeffclass.JeffClass#STATIC_FIELD} and {@link com.jeffclass.JeffClass#memberField} */ public void testme() { } } <file_sep>This is a sample project for demonstrating that a symbol defined in another project is not found run ./test.sh to demonstrate <file_sep>settings.include(":jefflib-with-kotlin-android-plugin") settings.include(":jefflib-without-kotlin-android-plugin") <file_sep>This is a sample project for demonstrating that the kotlin-android plugin is required for the dokka-android plugin to generate an index-outline.html listing a nonzero number of classes. Is that expected? run ./test.sh to demonstrate <file_sep>buildscript { project.ext.dokka_version = '0.9.16-eap-3' project.ext.kotlin_version = '1.2.20' repositories { jcenter() google() maven { url "https://dl.bintray.com/kotlin/kotlin-eap/" } } dependencies { classpath "org.jetbrains.dokka:dokka-android-gradle-plugin:${dokka_version}" classpath 'com.android.tools.build:gradle:3.0.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlin_version}" } } apply plugin: 'com.android.library' apply plugin: 'kotlin-android' apply plugin: 'org.jetbrains.dokka-android' dependencies { api(project(":jefflib1")) } android { compileSdkVersion = 23 lintOptions { abortOnError false } } afterEvaluate { dokka { sourceDirs = project.files('src') classpath = new ArrayList<File>(project.tasks['assemble'].outputs.files.files) } } <file_sep>This is a sample project demonstrating that Gradle displays a confusing error message when the java plugin is applied to a dependency project: FAILURE: Build failed with an exception. * What went wrong: Could not determine the dependencies of task ':jefflib2:dokka'. > Could not resolve all files for configuration ':jefflib2:debugCompileClasspath'. > Failed to transform file 'jefflib1.jar' to match attributes {artifactType=android-classes} using transform JarTransform > Transform output file /usr/local/google/workspace/dokka-tests/temp/jefflib1/build/libs/jefflib1.jar does not exist. Note that when the java plugin is applied to the same project as the dokka-android plugin, then a slightly clearer message (generated by the "com.android.library" plugin) is shown, saying "> The 'java' plugin has been applied, but it is not compatible with the Android plugins." I'm not sure whether this compatibility should be checked within the dokka-android plugin or within the com.android.library plugin or whether it's something that the dokka-android plugin can in fact support. Also note that although `find -name build | xargs rm -rf && ./gradlew dokka` fails, `find -name build | xargs rm -rf && ./gradlew build && ./gradlew dokka` succeeds
fb99b822fe07ef1444f2e02403453b15b209ea09
[ "Markdown", "Gradle", "Java", "Text", "Shell" ]
13
Markdown
mathjeff/dokka-tests
96bef18519f1401d9da158b7ce3910d17858b715
b30a3c79648c6ba6751d0c0c720f42c8febcee3a
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'mutiplication-table', templateUrl: './mutiplication-table.component.html', styleUrls: ['./mutiplication-table.component.css'] }) export class MutiplicationTableComponent implements OnInit { list : number[] ; constructor() { } ngOnInit() { this.list =[1,2,3,4,5,6,7,8,9]; } }
43f396e1eec638a87e9a8772625147b89dfa8f7e
[ "TypeScript" ]
1
TypeScript
tribh1/angular-zzlmj7
986988940569679cbe601a63e1595eb54400c096
98af66fb1d46bae9959615b51244c5200039d089
refs/heads/master
<repo_name>aur-archive/librocket-git<file_sep>/PKGBUILD # Maintainer: <NAME> <<EMAIL>> pkgname=librocket-git pkgver=release.1.2.1.164.g96d91c3 pkgrel=1 pkgdesc="libRocket - The HTML/CSS User Interface library" arch=('i686' 'x86_64') url="http://librocket.com" license=('MIT') depends=(freetype2) makedepends=(git cmake) conflicts=(librocket) provides=(librocket) source=('git+http://github.com/lloydw/libRocket.git') md5sums=('SKIP') _gitname=libRocket pkgver() { cd $_gitname echo $(git describe --always | sed 's/-/./g') } build() { cd "$srcdir" cd $_gitname/Build cmake -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_BUILD_TYPE=Release . make } package () { cd $_gitname/Build make install DESTDIR=$pkgdir } # vim:set ts=4 sw=4 et:
b86cddff9e8474c53d128050f109f9bc81cf387c
[ "Shell" ]
1
Shell
aur-archive/librocket-git
335ab62352d10330395387c2596ca152bdae1ab6
58a3de62182ad73b415404dd6b19395a0a28a0f2
refs/heads/master
<repo_name>farezv/infectr<file_sep>/User.java import java.util.*; public class User { private int siteVersion; private int uid; private String name; private ArrayList<Integer> students; private ArrayList<Integer> coaches; public User(String name, int uid, int version) { this.name = name; this.uid = uid; this.siteVersion = version; this.students = new ArrayList<Integer>(); this.coaches = new ArrayList<Integer>(); } /* Getters */ public String getName() { return this.name; } public int getUid() { return this.uid; } public int getVersion() { return this.siteVersion; } public ArrayList<Integer> getStudents() { return this.students; } public ArrayList<Integer> getCoaches() { return this.coaches; } /* Setters */ public void setVersion(int newVersion) { this.siteVersion = newVersion; } /* Helpers */ public void addCoach(int uid) { if(!this.coaches.contains(uid)) this.coaches.add(uid); } public void addStudent(int uid) { if(!this.students.contains(uid)) this.students.add(uid); } public boolean isInfected(int infectedVersion) { return this.siteVersion == infectedVersion; } } <file_sep>/README.md # infectr Java implementation of a graph problem ### Instructions The test cases will all run from the end of `main()` 1. To clone, just type `git clone https://github.com/farezv/infectr.git` in your terminal or click the `Clone in Desktop button` if you have [GitHub for Mac](https://mac.github.com) or [GitHub for Windows](https://windows.github.com) installed or just `Download ZIP` if you don't (be sure to unzip the file!). 2. Enter the directory `cd ../path/to/infectr` 3. Compile the files using `javac Infectr.java` 4. Provide command line args, like `java Infectr 30` to create 30 users and execute the first 2 test cases `java Infectr 30 3` to create 30 users and execute all 4 test cases
4c871b758935136b76426ac3827b71a1923213dc
[ "Markdown", "Java" ]
2
Java
farezv/infectr
fb7abfd8f72981a21218caa808dc1a6d8ee26108
fce76fd9fa3301e686935de768fdbb065b72b0a5
refs/heads/master
<repo_name>Myitschoolby/FinanceApp<file_sep>/components/PageCardForm.js import DOM from './Dom.js'; import render from './Router.js'; class PageCardForm { constructor() { this.element = DOM.create('div'); DOM.addClass(this.element, 'page_card_form'); DOM.html( this.element, ` <h3>Add your card</h3> <input type="text" name="name" placeholder="Your name" /> <input type="number" name="card_number" placeholder="Card number" /> <input type="text" name="card_expiry" placeholder="Card expiry date" /> <input type="number" name="card_secret" placeholder="Card secret number" /> ` ); const btnAddCard = DOM.create('button'); DOM.addClass(btnAddCard, 'page_card_form_add'); DOM.html(btnAddCard, 'Add card'); DOM.append(this.element, btnAddCard); DOM.on(btnAddCard, 'click', this.addCard); } addCard() { const name = DOM.search(this.element, 'input[name="name"]'); const card_number = DOM.search(this.element, 'input[name="card_number"]'); const card_expiry = DOM.search(this.element, 'input[name="card_expiry"]'); const card_secret = DOM.search(this.element, 'input[name="card_secret"]'); if (!name || !card_number || !card_expiry || !card_secret) return; if (name.value.length == 0 || card_number.value.length == 0 || card_expiry.value.length == 0 || card_secret.value.length == 0) return; const cardInfo = { name: name.value, number: card_number.value, expiry: card_expiry.value, secret: card_secret.value }; const cardInfoJson = JSON.stringify(cardInfo); localStorage.setItem('cardInfo', cardInfoJson); // render(); location.reload(); } render() { return this.element; } }; const pageCardForm = new PageCardForm().render(); export default pageCardForm;<file_sep>/index.js import render from './components/Router.js'; import './components/Head.js'; import DOM from './components/Dom.js'; render(); DOM.on(window, 'hashchange', render);<file_sep>/components/Dom.js export default class DOM { static attr = function(element, name, value) { if (!element || !name) return; if (value != undefined && value != '') element.setAttribute(name, value); else return element.getAttribute(name); }; static create = function(name) { return document.createElement(name); }; static append = function(toElement, element, beforeElement) { if (!toElement || !element) return; if (!beforeElement) toElement.appendChild(element); else toElement.insertBefore(element, beforeElement); }; static search = function(element, selector) { if (typeof element === 'string') { selector = element; element = undefined; } if (!element) element = document; let result = element.querySelectorAll(selector); if (result.length == 1) return result[0]; return result; }; static html = function(element, html) { if (!element || !html) return; element.innerHTML = html; }; static addClass = function(element, name) { if (!element || !name) return; element.classList.add(name); }; static removeClass = function(element, name) { if (!element || !name) return; element.classList.remove(name); }; static toggleClass = function(element, name) { if (!element || !name) return; element.classList.toggle(name); }; static hasClass = function(element, name) { if (!element || !name) return; return element.classList.contains(name); }; static on = function(element, eventName, func) { if (!element || !eventName || !func) return; element.addEventListener(eventName, function(event) { func.apply(this, [event]); }); }; };<file_sep>/components/PageCard.js import DOM from './Dom.js'; class PageCard { constructor() { this.element = DOM.create('div'); DOM.addClass(this.element, 'page_card'); DOM.html( this.element, `<header class="header"> <div class="container"> <h1>Debit card</h1> </div> </header> <main class="main"> <div class="container"> </div> </main>` ); const cardInfoJson = localStorage.getItem('cardInfo'); const self = this; import((cardInfoJson && cardInfoJson.length > 0) ? './PageCardBalance.js' : './PageCardForm.js') .then(function(module) { const container = DOM.search(self.element, '.main .container'); if (!container) return; DOM.append(container, module.default); }); } render() { return this.element; } }; const pageCard = new PageCard().render(); export default pageCard;<file_sep>/components/Router.js import DOM from './Dom.js'; const render = function () { document.body.innerHTML = ''; if (location.href.indexOf('.html') != -1) location.href = location.origin; const page = location.hash.length > 0 ? location.hash.substr(1) : ''; const infoModule = { name: 'startPage', path: './StartPage.js' }; switch (page) { case 'cards': infoModule.name = 'pageCard'; infoModule.path = './PageCard.js'; break; case 'transactions': infoModule.name = 'pageTransaction'; infoModule.path = './PageTransaction.js'; break; } import(infoModule.path) .then(function(module) { DOM.addClass(module.default, 'app'); DOM.append(document.body, module.default); }); }; export default render;<file_sep>/components/PageTransaction.js import DOM from './Dom.js'; class PageTransaction { constructor() { this.element = DOM.create('div'); DOM.addClass(this.element, 'page_transaction'); let cardTransaction = localStorage.getItem('cardTransaction') || []; if (cardTransaction.length > 0) cardTransaction = JSON.parse(cardTransaction); let listTransactionHtml = ''; cardTransaction.forEach(function(transaction) { listTransactionHtml += ` <li> <div class="icon"></div> <div class="info"> <div class="name">${transaction.name}</div> <div class="date">${transaction.date}</div> </div> <div class="cost">${transaction.amount}</div> </li> `; }); DOM.html( this.element, `<header class="header"> <div class="container"> <button class="page_transaction_back_button" onClick="location.href='#cards'"><</button> <h1>Transactions</h1> </div> </header> <main class="main"> <div class="container"> <ul class="page_transaction_list"> ${listTransactionHtml} </ul> </div> </main>` ); } render() { return this.element; } }; const pageTransaction = new PageTransaction().render(); export default pageTransaction; <file_sep>/components/PageCardBalance.js import DOM from './Dom.js'; import pageCardFormTransaction from './PageCardFormTransaction.js'; class PageCardBalance { constructor() { this.balance = 0; this.getBalance(); this.element = DOM.create('div'); DOM.addClass(this.element, 'page_card_balance'); DOM.html( this.element, ` <h3>Your balance</h3> <div class="balance">$${this.balance}</div> <a class="to_transactions" href="#transactions">All transactions</a> ` ); const btnAddTransaction = DOM.create('button'); DOM.addClass(btnAddTransaction, 'page_card_add_button'); DOM.html(btnAddTransaction, '+'); DOM.append(this.element, btnAddTransaction); DOM.on(btnAddTransaction, 'click', this.addTransaction); } getBalance() { let cardTransaction = localStorage.getItem('cardTransaction') || []; if (cardTransaction.length > 0) cardTransaction = JSON.parse(cardTransaction); let amount = 0; cardTransaction.forEach(function(transaction) { amount += +transaction.amount; }); if (!isNaN(amount)) this.balance = amount; } addTransaction() { DOM.append(DOM.search('.page_card_balance'), pageCardFormTransaction, DOM.search('.to_transactions')); } render() { return this.element; } }; const pageCardBalance = new PageCardBalance().render(); export default pageCardBalance;
fbc2e46c47524df44e7964abbf6ddead74c9c787
[ "JavaScript" ]
7
JavaScript
Myitschoolby/FinanceApp
1d172094575c420d4808b42305044dba7972bfa4
3340608cd47b305f908454958399734077a3c226
refs/heads/master
<file_sep>import '../styles/main.scss'; import 'bootstrap'; import projects from './components/portfolio/portfolio'; const init = () => { projects.portfolioBuilder(); }; init(); <file_sep>import util from '../../helpers/util'; import portfolioData from '../../helpers/portfolioData'; import './portfolio.scss'; const portfolioBuilder = () => { portfolioData.getProjects().then((projects) => { let domString = '<h1 class="project-section-title">Portfolio</h1><div class="project-arrow">'; projects.forEach((project) => { domString += `<div id="${project.id}" class="project">`; domString += `<img class="card-img-top" src=${project.screenshot} alt="${project.name}">`; domString += `<h3 class="project-title">${project.title}<h3>`; domString += `<h6 class="description">${project.description}</h6>`; domString += '<div class="project-links">'; domString += `<a href=${project.githubUrl}><button class="btn btn-warning project-link">GitHub</button></a>`; domString += `<a href=${project.url}><button class="project-link btn btn-warning">Website</button></a>`; domString += '</div>'; domString += '<hr>'; }); domString += '</div>'; util.printToDom('projects', domString); }) .catch(err => console.error('no projects', err)); }; export default { portfolioBuilder }; <file_sep>const printToDom = (divId, textToPrint) => { const selectDiv = document.getElementById(divId); selectDiv.innerHTML = textToPrint; }; const scrollToTop = () => { const c = document.documentElement.scrollTop || document.body.scrollTop; if (c > 0) { window.requestAnimationFrame(scrollToTop); window.scrollTo(0, c - c / 8); } }; export default { printToDom, scrollToTop }; <file_sep># portfolio Software development portfolio site for <NAME>
3ebfe182e005554f2e62435996be4554635c65e8
[ "JavaScript", "Markdown" ]
4
JavaScript
jeressia/portfolio
bbe8628deb96ca5d2e13c1a2f5ef6e5c830d2f1d
d22b9eee38a4f2dec5df60592e3290c456cb3e25
refs/heads/master
<file_sep>blinker==1.4 decorator==4.0.2 facebook-sdk==0.4.0 flake8==2.4.1 Flask==0.10.1 Flask-Mail==0.9.1 Flask-Triangle==0.5.4 functools32==3.2.3.post2 ipdb==0.8.1 ipython==4.0.0 ipython-genutils==0.1.0 itsdangerous==0.24 Jinja2==2.8 jsonschema==2.5.1 MarkupSafe==0.23 mccabe==0.3.1 path.py==8.1 pep8==1.5.7 pexpect==3.3 pickleshare==0.5 pyflakes==0.8.1 redis==2.10.3 requests==2.7.0 rethinkdb==2.1.0 simplegeneric==0.8.1 traitlets==4.0.0 uWSGI==2.0.11.1 Werkzeug==0.10.4 wheel==0.24.0 <file_sep>$('#ratings').addClass("active item"); // var app = angular.module('knuth', []); $('#table').DataTable(); linebreak = document.createElement("br"); table_filter.appendChild(linebreak); linebreak = document.createElement("br"); table_filter.appendChild(linebreak); // var TextInside = ctrl.getElementsByTagName('label')[0].innerHTML; var TextInside = $( "label" ).text(); console.log(TextInside); TextInside.bold(); // alert("af"); // document.getElementById(table_filter).style.fontWeight = 'bold'; <file_sep>from functools import wraps from flask import request from itsdangerous import URLSafeSerializer from config import * import json def response_msg(status, msg, **kwargs): res = {} res['status'] = status res['msg'] = msg for name, value in kwargs.items(): res[name] = value return json.dumps(res), 200 def get_user_from_auth(auth_key): s = URLSafeSerializer('secret-key', salt='be_efficient') return s.loads(auth_key) def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): # import ipdb; ipdb.set_trace(); try: if request.headers.get('key'): key = request.headers.get('key') else: key = "" if key: if key != ANDROID_HEADER_KEY: return response_msg('error', 'Authentication faiiled') try: user = get_user_from_auth(request.headers.get('auth_key')) except: user = "" else: user = get_user_from_auth(request.cookies['auth_key']) if user == kwargs['name']: return f(*args, **kwargs) else: return response_msg('error', 'user not authorized') except: return response_msg('error', 'some error occured') return decorated_function def admin_required(f): @wraps(f) def decorated_function(*args, **kwargs): # import ipdb; ipdb.set_trace(); try: user = get_user_from_auth(request.cookies['admin_key']) if user == 'admin': return f(*args, **kwargs) else: return response_msg('error', 'user not authorized') except: return response_msg('error', 'some error occured') return decorated_function<file_sep>from redis import Redis from runserver import host # rethink config RDB_HOST = 'localhost' RDB_PORT = 28015 TODO_DB = 'knuth' rds = Redis() DEFAULT_PIC = 'https://github.com/identicons/' FB_APP_ID = 122742198082740 FB_APP_SECRET = "8474009531f56532cf1e194df6afd53d" CAPTCHA_SECRET = '<KEY>' ANDROID_HEADER_KEY = 'a12eaa81ccd9743e3baee14f4425a4f5e23574dc6a505afb9c1a5d1b' redis = Redis() <file_sep>{% extends "parent.html" %} {% block child %} <div class="ui active tab raised segment"> <div class="ui teal large label"> <i class="code icon"></i> Problems : </div> <table class="ui sortable selectable padded celled table"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Tags</th> <th>Level</th> </tr> </thead> <tbody class="problems"> {% for problem in problems %} <tr> <td> {{ problem.prob_id }} </td> <td><a target="_blank" href="/problem/{{problem.prob_id}}"> {{ problem.name }} </a></td> <td> {% for tag in problem.tags %} {{tag}}&nbsp; {% endfor %} </td> <td> {{ problem.level }} </td> </tr> {% endfor %} </tbody> <tfoot> <tr> <th colspan="4"> <div class="ui pagination menu"> <a class="icon item" href=""> <i class="left chevron icon"></i> </a> {% for i in range(0,count) %} <a href="/problemset/page/{{i+1}}" class="item">{{i+1}}</a> {% endfor %} <!-- <a class="item">2</a> --> <!-- <a class="item">3</a> --> <!-- <a class="item">4</a> --> <a class="icon item" href=""> <i class="right chevron icon"></i> </a> </div> </th> </tr> </tfoot> </table> </div> <br> <br> <br> <script type="text/javascript" src="/static/problems.js"> </script> {% endblock %} <file_sep>// $('#date').dateSelector(); $("#datepicker").datepicker(); $("#datepicker").datepicker("option", "showAnim", "clip"); var signupapp = angular.module("sign_up", ["ngCookies"]); signupapp.controller("formctrl", ['$scope', '$http', '$element', '$cookies', function($scope, $http, $element, $cookies) { var form_element = $($element); // $scope.uname = ""; // $scope.passw = ""; $scope.isInvalid = function() { return !form_element.form('validate form'); } $scope.form_validate = function() { if (this.isInvalid()) { return; } this.signup(); } $scope.signup = function() { $('#form').addClass('loading'); var dataObj = $scope.user; dataObj['g-recaptcha-response'] = $('#g-recaptcha-response').val(); $http({ method: 'POST', url: '/signup/', data: dataObj, // pass in data as strings }).success(function(data) { $('#form').removeClass('loading'); console.log(data); if (data['status'] != 'success') { // if not successful, bind errors to error variables $('#form').addClass('error'); $('.ui.error.message').html('<ul class="list"><li>' + data['msg'] + '</li></ul>'); } else { // if successful, bind success message to message // alert('success'); $cookies.put('auth_key', data['auth_key'], { 'path': '/' }); $(location).attr('href', '/profile/' + data['user'] + '/'); } }); } } ]); $('#form') .form({ fname: { identifier: 'fname', rules: [{ type: 'empty', prompt: 'Please enter your first name' }] }, lname: { identifier: 'lname', rules: [{ type: 'empty', prompt: 'Please enter your last name' }] }, user: { identifier: 'user', rules: [{ type: 'empty', prompt: 'Please enter a user name' }] }, email: { identifier: 'email', rules: [{ type: 'email', prompt: 'Please enter a valid e-mail' }] }, passwd: { identifier: 'passwd', rules: [{ type: 'empty', prompt: 'Please enter password' }, { type: 'minLength[6]', prompt: 'Your password must be at least 6 characters' }] }, cpasswd: { identifier: 'cpasswd', rules: [{ type: 'match[passwd]', prompt: 'Passwords do not match' }] } }); <file_sep>$('table').tablesort(); $('.ui.sticky') .sticky({ offset : 50, context: '#stick' }); $('.dropdown') .dropdown({ // you can use any ui transition transition: 'horizontal flip' }); var fileExtentionRange = '.c .cpp .java'; var MAX_SIZE = 5; // MB $(document).on('change', '.btn-file :file', function() { var input = $(this); if (navigator.appVersion.indexOf("MSIE") != -1) { // IE var label = input.val(); input.trigger('fileselect', [1, label, 0]); } else { var label = input.val().replace(/\\/g, '/').replace(/.*\//, ''); var numFiles = input.get(0).files ? input.get(0).files.length : 1; var size = input.get(0).files[0].size; input.trigger('fileselect', [numFiles, label, size]); } }); $('.btn-file :file').on('fileselect', function(event, numFiles, label, size) { $('#attachmentName').attr('name', 'attachmentName'); // allow upload. var postfix = label.substr(label.lastIndexOf('.')); if (fileExtentionRange.indexOf(postfix.toLowerCase()) > -1) { if (size > 1024 * 1024 * MAX_SIZE) { alert('max size:<strong>' + MAX_SIZE + '</strong> MB.'); $('#attachmentName').removeAttr('name'); // cancel upload file. } else { $('#_attachmentName').val(label); } } else { alert('file type:<br/> <strong>' + fileExtentionRange + '</strong>'); $('#attachmentName').removeAttr('name'); // cancel upload file. } }); <file_sep>from longclaw import app import socket import fcntl import struct import sys def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', ifname[:15]) )[20:24]) host = '' if len(sys.argv) <= 1: host = '' else: if sys.argv[1] == 'ip': try: host = get_ip_address('wlan0') except: host = get_ip_address('eth0') else: host = '' if host == '': host = 'localhost' if __name__ == '__main__': app.run( host=host, port=8000, debug=True) <file_sep>var adminapp = angular.module("admin", ["ngCookies"]); adminapp.controller("adminctrl", ['$scope', '$http', '$element', '$cookies', function($scope, $http, $element, $cookies) { var form_element = $($element); // $scope.uname = ""; // $scope.passw = ""; $scope.isInvalid = function() { return !($('#form').form('validate form')); } $scope.form_validate = function() { if (this.isInvalid()) { return; } this.adminlogin(); } $scope.adminlogin = function() { $('#form').addClass('loading'); var dataObj = $scope.user; $http({ method: 'POST', url: '/admin/', data: dataObj, // pass in data as strings }).success(function(data) { $('#form').removeClass('loading'); console.log(data); if (data['status'] != 'success') { // if not successful, bind errors to error variables $('#form').addClass('error'); $('.ui.error.message').html('<ul class="list"><li>' + data['msg'] + '</li></ul>'); } else { // if successful, bind success message to message // alert('success'); $cookies.put('admin_key', data['admin_key'], { 'path': '/' }); $(location).attr('href', '/select'); } }); } } ]); $('#form').form({ uname: { identifier: 'uname', rules: [{ type: 'empty', prompt: 'Please enter a username' }, { type: 'regExp[/^[a-zA-Z0-9_-]{4,16}$/]', prompt: 'Please enter a 4-16 letter username with a-z 0-9 _-' }] }, pwd: { identifier: 'pwd', rules: [{ type: 'empty', prompt: 'Please enter password' }, { type: 'minLength[6]', prompt: 'Your password must be at least 6 characters' }] } });<file_sep># Longclaw Web App of the JIIT Programming Hub. # JIIT Programming Hub ##Link for presentation: http://192.168.3.11/ # Technologies used: + Python ( Flask web framework ) for creating API. + MongoDB as the primary database. + Redis - a key-value in-memory data storage. + Semantic UI + Angular JS & jQuery. + OAuth 2.0 for high-level authentication on server side. + Site will be served through nginx server ##Bold Features: + Webkiosk Authentication, while signing up for security purposes + Option for signing in with Fb using Facebook Graph API + Included Google Re-captcha while Signing Up and Signing In + All the activities of Programming Hub Group on Facebook will be synced (posts, photos etc) - using Graph API-using AngularJS + OAuth 2.0 for high-level authentication on the server side. + Site is served by Nginx server + College’s Rank list was synced with competitive programming sites like Codechef and Codeforces + Discussion forum like StackOverflow based on “Reputation”, which will ensure that there is no spamming + Blogs feature (with markdown-using AngularJS) which allows the user to post blog on the home page of the website. + View and solve problems asked in previous “Execute”, “Knuth Cup” and other competitions hosted by the Programming Hub. + Admin page for adding problems and serve editorials for these problems, (here too markdown is used for writing expressions, etc which otherwise can't be written in plain text) <file_sep>/** * jquery.pfold.js v1.0.0 * http://www.codrops.com * * Licensed under the MIT license. * http://www.opensource.org/licenses/mit-license.php * * Copyright 2012, Codrops * http://www.codrops.com */ ;( function( $, window, undefined ) { 'use strict'; /* * debouncedresize: special jQuery event that happens once after a window resize * * latest version and complete README available on Github: * https://github.com/louisremi/jquery-smartresize/blob/master/jquery.debouncedresize.js * * Copyright 2011 @louis_remi * Licensed under the MIT license. */ var $event = $.event, $special, resizeTimeout; $special = $event.special.debouncedresize = { setup: function() { $( this ).on( "resize", $special.handler ); }, teardown: function() { $( this ).off( "resize", $special.handler ); }, handler: function( event, execAsap ) { // Save the context var context = this, args = arguments, dispatch = function() { // set correct event type event.type = "debouncedresize"; $event.dispatch.apply( context, args ); }; if ( resizeTimeout ) { clearTimeout( resizeTimeout ); } execAsap ? dispatch() : resizeTimeout = setTimeout( dispatch, $special.threshold ); }, threshold: 50 }; // global var $window = $( window ), Modernizr = window.Modernizr; $.PFold = function( options, element ) { this.$el = $( element ); this._init( options ); }; // the options $.PFold.defaults = { // perspective value perspective : 1200, // each folding step's speed speed : 450, // each folding step's easing easing : 'linear', // delay between each (un)folding step (ms) folddelay : 0, // number of times the element will fold folds : 2, // the direction of each unfolding step folddirection : ['right','top'], // use overlays to simulate a shadow for each folding step overlays : true, // the main container moves (translation) in order to keep its initial position centered : false, // allows us to specify a different speed for the container's translation // values range : [0 - 1] // if 0 the container jumps immediately to the final position (translation). // this is only valid if centered is true containerSpeedFactor : 1, // easing for the container transition // this is only valid if centered is true containerEasing : 'linear', // callbacks onEndFolding : function() { return false; }, onEndUnfolding : function() { return false; } }; $.PFold.prototype = { _init : function( options ) { // options this.options = $.extend( true, {}, $.PFold.defaults, options ); // https://github.com/twitter/bootstrap/issues/2870 this.transEndEventNames = { 'WebkitTransition' : 'webkitTransitionEnd', 'MozTransition' : 'transitionend', 'OTransition' : 'oTransitionEnd', 'msTransition' : 'MSTransitionEnd', 'transition' : 'transitionend' }; this.transEndEventName = this.transEndEventNames[ Modernizr.prefixed( 'transition' ) ]; // suport for css 3d transforms and css transitions this.support = Modernizr.csstransitions && Modernizr.csstransforms3d; // apply perspective to the main container if( this.support ) { this.$el.css( 'perspective', this.options.perspective + 'px' ); // set the transition to the main container // we will need to move it if: // this.options.centered is true; // the opened element goes outside of the viewport this.$el.css( 'transition', 'all ' + ( this.options.speed * this.options.folds * this.options.containerSpeedFactor ) + 'ms ' + this.options.containerEasing ); } // initial sizes this.initialDim = { width : this.$el.width(), height : this.$el.height(), left : 0, top : 0 }; // change the layout this._layout(); // cache some initial values: // initial content this.$iContent = this.$el.find( '.uc-initial' ); this.iContent = this.$iContent.html(); // final content this.$fContent = this.$el.find( '.uc-final' ); this.fContent = this.$fContent.html(); // this element is inserted in the main container and it will contain the initial and final content elements this.$finalEl = $( '<div class="uc-final-wrapper"></div>' ).append( this.$iContent.clone().hide(), this.$fContent ).hide(); this.$el.append( this.$finalEl ); // initial element's offset this._setDimOffset(); // status this.opened = false; this.animating = false; // initialize events this._initEvents(); }, // changes the initial html structure // adds wrappers to the uc-initial-content and uc-final-content divs _layout : function() { var $initialContentEl = this.$el.children( 'div.uc-initial-content' ), finalDim = this._getFinalDim(), $finalContentEl = this.$el.children( 'div.uc-final-content' ).css( { width : finalDim.width, height : finalDim.height } ); $initialContentEl.wrap( '<div class="uc-initial"></div>' ); $finalContentEl.show().wrap( $( '<div class="uc-final"></div>' ) ); }, // initialize the necessary events _initEvents : function() { var self = this; $window.on( 'debouncedresize.pfold', function( event ) { // update offsets self._setDimOffset(); } ); }, // set/update offsets _setDimOffset : function() { this.initialDim.offsetL = this.$el.offset().left - $window.scrollLeft(); this.initialDim.offsetT = this.$el.offset().top - $window.scrollTop(); this.initialDim.offsetR = $window.width() - this.initialDim.offsetL - this.initialDim.width; this.initialDim.offsetB = $window.height() - this.initialDim.offsetT - this.initialDim.height; }, // gets the values needed to translate the main container (if options.centered is true) _getTranslationValue : function() { var x = 0, y = 0, horizTimes = 0, vertTimes = 0; for( var i = 0; i < this.options.folds; ++i ) { // bottom as default var dir = this.options.folddirection[ i ] || 'bottom'; switch( dir ) { case 'left' : x += this.initialDim.width * Math.pow( 2, horizTimes ) / 2; horizTimes += 1; break; case 'right' : x -= this.initialDim.width * Math.pow( 2, horizTimes ) / 2; horizTimes += 1; break; case 'top' : y += this.initialDim.height * Math.pow( 2, vertTimes ) / 2; vertTimes += 1; break; case 'bottom' : y -= this.initialDim.height * Math.pow( 2, vertTimes ) / 2; vertTimes += 1; break; } } return { x : x, y : y }; }, // gets the accumulated values for left, right, top and bottom once the element is opened _getAccumulatedValue : function() { var l = 0, r = 0, t = 0, b = 0, horizTimes = 0, vertTimes = 0; for( var i = 0; i < this.options.folds; ++i ) { // bottom as default var dir = this.options.folddirection[ i ] || 'bottom'; switch( dir ) { case 'left' : l += this.initialDim.width * Math.pow( 2, horizTimes ); horizTimes += 1; break; case 'right' : r += this.initialDim.width * Math.pow( 2, horizTimes ); horizTimes += 1; break; case 'top' : t += this.initialDim.height * Math.pow( 2, vertTimes ); vertTimes += 1; break; case 'bottom' : b += this.initialDim.height * Math.pow( 2, vertTimes ); vertTimes += 1; break; } } return { l : l, r : r, t : t, b : b }; }, // gets the width and height of the element when it is opened _getFinalDim : function() { var l = 0, r = 0, t = 0, b = 0, horizTimes = 0, vertTimes = 0; for( var i = 0; i < this.options.folds; ++i ) { // bottom as default var dir = this.options.folddirection[ i ] || 'bottom'; switch( dir ) { case 'left' : case 'right' : horizTimes += 1; break; case 'top' : case 'bottom' : vertTimes += 1; break; } } return { width : this.initialDim.width * Math.pow( 2, horizTimes ), height : this.initialDim.height * Math.pow( 2, vertTimes ) }; }, // returns the sizes and positions for the element after each (un)folding step _updateStepStyle : function( action ) { var w, h, l, t; if( action === 'fold' ) { w = this.lastDirection === 'left' || this.lastDirection === 'right' ? this.lastStyle.width / 2 : this.lastStyle.width, h = this.lastDirection === 'left' || this.lastDirection === 'right' ? this.lastStyle.height : this.lastStyle.height / 2, l = this.lastDirection === 'left' ? this.lastStyle.left + this.lastStyle.width / 2 : this.lastStyle.left, t = this.lastDirection === 'top' ? this.lastStyle.top + this.lastStyle.height / 2 : this.lastStyle.top; } else { w = this.lastDirection === 'left' || this.lastDirection === 'right' ? this.lastStyle.width * 2 : this.lastStyle.width, h = this.lastDirection === 'left' || this.lastDirection === 'right' ? this.lastStyle.height : this.lastStyle.height * 2, l = this.lastDirection === 'left' ? this.lastStyle.left - this.lastStyle.width : this.lastStyle.left, t = this.lastDirection === 'top' ? this.lastStyle.top - this.lastStyle.height : this.lastStyle.top; } return { width : w, height : h, left : l, top : t }; }, // get the opposite direction _getOppositeDirection : function( realdirection ) { var rvd; switch( realdirection ) { case 'left' : rvd = 'right'; break; case 'right' : rvd = 'left'; break; case 'top' : rvd = 'bottom'; break; case 'bottom' : rvd = 'top'; break; } return rvd; }, // main function: unfolds and folds the element [options.folds] times by using recursive calls _start : function( action, step ) { // Basically we are replacing the element's content with 2 divisions, the top and bottom elements. // The top element will have a front and back faces. The front has the initial content for the first step // and the back will have the final content for the last step. For all the other cases the top element will be blank. // The bottom element will have the final content for the last step and will be blank for all the other cases. // We need to keep the right sizes and positions for these 2 elements, so we need to cache the previous step's state. step |= 0; var self = this, styleCSS = ( action === 'fold' ) ? { width : this.lastStyle.width, height : this.lastStyle.height, left : this.lastStyle.left, top : this.lastStyle.top } : this.initialDim, contentTopFront = '', contentBottom = '', contentTopBack = '', // direction for step [step] // bottom is the default value if none is present direction = ( action === 'fold' ) ? this.options.folddirection[ this.options.folds - 1 - step ] || 'bottom' : this.options.folddirection[ step ] || 'bottom', // future direction value (only for the "fold" action) nextdirection = ( action === 'fold' ) ? this.options.folddirection[ this.options.folds - 2 - step ] || 'bottom' : ''; // remove uc-part divs inside the container (the top and bottom elements) this.$el.find( 'div.uc-part' ).remove(); switch( step ) { // first step & last transition step case 0 : case this.options.folds - 1 : if( action === 'fold' ) { if( step === this.options.folds - 1 ) { styleCSS = this.initialDim; contentTopFront = this.iContent; } if( step === 0 ) { this._setDimOffset(); // reset the translation of the main container this.$el.css( { left : 0, top : 0 } ); var content = this._setLastStep( direction, styleCSS ), contentBottom = content.bottom, contentTopBack = content.top; this.$finalEl.hide().children().hide(); } } else { // unfolding if( step === 0 ) { this._setDimOffset(); // if options.centered is true, we need to center the container. // either ways we need to make sure the container does not move outside the viewport. // let's get the correct translation values for the container's transition var coords = this._getTranslationViewport(); this.$el.addClass( 'uc-current' ).css( { left : coords.ftx, top : coords.fty } ); contentTopFront = this.iContent; this.$finalEl.hide().children().hide(); } else { styleCSS = this._updateStepStyle( action ); } if( step === this.options.folds - 1 ) { var content = this._setLastStep( direction, styleCSS ), contentBottom = content.bottom, contentTopBack = content.top; } } break; // last step is to replace the topElement and bottomElement with a division that has the final content case this.options.folds : styleCSS = ( action === 'fold') ? this.initialDim : this._updateStepStyle( action ); // remove top and bottom elements var contentIdx = ( action === 'fold' ) ? 0 : 1; this.$el .find( '.uc-part' ) .remove(); this.$finalEl.css( styleCSS ).show().children().eq( contentIdx ).show(); this.opened = ( action === 'fold' ) ? false : true; this.animating = false; // nothing else to do if( action === 'fold' ) { this.$el.removeClass( 'uc-current' ); this.options.onEndFolding(); } else { this.options.onEndUnfolding(); } return false; break; // all the other steps default : // style of new layout will depend on the last step direction styleCSS = this._updateStepStyle( action ); break; } // transition properties for the step if( this.support ) { styleCSS.transition = 'all ' + this.options.speed + 'ms ' + this.options.easing; } var unfoldClass = 'uc-unfold-' + direction, topElClasses = ( action === 'fold' ) ? 'uc-unfold uc-part ' + unfoldClass : 'uc-part ' + unfoldClass, $topEl = $( '<div class="' + topElClasses + '"><div class="uc-front">' + contentTopFront + '</div><div class="uc-back">' + contentTopBack + '</div></div>' ).css( styleCSS ), $bottomEl = $( '<div class="uc-part uc-single">' + contentBottom + '</div>' ).css( styleCSS ); // cache last direction and style this.lastDirection = ( action === 'fold' ) ? nextdirection : direction; this.lastStyle = styleCSS; // append new elements this.$el.append( $bottomEl, $topEl ); // add overlays if( this.options.overlays && this.support ) { this._addOverlays( action, $bottomEl, $topEl ); } setTimeout( function() { // apply style ( action === 'fold' ) ? $topEl.removeClass( 'uc-unfold' ) : $topEl.addClass( 'uc-unfold' ); if( self.support ) { $topEl.on( self.transEndEventName , function(event) { if( event.target.className !== 'uc-flipoverlay' && step < self.options.folds ) { // goto next step in [options.folddelay] ms setTimeout( function() { self._start( action, step + 1 ); }, self.options.folddelay ); } } ); } else { // goto next step self._start( action, step + 1 ); } if( self.options.overlays && self.support ) { var bo = ( action === 'fold' ) ? 1 : 0, tbo = ( action === 'fold' ) ? .5 : 0, tfo = ( action === 'fold' ) ? 0 : .5; self.$bottomOverlay.css( 'opacity', bo ); self.$topBackOverlay.css( 'opacity', tbo ); self.$topFrontOverlay.css( 'opacity', tfo ); } } , 30 ); }, // gets the translation values for the container's transition _getTranslationViewport : function() { // the accumulatedValues stores the left, right, top and bottom increments to the final/opened element relatively to the initial/closed element var accumulatedValues = this._getAccumulatedValue(), tx = 0, ty = 0; // the final offsets for the opened element this.fOffsetL = this.initialDim.offsetL - accumulatedValues.l; this.fOffsetT = this.initialDim.offsetT - accumulatedValues.t; this.fOffsetR = this.initialDim.offsetR - accumulatedValues.r; this.fOffsetB = this.initialDim.offsetB - accumulatedValues.b; if( this.fOffsetL < 0 ) { tx = Math.abs( this.fOffsetL ); } if( this.fOffsetT < 0 ) { ty = Math.abs( this.fOffsetT ); } if( this.fOffsetR < 0 ) { tx -= Math.abs( this.fOffsetR ); } if( this.fOffsetB < 0 ) { ty -= Math.abs( this.fOffsetB ); } // final translation values var ftx = tx, fty = ty; if( this.options.centered ) { var translationValue = this._getTranslationValue(); if( translationValue.x > 0 && this.fOffsetR + translationValue.x >= 0 ) { ftx = ( this.fOffsetL >= 0 ) ? Math.min( translationValue.x , this.fOffsetR ) : translationValue.x + ( tx - translationValue.x ); } else if( translationValue.x < 0 && this.fOffsetL + translationValue.x >= 0 ) { ftx = ( this.fOffsetR >= 0 ) ? Math.min( translationValue.x , this.fOffsetL ) : translationValue.x + ( tx - translationValue.x ); } else { ftx = translationValue.x + ( tx - translationValue.x ); } if( translationValue.y > 0 && this.fOffsetB + translationValue.y >= 0 ) { fty = ( this.fOffsetT >= 0 ) ? Math.min( translationValue.y , this.fOffsetB ) : translationValue.y + ( ty - translationValue.y ); } else if( translationValue.y < 0 && this.fOffsetT + translationValue.y >= 0 ) { fty = ( this.fOffsetB >= 0 ) ? Math.min( translationValue.y , this.fOffsetT ) : translationValue.y + ( ty - translationValue.y ); } else { fty = translationValue.y + ( ty - translationValue.y ); } } return { ftx : ftx, fty : fty }; }, // sets the last step's content _setLastStep : function( direction, styleCSS ) { var contentBottom, contentTopBack, contentBottomStyle = '', contentTopBackStyle = ''; switch( direction ) { case 'bottom' : contentTopBackStyle = 'margin-top: -' + styleCSS.height + 'px'; break; case 'top' : contentBottomStyle = 'margin-top: -' + styleCSS.height + 'px'; break; case 'left' : contentTopBackStyle = 'width:' + ( styleCSS.width * 2 ) + 'px'; contentBottomStyle = 'width:' + ( styleCSS.width * 2 ) + 'px;margin-left: -' + styleCSS.width + 'px'; break; case 'right' : contentTopBackStyle = 'with:' + ( styleCSS.width * 2 ) + 'px;margin-left: -' + styleCSS.width + 'px'; contentBottomStyle = 'width:' + ( styleCSS.width * 2 ) + 'px'; break; } contentBottom = '<div class="uc-inner"><div class="uc-inner-content" style="' + contentBottomStyle + '">' + this.fContent + '</div></div>'; var contentTopBackClasses = direction === 'top' || direction === 'bottom' ? 'uc-inner uc-inner-rotate' : 'uc-inner'; contentTopBack = '<div class="' + contentTopBackClasses + '"><div class="uc-inner-content" style="' + contentTopBackStyle + '">' + this.fContent + '</div></div>'; return { bottom : contentBottom, top : contentTopBack }; }, // adds overlays to the "(un)folding" elements if the options.overlays is true _addOverlays : function( action, $bottomEl, $topEl ) { var bottomOverlayStyle, topFrontOverlayStyle, topBackOverlayStyle; this.$bottomOverlay = $( '<div class="uc-overlay"></div>' ); this.$topFrontOverlay = $( '<div class="uc-flipoverlay"></div>' ); this.$topBackOverlay = $( '<div class="uc-flipoverlay"></div>' ); if( action === 'fold' ) { bottomOverlayStyle = { transition : 'opacity ' + ( this.options.speed / 2 ) + 'ms ' + this.options.easing + ' ' + ( this.options.speed / 2 ) + 'ms' }; topFrontOverlayStyle = { opacity : .5, transition : 'opacity ' + ( this.options.speed / 2 ) + 'ms ' + this.options.easing }; topBackOverlayStyle = { opacity : 0, transition : 'opacity ' + ( this.options.speed / 2 ) + 'ms ' + this.options.easing }; } else { bottomOverlayStyle = { opacity : 1, transition : 'opacity ' + ( this.options.speed / 2 ) + 'ms ' + this.options.easing }; topFrontOverlayStyle = { transition : 'opacity ' + ( this.options.speed / 2 ) + 'ms ' + this.options.easing }; topBackOverlayStyle = { opacity : .5, transition : 'opacity ' + ( this.options.speed / 2 ) + 'ms ' + this.options.easing + ' ' + ( this.options.speed / 2 ) + 'ms' }; } $bottomEl.append( this.$bottomOverlay.css( bottomOverlayStyle ) ); $topEl.children( 'div.uc-front' ) .append( this.$topFrontOverlay.css( topFrontOverlayStyle ) ) .end() .children( 'div.uc-back' ) .append( this.$topBackOverlay.css( topBackOverlayStyle ) ); }, // public method: unfolds the element unfold : function() { // if opened already or currently (un)folding return if( this.opened || this.animating ) { return false; } this.animating = true; this._start( 'unfold' ); }, // public method: folds the element fold : function() { // if not opened or currently (un)folding return if( !this.opened || this.animating ) { return false; } this.animating = true; this._start( 'fold' ); }, // public method: returns 'opened' or 'closed' getStatus : function() { return ( this.opened ) ? 'opened' : 'closed'; } }; var logError = function( message ) { if ( window.console ) { window.console.error( message ); } }; $.fn.pfold = function( options ) { var instance = $.data( this, 'pfold' ); if ( typeof options === 'string' ) { var args = Array.prototype.slice.call( arguments, 1 ); this.each(function() { if ( !instance ) { logError( "cannot call methods on pfold prior to initialization; " + "attempted to call method '" + options + "'" ); return; } if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) { logError( "no such method '" + options + "' for pfold instance" ); return; } instance[ options ].apply( instance, args ); }); } else { this.each(function() { if ( instance ) { instance._init(); } else { instance = $.data( this, 'pfold', new $.PFold( options, this ) ); } }); } return instance; }; } )( jQuery, window );<file_sep>$('#profile').addClass("active item"); $('#overview_tab').addClass('active'); <file_sep>var selectapp = angular.module("select", []); window.fbAsyncInit = function() { FB.init({ appId: app_id, xfbml: true, version: 'v2.5' }); // checkLoginState(); }; // Load the SDK asynchronously (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/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); selectapp.controller('selectctrl', function($scope, $http) { // $scope.admin_token = function() { // alert('hello'); $scope.dataObj = {}; $scope.fb_login = function() { FB.login(function(response) { // handle the response $scope.signwithfb(response); }, { scope: 'public_profile,email,user_managed_groups' }); } $scope.statusChangeCallback = function(response) { // The response object is returned with a status field that lets the // app know the current login status of the person. // Full docs on the response object can be found in the documentation // for FB.getLoginStatus(). if (response.status === 'connected') { // Logged into your app and Facebook. // alert('h'); this.signwithfb(response); } else { this.fb_login(); // The person is not logged into Facebook, so we're not sure if // they are logged into this app or not. } } $scope.checkLoginState = function() { $('#form').addClass('loading'); // alert('h'); FB.getLoginStatus(function(response) { $scope.statusChangeCallback(response); }); } $scope.signwithfb = function(response) { // FB.api('/me/picture?width=400&height=400', function(response) { // console.log(response); // }); if (response && !response.error) { $scope.dataObj['access_token'] = response['authResponse']['accessToken']; $http({ method: 'POST', url: '/admin/access_token/', data: $scope.dataObj, // pass in data as strings }).success(function(data) { console.log(data); }); } else { console.log(response); } } });<file_sep>from flask import Flask from flask.ext.triangle import Triangle #from flask.ext.mail import Mail app = Flask(__name__) Triangle(app) # # app.config.update(dict( # # DEBUG=True, # # MAIL_SERVER='smtp.gmail.com', # # MAIL_PORT=465, # # MAIL_USE_TLS=False, # # MAIL_USE_SSL=True, # # MAIL_USERNAME='<EMAIL>', # # MAIL_PASSWORD='' # # )) # mail = Mail(app) from longclaw import views <file_sep>window.fbAsyncInit = function() { FB.init({ appId: app_id , xfbml: true, version: 'v2.5' }); // checkLoginState(); }; // Load the SDK asynchronously (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/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); var signinapp = angular.module("sign_in", ["ngCookies"]); signinapp.controller("formctrl", ['$scope', '$http', '$element', '$cookies', function($scope, $http, $element, $cookies) { var form_element = $($element); // $scope.uname = ""; // $scope.passw = ""; $scope.isInvalid = function() { return !($('#form').form('validate form')); } $scope.form_validate = function() { if (this.isInvalid()) { return; } this.login(); } $scope.login = function() { $('#form').addClass('loading'); var dataObj = { user: $scope.uname, passwd: $scope.passwd, 'g-recaptcha-response': $('#g-recaptcha-response').val(), }; $http({ method: 'POST', url: '/signin/', data: dataObj, // pass in data as strings }).success(function(data) { $('#form').removeClass('loading'); console.log(data); if (data['status'] != 'success') { // if not successful, bind errors to error variables $('#form').addClass('error'); $('#form').removeClass('loading'); $('.ui.error.message').html('<ul class="list"><li>' + data['msg'] + '</li></ul>'); grecaptcha.reset(); } else { // if successful, bind success message to message // alert('success'); $cookies.put('auth_key', data['auth_key'], { 'path': '/' }); $(location).attr('href', '/profile/' + data['user'] + '/'); } }); } } ]); signinapp.controller("signwithfb", ['$scope', '$http', '$cookies', function($scope, $http, $cookies) { $scope.dataObj = {}; $scope.fb_login = function() { FB.login(function(response) { // handle the response $scope.signwithfb(response); }, { scope: 'public_profile,email,user_managed_groups' }); } $scope.statusChangeCallback = function(response) { // The response object is returned with a status field that lets the // app know the current login status of the person. // Full docs on the response object can be found in the documentation // for FB.getLoginStatus(). if (response.status === 'connected') { // Logged into your app and Facebook. // alert('h'); this.signwithfb(response); } else { this.fb_login(); // The person is not logged into Facebook, so we're not sure if // they are logged into this app or not. } } $scope.checkLoginState = function() { $('#form').addClass('loading'); FB.getLoginStatus(function(response) { $scope.statusChangeCallback(response); }); } $scope.signwithfb = function(response) { // FB.api('/me/picture?width=400&height=400', function(response) { // console.log(response); // }); if (response && !response.error) { $scope.dataObj['access_token'] = response['authResponse']['accessToken']; FB.api('/me?fields=email', function(response) { if (response && !response.error) { $scope.dataObj['fb_email'] = response['email']; $http({ method: 'POST', url: '/signin/facebook/', data: $scope.dataObj, // pass in data as strings }).success(function(data) { $('#form').removeClass('loading'); console.log(data); if (data['status'] != 'success') { // if not successful, bind errors to error variables $('#form').addClass('error'); $('#form').removeClass('loading'); $('.ui.error.message').html('<ul class="list"><li>' + data['msg'] + '</li></ul>'); } else { $cookies.put('auth_key', data['auth_key'], { 'path': '/' }); $(location).attr('href', '/profile/' + data['user'] + '/'); } }); } }); } else { console.log(response); } } } ]); $('#form').form({ user: { identifier: 'user', rules: [{ type: 'empty', prompt: 'Please enter a username' }, { type: 'regExp[/^[a-zA-Z0-9_-]{4,16}$/]', prompt: 'Please enter a 4-16 letter username with a-z 0-9 _-' }] }, passwd: { identifier: 'passwd', rules: [{ type: 'empty', prompt: 'Please enter password' }, { type: 'minLength[6]', prompt: 'Your password must be at least 6 characters' }] } }); $(document).ready(function() { $("#forgot").click(function() { $('#modaldiv').modal('show'); }); }); <file_sep>$('#discuss').addClass("active item"); semantic.visiblity = {}; // ready event semantic.visiblity.ready = function() { // selector cache var $pageTabs = $('.masthead.tab.segment .stackable.menu .item'), $firstColumn = $('.first.example .main.column'), $firstSegment = $('.first.example .demo.segment'), $firstSticky = $('.first.example .grid .sticky'), $secondColumn = $('.second.example .main.column'), $secondSegment = $('.second.example .demo.segment'), $secondSticky = $('.second.example .grid .sticky'), $settingsCheckboxes = $('.second.example .checkbox'), $log = $('.second.example .console'), $clearButton = $('.second.example .clear.button'), handler ; // event handlers handler = { clearConsole: function() { $log.empty(); }, updateTable: function(calculations) { $.each(calculations, function(name, value) { var value = (typeof value == 'integer') ? parseInt(value, 10) : value.toString(), $td ; if(name == 'pixelsPassed' || name == 'width' || name == 'height') { value = parseInt(value, 10) + 'px'; } else if(name == 'percentagePassed') { value = parseInt(value * 100, 10) + '%'; } $td = $('.first.example .grid .sticky tr.'+ name +' td:last-child'); if($td.html() !== value) { if(value == 'true' || value == 'false') { $td.removeClass('highlight').addClass('highlight'); setTimeout(function(){ $td.removeClass('highlight'); }, 2000); } $td.html(value); } }); } }; $pageTabs.tab('setting', 'onLoad', function() { $('.ui.sticky') .sticky('refresh') ; $(this).find('.visibility.example .overlay, .visibility.example .demo.segment, .visibility.example .items img') .visibility('refresh') ; }); $firstSticky .sticky({ observeChanges : false, pushing : true, context : $firstColumn, offset : 60 }) ; $clearButton .on('click', handler.clearConsole) ; $firstSegment .visibility({ once : false, continuous : true, observeChanges : false, onUpdate : handler.updateTable }) ; $secondSegment .visibility({ onOnScreen: function() { $log.append('<div class="highlight">onOnScreen fired</div>'); $log.scrollTop(999999); }, onOffScreen: function() { $log.append('<div class="highlight">onOffScreen fired</div>'); $log.scrollTop(999999); }, onTopVisible: function() { $log.append('<div class="highlight">onTopVisible fired</div>'); $log.scrollTop(999999); }, onBottomVisible: function() { $log.append('<div class="highlight">onBottomVisible fired</div>'); $log.scrollTop(999999); }, onPassing: function() { $log.append('<div class="highlight">onPassing fired</div>'); $log.scrollTop(999999); }, onTopPassed: function() { $log.append('<div class="highlight">onTopPassed fired</div>'); $log.scrollTop(999999); }, onBottomPassed: function() { $log.append('<div class="highlight">onBottomPassed fired</div>'); $log.scrollTop(999999); }, onTopVisibleReverse: function() { $log.append('<div class="highlight">onTopVisibleReverse fired</div>'); $log.scrollTop(999999); }, onBottomVisibleReverse: function() { $log.append('<div class="highlight">onBottomVisibleReverse fired</div>'); $log.scrollTop(999999); }, onPassingReverse: function() { $log.append('<div class="highlight">onPassingReverse fired</div>'); $log.scrollTop(999999); }, onTopPassedReverse: function() { $log.append('<div class="highlight">onTopPassedReverse fired</div>'); $log.scrollTop(999999); }, onBottomPassedReverse: function() { $log.append('<div class="highlight">onBottomPassedReverse fired</div>'); $log.scrollTop(999999); } }) ; $settingsCheckboxes .checkbox({ onChecked: function() { var setting = $(this).attr('name'); $secondSegment.visibility('setting', setting, true); }, onUnchecked: function() { var setting = $(this).attr('name'); $secondSegment.visibility('setting', setting, false); } }) ; $secondSticky .sticky({ observeChanges : false, pushing : true, context : $secondColumn, offset : 60 }) ; }; var count = 1; window.loadFakeContent = function() { // load fake content var $segment = $('.infinite .demo.segment'), $loader = $segment.find('.inline.loader'), $content = $('<h3 class="ui header">Loaded Content #' + count + '</h3><img class="ui image" src="/static/images/logo.png">') ; if(count <= 5) { $loader.addClass('active'); setTimeout(function() { $loader .removeClass('active') .before($content) ; $('.ui.sticky') .sticky('refresh') ; $('.visibility.example > .overlay, .visibility.example > .demo.segment, .visibility.example .items img') .visibility('refresh') ; }, 1000); } count++; } // attach ready event $(document) .ready(semantic.visiblity.ready) ;<file_sep> window.fbAsyncInit = function() { FB.init({ appId: app_id, xfbml: true, version: 'v2.4' }); // checkLoginState(); }; // Load the SDK asynchronously (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/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); // Here we run a very simple test of the Graph API after login is // successful. See statusChangeCallback() for when this call is made. knuth.controller("facebook", ['$scope', '$http', function($scope, $http) { $scope.dataObj = {}; $scope.fb_login = function() { FB.login(function(response) { // handle the response sync_with_facebook(); }, { scope: 'public_profile,email,user_managed_groups' }); } $scope.statusChangeCallback = function(response) { // The response object is returned with a status field that lets the // app know the current login status of the person. // Full docs on the response object can be found in the documentation // for FB.getLoginStatus(). if (response.status === 'connected') { // Logged into your app and Facebook. this.sync_with_facebook(response); } else { this.fb_login(); // The person is not logged into Facebook, so we're not sure if // they are logged into this app or not. } } $scope.checkLoginState = function() { FB.getLoginStatus(function(response) { $scope.statusChangeCallback(response); }); } $scope.sync_with_facebook = function(response) { // FB.api('/me/picture?width=400&height=400', function(response) { // console.log(response); // }); if (response && !response.error) { $scope.dataObj['access_token'] = response['authResponse']['accessToken']; FB.api('/me?fields=email', function(response) { if (response && !response.error) { $scope.dataObj['fb_email'] = response['email']; $('#sync').addClass('loading'); $http({ method: 'POST', url: '/sync/' + login_user + '/', data: $scope.dataObj, // pass in data as strings }).success(function(data) { $('#form').removeClass('loading'); console.log(data); if (data['status'] != 'success') { // if not successful, bind errors to error variables $('#sync').removeClass('loading'); alert(data['msg']); } else { location.reload(); } }).error(function(data) { alert('Error'); }); } }); } } } ]); knuth.controller("settings", ['$scope', '$http', function($scope, $http) { $scope.save = function() { // var postData = {}; var postData = new FormData(); if ($scope.settings) { postData['settings'] = $scope.settings; } $('#settings').addClass('loading'); $http({ method: 'POST', url: '/settings/' + login_user + '/', data: $scope.settings, // pass in data as strings }).success(function(data) { // $('#form').removeClass('loading'); // console.log(data); if (data['status'] != 'success') { // // if not successful, bind errors to error variables // $('#sync').removeClass('loading'); alert(data['msg']); $('#settings').removeClass('loading'); } else { location.reload(); } }).error(function(data) { alert('Error'); $('#settings').removeClass('loading'); }); // if ($('#pic')[0].files.length == 1) { // postData['pic'] = $('#pic')[0]; // } } } ]);<file_sep>from longclaw import app import rethinkdb as rdb import json from rethinkdb.errors import RqlRuntimeError from flask import request, render_template, redirect import requests from urllib import urlencode from urllib2 import urlopen import re import hashlib from facebook import GraphAPI, GraphAPIError from auth import * from cors import * import math from bs4 import BeautifulSoup import re #from flask.ext.mail import Message #from mail_config import * #from longclaw import mail import os #from markdown2 import markdown @app.route('/xyz/') def test(): return render_template('test.html') def authenticate_webkiosk(enroll, passwd, dob): try: check = requests.get( 'https://webkiosk.jiit.ac.in/CommonFiles/UserActionn.jsp?' + 'x=&txtInst=Institute&' + 'InstCode=JIIT&' + 'txtuType=Member+Type&' + 'UserType=S&' + 'txtCode=Enrollment+No&' + 'MemberCode=' + enroll + '&DOB=DOB' + '&DATE1=' + dob + '&txtPin=Password%2FPin&' + 'Password=' + <PASSWORD> + '&BTNSubmit=Submit', timeout=5) except: return False response = check.content # check if enroll and passwd are correct incorrect = ['please', 'Administrator', 'Invalid', 'NullPointer'] if any(word in response for word in incorrect): return False return True def get_rdb_conn(): connection = rdb.connect(host=RDB_HOST, port=RDB_PORT) return connection def gen_auth_key(user): s = URLSafeSerializer('secret-key', salt='be_efficient') return s.dumps(user) # db setup; only run once # will add a check that this is only run by admin @app.route('/create_db/') def dbSetup(): res = "" connection = rdb.connect(host=RDB_HOST, port=RDB_PORT) try: rdb.db_create(TODO_DB).run(connection) res = 'Database setup completed' except RqlRuntimeError: res = 'Database already exists.' finally: connection.close() return res @app.route('/') def hello_world(): try: user = get_user_from_auth(request.cookies['auth_key']) # return redirect('/') except: user = '' return render_template('home.html', login_user=user), 200 #return 'Hello World!' # error 404 not found @app.errorhandler(404) def page_not_found(e): return render_template("404.html"), 404 def check_captcha(response, remoteip): # ipdb.set_trace() captcha_url = 'https://www.google.com/recaptcha/api/siteverify' params = urlencode({ 'secret': CAPTCHA_SECRET, 'response': response, 'remoteip': remoteip }) response = urlopen(captcha_url, params) try: ret = json.load(response)['success'] except: ret = False return ret def validate_fb_email(email, access_token): # check if user is has synced fb email try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['fb_email'] == email ).run(connection) except: return response_msg('error', 'Could not connect to db') if len(cursor.items) == 0: return response_msg('error', 'facebook not synced or user not registered') # if user has already synced fb email # check whether access token and email is valid try: graph = GraphAPI(access_token) profile = graph.get_object('me', fields='email') fb_email = profile['email'] except GraphAPIError as e: return response_msg('error', e) except: return response_msg('error', 'Could not connect to facebook') if fb_email == email: return response_msg('success', 'OK') else: return response_msg('error', 'invalid fb details') @app.route('/signup/', methods=['GET', 'POST', 'OPTIONS']) @crossdomain(origin='*', headers=['Content-Type', 'auth_key']) def signup(): #import ipdb; ipdb.set_trace(); if request.method == 'GET': return render_template("signup.html") elif request.method == 'POST': form_data = json.loads(request.data) try: dob = form_data['dob'] fname = form_data['fname'] lname = form_data['lname'] email = form_data['email'] username = form_data['user'] passwd = form_data['passwd'] cpasswd = form_data['cpasswd'] enroll = form_data['enroll'] wbpass = form_data['wbpass'] ccuser = form_data['ccuser'] cfuser = form_data['cfuser'] if request.headers.get('key'): key = request.headers.get('key') captcha_resp = "" else: key = "" captcha_resp = form_data['g-recaptcha-response'] except: return response_msg('error', 'form data not complete') remoteip = request.remote_addr # form validation if len(fname) <= 0: return response_msg('error', "First name shouldn't be empty") if len(lname) <= 0: return response_msg('error', "Last name shouldn't be empty") if not re.match("^[a-zA-Z0-9_.-]+$", username): return response_msg( 'error', 'username should be alphnumeric and/or -_' ) if not re.match(r"[^@]+@[^@]+\.[^@]+", email): return response_msg('error', 'Invalid email') if len(username) < 4 or len(username) > 16: return response_msg('error', 'Please enter a 4-16 letter username') if len(passwd) < 6: return response_msg( 'error', 'Password should be minimum of 6 characters' ) if cpasswd != passwd: return response_msg('error', 'Passwords do not match') if not authenticate_webkiosk(enroll, wbpass, dob): return response_msg('error', 'Webkiosk authentication faiiled') if key: if key != ANDROID_HEADER_KEY: return response_msg('error', 'Authentication faiiled') else: if not check_captcha(captcha_resp, remoteip): return response_msg('error', 'Captcha authentication faiiled') # authenticate online judge handles cc_url = requests.get('https://www.codechef.com/users/' + ccuser) try: if cc_url.url == 'https://www.codechef.com/': return response_msg('error', 'Incorrect Codechef Handle') except: return response_msg('error', 'could not connect to codeforces') cf_url = requests.get( 'http://codeforces.com/api/user.info?handles=' + cfuser ) try: if json.loads(cf_url.text)['status'] != 'OK': return response_msg('error', 'Incorrect Codeforces Handle') except: return response_msg('error', 'could not connect to codeforces') # check if user exists try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['enroll'] == enroll ).run(connection) except: return response_msg('error', 'Could not connect to db') if len(cursor.items) != 0: return response_msg('error', 'User is already registered') # check if username is unique try: cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == username ).run(connection) except: return response_msg('error', 'Could not connect to db') if len(cursor.items) != 0: return response_msg('error', 'Username is already taken') # finally inserting in db #import ipdb; ipdb.set_trace() try: new_user = rdb.db(TODO_DB).table("user").insert({ "fname": fname, "lname": lname, "email": email, "fb_email": "", "username": username, "passwd": hashlib.sha224(passwd).hexdigest(), "enroll": enroll, "cchandle": ccuser, "cfhandle": cfuser, "pic": DEFAULT_PIC + username + '.png' }).run(connection) except: return response_msg('error', 'error inserting in db') try: if new_user['inserted'] != 1: return response_msg('error', 'error inserting in db') except: return response_msg('error', 'error inserting in db') #import ipdb;ipdb.set_trace() ratings = rating(cfuser, ccuser,0) ratings = json.loads(ratings[0]) try: lrating = ratings['lrating'] cfrating = ratings['cf_rating'] srating = ratings['srating'] except: lrating = 0 srating = 0 cfrating = 0 colg_rating = 20 * ((cfrating/100)**2) colg_rating = colg_rating + 2000 + 7 * (((lrating/1000)**2) + (lrating/20)) colg_rating = colg_rating + 2000 + 5 * (((srating/100)**2) + (srating/20)) try: cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == username ).update({ 'lrating': lrating, 'srating': srating, 'cfrating': cfrating, 'colg_rating': colg_rating/3 }).run(connection) except: pass # return response_msg('success', 'OK') return response_msg('success', 'OK', auth_key=gen_auth_key(username), user=username) else: return response_msg('error', 'only GET/POST supported') @app.route('/signin/', methods=['GET', 'POST', 'OPTIONS']) @crossdomain(origin='*', headers=['Content-Type', 'auth_key']) def signin(): # #import ipdb; ipdb.set_trace() remoteip = request.remote_addr if request.method == 'GET': try: user = get_user_from_auth(request.cookies['auth_key']) return redirect('/') except: pass return render_template('signin.html', app_id=FB_APP_ID) elif request.method == 'POST': form_data = json.loads(request.data) try: username = form_data['user'] passwd = hashlib.sha224(form_data['passwd']).hexdigest() if request.headers.get('key'): key = request.headers.get('key') captcha_resp = '' else: key = "" captcha_resp = form_data['g-recaptcha-response'] except: return response_msg('error', 'form data not complete') if key: if key != ANDROID_HEADER_KEY: return response_msg('error', 'Authentication faiiled') else: if not check_captcha(captcha_resp, remoteip): return response_msg('error', 'Captcha authentication faiiled') # check if credentials are correct try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == username ).run(connection) except: return response_msg('error', 'Could not connect to db') if len(cursor.items) == 0: return response_msg('error', "User doesn't exists") db_pass = cursor.items[0]['passwd'] if db_pass != passwd: return response_msg('error', 'Passwords do not match') return response_msg('success', 'logged in', auth_key=gen_auth_key(username), user=username) else: return response_msg('error', 'only GET/POST supported') def auth_username(name): # #import ipdb; ipdb.set_trace(); try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == name ).run(connection) except: return False if len(cursor.items) == 0: return False return True @app.route('/profile/<name>/', methods=['GET']) def profile(name): # #import ipdb; ipdb.set_trace(); auth = auth_username(name) if auth != True: return render_template('404.html'), 404 try: user = get_user_from_auth(request.cookies['auth_key']) # return redirect('/') except: user = '' try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == name ).run(connection) pic = cursor.items[0]['pic'] except: return response_msg('error', 'Could not connect to db') return render_template('profile.html', user=cursor.items[0], login_user=user, username=name) @app.route('/blog/new/<name>/', methods=['GET', 'POST']) @login_required def blog(name): return render_template('new_blog.html', username=name, login_user=name) @app.route('/settings/<name>/', methods=['GET', 'POST']) @login_required def user_settings(name): auth = auth_username(name) if auth != True: return render_template('404.html'), 404 # #import ipdb;ipdb.set_trace() if request.method == 'GET': try: user = get_user_from_auth(request.cookies['auth_key']) # return redirect('/') except: user = '' try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == name ).run(connection) pic = cursor.items[0]['pic'] except: return response_msg('error', 'Could not connect to db') return render_template('settings.html',pic=pic, username=name, login_user=user, app_id=FB_APP_ID) else: # #import ipdb; ipdb.set_trace(); try: form_data = json.loads(request.data) passwd = form_data['passwd'] cpasswd = form_data['cpasswd'] npasswd = form_data['npasswd'] if len(npasswd) < 6: return response_msg( 'error', 'Password should be minimum of 6 characters' ) passwd = hashlib.sha224(form_data['passwd']).hexdigest() cpasswd = hashlib.sha224(form_data['cpasswd']).hexdigest() npasswd = hashlib.sha224(form_data['npasswd']).hexdigest() if request.headers.get('key'): key = request.headers.get('key') else: key = "" except: return response_msg('error', 'form data not complete') if key: if key != ANDROID_HEADER_KEY: return response_msg('error', 'Authentication faiiled') # check if credentials are correct try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == name ).run(connection) except: return response_msg('error', 'Could not connect to db') db_pass = cursor.items[0]['passwd'] if db_pass != passwd: return response_msg('error', 'Current Password does not match') if cpasswd != npasswd: return response_msg('error', 'New Passwords do not match') try: cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == name ).update({'passwd': cpasswd} ).run(connection) except: return response_msg('error', 'Could not connect to db') return response_msg('success', 'OK') @app.route('/sync/<name>/', methods=['POST']) @login_required def sync_facebook(name): #import ipdb; ipdb.set_trace(); try: form_data = json.loads(request.data) except: return response_msg('error', 'data not correct') try: graph = GraphAPI(form_data['access_token']) try: # #import ipdb; ipdb.set_trace(); email = graph.get_object('me', fields='email')['email'] pic = graph.get_object('me/picture', width='400', height='400')['url'] print pic if email != form_data['fb_email']: return response_msg('error', 'incorrect facebook email') except: return response_msg('error', 'data not complete') except: return response_msg('error', 'invalid access token') try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == name ).update({'fb_email': email, 'pic': pic} ).run(connection) cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == name ).run(connection) except: return response_msg('error', 'Could not connect to db') return response_msg('success', 'OK', data=cursor.items[0]) @app.route('/about/', methods=['GET']) def about(): try: user = get_user_from_auth(request.cookies['auth_key']) # return redirect('/') except: user = '' return render_template('about_us.html', login_user=user), 200 @app.route('/ratings/', methods=['GET']) def ratings(): try: user = get_user_from_auth(request.cookies['auth_key']) # return redirect('/') except: user = '' return render_template('ratings.html', login_user=user), 200 @app.route('/all_ratings/', methods=['GET']) def all_ratings(): # import ipdb; ipdb.set_trace() try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row["username"] != "admin").pluck( "srating", "lrating", "cfrating", "colg_rating", "username" ).run(connection) except: return response_msg('error', 'could not connect to db') return response_msg('success', 'OK', users=cursor.items) @app.route('/discuss/', methods=['GET']) def discuss(): try: user = get_user_from_auth(request.cookies['auth_key']) # return redirect('/') except: user = '' return render_template('discuss.html', login_user=user), 200 @app.route('/facebook/', methods=['GET']) def facebook(): try: user = get_user_from_auth(request.cookies['auth_key']) # return redirect('/') except: user = '' try: access_token = rds.get('access_token') except: access_token = '' return render_template('facebook.html', login_user=user, access_token=access_token), 200 @app.route('/facebook/album/<id>/', methods=['GET']) def album(id): try: user = get_user_from_auth(request.cookies['auth_key']) # return redirect('/') except: user = '' try: access_token = rds.get('access_token') except: access_token = '' return render_template('album.html', login_user=user, album_id=id, access_token=access_token), 200 # @app.route('/facebook/album/<page>/', methods=['GET']) # def album(page): # try: # user = get_user_from_auth(request.cookies['auth_key']) # # return redirect('/') # except: # user = '' # except Exception as e: # print e # return response_msg('error', 'Could not connect to db') # # #import ipdb; ipdb.set_trace() # return render_template('album.html', problems=cursor.items, count=count, login_user=user), 200 @app.route('/problem/<id>/', methods=['GET']) def problems(id): try: user = get_user_from_auth(request.cookies['auth_key']) # return redirect('/') except: user = '' try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('problems').filter( rdb.row['prob_id'] == int(id) ).run(connection) except: return response_msg('error', 'Could not connect to db') if len(cursor.items) == 0: return render_template('404.html'), 404 return render_template('problems.html', problem=cursor.items[0], login_user=user), 200 @app.route('/select/', methods=['GET']) @admin_required def select(): try: user = get_user_from_auth(request.cookies['auth_key']) # return redirect('/') except: user = '' return render_template('select.html', login_user=user, app_id=FB_APP_ID), 200 @app.route('/add_problem/', methods=['GET', 'POST']) @admin_required def add_problem(): try: user = get_user_from_auth(request.cookies['auth_key']) # return redirect('/') except: user = '' if request.method == 'GET': return render_template('add_problem.html'), 200 elif request.method == 'POST': #import ipdb; ipdb.set_trace() try: form_data = json.loads(request.data) except: return response_msg('error', 'data not complete') try: name = form_data['name'] tl = form_data['time'] tags = form_data['tags'].split(',') statement = markdown(form_data['statement']) ip = markdown(form_data['ip']) op = markdown(form_data['op']) sip = markdown(form_data['sip']) sop = markdown(form_data['sop']) level = form_data['level'] except: return response_msg('error', 'data not complete') try: connection = get_rdb_conn() prob_id = rdb.db(TODO_DB).table("problems").max( 'prob_id' ).run(connection) prob_id = prob_id['prob_id'] + 1 new_user = rdb.db(TODO_DB).table("problems").insert({ "name": name, "level": level, "input": ip, "output": op, "prob_id": prob_id, "sample_input": sip, "sample_output": sop, "statement": statement, "tags": tags, "time_limit": float(tl) }).run(connection) except: return response_msg('error', 'error inserting in db') try: if new_user['inserted'] != 1: return response_msg('error', 'error inserting in db') except: return response_msg('error', 'error inserting in db') # return response_msg('success', 'OK') return response_msg('success', 'OK') else: return response_msg('error', 'only GET/POST') @app.route('/admin/', methods=['GET', 'POST']) def admin(): # #import ipdb; ipdb.set_trace() if request.method == 'GET': return render_template('admin.html'), 200 elif request.method == 'POST': try: form_data = json.loads(request.data) except: return response_msg('error', 'data not complete') try: user = form_data['user'] passwd = hashlib.sha224(form_data['passwd']).hexdigest() except: return response_msg('error', 'data not complete') try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == user ).run(connection) except: return response_msg('error', 'Could not connect to db') if len(cursor.items) == 0: return response_msg('error', "User doesn't exists") db_pass = cursor.items[0]['passwd'] if db_pass != passwd: return response_msg('error', 'Passwords do not match') return response_msg('success', 'logged in', admin_key=gen_auth_key(user), user=user) else: return response_msg('error', 'only GET/POST') @app.route('/signin/facebook/', methods=['POST', 'OPTIONS']) @crossdomain(origin='*', headers='Content-Type') def fb_signin(): #import ipdb; ipdb.set_trace() try: form_data = json.loads(request.data) except: return response_msg('error', 'json not found') try: fb_email = form_data['fb_email'] access_token = form_data['access_token'] except: return response_msg('error', 'form data not complete') # check access_token is correct # ipdb.set_trace() res = validate_fb_email(fb_email, access_token) resp = json.loads(res[0]) if resp['status'] != 'success': return res # check if credentials are correct try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['fb_email'] == fb_email ).run(connection) except: return response_msg('error', 'Could not connect to db') if len(cursor.items) == 0: return response_msg('error', "User doesn't exists") # store in session return response_msg('success', 'logged in', auth_key=gen_auth_key(cursor.items[0]['username']), user=cursor.items[0]['username']) @app.route('/auth_key/', methods=['POST', 'OPTIONS']) @crossdomain(origin='*', headers='auth_key') def check_auth_key(): # ipdb.set_trace() try: auth_key = request.headers.get('auth_key') except: return response_msg('error', 'auth_key not found') try: user = get_user_from_auth(request.headers.get('auth_key')) try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == user ).run(connection) except: return response_msg('error', 'Could not connect to db') return response_msg('success', 'user authenticated', user=cursor.items[0]) except: return response_msg('error', 'invalid auth_key') @app.route('/get_user/<name>/', methods=['GET', 'POST', 'OPTIONS']) def get_user(name): try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == name ).run(connection) except: return response_msg('error', 'could not connect to db') if len(cursor.items) == 0: return response_msg('error', 'user doesn\'t exists') user = cursor.items[0] user.pop('id', None) user.pop('passwd', None) return response_msg('success', 'OK', data=user) @app.route('/problemset/', methods=['GET']) def problemset(): try: user = get_user_from_auth(request.cookies['auth_key']) # return redirect('/') except: user = '' try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('problems').filter( (rdb.row['prob_id'] >= 1) & (rdb.row['prob_id'] <= 10) ).run(connection) count = int(math.ceil(rdb.db(TODO_DB).table('problems').count().run(connection)/10.0)) except: return response_msg('error', 'Could not connect to db') # #import ipdb; ipdb.set_trace() return render_template('problem_set.html', problems=cursor.items, count=count, login_user=user), 200 @app.route('/problemset/page/<page>/', methods=['GET']) def problemset_page(page): try: user = get_user_from_auth(request.cookies['auth_key']) # return redirect('/') except: user = '' try: # #import ipdb; ipdb.set_trace() connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('problems').filter( (rdb.row['prob_id'] >= int(page)*10-9) & (rdb.row['prob_id'] <= int(page)*10) ).run(connection) count = int(math.ceil(rdb.db(TODO_DB).table('problems').count().run(connection)/10.0)) # count = 1 except Exception as e: print e return response_msg('error', 'Could not connect to db') # #import ipdb; ipdb.set_trace() return render_template('problem_set.html', problems=cursor.items, count=count, login_user=user), 200 def send_mail(body, to): msg = Message('Change Password', sender=ADMINS[0], recipients=[to]) msg.body = body mail.send(msg) @app.route('/change_pass/<token>/', methods=['GET', 'POST']) def change_pass(token): user = '' try: user = rds.get(token) except: return response_msg('error', 'could not connect to db') if request.method == 'GET': if not user: return response_msg('error', 'invalid token') return render_template('forgot.html', token=token), 200 elif request.method == 'POST': if not user: return response_msg('error', 'invalid token') try: passwd = form_data['passwd'] cpasswd = form_data['cpasswd'] except: return response_msg('error', 'data not complete') if len(passwd) < 6: return response_msg('error', 'password should minimum 6 characters long') if passwd != cpasswd: return response_msg('error', 'passwords do not match') try: cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == user ).update({'passwd': cpasswd} ).run(connection) except: return response_msg('error', 'Could not connect to db') return render_template('signin.html', app_id=FB_APP_ID) else: return response_msg('error', 'only GET/POST') @app.route('/forgot/', methods=['POST']) def forgot(): # #import ipdb; ipdb.set_trace() if request.method == 'POST': try: form_data = request.form except: return response_msg('error', 'data not complete') try: user = form_data['user'] except: return response_msg('error', 'data not complete') try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == user ).run(connection) except: return response_msg('error', 'could not connect to db') if len(cursor.items) == 0: return response_msg('error', 'user doesn\'t exists') email = cursor.items[0]['email'] token = hashlib.sha1(os.urandom(128)).hexdigest() try: if rds.set(token, user, ex=3600): pass else: return response_msg('error', 'could not generate token') except: return response_msg('error', 'could not connect to db') body = ('Please click the following link to change your password.\n' + 'http://' '' + host + ':5000/change_pass/' + token + '/') try: send_mail(body, email) except: return response_msg('error', 'could not send an email') return response_msg('success', 'OK', token=token) else: return response_msg('error', 'only POST') @app.route('/rating/<username>/', methods=['GET']) def get_rating(username): try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == username ).run(connection) if len(cursor.items) == 0: return response_msg('error', 'user doesnt exist') cf_username = cursor.items[0]['cfhandle'] cc_username = cursor.items[0]['cchandle'] try: colg_rating = cursor.items[0]['colg_rating'] except: colg_rating = 0 except: return response_msg('error', 'Could not connect to db') return rating(cf_username, cc_username, colg_rating) def rating(cf_username, cc_username, colg_rating): # import ipdb;ipdb.set_trace() try: page = requests.get("https://www.codechef.com/users/" + cc_username) soup = BeautifulSoup(page.text, "html.parser") table = soup.find_all('table', {'class':'rating-table'})[0] trs = table.find_all('tr') td = trs[1].find_all('td')[2].text lrating = re.findall(r'\d+', td) if len(lrating) > 0: lrating = lrating[0] else: lrating = 0 td = trs[2].find_all('td')[2].text srating = re.findall(r'\d+', td) if len(srating) > 0: srating = srating[0] else: srating = 0 # cf rating resp = requests.get("http://codeforces.com/api/user.info?handles=" + cf_username).json() try: cf_rating = resp['result'][0]['rating'] except: cf_rating = 0 return response_msg('success', 'OK',colg_rating=colg_rating,cf_rating=cf_rating, lrating=int(lrating), srating=int(srating)) except: return response_msg("error", 'unable to fetch') @app.route('/sync_ratings/') def sync_ratings(): try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').run(connection) except: return response_msg('error', 'could not connect to db') for user in cursor.items: ratings = rating(user['cfhandle'], user['cchandle'], user['colg_rating']) ratings = json.loads(ratings[0]) colg_rating = 0 try: colg_rating = colg_rating + 20 * ((ratings['cf_rating']/100)**2) colg_rating = colg_rating + 2000 + 7 * (((ratings['lrating']/1000)**2) + (ratings['lrating']/20)) colg_rating = colg_rating + 2000 + 5 * (((ratings['srating']/100)**2) + (ratings['srating']/20)) except: pass print colg_rating try: cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == user['username'] ).update({ 'lrating': ratings['lrating'], 'srating': ratings['srating'], 'cfrating': ratings['cf_rating'], 'colg_rating': colg_rating/3, }).run(connection) print user['username'] except: print 'error' + user['username'] return response_msg('sucess', 'OK') @app.route("/admin/access_token/", methods=['POST']) def sync_access_token(): # import ipdb; ipdb.set_trace() form_data = json.loads(request.data) access_token = form_data['access_token'] long_lived_url = ("https://graph.facebook.com/oauth/access_token?" "client_id=" + str(FB_APP_ID) + "&client_secret=" + FB_APP_SECRET + "&grant_type=fb_exchange_token&fb_exchange_token=" + access_token) long_lived_resp = requests.get(long_lived_url).text long_lived_token = long_lived_resp.split('&')[0].split('=')[1] if rds.set('access_token', long_lived_token): return response_msg('success', 'OK') else: return response_msg('error', 'could not connect to redis server') <file_sep>$('.ui.slider.checkbox') .checkbox(); $('#level') .dropdown({ action: 'activate', onChange: function(value, text, $selectedItem) { // custom action action: 'hide' } // maxSelections: 1 }); $('#tag') .dropdown({ allowAdditions: true, maxSelections: false }); var knuth = angular.module("knuth", []); knuth.controller("markdown", ['$scope', '$http', function($scope, $http) { $scope.toHTML = function() { $('#m2html').text(''); $('#m2html').append(markdown.toHTML($scope.content.statement)); } $scope.toHTML_ip = function() { $('#m2html_ip').text(''); $('#m2html_ip').append(markdown.toHTML($scope.content.ip)); } $scope.toHTML_op = function() { $('#m2html_op').text(''); $('#m2html_op').append(markdown.toHTML($scope.content.op)); } $scope.toHTML_sip = function() { $('#m2html_sip').text(''); $('#m2html_sip').append(markdown.toHTML($scope.content.sip)); } $scope.toHTML_sop = function() { $('#m2html_sop').text(''); $('#m2html_sop').append(markdown.toHTML($scope.content.sop)); } $scope.submitpro= function() { $('#form').addClass('loading'); var dataObj = $scope.content; dataObj['tags'] = $('#tags').val(); dataObj['level'] = $('#prob_level').val(); console.log(dataObj); $http({ method: 'POST', url: '/add_problem/', data: dataObj, // pass in data as strings }).success(function(data) { $('#form').removeClass('loading'); console.log(data); if (data['status'] != 'success') { // if not successful, bind errors to error variables $('#form').addClass('error'); $('.ui.error.message').html('<ul class="list"><li>' + data['msg'] + '</li></ul>'); } else { // if successful, bind success message to message // alert('success'); $(location).attr('href', '/add_problem'); } }); } // $scope.content="hello"; // $scope.content = $scope.content + 'vvv'; } ]); <file_sep>var knuth1 = angular.module('knuth'); knuth1.directive('onFinishRender', function($timeout) { return { restrict: 'A', link: function(scope, element, attr) { if (scope.$last === true) { $timeout(function() { scope.$emit('ngRepeatFinished'); }); } } } }).controller('album', ['$scope', '$http', '$window', function($scope, $http, $window) { $scope.aid = $window.hell; var aid = $scope.aid; var fb = "https://graph.facebook.com/v2.5/"; // var access = "<KEY>"; $scope.accesstoken = access; var url = fb + aid + "/photos?access_token=" + access; $http.get(url) .then(function(response) { $scope.images = response.data.data; console.log($scope.images); angular.forEach($scope.images, function(value, key) { console.log(value.id); value.pic = fb + value.id + "/picture?access_token=" + access; }); }) $scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) { //you also get the actual event object //do stuff, execute functions -- whatever... $(function() { // say we want to have only one item opened at one moment var opened = false; $('#repeat > div.uc-container').each(function(i) { // alert("hello"); var $item = $(this), direction; switch (i) { case 0: direction = ['right', 'bottom']; break; case 1: direction = ['left', 'bottom']; break; case 2: direction = ['right', 'top']; break; case 3: direction = ['left', 'top']; break; } var pfold = $item.pfold({ folddirection: direction, speed: 300, onEndFolding: function() { opened = false; }, centered: true }); $item.find('span.icon-eye').on('click', function() { if (!opened) { opened = true; pfold.unfold(); } }).end().find('span.icon-cancel').on('click', function() { pfold.fold(); }); }); }); }); } ]); // $('.primary.button') // .api({ // url: '/facebook/' // }) // ;
db4bb5b8d5361a39f617c1b0bfa301681cbf45e8
[ "HTML", "JavaScript", "Markdown", "Python", "Text" ]
20
Text
tanmaydatta/longclaw
1a935c6220a436117d1b4be620dfb2a540506c33
e2c12dc1f27055a6f5e3a6990d78ba2810a44c6f
refs/heads/master
<file_sep>package xyz.kfdykme.gank.web; import android.webkit.*; import android.widget.*; import xyz.kfdykme.gank.base.*; import xyz.kfdykme.gank.bean.*; import javax.xml.transform.*; public class WebContract { public interface Presenter extends BasePresenter{ void onGoBackWebDow( ); void initWebView(WebView webview, final ProgressBar progressBar); void openWebDow( DataEntity.result loadResult); void openWebDow(Likes loadLike); } } <file_sep>package xyz.kfdykme.gank.likes import xyz.kfdykme.gank.GankActivity import xyz.kfdykme.gank.base.BasePresenter import xyz.kfdykme.gank.base.OnDetachListener import xyz.kfdykme.gank.bean.Likes /** * Created by wimkf on 2018/4/10. */ class LikedPresenter(val view: LikedView,val l:OnDetachListener):BasePresenter{ init { view.presenter = this } override fun attach() { view.attach() } fun openWebDow(liked: Likes){ GankActivity.gankPresenter.openWebDow(liked) detach() } override fun detach() { l?.onPresenterDetach() view.deAttach() } }<file_sep>package xyz.kfdykme.gank import android.support.v4.app.FragmentActivity import android.support.v4.app.FragmentPagerAdapter import android.support.v4.view.ViewPager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import xyz.kfdykme.gank.view.ViewPagerIndicator import xyz.kfdykme.gank.web.WebDow import java.util.* /** * Created by wimkf on 2018/4/10. */ class GankView(val parent: ViewGroup) { var presenter:GankPresenter? = null internal var view: View? = null var vp: ViewPager? = null var mAdapter: FragmentPagerAdapter? = null var mContents = ArrayList<ArtcleListFragment>() val mTitles = Arrays.asList("Android", "iOS", "前端", "福利") var wv:WebDow? = null init { view = LayoutInflater.from(parent.context) .inflate(R.layout.view_gank,parent,false) initDatas(parent.context as FragmentActivity) initViews() } fun attach(){ parent.removeAllViews() parent.addView(view) } fun initDatas(context: FragmentActivity) { for (title in mTitles) { val fragment = ArtcleListFragment.newInstance(title) fragment.title = title mContents.add(fragment) } mAdapter = object : FragmentPagerAdapter(context.supportFragmentManager) { override fun getItem(p1: Int): android.support.v4.app.Fragment { return mContents[p1] } override fun getCount(): Int { return mContents.size } } } fun initViews(){ vp = view!!.findViewById(R.id.mViewPager) wv = view!!.findViewById<WebDow>(R.id.mWebDow) val vpindicator = view!!.findViewById<ViewPagerIndicator>(R.id.mViewPagerIndicator) vpindicator!!.setVisibleTabCount(4) vpindicator!!.setTabItems(mTitles) vp!!.setAdapter(mAdapter) vpindicator!!.setViewPager(vp, 0) } } <file_sep>package xyz.kfdykme.gank.web; import android.content.*; import android.webkit.*; import android.widget.*; import android.view.*; import xyz.kfdykme.gank.bean.DataEntity.*; import xyz.kfdykme.gank.bean.*; public class WebPresenter implements WebContract.Presenter { private WebDow view; @Override public void openWebDow(Likes loadLike) { view.setVisibility(View.VISIBLE); view.getWebView().loadUrl(loadLike.url); } @Override public void openWebDow(DataEntity.result loadResult) { view.setVisibility(View.VISIBLE); view.getWebView().loadUrl(loadResult.getUrl()); view.setLoadResult(loadResult); } @Override public void onGoBackWebDow( ) { if ((!view.getWebView().canGoBack())||view.getWebView().getUrl().equals(WebDow.BLANK_URL)) { view.setVisibility(View.GONE); view.getWebView().loadUrl(WebDow.BLANK_URL); } else { view.getWebView().goBack(); } } @Override public void initWebView(WebView webview,final ProgressBar progressBar) { WebSettings wb = webview.getSettings(); wb.setJavaScriptEnabled(true); wb.setJavaScriptCanOpenWindowsAutomatically(true); wb.setBuiltInZoomControls(true); WebViewClient wvc = new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }; WebChromeClient wcc = new WebChromeClient(){ @Override public void onProgressChanged(WebView view, int newProgress) { if(newProgress <= 20) progressBar.setVisibility(View.VISIBLE); else if(newProgress >= 100){ progressBar.setVisibility(View.GONE); } progressBar.setProgress(newProgress); } }; webview.setWebChromeClient(wcc); webview.setWebViewClient(wvc); } public WebPresenter(WebDow view){ this.view = view; } @Override public void attach() { } @Override public void detach() { } } <file_sep>package xyz.kfdykme.gank import retrofit2.Call import retrofit2.Retrofit import retrofit2.http.GET import retrofit2.http.Path import rx.Observable import xyz.kfdykme.gank.bean.DataEntity /** * Created by wimkf on 2018/4/10. */ interface GankService{ companion object { val BASEURL="http://gank.io/api/" val DEFAULT_NUMBER_PER_PAGE = "15" } @GET("data/{type}/{perPage}/{page}") fun getActivity( @Path("type") type:String, @Path("perPage") perPage:String, @Path("page") page:String ):Observable<DataEntity> @GET("search/query/{key}/category/{type}/count/{perPage}/page/{pageNum}") fun doSerach( @Path("key") key:String, @Path("type") type:String, @Path("perPage") perPage:String, @Path("pageNum") pageNum:String ):Observable<DataEntity> }<file_sep>package xyz.kfdykme.gank.base; public interface BasePresenter { void attach(); void detach(); } <file_sep>package xyz.kfdykme.gank.bean; import io.realm.RealmObject; public class Likes extends RealmObject { public String desc; public String url; public String who; public Likes(){ } } <file_sep>package xyz.kfdykme.gank.adapter; import android.support.v7.widget.*; import android.view.*; import java.util.*; import android.content.*; import java.util.zip.*; import xyz.kfdykme.gank.*; import android.widget.*; import xyz.kfdykme.gank.bean.*; import xyz.kfdykme.gank.adapter.RecyclerViewAdapter.*; import android.widget.AdapterView.*; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public final static int TYPE_ITEM = 0; public final static int TYPE_FOOTER =1; //上拉加载更多 public static final int PULLUP_LOAD_MORE=0; //正在加载中 public static final int LOADING_MORE=1; //上拉加载更多状态-默认为0 private int footer_status=0; public static final String STRING_PULLUP_LOAD_MORE = "Pull up to load more."; public static final String STRING_LOADING_MORE ="Loading more."; public List<DataEntity.result> mResults; private Context context; private LayoutInflater Inflater; private RecyclerViewAdapter.OnItemClickListener mOnItemClickListener; private RecyclerViewAdapter.OnItemLongClickListener mOnItemLongClickListener; // init my recyclerview public RecyclerViewAdapter(Context context, List<DataEntity.result> mResults) { this.mResults = mResults; this.context = context; Inflater = LayoutInflater.from(context); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == TYPE_ITEM){ View view = Inflater.inflate(R.layout.item_recyclerview ,parent,false); ItemHolder holder = new ItemHolder(view); return holder; } else if (viewType == TYPE_FOOTER){ View view = Inflater.inflate(R.layout.item_recyclerview_footer,parent,false); FooterHolder holder = new FooterHolder (view); return holder; } return null; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { if (holder instanceof ItemHolder){ ItemHolder mHolder = (ItemHolder)holder; DataEntity.result r = mResults.get(position); mHolder .descTextView.setText(r.getDesc()); mHolder .idTextView.setText(position+1+""); mHolder .dateTextView.setText(r.getPublishedAt()); mHolder .whoTextView.setText(r.getWho()); //bind Listeners if( mOnItemClickListener!= null){ holder. itemView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { mOnItemClickListener.onClick(position); } }); } if(mOnItemLongClickListener != null){ holder. itemView.setOnLongClickListener( new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { mOnItemClickListener.onClick(position); return false; } }); } } else if (holder instanceof FooterHolder){ FooterHolder mHolder = (FooterHolder)holder; switch (footer_status) { case PULLUP_LOAD_MORE: mHolder.mTextView.setText(STRING_PULLUP_LOAD_MORE); break; case LOADING_MORE: mHolder.mTextView.setText(STRING_LOADING_MORE); break; } } } @Override public int getItemCount() { return mResults.size() +1 ; } @Override public int getItemViewType(int position) { if(position +1 == getItemCount()){ return TYPE_FOOTER; } else { return TYPE_ITEM; } } public void addData(List<DataEntity.result> result){ mResults.addAll(result); notifyDataSetChanged(); } // create my viewholder public class ItemHolder extends RecyclerView.ViewHolder{ TextView descTextView ; TextView idTextView ; TextView dateTextView ; TextView whoTextView ; public ItemHolder(View view){ super(view); descTextView = (TextView) view.findViewById(R.id.item_recyclerview_descText); idTextView = (TextView) view.findViewById(R.id.item_recyclerview_idText); whoTextView = (TextView) view.findViewById(R.id.item_recyclerview_whoText); dateTextView = (TextView) view.findViewById(R.id.item_recyclerview_dateText); } } //create footer holder public class FooterHolder extends RecyclerView.ViewHolder{ TextView mTextView; public FooterHolder(View view){ super(view); mTextView = (TextView) view.findViewById(R.id.item_recyclerview_footer_textview); } } public void changeFooterStatus(int status){ footer_status=status; notifyDataSetChanged(); } //implements onclicklistener public interface OnItemClickListener{ void onClick(int position); } public interface OnItemLongClickListener{ void onLongClick( int position); } public void setOnItemClickListener(OnItemClickListener onItemClickListener){ this.mOnItemClickListener = onItemClickListener; } public void setOnItemLongClickListener(OnItemLongClickListener onItemLongClickListener){ this.mOnItemLongClickListener = onItemLongClickListener; } } <file_sep>package xyz.kfdykme.gank.search import android.os.* import android.support.design.widget.Snackbar import android.support.v4.app.* import android.view.* import android.widget.* import android.widget.AdapterView.* import retrofit2.Retrofit import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import rx.android.schedulers.AndroidSchedulers import rx.functions.Action1 import rx.schedulers.Schedulers import xyz.kfdykme.gank.* import xyz.kfdykme.gank.bean.* import java.util.* import android.view.View.OnClickListener import android.widget.TextView.* import android.support.v7.widget.* import xyz.kfdykme.gank.adapter.* import xyz.kfdykme.gank.base.OnDetachListener class SearchView(val parent:ViewGroup) { private var mSpinner: Spinner? = null private var mButton: Button? = null private var mEditText: EditText? = null private var mRecyclerView: RecyclerView? = null private var mRecyclerViewAdpter: RecyclerViewAdapter? = null private var mResults: MutableList<DataEntity.result>? = null private val page = 1 private var type = "all" private var lastKeyNType = "nullnull" private val SEARCH = "search" //private final String UPDATE = "update"; private val LOADING = "loading" //check is Search a new key or search more data private val isSearch: Boolean get() = lastKeyNType != mEditText!!.text.toString() + type val view:View var presenter:SearchPresenter? = null init { view = LayoutInflater.from(parent.context).inflate(R.layout.view_search,parent,false) initViews(view) //reload data at restart if (mResults != null) { addViews(mResults) } } fun onAttach() { parent!!.removeAllViews() parent!!.addView(view) } fun onDetach() { parent!!.removeView(view) } private fun initViews(view: View) { //initial RecyclerView mRecyclerView = view.findViewById<View>(R.id.dialog_fargment_search_recyclerview) as RecyclerView val manager = LinearLayoutManager(parent.context) manager.orientation = OrientationHelper.VERTICAL mRecyclerView!!.layoutManager = manager mRecyclerView!!.itemAnimator = DefaultItemAnimator() //initial mEditText mEditText = view.findViewById<View>(R.id.searchEditText) as EditText //no action now ?????????????? mEditText!!.setOnEditorActionListener { p1, p2, p3 -> doSearch() false } //initial searchButton mButton = view.findViewById<View>(R.id.searchButton) as Button mButton!!.setOnClickListener { doSearch() } //initial spinner mSpinner = view.findViewById<View>(R.id.searchSpinner) as Spinner val spinnerStrings = arrayOf("all", "Android", "iOS", "前端") val mSpinnerAdapter = ArrayAdapter(parent.context, android.R.layout.simple_list_item_1, spinnerStrings) mSpinnerAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item) mSpinner!!.adapter = mSpinnerAdapter mSpinner!!.onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected(p1: AdapterView<*>, view: View, p3: Int, p4: Long) { val mTv = view as TextView type = mTv.text.toString() } override fun onNothingSelected(p1: AdapterView<*>) { } } } private fun doSearch() { //as a tip to tell it is loading data from net mButton!!.text = LOADING val key = mEditText!!.text.toString() Retrofit.Builder() .baseUrl(GankService.BASEURL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build() .create(GankService::class.java) .doSerach(key, type, GankService.DEFAULT_NUMBER_PER_PAGE, page.toString()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { dataEntity -> Snackbar.make(mButton!!,"Search finished.",Snackbar.LENGTH_SHORT).show() if (!isSearch) { mResults!!.addAll(dataEntity.results) } else { mResults = dataEntity.results } addViews(mResults) lastKeyNType = mEditText!!.text.toString() + type } } fun addViews(results: List<DataEntity.result>?) { //set search TextView's text to loading mButton!!.text = LOADING if (mRecyclerViewAdpter == null) { //initRecyclerViewAdapter mRecyclerViewAdpter = RecyclerViewAdapter(parent.context, results) mRecyclerViewAdpter!!.setOnItemClickListener { position -> presenter?.openWebDow( mRecyclerViewAdpter!!.mResults[position]) } //setAdapter mRecyclerView!!.adapter = mRecyclerViewAdpter } else { mRecyclerViewAdpter!!.addData(results) } mButton!!.text = SEARCH } } <file_sep>package xyz.kfdykme.gank.base /** * Created by wimkf on 2018/4/10. */ interface OnDetachListener{ fun onPresenterDetach() } <file_sep>package xyz.kfdykme.gank import android.os.Bundle import android.support.v4.widget.DrawerLayout import android.support.design.widget.NavigationView import android.support.design.widget.Snackbar import android.support.v4.app.FragmentActivity import android.view.View import android.view.ViewGroup import android.widget.Toast import xyz.kfdykme.gank.base.BasePresenter import xyz.kfdykme.gank.base.OnDetachListener import xyz.kfdykme.gank.likes.LikedPresenter import xyz.kfdykme.gank.likes.LikedView import xyz.kfdykme.gank.search.SearchPresenter import xyz.kfdykme.gank.search.SearchView import java.util.* class GankActivity : FragmentActivity(),OnDetachListener { private var mDrawerLayout: DrawerLayout? = null private var mNavigationView: NavigationView? = null var container:ViewGroup? = null var presenters :Stack<BasePresenter> = Stack() var cPresenter :BasePresenter? = null companion object { lateinit var gankPresenter:GankPresenter } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initViews() gankPresenter = GankPresenter( GankView(container!!) ) gankPresenter.attach() cPresenter = gankPresenter } override fun onPresenterDetach() { if(!presenters.empty()) { var p = presenters.pop() cPresenter = p cPresenter!!.attach() } } override fun onBackPressed() { if(cPresenter == gankPresenter) { gankPresenter.onBack() } else if(!presenters.empty()){ var p = presenters.pop() cPresenter = p cPresenter!!.attach() } else super.onBackPressed() } private fun initViews() { mDrawerLayout = findViewById<View>(R.id.main_DrawerLayout) as DrawerLayout mNavigationView = findViewById<View>(R.id.nav_view) as NavigationView container = findViewById(R.id.container) mDrawerLayout!!.addDrawerListener(object : DrawerLayout.DrawerListener { override fun onDrawerSlide(drawerView: View, slideOffset: Float) { val width = drawerView.width container!!.translationX = width * slideOffset val paddingLeft = width.toDouble() * 0.618 * (1 - slideOffset).toDouble() mNavigationView!!.setPadding(paddingLeft.toInt(), 0, 0, 0) } override fun onDrawerOpened(drawerView: View) { } override fun onDrawerClosed(drawerView: View) { } override fun onDrawerStateChanged(newState: Int) { } }) mNavigationView!!.setNavigationItemSelectedListener { menuItem -> mDrawerLayout!!.closeDrawers() when (menuItem.itemId) { R.id.nav_liked -> { presenters.push(cPresenter) var likedPresenter = LikedPresenter( LikedView(container!!), this ) likedPresenter.attach() cPresenter = likedPresenter Snackbar.make(container!!,"Liked",Snackbar.LENGTH_SHORT).show() //Toast.makeText(this@GankActivity, "Selected Liked", Toast.LENGTH_SHORT).show() } R.id.nav_search -> { presenters.push(cPresenter) var searchPresenter = SearchPresenter( SearchView(container!!), this ) searchPresenter.attach() cPresenter = searchPresenter Snackbar.make(container!!,"Selected Search",Snackbar.LENGTH_SHORT).show() } } false } } } <file_sep>package xyz.kfdykme.gank.likes import android.view.* import io.realm.Realm import xyz.kfdykme.gank.* import xyz.kfdykme.gank.bean.* import java.util.* import android.support.v7.app.* import android.content.* import android.support.v7.widget.* import xyz.kfdykme.gank.adapter.* public class LikedView(val parent: ViewGroup) { private val mRecyclerView: RecyclerView private var adapter: RecyclerViewAdapter2Like? = null private var mLikes: List<Likes>? = null var view: View? = null var presenter: LikedPresenter? = null init { view = LayoutInflater.from(parent.context) .inflate(R.layout.view_liked, parent, false) //initRecyclerView mRecyclerView = view!!.findViewById<View>(R.id.dialog_fragment_like_recyclerview) as RecyclerView val manager = LinearLayoutManager(parent.context) manager.orientation = OrientationHelper.VERTICAL mRecyclerView.layoutManager = manager mRecyclerView.itemAnimator = DefaultItemAnimator() mLikes = Realm.getDefaultInstance().where(Likes::class.java).findAll() if (mLikes != null) { addViews(mLikes) } } fun attach() { parent!!.removeAllViews() parent!!.addView(view) } fun deAttach() { parent!!.removeView(view) } fun addViews(likes: List<Likes>?) { adapter = RecyclerViewAdapter2Like(parent!!.context, likes) //set listener adapter!!.setOnItemClickListener { position -> presenter?.openWebDow(adapter!!.mLikes[position]) } adapter!!.setOnItemLongClickListener { position -> //create a dialog to ask is sure val builder = AlertDialog.Builder(parent!!.context) builder.setTitle("Detele this record?") .setPositiveButton("Yes") { p1, p2 -> Realm.getDefaultInstance() .executeTransaction { realm -> adapter!!.mLikes[position].deleteFromRealm() mLikes = realm.where(Likes::class.java).findAll() addViews(mLikes) } }.setNegativeButton("No", null) builder.create().show() } mRecyclerView.adapter = adapter } } <file_sep>package xyz.kfdykme.gank import android.view.KeyEvent import android.view.View import xyz.kfdykme.gank.base.BasePresenter import xyz.kfdykme.gank.bean.DataEntity import xyz.kfdykme.gank.bean.Likes /** * Created by wimkf on 2018/4/10. */ class GankPresenter(val view:GankView):BasePresenter{ override fun detach() { } init { view.presenter = this } override fun attach(){ view.attach() } fun onBack():Boolean{ if (view.wv?.webView!!.visibility != View.GONE) { if (view.wv?.webView!!.canGoBack()) { view.wv?.webView!!.goBack() } else { view.wv?.presenter!!.onGoBackWebDow() } return true } else { return false } } fun openWebDow(re: DataEntity.result){ view.wv?.presenter!!.openWebDow(re); } fun openWebDow(likes: Likes ){ view.wv?.presenter!!.openWebDow(likes); } }<file_sep># Gank ## todo - 完善RecyclerView的刷新机制 <file_sep>package xyz.kfdykme.gank import retrofit2.Retrofit import xyz.kfdykme.gank.bean.* import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers class ArtcleListPresenter(private val mView: ArtcleListContract.View) : ArtcleListContract.Presenter { override fun attach() { } init { this.mView.setPresenter(this) } override fun detach() { } override fun loadArticle(type: String, page: Int) { Retrofit .Builder() .baseUrl(GankService.BASEURL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build() .create(GankService::class.java) .getActivity(type,GankService.DEFAULT_NUMBER_PER_PAGE,page.toString()) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe({date: DataEntity? -> mView.addViews(date?.results) }) } } <file_sep>package xyz.kfdykme.gank.search import xyz.kfdykme.gank.GankActivity import xyz.kfdykme.gank.base.BasePresenter import xyz.kfdykme.gank.base.OnDetachListener import xyz.kfdykme.gank.bean.DataEntity import xyz.kfdykme.gank.bean.result /** * Created by wimkf on 2018/4/10. */ class SearchPresenter(val view:SearchView,val l:OnDetachListener):BasePresenter{ init { view.presenter =this } fun openWebDow(result: DataEntity.result){ GankActivity.gankPresenter.openWebDow(result) detach() } override fun attach() { view.onAttach() } override fun detach() { l.onPresenterDetach() view.onDetach() } }
57ddce5e1aca741be08dba06e99cadf29ce7da32
[ "Markdown", "Java", "Kotlin" ]
16
Java
kfdykme/Gank
fcdd97416a25bd1c584dc5b063ccb6bb23df3a71
75fbd538877da147b0aa55406eade074b3e4c871
refs/heads/master
<file_sep># esphome-door-lock This is project of door lock based on Wemos D1 mini and cheap RC522 RFID module. Software side is based on ESPHome with custom component which exposes data read by RC522 through ESPHome sensors. That way it's super simple to connect it to Home Assistant. # Hardware Project is designed for Wemos D1 mini but can be easily adopted to any other ESPHome compatible hardware as long as it have enough GPIOs. PCB project and component list is available here and on easyeda if you want to order it from JLCPCB: https://easyeda.com/hausnerr/door-lock. # Software Project contains: - door_lock.yaml - ESPHome configuration file. It defines all sensors, services and door lock switch for firmware, - door_lock_rfid.h - ESPHome custom component. It exposes data read by RC522 as sensors and verify if tag is from allowed list. List can be viewed and updated using services, - pcb - components list and gerber files for PCB etching. # Updating users list To update users list you need to expose `users list file` on any HTTP server. Simplest way is to use built-in HA server. Create directory `www` inside your HA config dir and put there your `users list file`. It will be available at http://HA:8123/local/filename. Then through Home Assistant execute service `esphome.door_lock_sync_users_list_from_server` and send service data like: `{"url":"http://HA:8123/local/filename"}`. <file_sep>/* * ESPhome RC522 RFID plugin with access control * * Created on: 17.03.2019 * * Copyright (c) 2019 <NAME>. All rights reserved. * */ #include "esphome.h" #include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> #include <FS.h> #include <SPI.h> #include <MFRC522.h> using namespace esphome; using namespace std; class RfidSensorsComponent : public Component { private: MFRC522 rfid; typedef struct { String id; String description; } user; vector<user> users_list; unsigned long last_tag_read_milis = 0; void send_notification(String title, String message, String notification_id) { vector<api::KeyValuePair> data; data.push_back(api::KeyValuePair("title", title.c_str())); data.push_back(api::KeyValuePair("message", message.c_str())); data.push_back(api::KeyValuePair("notification_id", notification_id.c_str())); api::ServiceCallResponse resp; resp.set_service("persistent_notification.create"); resp.set_data(data); api::global_api_server->send_service_call(resp); } void import_users_list(Stream* f) { ESP_LOGD("rfid", "Parsing users list..."); users_list.clear(); while (f->available()) { String line; char tmp = 0; while (f->available() && tmp != '\n'){ tmp = f->read(); line += tmp; } line.trim(); size_t split_pos = line.indexOf('='); if (split_pos == 11) { //Naive ID check: XX:XX:XX:XX=DESCRIPTION user row; row.id = line.substring(0, split_pos); row.description = line.substring(split_pos + 1); users_list.push_back(row); } } } bool load_users_list() { ESP_LOGD("rfid", "Loading users list from file..."); File f = SPIFFS.open("/rfid_users_list", "r"); if (!f) { ESP_LOGE("rfid", "Failed to open users list file!"); return false; } import_users_list(&f); f.close(); return true; } bool save_users_list() { ESP_LOGD("rfid", "Saving users list to file..."); File f = SPIFFS.open("/rfid_users_list", "w"); if (!f) { ESP_LOGE("rfid", "Failed to open users list file!"); return false; } for (auto &user : users_list) { f.print(user.id + "=" + user.description + '\n'); } f.close(); return true; } void handle_tag_read() { if (last_tag_read_milis != 0 && (last_tag_read_milis + 5000) > millis()) return; valid_tag_sensor->publish_state(false); invalid_tag_sensor->publish_state(false); if (!rfid.PICC_IsNewCardPresent() || !rfid.PICC_ReadCardSerial()) return; user current_tag; bool known_tag = false; char tag_id_buffer[12]; sprintf(tag_id_buffer, "%02X:%02X:%02X:%02X", rfid.uid.uidByte[0], rfid.uid.uidByte[1], rfid.uid.uidByte[2], rfid.uid.uidByte[3]); current_tag.id = tag_id_buffer; current_tag.description = "UNKNOWN"; rfid.PICC_HaltA(); rfid.PCD_StopCrypto1(); for (size_t i = 0; i < users_list.size(); i++) { if (users_list[i].id == current_tag.id) { current_tag = users_list[i]; known_tag = true; break; } } ESP_LOGD("rfid", "Tag with id %s found!", current_tag.id.c_str()); ESP_LOGD("rfid", "Setting sensor states..."); last_tag_read_milis = millis(); valid_tag_sensor->publish_state(known_tag); invalid_tag_sensor->publish_state(!known_tag); last_tag_id_sensor->publish_state(current_tag.id.c_str()); last_tag_description_sensor->publish_state(current_tag.description.c_str()); } public: binary_sensor::BinarySensor *valid_tag_sensor = new binary_sensor::BinarySensor(); binary_sensor::BinarySensor *invalid_tag_sensor = new binary_sensor::BinarySensor(); text_sensor::TextSensor *last_tag_id_sensor = new text_sensor::TextSensor(); text_sensor::TextSensor *last_tag_description_sensor = new text_sensor::TextSensor(); void send_users_list_notification() { String message; for (auto &user : users_list) { message += user.id + " - " + user.description + '\n'; } send_notification((App.get_name() + ": users list").c_str(), message, (App.get_name() + "_users_list_print").c_str()); } void sync_users_list_from_server(string users_server_url) { if (WiFi.status() != WL_CONNECTED) return; if (users_server_url.length() == 0) return; String title = (App.get_name() + ": users list update").c_str(); String id = (App.get_name() + "_users_list_update").c_str(); ESP_LOGD("rfid", "Fetching users list from server..."); HTTPClient http; http.begin(users_server_url.c_str()); int httpCode = http.GET(); if (httpCode == 200) { import_users_list(http.getStreamPtr()); } else { ESP_LOGE("rfid", "Invalid server response. Server unavailable?"); send_notification(title, "Invalid server response. Server unavailable?", id); return; } http.end(); save_users_list(); send_users_list_notification(); } void setup() override { SPIFFS.begin(); SPI.begin(); rfid.PCD_Init(D8, D3); load_users_list(); } void loop() override { handle_tag_read(); } };
e4aefb50feffd61ee0ddae67e0d8edc6b3def506
[ "Markdown", "C++" ]
2
Markdown
baomin/esphome-door-lock
4dfec7a635429b70dbb75194fafe3c5328eae2a3
5d0809cea857b3329f3b50c60d46ec268a41c8af
refs/heads/master
<file_sep>using System; using System.Diagnostics; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace cw1 { class Program { static void testMyClass(MyClass myObj) { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); myObj.e1(); stopWatch.Stop(); Console.WriteLine("E1: " + stopWatch.ElapsedMilliseconds + "\n"); stopWatch.Restart(); myObj.e2(); stopWatch.Stop(); Console.WriteLine("E2: " + stopWatch.ElapsedMilliseconds + "\n"); stopWatch.Restart(); myObj.e3(); stopWatch.Stop(); Console.WriteLine("E3: " + stopWatch.ElapsedMilliseconds + "\n"); stopWatch.Restart(); myObj.e4(); stopWatch.Stop(); Console.WriteLine("E4: " + stopWatch.ElapsedMilliseconds + "\n"); stopWatch.Restart(); myObj.e5(); stopWatch.Stop(); Console.WriteLine("E5: " + stopWatch.ElapsedMilliseconds + "\n"); stopWatch.Restart(); myObj.e6(); stopWatch.Stop(); Console.WriteLine("E6: " + stopWatch.ElapsedMilliseconds + "\n"); } static void Main(string[] args) { MyClass myObj = new MyClass(5000, 5500); testMyClass(myObj); Console.ReadKey(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using cw1; using System.Threading; namespace WindowsFormsApplication1 { public partial class Form1 : Form { private MyClass obj; private void errorMsg(string msg) { MessageBox.Show(msg); } public Form1() { InitializeComponent(); obj = new MyClass(25, 10000); obj.ed = errorMsg; /* backgroundWorker1.DoWork += backgroundWorker1_DoWork; backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;*/ backgroundWorker1.WorkerReportsProgress = true; } private void button1_Click(object sender, EventArgs e) { obj.e1(); chart1.Series[0].Points.Clear(); richTextBox1.Text = ""; } private void button2_Click(object sender, EventArgs e) { obj.e2(); } private void button5_Click(object sender, EventArgs e) { obj.e5(); } private void button6_Click(object sender, EventArgs e) { string temp = ""; for (int i = 0; i < obj.tab.Length; i++) { if (i % 5 == 0) { temp += "\n"; } temp += String.Format("{0}\t{1}\t", obj.sortTab[i], obj.roznica[i]); } //backgroundWorker1.RunWorkerAsync(); chart1.Series[0].Points.DataBindXY(obj.sortTab, obj.roznica); richTextBox1.Text = temp; obj.e6(); } private void richTextBox1_TextChanged(object sender, EventArgs e) { } private void button3_Click(object sender, EventArgs e) { obj.e3(); } private void button4_Click(object sender, EventArgs e) { obj.e4(); } private void chart1_Click(object sender, EventArgs e) { } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { for (int i = 0; i < obj.tab.Length; i++) { Thread.Sleep(100); backgroundWorker1.ReportProgress(i/ obj.tab.Length, new WorkerArgument { }); } } private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { } public class WorkerArgument { public double X { get; set; } public double Y { get; set; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace cw1 { delegate void ErrorDelegate(string message); class MyClass { public int[] tab; public int[] sortTab; public double[] opisaneKwadraty; public double[] wpisaneKwadraty; public double[] roznica; private int n1, n2; public ErrorDelegate ed; public MyClass(int _n1 = 10, int _n2 = 500) { n1 = _n1; n2 = _n2; } public void e1() { try { Random rnd = new Random(); tab = new int[n2 - n1]; for (int i = 0; i < n2 - n1; i++) { tab[i] = rnd.Next(n1, n2); } } catch (NullReferenceException) { ed?.Invoke("Error 1"); } } public void e2() { try { sortTab = new int[tab.Length]; Array.Copy(tab, sortTab, tab.Length); Array.Sort(sortTab); } catch (NullReferenceException) { ed?.Invoke("Error 2"); } } public void e3() { try { opisaneKwadraty = new double[tab.Length]; for (int i = 0; i < opisaneKwadraty.Length; i++) { opisaneKwadraty[i] = Math.Pow(sortTab[i] * 2, 2); } } catch (NullReferenceException) { ed?.Invoke("Error 3"); } } public void e4() { try { wpisaneKwadraty = new double[tab.Length]; for (int i = 0; i < wpisaneKwadraty.Length; i++) { wpisaneKwadraty[i] = (2 * Math.Pow(sortTab[i], 2)); } } catch (NullReferenceException) { ed?.Invoke("Error 4 "); } } public void e5() { try { roznica = new double[sortTab.Length]; for (int i = 0; i < roznica.Length; i++) { roznica[i] = opisaneKwadraty[i] - wpisaneKwadraty[i]; } } catch (NullReferenceException) { ed?.Invoke("Error 5"); } } public void e6() { try { /* for (int i = 0; i < roznica.Length; i++) { if (i % 4 == 0) { Console.WriteLine(); } Console.Write(sortTab[i] + " " + roznica[i] + " "); } Console.WriteLine("\n");*/ } catch (NullReferenceException) { ed?.Invoke("Error 6"); } } } }
f5bc995436fc59542d43656522ebcd2a148a4272
[ "C#" ]
3
C#
bmalecki/SCR-put
b6b5212eaf8c2e0279a60a9862a30ac9986718b0
f195d1a6bc77f7fd2d73d71d692cae90c7804475
refs/heads/master
<repo_name>BryanBonner/Project1-473<file_sep>/README.md # Project1-473 Share Excuses for Missing Class with Professors CPSC 473 Project 1 for Professor Avery Team Unlamented Epicurean - CPSC 473 Project 1 Authors: <NAME>, <NAME>, <NAME>, <NAME>, <NAME> To Run 1. Download the zip 2. Navigate to the directory in git bash or a terminal 3. Install node dependencies using command $npm install 4. start the app with command $node app.js 5. Server runs on Localhost:3000 <file_sep>/app.js // Project 1 for Unlamented Something - Share excuses for missing class // var express = require('express'), expressValidator = require('express-validator'), cookieParser = require('cookie-parser'), bodyParser = require('body-parser'), mongoose = require('mongoose'), mongo = require('mongodb'), session = require('express-session'), passport = require('passport'), flash = require('connect-flash'), path = require('path'), exphbs = require('express-handlebars'), LocalStrategy = require('passport-local').Strategy; // Create our routes & Schema vars var routes = require('./routes/index'), users = require('./routes/users'), User = require('./models/user'), excuses = require('./routes/excuses'), Excuse = require('./models/excuse'); // Initialize our app var app = express(); // Set view path directory app.set('views', path); app.set('views', path.join(__dirname, 'views')); // Set public directory app.use(express.static(path.join(__dirname, 'public'))); //Set our view engine as handlebars app.engine('handlebars', exphbs({defaultLayout:'layout'})); app.set('view engine', 'handlebars'); // Connect to the database mongoose.connect('mongodb://473:<EMAIL>:39674/cpsc473'); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function() { console.log("Connected to Mlab 473 Project 1 Database"); }); // Body Parser for JSON & URL-encoded app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended:false})); app.use(cookieParser()); // Creates our session app.use(session({ secret: 'secret', //whatever we want as the super secret secret resave: true, saveUninitialized: true })); // Initialize passport - used for our authentication app.use(passport.initialize()); app.use(passport.session()); //Express Validator - Copied from express-validator documentation app.use(expressValidator({ errorFormatter: function(param, msg, value) { var namespace = param.split('.'), root = namespace.shift(), formParam = root; while(namespace.length) { formParam += '[' + namespace.shift() + ']'; } return { param : formParam, msg : msg, value : value }; } })); // Connect flash for our messages app.use(flash()); // Global vars for flash messages app.use(function (req, res, next) { // We'll use this to display success and error messages when we render pages res.locals.success_msg = req.flash('success_msg'); res.locals.error_msg = req.flash('error_msg'); //passport sets its own error msg that's why this one is necessary res.locals.error = req.flash('error'); next(); }); // Set our routes app.use('/', routes); app.use('/users', users); app.use('/excuses', excuses); // Listening Port app.listen(3000); console.log('Listening on port 3000'); <file_sep>/routes/users.js var express = require('express'), router = express.Router(), passport = require('passport'), LocalStrategy = require('passport-local').Strategy, User = require('../models/user'); // GET - Register router.get('/register', function(req, res) { res.render('register'); }); // GET - login router.get('/login', function(req, res) { res.render('login'); }); // Register User - gets data from the user end and validates it router.post('/register', function(req, res) { var email = req.body.email, username = req.body.username, password = req.body.password, password2 = req.body.password2; // For confirm password field //test if it's working -- delete this later console.log(email); // Validation req.checkBody('email', 'E-mail is required').isEmail(); req.checkBody('username', 'Username is required').notEmpty(); req.checkBody('password', '<PASSWORD>').notEmpty(); req.checkBody('password2', 'passwords do not match').equals(req.body.password); // Get the validation errors var errors = req.validationErrors(); // Re-render the register page with the errors if(errors) { res.render('register', { errors: errors }); } else { // Validation passed so lets create our new user var newUser = new User({ email: email, username: username, password: <PASSWORD> }); // Create our user - throw an error if it fails User.createUser(newUser, function(err, user) { if(err) throw err; console.log(user); }); // For this to work we need to create a placeholder in our layouts file // that checks all 3 of our global vars req.flash('success_msg', 'You are now registered and can login'); res.redirect('/users/login'); } }); // Gets user name, checks for match in our db, validates the password // Functions comparePassword & getUserByUsername found in models/user.js passport.use(new LocalStrategy( function(username, password, done) { User.getUserByUsername(username), function(err, user) { if(err) throw err; // Is there a user in our db? if(!user) { return done(null, false, {message: 'No User Found'}); } // Does password match? User.comparePassword(password, user.password, function(err, isMatch) { if(err) throw err; if(isMatch) { return done(null, user); } else { return done(null, false, {message: 'Invalid Password'}); } }); }; })); // Passport serialization //Taken from official passport docs - getUserById found in our schema passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { User.getUserbyId(id, function(err, user) { done(err, user); }); }); // POST login // redirects to home page if accepted, otherwise to the login router.post('/login', //failureFlash true - we are using flash messages passport.authenticate('local', { successRedirect: '/', failureRedirect: '/users/login', failureFlash: true}), function(req, res) { res.redirect('/'); }); // Log the user out router.get('/logout', function(req, res) { req.logout(); req.flash('success_msg', 'Successfully logged out'); //redirect to the login page after logging out res.redirect('/users/login'); }); module.exports = router; <file_sep>/routes/excuses.js var express = require('express'); var router = express.Router(); var Excuse = require('../models/excuse'); var mongoose = require('mongoose'); mongoose.connect('mongodb://473:<EMAIL>:39674/cpsc473'); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function() { console.log("Excuses opened it's own connection to Mlab 473"); }); var ObjectId = require('mongoose').Types.ObjectId; // POST - excuses router.post('/submitExcuse', function(req, res) { var excuse = new Excuse(); excuse.title = req.body.title; excuse.postMaker = req.body.postMaker; excuse.users_id = req.body.user_id; excuse.excuse = req.body.excuse; console.log('posting excuse'); excuse.save(function(err, savedExcuse) { if (err) { console.log(err); return res.status(500).send(); } return res.status(200).send(); }); }); // GET - excuses //get the list of excuse posts from the database router.get('/getExcuses', function(req, res) { var sortBy = req.query.sortBy; var action = {}; action[sortBy] = -1; Excuse.find({}).sort(action).exec(function(err, excuses) { var excuseMap = {}; excuses.forEach(function(excuse) { excuseMap[excuse._id] = excuse; }); res.json(excuseMap); }); }); // Rating System for Posts router.post('/increaseExcuseRating', function(req, res) { var updateField = ""; var action = {}; switch (req.body.rate) { case "L": updateField = "liked"; break; case "G": updateField = "legit"; break; case "E": updateField = "embarrassing"; break; case "H": updateField = "hilarious"; break; case "W": updateField = "cringeworthy"; break; } action[updateField] = 1; action["voteCount"] = 1; db.collection('excuses').findAndModify( {"_id": ObjectId(req.body._id)}, {}, {$inc: action}, {}, function(err, db) { if (err) { console.log(err); return res.status(500).send(); } return res.status(200).send(); } ); }); module.exports = router;
9087d31bee0976d33f94a9ff7c8406306209f18a
[ "Markdown", "JavaScript" ]
4
Markdown
BryanBonner/Project1-473
0eabfc3378c68709227db9c93249694b48c57b41
ee5c12b78bb2d89ee3d15a11e5156cda5152e2ea
refs/heads/master
<repo_name>prks18/LeafletJS<file_sep>/india.js let mymap = L.map('mapid', { zoomControl: true }) mymap.setView([28.7041, 77.1025], 4) let myIcon = new L.Icon({ iconUrl: 'map-marker-alt-solid.svg', shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png', iconSize: [50, 82], iconAnchor: [25, 71], popupAnchor: [1, -54], shadowSize: [41, 41] }); // navigator.geolocation.getCurrentPosition((pos) => { // mymap.setView([pos.coords.latitude, pos.coords.longitude], 9); // let marker = L.marker([pos.coords.latitude, pos.coords.longitude], { icon: myIcon }).addTo(mymap).bindPopup(`<div class="popup"><p>This is location<br>Latitude&nbsp;${pos.coords.latitude}&nbsp;Longitude:${pos.coords.longitude}</div>`); // L.circle([pos.coords.latitude, pos.coords.longitude], 500, { // color: 'blue', // fillOpacity: 1 // }).addTo(mymap).bindPopup() // }) function locateMe() { located = mymap.locate({ setView: true, maxZoom: 2 }); } L.tileLayer('https://api.mapbox.com/styles/v1/{affected}/tiles/{z}/{x}/{y}?access_token=<KEY>', { maxZoom: 18, affected: 'mapbox/streets-v11', tileSize: 512, zoomOffset: -1, accessToken: '<KEY>emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' + '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' + 'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>' }).addTo(mymap); function styleIndia(feature) { return { fillColor: getColor(feature.properties.coronaCases), weight: 2, opacity: 1, color: 'white', dashArray: '3', fillOpacity: 0.7 } } function getColor(affected) { console.log(affected) return affected >= 12000 ? '#ff1414' : affected >= 10000 ? '#e30b0b' : affected >= 8000 ? '#e3240b' : affected >= 6000 ? '#e3360b' : affected >= 4000 ? '#e3450b' : affected >= 2000 ? '#e35e0b' : affected >= 1000 ? '#e3a60b' : affected >= 900 ? '#e3b80b' : affected >= 500 ? '#e3d80b' : affected >= 200 ? '#d3e01b' : affected >= 100 ? '#adc447' : affected >= 50 ? '#a5c922' : affected >= 10 ? '#9dc922' : affected >= 1 ? '#699d00' : '#00b300'; } axios.get('assamgeo.json').then((geoJson) => { let data = geoJson.data; // axios.get('https://www.mohfw.gov.in/data/data.json').then((covidData) => { // geoJson.data.features.forEach((geoJsonres) => { // covidData.data.forEach((element) => { // if (element.state_name.toLowerCase() === geoJsonres.properties.STATE.toLowerCase()) { // geoJsonres.properties.coronaCases = element.positive; // geoJsonres.properties.deaths = element.death // } // }) // }) let statesData = data; let geojson = L.geoJson(statesData, { style: styleIndia, onEachFeature: onEachFeature }).addTo(mymap); //Interactivity function onEachFeature(feature, layer) { layer.on({ mouseover: highlightFeature, mouseout: resetHighlight, click: zoomToFeature }); layer.bindTooltip(`<div class="tooltipdiv">${layer.feature.properties.STATE}<br>Positive cases:<span class="positive">${feature.properties.coronaCases}</span><br><span class="death">Deaths:${feature.properties.deaths}</span></div></div>`, { className: "tooltip", direction: 'top', interactive: true, offset: L.point({ x: -10, y: -5 }) }) } function highlightFeature(e) { let state = e.target; state.setStyle({ weight: 5, color: '#fff', dashArray: '', fillOpacity: 0.7 }); if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) { state.bringToFront(); } } function zoomToFeature(e) { mymap.fitBounds(e.target.getBounds()); } function resetHighlight(e) { geojson.resetStyle(e.target); } }) // Custom Control let info = L.control(); info.onAdd = function(mymap) { this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info" this.update(); return this._div; }; // method that we will use to update the control based on feature properties passed info.update = function(props) { // this._div = L.DomUtil.create('div', 'info'); this._div.innerHTML = '<h4>Indian Corona Details</h4>' + (props ? '<b>' + props.name + '</b><br />' + props.density + ' people / mi<sup>2</sup>' : 'Hover over a state'); }; info.addTo(mymap); // }); // let geojson = { // "type": "FeatureCollection", // "features": [{ // "type": "Feature", // "properties": { "corona": "red" }, // "geometry": { // "type": "Polygon", // "coordinates": [ // [ // [79.3927001953125, 12.942998943409737], // [79.43115234375, 12.843937692841445], // [79.5465087890625, 12.669816747262848], // [79.82391357421875, 12.656417878339736], // [79.87060546875, 12.747516274952726], // [79.87335205078125, 12.88142493762357], // [79.749755859375, 13.03131768257082], // [79.60693359375, 13.058074727480722], // [79.47784423828125, 13.023290004843894], // [79.3927001953125, 12.942998943409737] // ] // ] // } // }] // } // L.geoJSON(geojson, { // style: function(feature) { // if (feature.properties.corona == "red") { // feature.setStyle({ color: "red" }) // } // } // }).addTo(mymap)<file_sep>/readme.md The geojson files in this project are all extracted from https://raw.githubusercontent.com/geohacker/india/master/district/india_district.geojson The covid dataset found in this project is from Government Of India's official website : https://api.covid19india.org <file_sep>/Routing/play.js let display = document.getElementById("display"); let map = L.map('mapid', { center: [12.9709931, 80.1938839], zoom: 13 }); const route = document.getElementById("route"); L.tileLayer('https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/{z}/{x}/{y}{r}.png?access_token=<KEY>', { attribution: '&copy; <a href="https://stadiamaps.com/">Stadia Maps</a>, &copy; <a href="https://openmaptiles.org/">OpenMapTiles</a> &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors', }).addTo(map) axios.get('./hotspots.geojson').then((res) => { let raw = res.data; let geojson = L.geoJSON(raw).addTo(map) map.fitBounds(geojson.getBounds()) }) let myIcon = new L.Icon({ iconUrl: 'map-marker-alt-solid.svg', shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png', iconSize: [25, 41], iconAnchor: [12.5, 20.5], popupAnchor: [1, -54], shadowSize: [41, 41] }); // const provider = new GeoSearch.OpenStreetMapProvider(); // const searchControl = new GeoSearchControl({ // provider: provider, // style: 'bar', // autoComplete: true, // autoCompleteDelay: 250 // }) let options1 = { url: 'https://api.geocode.earth/v1', focus: true, expanded: true, position: 'topright', focus: true, placeholder: "From..", polygonIcon: true } let options2 = { url: 'https://api.geocode.earth/v1', focus: true, expanded: true, position: 'topright', placeholder: "To..", } let from = L.control.geocoder('ge-6071d21825e9421c', options1).addTo(map) let to = L.control.geocoder('ge-6071d21825e9421c', options2).addTo(map) let from_lat; let from_lng; let to_lat; let to_lng; from.on('select', (e) => { from_lat = e.latlng.lat; from_lng = e.latlng.lng; let center = e.latlng; console.log(e) let circle = L.circle(center, { radius: 200, interactive: false }).addTo(map) // let from_place = L.geoJSON(geoJsonFrom, { style: () => { color: "#fff" } }).addTo(map); }) to.on('select', (e) => { to_lat = e.latlng.lat; to_lng = e.latlng.lng; let center = e.latlng; let circle = L.circle(center, { radius: 200, interactive: false }).addTo(map) }) function styleLine(feature) { feature.properties.color = "#fff" return { color: "#29c3c3", weight: 7 } } route.addEventListener("click", () => { axios.get(`https://api.mapbox.com/directions/v5/mapbox/cycling/${from_lng},${from_lat};${to_lng},${to_lat}?overview=full&geometries=geojson&steps=true&voice_instructions=true&banner_instructions=true&voice_units=imperial&waypoint_names=Home;Work&access_token=<KEY>`, { responseType: 'json' }).then((res) => { let rawjson = res.data; let route = rawjson.routes[0] let track = route.geometry.coordinates; console.log(res) let geoJsonRaw = { type: 'Feature', properties: {}, geometry: { type: 'LineString', coordinates: track } }; // let layer = L.layerGroup({ // "id": "route", // "type": "line", // "source": { // "type": "geojson", // "data": { // "type": "Feature", // "properties": {}, // "geometry": track // } // }, // "layout": { // "line-join": "round", // "line-cap": "round" // }, // "paint": { // "line-color": "#1db7dd", // "line-width": 8, // "line-opacity": 0.8 // } // }); let geojson = L.geoJSON(geoJsonRaw, { style: styleLine }).addTo(map) map.fitBounds(geojson.getBounds(), { padding: 20 }) }) }) // map.on('click', function(e) { // console.table('Hello') // if (featureGroup.getLayers().length < 2) { // let marker = L.marker(e.latlng).bindPopup("I am a point").addTo(map); // featureGroup.addLayer(marker); // layer1 == undefined ? layer1 = featureGroup.getLayerId(marker) : layer2 = featureGroup.getLayerId(marker); // } else { // map.off('click'); // let point1 = featureGroup.getLayer(layer1); // let point2 = featureGroup.getLayer(layer2); // let from = turf.point([point1.getLatLng().lat, point1.getLatLng().lng]); // let to = turf.point([point2.getLatLng().lat, point2.getLatLng().lng]); // let options = { units: 'kilometers' }; // let distance1 = turf.distance(from, to, options); // } // })<file_sep>/Routing/readme.md Resources: Chennai containment zones(kml): https://covid.gccservice.in/api/csr/hotspots?dummy=1590406489535<file_sep>/pondy.js let mymap = L.map('mapid', { zoomControl: true }) let geocoder = L.Control.Geocoder.mapbox('<KEY>'); // 'Bing': L.Control.Geocoder.bing('<KEY>'), // 'Mapbox': L.Control.Geocoder.mapbox(LCG.apiToken), // 'Photon': L.Control.Geocoder.photon(), mymap.setView([28.7041, 77.1025], 4) let myIcon = new L.Icon({ iconUrl: 'map-marker-alt-solid.svg', shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png', iconSize: [25, 41], iconAnchor: [12.5, 20.5], popupAnchor: [1, -54], shadowSize: [41, 41] }); mymap.on('load', function() { mymap.resize(); }) let marker = L.marker([26.1433, 91.7898], { icon: myIcon }).addTo(mymap).bindPopup(`<div class="popup"><p>Dispur,Capital Of Assam</p></div>`); mymap.on('click', function(e) { geocoder.reverse(e.latlng, mymap.options.crs.scale(mymap.getZoom()), function(results) { let r = results[0]; if (r) { if (marker) { marker .setLatLng(r.center) .setPopupContent(r.html || r.name) .openPopup() setTimeout(() => { marker.closePopup() }, 2000) } else { marker = L.marker(r.center) .bindPopup(r.name) .addTo(mymap) setTimeout(() => { marker.closePopup() }, 2000) } } }); }); function locateMe() { mymap.locate({ setView: true, maxZoom: 10 }); mymap.on('locationfound', locationFound) mymap.on('locationerror', locationError) } function locationFound(e) { if (marker) { marker.setLatLng(e.latlng).bindPopup("You are within 2m radius of this location"); let markerLayer = L.featureGroup([marker]).addTo(mymap) mymap.fitBounds(markerLayer.getBounds()) } else { marker = L.marker(e.latlng).bindPopup("You are withing 2m radius of this location").addTo(mymap); } } function locationError(e) { console.error(e); alert("Location tracing is blocked!") } L.tileLayer('https://api.mapbox.com/styles/v1/{affected}/tiles/{z}/{x}/{y}?access_token=<KEY>', { maxZoom: 18, affected: 'mapbox/streets-v11', tileSize: 512, zoomOffset: -1, accessToken: '<KEY>', attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' + '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' + 'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>' }).addTo(mymap); function styleFeature(feature) { return { fillColor: getColor(feature.properties.coronaCases), weight: 2, opacity: 1, color: 'white', dashArray: '3', fillOpacity: 0.7 } } function getColor(affected) { return affected >= 12000 ? '#ff1414' : affected >= 10000 ? '#e30b0b' : affected >= 8000 ? '#e3240b' : affected >= 6000 ? '#e3360b' : affected >= 4000 ? '#e3450b' : affected >= 2000 ? '#e35e0b' : affected >= 1000 ? '#e3a60b' : affected >= 900 ? '#e3b80b' : affected >= 500 ? '#e3d80b' : affected >= 200 ? '#d3e01b' : affected >= 100 ? '#adc447' : affected >= 50 ? '#a5c922' : affected >= 10 ? '#9dc922' : affected >= 1 ? '#699d00' : '#00b300'; } axios.get('pondygeo.json').then((geoJson) => { let assamdata = geoJson.data; axios.get('https://api.covid19india.org/v2/state_district_wise.json').then((covidData) => { assamdata.features.forEach((geoJsonres) => { covidData.data.forEach((element) => { if (element.state == "Puducherry") element.districtData.forEach((district) => { if (district.district.toLowerCase() === geoJsonres.properties.NAME_2.toLowerCase()) { geoJsonres.properties.coronaCases = district.confirmed; geoJsonres.properties.deaths = district.deceased; } }) }) }); let statesData = assamdata; let geojson = L.geoJson(statesData, { style: styleFeature, onEachFeature: onEachFeature }).addTo(mymap); mymap.fitBounds(geojson.getBounds()); //Interactivity function onEachFeature(feature, layer) { layer.on({ mouseover: highlightFeature, mouseout: resetHighlight, click: zoomToFeature }); layer.bindTooltip(`<div class="tooltipdiv">${layer.feature.properties.NAME_2}<br>Positive cases:<span class="positive">${feature.properties.coronaCases}</span><br><span class="death">Deaths:${feature.properties.deaths}</span></div></div>`, { className: "tooltip", direction: 'top', interactive: true, offset: L.point({ x: -10, y: -5 }) }) } function highlightFeature(e) { let state = e.target; state.setStyle({ weight: 5, color: '#fff', dashArray: '', fillOpacity: 0.7 }); if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) { state.bringToFront(); } } function zoomToFeature(e) { mymap.fitBounds(e.target.getBounds()); marker.setLatLng(e.latlng) if (e.target.feature.properties.coronaCases >= 1) { if (alertify) alertify.alert('We want you to know..', 'You are in a covid-19 - prone zone!'); else setTimeout(() => { alert('You are in a covid19-prone zone!') }, 500); } else { if (alertify) alertify.alert('We want you to know..', 'You are in a covid-19 - free zone!'); else setTimeout(() => { alert('You are in a covid19-free zone!') }, 500); } } function resetHighlight(e) { geojson.resetStyle(e.target); } }) });
3bded1348b92273c702bc04b41b17566dcf3ed5a
[ "JavaScript", "Markdown" ]
5
JavaScript
prks18/LeafletJS
d186386b033ef122a115c1153d477b89e6077580
19f6341c4a5502845865196ae5627e00626c1a3d
refs/heads/master
<repo_name>ach4m0/changeswindow<file_sep>/Resources/app.js (function(){ //Global var with version version = '0.2'; // Open MainWindow var ChangesWindow = require('/ui/ChangesWindow'), WhiteWindow = require('/ui/WhiteWindow'); if(Ti.App.Properties.getString('version',0) == version){ WhiteWindow().open(); }else{ ChangesWindow().open(); } })(); <file_sep>/Resources/ui/WhiteWindow.js function WhiteWindow(){ var self = Ti.UI.createWindow({ backgroundColor: '#AAAAAA' }); return self; }; module.exports = WhiteWindow <file_sep>/Resources/ui/ChangesWindow.js function ChangesWindow(){ var firstColor='#A30000', secondColor='#840000', textColor='#FFFFFF', self = Ti.UI.createWindow({ backgroundColor: firstColor, exitOnClose: true, navBarHidden: true }), //End custom parameters WhiteWindow = require('/ui/WhiteWindow'), //End requires view1 = Ti.UI.createView({ backgroundColor: 'transparent' }), text1 = Ti.UI.createLabel({ color: textColor, font: { fontSize: 25 }, left: 10, text: 'Ya puedes ver el detalle de las escuderías', top: 30 }), picture1 = Ti.UI.createImageView({ borderRadius: 20, image: '/images/pic1.jpg', height: 250 }), view2 = Ti.UI.createView({ backgroundColor: 'transparent' }), view3 = Ti.UI.createView({ backgroundColor: 'transparent' }), scrollableView = Ti.UI.createScrollableView({ views: [view1,view2,view3], showPagingControl: false }), endButton = Ti.UI.createButton({ backgroundColor: 'transparent', bottom: 10, color: textColor, font: { fontSize: 25 }, right: 10, title: 'Finalizar' }); //Event to endButton endButton.addEventListener('click',function(event){ Ti.App.Properties.setString('version',version); self.close(); WhiteWindow().open(); }); //Adding elements view1.add(text1); view1.add(picture1); view1.add(createNextButton()); view2.add(createNextButton()); view2.add(createPreviousButton()); view3.add(createPreviousButton()); view3.add(endButton); self.add(scrollableView); return self; function createNextButton(){ var nextButton = Ti.UI.createButton({ backgroundColor: 'transparent', bottom: 10, color: textColor, font: { fontSize: 25 }, right: 10, title: 'Siguiente' }); nextButton.addEventListener('click',function(){ scrollableView.scrollToView(scrollableView.getCurrentPage() + 1); }); return nextButton; }; function createPreviousButton(){ var previousButton = Ti.UI.createButton({ backgroundColor: 'transparent', bottom: 10, color: textColor, font: { fontSize: 25 }, left: 10, title: 'Anterior' }); previousButton.addEventListener('click',function(){ scrollableView.scrollToView(scrollableView.getCurrentPage() - 1); }); return previousButton; }; }; module.exports = ChangesWindow; <file_sep>/README.md changeswindow ============= A scrollable view with the changes for application updates
2a655c52ebd61d8ceeaa213beebe5a50c085adc0
[ "JavaScript", "Markdown" ]
4
JavaScript
ach4m0/changeswindow
b21f5a0d207eb48f7a4a17afce75ea5f941ee035
e6a1a70a1fe498439a78447fb19ba9711c4aa47b
refs/heads/master
<repo_name>marcelovicarvalho/edenic<file_sep>/app/src/main/java/com/example/edenic/AddPersonagem.java package com.example.edenic; import androidx.annotation.ArrayRes; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.util.LogPrinter; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.NumberPicker; import android.widget.RadioButton; import android.widget.Spinner; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import static android.view.View.GONE; public class AddPersonagem extends AppCompatActivity { int HP = 0; String classe, raca, background; ArrayList<Integer> checkForca = new ArrayList<>(); ArrayList<Integer> checkDestreza = new ArrayList<>(); ArrayList<Integer> checkInteligencia = new ArrayList<>(); ArrayList<Integer> checkSabedoria = new ArrayList<>(); ArrayList<Integer> checkCarisma = new ArrayList<>(); int forca2 = 0; int destreza2 = 0; int constituicao2 = 0; int inteligencia2 = 0; int sabedoria2 = 0; int carisma2 = 0; int atletismo2 = 0; int acrobacia2 = 0; int furtividade2 = 0; int prestigitacao2 = 0; int arcanismo2 = 0; int historia2 = 0; int investigacao2 = 0; int natureza2 = 0; int religiao2 = 0; int adestraranimais2 = 0; int intuicao2 = 0; int medicina2 = 0; int percepcao2 = 0; int sobrevivencia2 = 0; int atuacao2 = 0; int enganacao2 = 0; int intimidacao2 = 0; int persuasao2 = 0; int somaStatus = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_personagem2); //forca final CheckBox atletismo = findViewById(R.id.atletismo); //destreza final CheckBox acrobacia = findViewById(R.id.acrobacia); final CheckBox furtividade = findViewById(R.id.furtividade); final CheckBox prestigitacao = findViewById(R.id.prestigitacao); //inteligencia final CheckBox arcanismo = findViewById(R.id.arcanismo); final CheckBox historia = findViewById(R.id.historia); final CheckBox investigacao = findViewById(R.id.investigacao); final CheckBox natureza = findViewById(R.id.natureza); final CheckBox religiao = findViewById(R.id.religiao); //sabedoria final CheckBox adestraranimais = findViewById(R.id.adestraranimais); final CheckBox intuicao = findViewById(R.id.intuicao); final CheckBox medicina = findViewById(R.id.medicina); final CheckBox percepcao = findViewById(R.id.percepcao); final CheckBox sobrevivencia = findViewById(R.id.sobrevivencia); //carisma final CheckBox atuacao = findViewById(R.id.atuacao); final CheckBox enganacao = findViewById(R.id.enganacao); final CheckBox intimidacao = findViewById(R.id.intimidacao); final CheckBox persuasao = findViewById(R.id.persuasao); //populando o number picker NumberPicker forca = (NumberPicker) findViewById(R.id.forca); NumberPicker destreza = (NumberPicker) findViewById(R.id.destreza); NumberPicker constituicao = (NumberPicker) findViewById(R.id.constituicao); NumberPicker inteligencia = (NumberPicker) findViewById(R.id.inteligencia); NumberPicker sabedoria = (NumberPicker) findViewById(R.id.sabedoria); NumberPicker carisma = (NumberPicker) findViewById(R.id.carisma); String[] nums = new String[20]; for(int i=0; i<nums.length; i++) nums[i] = Integer.toString(i+1); //forca forca.setMinValue(1); forca.setMaxValue(20); forca.setWrapSelectorWheel(false); forca.setDisplayedValues(nums); forca.setValue(8); //destreza destreza.setMinValue(1); destreza.setMaxValue(20); destreza.setWrapSelectorWheel(false); destreza.setDisplayedValues(nums); destreza.setValue(8); //constituicao constituicao.setMinValue(1); constituicao.setMaxValue(20); constituicao.setWrapSelectorWheel(false); constituicao.setDisplayedValues(nums); constituicao.setValue(8); //inteligencia inteligencia.setMinValue(1); inteligencia.setMaxValue(20); inteligencia.setWrapSelectorWheel(false); inteligencia.setDisplayedValues(nums); inteligencia.setValue(8); //sabedoria sabedoria.setMinValue(1); sabedoria.setMaxValue(20); sabedoria.setWrapSelectorWheel(false); sabedoria.setDisplayedValues(nums); sabedoria.setValue(8); //carisma carisma.setMinValue(1); carisma.setMaxValue(20); carisma.setWrapSelectorWheel(false); carisma.setDisplayedValues(nums); carisma.setValue(8); //spinner classe List<String> classes = new ArrayList<String>(); classes.add("Classe"); classes.add("Clerigo"); classes.add("Guerreiro"); classes.add("Ladino"); classes.add("Mago"); final ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_spinner_item, classes); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); Spinner sItems = (Spinner) findViewById(R.id.spnClasse); sItems.setAdapter(adapter); sItems.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { // Toast.makeText(AddPersonagem.this, adapterView.getSelectedItem().toString(), Toast.LENGTH_SHORT).show(); if (adapterView.getSelectedItem().equals("Clerigo")){ resetaBotoes(); historia.setEnabled(true); intuicao.setEnabled(true); medicina.setEnabled(true); persuasao.setEnabled(true); religiao.setEnabled(true); } else if(adapterView.getSelectedItem().equals("Guerreiro")){ resetaBotoes(); HP = HP + 10; acrobacia.setEnabled(true); adestraranimais.setEnabled(true); atletismo.setEnabled(true); historia.setEnabled(true); intuicao.setEnabled(true); intimidacao.setEnabled(true); percepcao.setEnabled(true); sobrevivencia.setEnabled(true); } else if(adapterView.getSelectedItem().equals("Ladino")){ resetaBotoes(); HP = HP + 8; acrobacia.setEnabled(true); atletismo.setEnabled(true); atuacao.setEnabled(true); furtividade.setEnabled(true); intimidacao.setEnabled(true); percepcao.setEnabled(true); persuasao.setEnabled(true); prestigitacao.setEnabled(true); } else if(adapterView.getSelectedItem().equals("Mago")){ resetaBotoes(); HP = HP + 6; arcanismo.setEnabled(true); historia.setEnabled(true); intuicao.setEnabled(true); investigacao.setEnabled(true); medicina.setEnabled(true); religiao.setEnabled(true); } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); //spinner raça List<String> racas = new ArrayList<String>(); racas.add("Raça"); racas.add("Humano"); racas.add("Anão"); racas.add("Elfo"); racas.add("Halfling"); ArrayAdapter<String> adapter2 = new ArrayAdapter<String>( this, android.R.layout.simple_spinner_item, racas); adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); Spinner sItems2 = (Spinner) findViewById(R.id.spnRaca); sItems2.setAdapter(adapter2); sItems2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { if (adapterView.getSelectedItem().equals("Humano")){ } else if(adapterView.getSelectedItem().equals("Anão")){ } else if(adapterView.getSelectedItem().equals("Elfo")){ } else if(adapterView.getSelectedItem().equals("Halfling")){ } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); //spinner background List<String> background = new ArrayList<String>(); background.add("Antecessor"); background.add("Acólito"); background.add("Criminoso"); background.add("Herói popular"); background.add("Sábio"); background.add("Soldado"); ArrayAdapter<String> adapter3 = new ArrayAdapter<String>( this, android.R.layout.simple_spinner_item, background); adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); Spinner sItems3 = (Spinner) findViewById(R.id.spnBackground); sItems3.setAdapter(adapter3); String selected3 = sItems3.getSelectedItem().toString(); sItems3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { if (adapterView.getSelectedItem().equals("Acólito")){ intuicao.setEnabled(false); intuicao.setChecked(true); religiao.setEnabled(false); religiao.setChecked(true); } else if (adapterView.getSelectedItem().equals("Criminoso")){ enganacao.setEnabled(false); enganacao.setChecked(true); furtividade.setEnabled(false); furtividade.setChecked(true); } else if (adapterView.getSelectedItem().equals("Herói popular")){ adestraranimais.setEnabled(false); adestraranimais.setChecked(true); sobrevivencia.setEnabled(false); sobrevivencia.setChecked(true); } else if (adapterView.getSelectedItem().equals("Sábio")){ arcanismo.setEnabled(false); arcanismo.setChecked(true); historia.setEnabled(false); historia.setChecked(true); } else if (adapterView.getSelectedItem().equals("Soldado")){ atletismo.setEnabled(false); atletismo.setChecked(true); intimidacao.setEnabled(false); intimidacao.setChecked(true); } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); Button salvar = findViewById(R.id.salvar); salvar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Pega o valor do spinner para enviar pro db local String nome = ((EditText) findViewById(R.id.nomepersonagem)).getText().toString(); String classe = ((Spinner) findViewById(R.id.spnClasse)).getSelectedItem().toString(); String raca = ((Spinner) findViewById(R.id.spnRaca)).getSelectedItem().toString(); String background = ((Spinner) findViewById(R.id.spnBackground)).getSelectedItem().toString(); //Pega o valor do number picker int forca = ((NumberPicker) findViewById(R.id.forca)).getValue(); int destreza = ((NumberPicker) findViewById(R.id.destreza)).getValue(); int constituicao = ((NumberPicker) findViewById(R.id.constituicao)).getValue(); int inteligencia = ((NumberPicker) findViewById(R.id.inteligencia)).getValue(); int sabedoria = ((NumberPicker) findViewById(R.id.sabedoria)).getValue(); int carisma = ((NumberPicker) findViewById(R.id.carisma)).getValue(); // switch (raca){ case "Anão": constituicao = constituicao + 2; forca2 = forca; destreza2 = destreza; constituicao2 = modificadorStatus(constituicao); inteligencia2 = inteligencia; sabedoria2 = sabedoria; carisma2 = carisma; modificadorStatus(forca); atletismo2 = somaStatus; destreza2 = modificadorStatus(destreza); acrobacia2 = somaStatus; furtividade2 = somaStatus; prestigitacao2 = somaStatus; constituicao2 = modificadorStatus(constituicao); calculaHP(classe); inteligencia2 = modificadorStatus(inteligencia); arcanismo2 = somaStatus; historia2 = somaStatus; investigacao2 = somaStatus; natureza2 = somaStatus; religiao2 = somaStatus; sabedoria2 = modificadorStatus(sabedoria); adestraranimais2 = somaStatus; intuicao2 = somaStatus; medicina2 = somaStatus; percepcao2 = somaStatus; sobrevivencia2 = somaStatus; carisma2 = modificadorStatus(carisma); atuacao2 = somaStatus; enganacao2 = somaStatus; intimidacao2 = somaStatus; persuasao2 = somaStatus; break; case "Elfo": destreza = destreza + 2; forca2 = forca; destreza2 = modificadorStatus(destreza); constituicao2 = constituicao; inteligencia2 = inteligencia; sabedoria2 = sabedoria; carisma2 = sabedoria; modificadorStatus(forca); atletismo2 = somaStatus; destreza2 = modificadorStatus(destreza); acrobacia2 = somaStatus; furtividade2 = somaStatus; prestigitacao2 = somaStatus; constituicao2 = modificadorStatus(constituicao); calculaHP(classe); inteligencia2 = modificadorStatus(inteligencia); arcanismo2 = somaStatus; historia2 = somaStatus; investigacao2 = somaStatus; natureza2 = somaStatus; religiao2 = somaStatus; sabedoria2 = modificadorStatus(sabedoria); adestraranimais2 = somaStatus; intuicao2 = somaStatus; medicina2 = somaStatus; percepcao2 = somaStatus; sobrevivencia2 = somaStatus; carisma2 = modificadorStatus(carisma); atuacao2 = somaStatus; enganacao2 = somaStatus; intimidacao2 = somaStatus; persuasao2 = somaStatus; break; case "Halfling": destreza = destreza + 2; forca2 = forca; destreza2 = modificadorStatus(destreza); constituicao2 = constituicao; inteligencia2 = inteligencia; sabedoria2 = sabedoria; carisma2 = sabedoria; modificadorStatus(forca); atletismo2 = somaStatus; destreza2 = modificadorStatus(destreza); acrobacia2 = somaStatus; furtividade2 = somaStatus; prestigitacao2 = somaStatus; constituicao2 = modificadorStatus(constituicao); calculaHP(classe); inteligencia2 = modificadorStatus(inteligencia); arcanismo2 = somaStatus; historia2 = somaStatus; investigacao2 = somaStatus; natureza2 = somaStatus; religiao2 = somaStatus; sabedoria2 = modificadorStatus(sabedoria); adestraranimais2 = somaStatus; intuicao2 = somaStatus; medicina2 = somaStatus; percepcao2 = somaStatus; sobrevivencia2 = somaStatus; carisma2 = modificadorStatus(carisma); atuacao2 = somaStatus; enganacao2 = somaStatus; intimidacao2 = somaStatus; persuasao2 = somaStatus; break; case "Humano": forca = forca + 1; destreza = destreza + 1; constituicao = constituicao + 1; inteligencia = inteligencia + 1; sabedoria = sabedoria + 1; carisma = carisma + 1; modificadorStatus(forca); atletismo2 = somaStatus; destreza2 = modificadorStatus(destreza); acrobacia2 = somaStatus; furtividade2 = somaStatus; prestigitacao2 = somaStatus; constituicao2 = modificadorStatus(constituicao); calculaHP(classe); inteligencia2 = modificadorStatus(inteligencia); arcanismo2 = somaStatus; historia2 = somaStatus; investigacao2 = somaStatus; natureza2 = somaStatus; religiao2 = somaStatus; sabedoria2 = modificadorStatus(sabedoria); adestraranimais2 = somaStatus; intuicao2 = somaStatus; medicina2 = somaStatus; percepcao2 = somaStatus; sobrevivencia2 = somaStatus; carisma2 = modificadorStatus(carisma); atuacao2 = somaStatus; enganacao2 = somaStatus; intimidacao2 = somaStatus; persuasao2 = somaStatus; break; } itemSelecionado(); Log.i("nome ", nome); Log.i("raca ", raca); Log.i("classe ", classe); Log.i("background ", background); Log.i("forca ", String.valueOf(forca2)); Log.i("destreza ", String.valueOf(destreza2)); Log.i("const ", String.valueOf(constituicao2)); Log.i("inte ", String.valueOf(inteligencia2)); Log.i("sabe ", String.valueOf(sabedoria2)); Log.i("caris ", String.valueOf(carisma2)); Log.i("hp+ ", String.valueOf(HP)); String SQLiteQuery = "INSERT INTO personagens (char_nome, char_nivel,char_raca,char_class,char_back,char_str,char_dex,char_cons,char_int,char_wis,char_char,char_hp) VALUES ('"+nome+"',1,'"+raca+"','"+classe+"','"+background+"','"+String.valueOf(forca2)+"','"+String.valueOf(destreza2)+"','"+String.valueOf(constituicao2)+"','"+String.valueOf(inteligencia2)+"','"+String.valueOf(sabedoria2)+"', '"+String.valueOf(carisma2)+"','"+String.valueOf(HP)+"')"; gravaBanco(getBaseContext()).rawQuery("INSERT INTO proficiencias (prof_atl,prof_acr,prof_furt,prof_prest,prof_arc,prof_his,prof_inves,prof_natu,prof_reli,prof_ades,prof_intui,prof_medic,prof_percep,prof_sobre,prof_atua,prof_engana,prof_inti,prof_persu) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", new String[]{String.valueOf(atletismo2),String.valueOf(acrobacia2),String.valueOf(furtividade2),String.valueOf(prestigitacao2),String.valueOf(arcanismo2),String.valueOf(historia2),String.valueOf(investigacao2),String.valueOf(natureza2),String.valueOf(religiao2),String.valueOf(adestraranimais2),String.valueOf(intuicao2),String.valueOf(medicina2),String.valueOf(percepcao2),String.valueOf(sobrevivencia2),String.valueOf(atuacao2),String.valueOf(enganacao2),String.valueOf(intimidacao2),String.valueOf(persuasao2)}); gravaBanco(getBaseContext()).execSQL(SQLiteQuery); Toast.makeText(AddPersonagem.this, "Personagem Salvo", Toast.LENGTH_SHORT).show(); finish(); } }); } private String calculaHP(String classe){ switch (classe){ case "Clerigo": HP = 8 + somaStatus; break; case "Guerreiro": HP = 10 + somaStatus; break; case "Ladino": HP = 8 + somaStatus; break; case "Mago": HP = 6 + somaStatus; break; } return String.valueOf(HP); } private int modificadorStatus(int status){ int status2 = 0; if(status == 1){ status2 = status - 5; somaStatus = -5; } else if(status == 2 || status == 3){ status2 = status - 4; somaStatus = -4; } else if(status == 4 || status == 5){ status2 = status - 3; somaStatus = -3; } else if(status == 6 || status == 7){ status2 = status - 2; somaStatus = -2; } else if(status == 8 || status == 9){ status2 = status - 1; somaStatus = -1; } else if(status == 10 || status == 11){ status2 = status; somaStatus = 0; } else if(status == 12 || status == 13){ status2 = status + 1; somaStatus = 1; } else if(status == 14 || status == 15){ status2 = status + 2; somaStatus = 2; } else if(status == 16 || status == 17){ status2 = status + 3; somaStatus = 3; } else if(status == 18 || status == 19){ status2 = status + 4; somaStatus = 4; } else if(status == 20){ status2 = status + 5; somaStatus = 5; } return status2; } private void itemSelecionado(){ final CheckBox atletismo = findViewById(R.id.atletismo); final CheckBox acrobacia = findViewById(R.id.acrobacia); final CheckBox furtividade = findViewById(R.id.furtividade); final CheckBox prestigitacao = findViewById(R.id.prestigitacao); final CheckBox arcanismo = findViewById(R.id.arcanismo); final CheckBox historia = findViewById(R.id.historia); final CheckBox investigacao = findViewById(R.id.investigacao); final CheckBox natureza = findViewById(R.id.natureza); final CheckBox religiao = findViewById(R.id.religiao); final CheckBox adestraranimais = findViewById(R.id.adestraranimais); final CheckBox intuicao = findViewById(R.id.intuicao); final CheckBox medicina = findViewById(R.id.medicina); final CheckBox percepcao = findViewById(R.id.percepcao); final CheckBox sobrevivencia = findViewById(R.id.sobrevivencia); final CheckBox atuacao = findViewById(R.id.atuacao); final CheckBox enganacao = findViewById(R.id.enganacao); final CheckBox intimidacao = findViewById(R.id.intimidacao); final CheckBox persuasao = findViewById(R.id.persuasao); // NAO ESTA PASSANDO O VALOR CORRETO PELA (retonarModStatus) //forca if (atletismo.isChecked()){ atletismo2 = 2 + atletismo2; } //destreza if (acrobacia.isChecked()){ acrobacia2 = 2 + acrobacia2; } if (furtividade.isChecked()){ furtividade2 = 2 + furtividade2; } if (prestigitacao.isChecked()){ prestigitacao2 = 2 + prestigitacao2; } //inteligencia if (arcanismo.isChecked()){ arcanismo2 = 2 + arcanismo2; } if (historia.isChecked()){ historia2 = 2 + historia2; } if (investigacao.isChecked()){ investigacao2 = 2 + investigacao2; } if (natureza.isChecked()){ natureza2 = 2 + natureza2; } if (religiao.isChecked()){ religiao2 = 2 + religiao2; } //sabedoria if (adestraranimais.isChecked()){ adestraranimais2 = 2 + adestraranimais2; } if (intuicao.isChecked()){ intuicao2 = 2 + intuicao2; } if (medicina.isChecked()){ medicina2 = 2 + medicina2; } if (percepcao.isChecked()){ percepcao2 = 2 + percepcao2; } if (sobrevivencia.isChecked()){ sobrevivencia2 = 2 + sobrevivencia2; } //carisma if (atuacao.isChecked()){ atuacao2 = 2 + atuacao2; } if (enganacao.isChecked()){ enganacao2 = 2 + enganacao2; } if (intimidacao.isChecked()){ intimidacao2 = 2 + intimidacao2; } if (persuasao.isChecked()){ persuasao2 = 2 + persuasao2; } } private SQLiteDatabase gravaBanco(Context context){ DatabaseHandler banco = new DatabaseHandler(context); SQLiteDatabase db = banco.getWritableDatabase(); return db; } private void resetaBotoes(){ //desliga todos as checkboxes //forca final CheckBox atletismo = findViewById(R.id.atletismo); atletismo.setEnabled(false); atletismo.setChecked(false); //destreza final CheckBox acrobacia = findViewById(R.id.acrobacia); acrobacia.setEnabled(false); acrobacia.setChecked(false); final CheckBox furtividade = findViewById(R.id.furtividade); furtividade.setEnabled(false); furtividade.setChecked(false); final CheckBox prestigitacao = findViewById(R.id.prestigitacao); prestigitacao.setEnabled(false); prestigitacao.setChecked(false); //inteligencia final CheckBox arcanismo = findViewById(R.id.arcanismo); arcanismo.setEnabled(false); arcanismo.setChecked(false); final CheckBox historia = findViewById(R.id.historia); historia.setEnabled(false); historia.setChecked(false); final CheckBox investigacao = findViewById(R.id.investigacao); investigacao.setEnabled(false); investigacao.setChecked(false); final CheckBox natureza = findViewById(R.id.natureza); natureza.setEnabled(false); natureza.setChecked(false); final CheckBox religiao = findViewById(R.id.religiao); religiao.setEnabled(false); religiao.setChecked(false); //sabedoria final CheckBox adestraranimais = findViewById(R.id.adestraranimais); adestraranimais.setEnabled(false); adestraranimais.setChecked(false); final CheckBox intuicao = findViewById(R.id.intuicao); intuicao.setEnabled(false); intuicao.setChecked(false); final CheckBox medicina = findViewById(R.id.medicina); medicina.setEnabled(false); medicina.setChecked(false); final CheckBox percepcao = findViewById(R.id.percepcao); percepcao.setEnabled(false); percepcao.setChecked(false); final CheckBox sobrevivencia = findViewById(R.id.sobrevivencia); sobrevivencia.setEnabled(false); sobrevivencia.setChecked(false); //carisma final CheckBox atuacao = findViewById(R.id.atuacao); atuacao.setEnabled(false); atuacao.setChecked(false); final CheckBox enganacao = findViewById(R.id.enganacao); enganacao.setEnabled(false); enganacao.setChecked(false); final CheckBox intimidacao = findViewById(R.id.intimidacao); intimidacao.setEnabled(false); intimidacao.setChecked(false); final CheckBox persuasao = findViewById(R.id.persuasao); persuasao.setEnabled(false); persuasao.setChecked(false); } } <file_sep>/app/src/main/java/com/example/edenic/FeiticosRecycler.java package com.example.edenic; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Filter; import android.widget.Filterable; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.RecyclerView; import org.w3c.dom.Text; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class FeiticosRecycler extends RecyclerView.Adapter<FeiticosRecycler.MyViewHolder> implements Filterable { ArrayList<String> spell_nome_all = new ArrayList<>(); ArrayList<String> spell_nome = new ArrayList<>(); ArrayList<String> spell_nivel = new ArrayList<>(); ArrayList<String> spell_cast_time = new ArrayList<>(); ArrayList<String> spell_range = new ArrayList<>(); ArrayList<String> spell_duration = new ArrayList<>(); ArrayList<String> spell_classe = new ArrayList<>(); ArrayList<String> spell_desc = new ArrayList<>(); Context context; public FeiticosRecycler(Context context, ArrayList<String> spell_nome, ArrayList<String> spell_nivel, ArrayList<String> spell_cast_time, ArrayList<String> spell_range, ArrayList<String> spell_duration, ArrayList<String> spell_classe, ArrayList<String> spell_desc) { context = context; this.spell_nome = spell_nome; this.spell_nivel = spell_nivel; this.spell_cast_time = spell_cast_time; this.spell_range = spell_range; this.spell_duration = spell_duration; this.spell_classe = spell_classe; this.spell_desc = spell_desc; this.spell_nome_all = new ArrayList<>(spell_nome); } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) { LinearLayout txt = (LinearLayout) LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_feiticos, viewGroup, false); FeiticosRecycler.MyViewHolder myViewHolder = new FeiticosRecycler.MyViewHolder(txt); Collections.sort(spell_nome); return myViewHolder; } @Override public void onBindViewHolder(@NonNull final FeiticosRecycler.MyViewHolder Holder, final int i) { Holder.spell_nome.setText(spell_nome.get(i)); Holder.spell_nivel.setText(spell_nivel.get(i)); Holder.spell_cast_time.setText(spell_cast_time.get(i)); Holder.spell_range.setText(spell_range.get(i)); Holder.spell_duration.setText(spell_duration.get(i)); Holder.spell_classe.setText(spell_classe.get(i)); Holder.cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final AlertDialog alertDialog = new AlertDialog.Builder(view.getContext()).create(); //Read Update alertDialog.setTitle("Descrição"); alertDialog.setMessage(spell_desc.get(i)); alertDialog.setButton("Fechar", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { alertDialog.dismiss(); } }); alertDialog.show(); //<-- See This! } }); } @Override public int getItemCount() { return spell_nome.size(); } @Override public Filter getFilter() { return null; } Filter filter = new Filter() { @Override //run on background thread protected FilterResults performFiltering(CharSequence constraint) { List<String> filteredList = new ArrayList<>(); if (constraint.toString().isEmpty()){ filteredList.addAll(spell_nome_all); } else { for (String spellnome : spell_nome_all){ if (spellnome.toLowerCase().contains(constraint.toString().toLowerCase())){ filteredList.add(spellnome); } } } FilterResults filterResults = new FilterResults(); filterResults.values = filteredList; return filterResults; } //run on ui thread @Override protected void publishResults(CharSequence constraint, FilterResults results) { spell_nome.clear(); spell_nome.addAll((Collection<? extends String>) results.values); notifyDataSetChanged(); } }; public static class MyViewHolder extends RecyclerView.ViewHolder { TextView spell_nome; TextView spell_nivel; TextView spell_cast_time; TextView spell_range; TextView spell_duration; TextView spell_classe; CardView cardView; public MyViewHolder(@NonNull View itemView) { super(itemView); spell_nome = itemView.findViewById(R.id.nomeFeitico); spell_nivel = itemView.findViewById(R.id.nivelFeitico); spell_cast_time = itemView.findViewById(R.id.tempo); spell_range = itemView.findViewById(R.id.range); spell_duration = itemView.findViewById(R.id.duracao); spell_classe = itemView.findViewById(R.id.classeFeitico); cardView = itemView.findViewById(R.id.cardV); } } } <file_sep>/app/src/main/java/com/example/edenic/Personagens.java package com.example.edenic; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.media.Image; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.google.android.material.floatingactionbutton.FloatingActionButton; import java.util.ArrayList; public class Personagens extends AppCompatActivity { final ArrayList<String> nome = new ArrayList<>(); final ArrayList<String> nivel = new ArrayList<>(); final ArrayList<String> classe = new ArrayList<>(); final ArrayList<String> raca= new ArrayList<>(); final ArrayList<String> background = new ArrayList<>(); RecyclerView rv2; RecyclerView.LayoutManager mRv2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_personagens); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); rv2 = findViewById(R.id.recyclerviewPersonagens); setAdapter(); FloatingActionButton button = findViewById(R.id.addChar); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AddPersonagem(); } }); FloatingActionButton button2 = findViewById(R.id.charUpdate); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { updatePersonagem(); } }); } public void AddPersonagem() { Intent intent = new Intent(Personagens.this, AddPersonagem.class); startActivity(intent); } public void updatePersonagem() { this.finish(); rv2 = findViewById(R.id.recyclerviewPersonagens); setAdapter(); Intent intent = new Intent(Personagens.this, Personagens.class); startActivity(intent); } public void setAdapter(){ DatabaseHandler banco = new DatabaseHandler(this); SQLiteDatabase db = banco.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from personagens", new String[]{}); cursor.moveToFirst(); do { nome.add(cursor.getString(1)); nivel.add(cursor.getString(2)); classe.add(cursor.getString(4)); raca.add(cursor.getString(3)); background.add(cursor.getString(5)); Log.i("aaa", cursor.getString(1)); } while (cursor.moveToNext()); PersonagensRecycler adapter = new PersonagensRecycler(this, nome, nivel, classe, raca, background); rv2.setAdapter(adapter); mRv2 = new GridLayoutManager(this.getBaseContext(), 1); rv2.setLayoutManager(mRv2); } public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { this.finish(); } return super.onOptionsItemSelected(item); } } <file_sep>/app/src/main/java/com/example/edenic/MainActivity.java package com.example.edenic; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDelegate; import androidx.cardview.widget.CardView; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); super.onCreate(savedInstanceState); getSupportActionBar().hide(); setContentView(R.layout.activity_main); CardView personagens = findViewById(R.id.personagens); personagens.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openPersonagens(); } }); CardView feiticos = findViewById(R.id.feiticos); feiticos.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { openFeiticos(); } }); } public void openPersonagens(){ Intent intent = new Intent(this, Personagens.class); startActivity(intent); } public void openFeiticos(){ Intent intent = new Intent(this, Feiticos.class); startActivity(intent); } }
962de31db239e78d42e965163ed194ebef780c24
[ "Java" ]
4
Java
marcelovicarvalho/edenic
48a2ebb8f3c426b0e62ce5146651ce19707ea9e2
2a08f88cf1ea8bd660e7376907fe472aa52783ec
refs/heads/main
<file_sep>.. toctree:: :hidden: :maxdepth: 1 .. _view-scan-label: Viewing Scan Results ==================== As of version 0.9.0, scan results are stored in a database located (by default) at ``~/.local/recon-pipeline/databases``. Databases themselves are managed through the :ref:`database_command` command while viewing their contents is done via :ref:`view_command`. The view command allows one to inspect different pieces of scan information via the following sub-commands - endpoints (gobuster results) - nmap-scans - ports - searchsploit-results - targets - web-technologies (webanalyze results) Each of the sub-commands has a list of tab-completable options and values that can help drilling down to the data you care about. All of the subcommands offer a ``--paged`` option for dealing with large amounts of output. ``--paged`` will show you one page of output at a time (using ``less`` under the hood). .. raw:: html <script id="asciicast-320494" src="https://asciinema.org/a/320494.js" async></script> Chaining Results w/ Commands ############################ All of the results can be **piped out to other commands**. Let's say you want to feed some results from ``recon-pipeline`` into another tool that isn't part of the pipeline. Simply using a normal unix pipe ``|`` followed by the next command will get that done for you. Below is an example of piping targets into `gau <https://github.com/lc/gau>`_ .. code-block:: console [db-2] recon-pipeline> view targets --paged 3.tesla.cn 3.tesla.com api-internal.sn.tesla.services api-toolbox.tesla.com api.mp.tesla.services api.sn.tesla.services api.tesla.cn api.toolbox.tb.tesla.services ... [db-2] recon-pipeline> view targets | gau https://3.tesla.com/pt_PT/model3/design https://3.tesla.com/pt_PT/model3/design?redirect=no https://3.tesla.com/robots.txt https://3.tesla.com/sites/all/themes/custom/tesla_theme/assets/img/icons/favicon-160x160.png?2 https://3.tesla.com/sites/all/themes/custom/tesla_theme/assets/img/icons/favicon-16x16.png?2 https://3.tesla.com/sites/all/themes/custom/tesla_theme/assets/img/icons/favicon-196x196.png?2 https://3.tesla.com/sites/all/themes/custom/tesla_theme/assets/img/icons/favicon-32x32.png?2 https://3.tesla.com/sites/all/themes/custom/tesla_theme/assets/img/icons/favicon-96x96.png?2 https://3.tesla.com/sv_SE/model3/design ... view endpoints ############## An endpoint consists of a status code and the scanned URL. Endpoints are populated via gobuster. Show All Endpoints ------------------ .. code-block:: console [db-2] recon-pipeline> view endpoints --paged [200] http://westream.teslamotors.com/y [301] https://mobileapps.teslamotors.com/aspnet_client [403] https://192.168.127.12/analog.html [302] https://192.168.127.12/api [403] https://192.168.127.12/cgi-bin/ [200] https://192.168.127.12/client ... Filter by Host -------------- .. code-block:: console [db-2] recon-pipeline> view endpoints --host shop.uk.teslamotors.com [402] http://shop.uk.teslamotors.com/ [403] https://shop.uk.teslamotors.com:8443/ [301] http://shop.uk.teslamotors.com/assets [302] http://shop.uk.teslamotors.com/admin.cgi [200] http://shop.uk.teslamotors.com/.well-known/apple-developer-merchantid-domain-association [302] http://shop.uk.teslamotors.com/admin [403] http://shop.uk.teslamotors.com:8080/ [302] http://shop.uk.teslamotors.com/admin.php [302] http://shop.uk.teslamotors.com/admin.pl [200] http://shop.uk.teslamotors.com/crossdomain.xml [403] https://shop.uk.teslamotors.com/ [db-2] recon-pipeline> Filter by Host and Status Code ------------------------------ .. code-block:: console [db-2] recon-pipeline> view endpoints --host shop.uk.teslamotors.com --status-code 200 [200] http://shop.uk.teslamotors.com/crossdomain.xml [200] http://shop.uk.teslamotors.com/.well-known/apple-developer-merchantid-domain-association [db-2] recon-pipeline> Remove Status Code from Output ------------------------------ Using ``--plain`` will remove the status-code prefix, allowing for easy piping of results into other commands. .. code-block:: console [db-2] recon-pipeline> view endpoints --host shop.uk.teslamotors.com --plain http://shop.uk.teslamotors.com/admin.pl http://shop.uk.teslamotors.com/admin http://shop.uk.teslamotors.com/ http://shop.uk.teslamotors.com/admin.cgi http://shop.uk.teslamotors.com/.well-known/apple-developer-merchantid-domain-association http://shop.uk.teslamotors.com:8080/ http://shop.uk.teslamotors.com/crossdomain.xml https://shop.uk.teslamotors.com:8443/ https://shop.uk.teslamotors.com/ http://shop.uk.teslamotors.com/admin.php http://shop.uk.teslamotors.com/assets [db-2] recon-pipeline> Include Headers --------------- If you'd like to include any headers found during scanning, ``--headers`` will do that for you. .. code-block:: console [db-2] recon-pipeline> view endpoints --host shop.uk.teslamotors.com --headers [302] http://shop.uk.teslamotors.com/admin.php [302] http://shop.uk.teslamotors.com/admin.cgi [302] http://shop.uk.teslamotors.com/admin [200] http://shop.uk.teslamotors.com/crossdomain.xml [403] https://shop.uk.teslamotors.com/ Server: cloudflare Date: Mon, 06 Apr 2020 13:56:12 GMT Content-Type: text/html Content-Length: 553 Retry-Count: 0 Cf-Ray: 57fc02c788f7e03f-DFW [403] https://shop.uk.teslamotors.com:8443/ Content-Type: text/html Content-Length: 553 Retry-Count: 0 Cf-Ray: 57fc06e5fcbfd266-DFW Server: cloudflare Date: Mon, 06 Apr 2020 13:59:00 GMT [302] http://shop.uk.teslamotors.com/admin.pl [200] http://shop.uk.teslamotors.com/.well-known/apple-developer-merchantid-domain-association [403] http://shop.uk.teslamotors.com:8080/ Server: cloudflare Date: Mon, 06 Apr 2020 13:58:50 GMT Content-Type: text/html; charset=UTF-8 Set-Cookie: __cfduid=dfbf45a8565fda1325b8c1482961518511586181530; expires=Wed, 06-May-20 13:58:50 GMT; path=/; domain=.shop.uk.teslamotors.com; HttpOnly; SameSite=Lax Cache-Control: max-age=15 X-Frame-Options: SAMEORIGIN Alt-Svc: h3-27=":443"; ma=86400, h3-25=":443"; ma=86400, h3-24=":443"; ma=86400, h3-23=":443"; ma=86400 Expires: Mon, 06 Apr 2020 13:59:05 GMT Cf-Ray: 57fc06a53887d286-DFW Retry-Count: 0 [402] http://shop.uk.teslamotors.com/ Cf-Cache-Status: DYNAMIC X-Dc: gcp-us-central1,gcp-us-central1 Date: Mon, 06 Apr 2020 13:54:49 GMT Cf-Ray: 57fc00c39c0b581d-DFW X-Request-Id: 79146367-4c68-4e1b-9784-31f76d51b60b Set-Cookie: __cfduid=d94fad82fbdc0c110cb03cbcf58d097e21586181289; expires=Wed, 06-May-20 13:54:49 GMT; path=/; domain=.shop.uk.teslamotors.com; HttpOnly; SameSite=Lax _shopify_y=e3f19482-99e9-46cd-af8d-89fb8557fd28; path=/; expires=Thu, 07 Apr 2022 01:33:13 GMT X-Shopid: 4232821 Content-Language: en Alt-Svc: h3-27=":443"; ma=86400, h3-25=":443"; ma=86400, h3-24=":443"; ma=86400, h3-23=":443"; ma=86400 X-Content-Type-Options: nosniff X-Permitted-Cross-Domain-Policies: none X-Xss-Protection: 1; mode=block; report=/xss-report?source%5Baction%5D=index&source%5Bapp%5D=Shopify&source%5Bcontroller%5D=storefront_section%2Fshop&source%5Bsection%5D=storefront&source%5Buuid%5D=79146367-4c68-4e1b-9784-31f76d51b60b Server: cloudflare Content-Type: text/html; charset=utf-8 X-Sorting-Hat-Shopid: 4232821 X-Shardid: 78 Content-Security-Policy: frame-ancestors *; report-uri /csp-report?source%5Baction%5D=index&source%5Bapp%5D=Shopify&source%5Bcontroller%5D=storefront_section%2Fshop&source%5Bsection%5D=storefront&source%5Buuid%5D=79146367-4c68-4e1b-9784-31f76d51b60b Retry-Count: 0 X-Sorting-Hat-Podid: 78 X-Shopify-Stage: production X-Download-Options: noopen [301] http://shop.uk.teslamotors.com/assets [db-2] recon-pipeline> view nmap-scans ############### Nmap results can be filtered by host, NSE script type, scanned port, and product. Show All Results ---------------- .. code-block:: console [db-2] recon-pipeline> view nmap-scans --paged fdf8:f53e:61e4::18 - http =========================================== tcp port: 80 - open - syn-ack product: Amazon CloudFront httpd :: None nse script(s) output: http-server-header CloudFront http-title ERROR: The request could not be satisfied ... Filter by product ----------------- .. code-block:: console [db-2] recon-pipeline> view nmap-scans --product "Splunkd httpd" 172.16.31.10 - http ===================== tcp port: 443 - open - syn-ack product: Splunkd httpd :: None nse script(s) output: http-robots.txt 1 disallowed entry / http-server-header Splunkd http-title 404 Not Found ssl-cert Subject: commonName=*.teslamotors.com/organizationName=Tesla Motors, Inc./stateOrProvinceName=California/countryName=US Subject Alternative Name: DNS:*.teslamotors.com, DNS:teslamotors.com Not valid before: 2019-01-17T00:00:00 Not valid after: 2021-02-03T12:00:00 ssl-date TLS randomness does not represent time Filter by NSE Script -------------------- .. code-block:: console [db-2] recon-pipeline> view nmap-scans --nse-script ssl-cert --paged 192.168.127.12 - http-proxy ======================== tcp port: 443 - open - syn-ack product: Varnish http accelerator :: None nse script(s) output: ssl-cert Subject: commonName=*.tesla.com/organizationName=Tesla, Inc./stateOrProvinceName=California/countryName=US Subject Alternative Name: DNS:*.tesla.com, DNS:tesla.com Not valid before: 2020-02-07T00:00:00 Not valid after: 2022-04-08T12:00:00 ... Filter by NSE Script and Port Number ------------------------------------ .. code-block:: console [db-2] recon-pipeline> view nmap-scans --nse-script ssl-cert --port 8443 172.16.31.10 - https-alt ======================== tcp port: 8443 - open - syn-ack product: cloudflare :: None nse script(s) output: ssl-cert Subject: commonName=sni.cloudflaressl.com/organizationName=Cloudflare, Inc./stateOrProvinceName=CA/countryName=US Subject Alternative Name: DNS:*.tesla.services, DNS:tesla.services, DNS:sni.cloudflaressl.com Not valid before: 2020-02-13T00:00:00 Not valid after: 2020-10-09T12:00:00 [db-2] recon-pipeline> Filter by Host (ipv4/6 or domain name) -------------------------------------- .. code-block:: console [db-2] recon-pipeline> view nmap-scans --host fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b - http =========================================== tcp port: 80 - open - syn-ack product: Amazon CloudFront httpd :: None nse script(s) output: http-server-header CloudFront http-title ERROR: The request could not be satisfied [db-2] recon-pipeline> Include Command Used to Scan ---------------------------- The ``--commandline`` option will append the command used to scan the target to the results. .. code-block:: console [db-2] recon-pipeline> view nmap-scans --host fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b --commandline fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b - http =========================================== tcp port: 80 - open - syn-ack product: Amazon CloudFront httpd :: None nse script(s) output: http-server-header CloudFront http-title ERROR: The request could not be satisfied command used: nmap --open -sT -n -sC -T 4 -sV -Pn -p 80 -6 -oA /home/epi/PycharmProjects/recon-pipeline/tests/data/tesla-results/nmap-results/nmap.2fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b-tcp fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b [db-2] recon-pipeline> view ports ########## Port results are populated via masscan. Ports can be filtered by host and port number. Show All Results ---------------- .. code-block:: console [db-2] recon-pipeline> view ports --paged apmv3.go.tesla.services: 80 autodiscover.teslamotors.com: 80 csp.teslamotors.com: 443 image.emails.tesla.com: 443 marketing.teslamotors.com: 443 partnerleadsharing.tesla.com: 443 service.tesla.cn: 80 shop.uk.teslamotors.com: 8080 sip.tesla.cn: 5061 ... Filter by Host -------------- .. code-block:: console [db-2] recon-pipeline> view ports --host tesla.services tesla.services: 8443,8080 [db-2] recon-pipeline> Filter by Port Number --------------------- .. code-block:: console [db-2] recon-pipeline> view ports --port-number 8443 tesla.services: 8443,8080 192.168.127.12: 8443,8080 172.16.31.10: 8443,8080 fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:a2a: 8443,8080 fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:b2a: 8443,8080 [db-2] recon-pipeline> view searchsploit-results ######################### Searchsploit results can be filtered by host and type, the full path to any relevant exploit code can be shown as well. Show All Results ---------------- .. code-block:: console [db-2] recon-pipeline> view searchsploit-results --paged 192.168.3.11, 172.16.58.3, 192.168.3.11, telemetry-eng.vn.tesla.services ============================================================================= local | 40768.sh | Nginx (Debian Based Distros + Gentoo) - 'logrotate' Local Privilege | Escalation remote | 12804.txt| Nginx 0.6.36 - Directory Traversal local | 14830.py | Nginx 0.6.38 - Heap Corruption webapps | 24967.txt| Nginx 0.6.x - Arbitrary Code Execution NullByte Injection dos | 9901.txt | Nginx 0.7.0 < 0.7.61 / 0.6.0 < 0.6.38 / 0.5.0 < 0.5.37 / 0.4.0 < | 0.4.14 - Denial of Service (PoC) remote | 9829.txt | Nginx 0.7.61 - WebDAV Directory Traversal remote | 33490.txt| Nginx 0.7.64 - Terminal Escape Sequence in Logs Command Injection remote | 13822.txt| Nginx 0.7.65/0.8.39 (dev) - Source Disclosure / Download remote | 13818.txt| Nginx 0.8.36 - Source Disclosure / Denial of Service remote | 38846.txt| Nginx 1.1.17 - URI Processing SecURIty Bypass remote | 25775.rb | Nginx 1.3.9 < 1.4.0 - Chuncked Encoding Stack Buffer Overflow | (Metasploit) dos | 25499.py | Nginx 1.3.9 < 1.4.0 - Denial of Service (PoC) remote | 26737.pl | Nginx 1.3.9/1.4.0 (x86) - Brute Force remote | 32277.txt| Nginx 1.4.0 (Generic Linux x64) - Remote Overflow webapps | 47553.md | PHP-FPM + Nginx - Remote Code Execution ... Filter by Host -------------- .. code-block:: console [db-2] recon-pipeline> view searchsploit-results --paged --host telemetry-eng.vn.tesla.services 192.168.3.11, 172.16.58.3, 192.168.3.11, telemetry-eng.vn.tesla.services ============================================================================= local | 40768.sh | Nginx (Debian Based Distros + Gentoo) - 'logrotate' Local Privilege | Escalation remote | 12804.txt| Nginx 0.6.36 - Directory Traversal local | 14830.py | Nginx 0.6.38 - Heap Corruption webapps | 24967.txt| Nginx 0.6.x - Arbitrary Code Execution NullByte Injection dos | 9901.txt | Nginx 0.7.0 < 0.7.61 / 0.6.0 < 0.6.38 / 0.5.0 < 0.5.37 / 0.4.0 < | 0.4.14 - Denial of Service (PoC) remote | 9829.txt | Nginx 0.7.61 - WebDAV Directory Traversal remote | 33490.txt| Nginx 0.7.64 - Terminal Escape Sequence in Logs Command Injection remote | 13822.txt| Nginx 0.7.65/0.8.39 (dev) - Source Disclosure / Download remote | 13818.txt| Nginx 0.8.36 - Source Disclosure / Denial of Service remote | 38846.txt| Nginx 1.1.17 - URI Processing SecURIty Bypass remote | 25775.rb | Nginx 1.3.9 < 1.4.0 - Chuncked Encoding Stack Buffer Overflow | (Metasploit) dos | 25499.py | Nginx 1.3.9 < 1.4.0 - Denial of Service (PoC) remote | 26737.pl | Nginx 1.3.9/1.4.0 (x86) - Brute Force remote | 32277.txt| Nginx 1.4.0 (Generic Linux x64) - Remote Overflow webapps | 47553.md | PHP-FPM + Nginx - Remote Code Execution [db-2] recon-pipeline> Filter by Type -------------- .. code-block:: console [db-2] recon-pipeline> view searchsploit-results --paged --type webapps 192.168.3.11, 172.16.58.3, 192.168.3.11, telemetry-eng.vn.tesla.services ============================================================================= webapps | 24967.txt| Nginx 0.6.x - Arbitrary Code Execution NullByte Injection webapps | 47553.md | PHP-FPM + Nginx - Remote Code Execution ... Include Full Path to Exploit Code --------------------------------- .. code-block:: console 192.168.3.11, 172.16.58.3, 192.168.3.11, telemetry-eng.vn.tesla.services ============================================================================= webapps | Nginx 0.6.x - Arbitrary Code Execution NullByte Injection | /home/epi/.recon-tools/exploitdb/exploits/multiple/webapps/24967.txt webapps | PHP-FPM + Nginx - Remote Code Execution | /home/epi/.recon-tools/exploitdb/exploits/php/webapps/47553.md ... view targets ############ Target results can be filtered by type and whether or not they've been reported as vulnerable to subdomain takeover. Show All Results ---------------- .. code-block:: console [db-2] recon-pipeline> view targets --paged 3.tesla.com api-internal.sn.tesla.services api-toolbox.tesla.com api.mp.tesla.services api.sn.tesla.services api.tesla.cn ... Filter by Target Type --------------------- .. code-block:: console [db-2] recon-pipeline> view targets --type ipv6 --paged fdf8:f53e:61e4::18 fc00:e968:6179::de52:7100 fc00:e968:6179::de52:7100 fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b fc00:e968:6179::de52:7100cf ... Filter by Possibility of Subdomain Takeover ------------------------------------------- .. code-block:: console [db-2] recon-pipeline> view targets --paged --vuln-to-subdomain-takeover [vulnerable] api-internal.sn.tesla.services ... view web-technologies ##################### Web technology results are produced by webanalyze. Web technology results can be filtered by host, type, and product. Show All Results ---------------- .. code-block:: console [db-2] recon-pipeline> view web-technologies --paged Varnish (Caching) ================= - inventory-assets.tesla.com - www.tesla.com - errlog.tesla.com - static-assets.tesla.com - partnerleadsharing.tesla.com - 192.168.127.12 - onboarding-pre-delivery-prod.teslamotors.com - fc00:e968:6179::de52:7100cf - fc00:db20:35b:7399::5cf ... Filter by Technology Type ------------------------- .. code-block:: console [db-2] recon-pipeline> view web-technologies --type "Programming languages" PHP (Programming languages) =========================== - www.tesla.com - dummy.teslamotors.com - 192.168.3.11 - 172.16.31.10 - trt.tesla.com - trt.teslamotors.com - cn-origin.teslamotors.com - www.tesla.cn - events.tesla.cn - 192.168.127.12 - service.teslamotors.com Python (Programming languages) ============================== - api-toolbox.tesla.com - 172.16.17.32 - 192.168.127.12 - 172.16.31.10 - api.toolbox.tb.tesla.services - toolbox.teslamotors.com - 172.16.17.32 Ruby (Programming languages) ============================ - storagesim.teslamotors.com - 172.16.31.10 ... Filter by Product ----------------- .. code-block:: console [db-2] recon-pipeline> view web-technologies --product OpenResty-1.15.8.2 OpenResty-1.15.8.2 (Web servers) ================================ - links.tesla.com [db-2] recon-pipeline> Filter by Host -------------- .. code-block:: console [db-2] recon-pipeline> view web-technologies --host api-toolbox.tesla.com api-toolbox.tesla.com ===================== - gunicorn-19.4.5 (Web servers) - Python (Programming languages) [db-2] recon-pipeline> Manually interacting with the Database ====================================== If for whatever reason you'd like to query the database manually, from within the recon-pipeline shell, you can use the ``py`` command to drop into a python REPL with your current ReconShell instance available as ``self``. .. code-block:: console ./pipeline/recon-pipeline.py recon-pipeline> py Python 3.7.5 (default, Nov 20 2019, 09:21:52) [GCC 9.2.1 20191008] on linux Type "help", "copyright", "credits" or "license" for more information. End with `Ctrl-D` (Unix) / `Ctrl-Z` (Windows), `quit()`, `exit()`. Non-Python commands can be issued with: app("your command") >>> self <__main__.ReconShell object at 0x7f69f457f790> Once in the REPL, the currently connected database is available as ``self.db_mgr``. The database is an instance of :ref:`db_manager_label` and has a ``session`` attribute which can be used to issue manual SQLAlchemy style queries. .. code-block:: console >>> from pipeline.models.port_model import Port >>> self.db_mgr.session.query(Port).filter_by(port_number=443) <sqlalchemy.orm.query.Query object at 0x7f8cef804250> >>> <file_sep>Getting Started =============== .. toctree:: :maxdepth: 1 :hidden: installation scope running_scans viewing_results scheduler visualization .. include:: summary.rst <file_sep>There are an `accompanying set of blog posts <https://epi052.gitlab.io/notes-to-self/blog/2019-09-01-how-to-build-an-automated-recon-pipeline-with-python-and-luigi/>`_ detailing the development process and underpinnings of the pipeline. Feel free to check them out if you're so inclined, but they're in no way required reading to use the tool. * :ref:`install-ref-label` - How to install ``recon-pipeline`` and associated dependencies * :ref:`scope-ref-label` - How to define the scope of your scans (list of targets and a blacklist) * :ref:`scan-ref-label` - Example scan of **tesla.com** using ``recon-pipeline`` * :ref:`view-scan-label` - How to view scan results * :ref:`scheduler-ref-label` - The Luigi schedulers and which to choose * :ref:`visualization-ref-label` - How to check on active tasks once they're running <file_sep>[[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] flake8 = "==3.7.9" pre-commit = "==2.2.0" coverage = "==5.0.4" sphinx = "==3.0.0" sphinx-argparse = "==0.2.5" sphinx-rtd-theme = "==0.4.3" sphinxcontrib-napoleon = "==0.7" pytest = "==5.4.1" black = "==19.10b0" [packages] cmd2 = "==1.0.1" luigi = "==2.8.12" sqlalchemy = "==1.3.15" python-libnmap = "==0.7.0" pyyaml = "==5.4.0" [requires] python_version = "3" <file_sep>import textwrap from sqlalchemy.orm import relationship from sqlalchemy import Column, Integer, ForeignKey, String, Boolean from .base_model import Base from .port_model import Port from .ip_address_model import IPAddress from .nse_model import nse_result_association_table class NmapResult(Base): """ Database model that describes the TARGET.nmap scan results. Represents nmap data. Relationships: ``target``: many to one -> :class:`pipeline.models.target_model.Target` ``ip_address``: one to one -> :class:`pipeline.models.ip_address_model.IPAddress` ``port``: one to one -> :class:`pipeline.models.port_model.Port` ``nse_results``: one to many -> :class:`pipeline.models.nse_model.NSEResult` """ def __str__(self): return self.pretty() def pretty(self, commandline=False, nse_results=None): pad = " " ip_address = self.ip_address.ipv4_address or self.ip_address.ipv6_address msg = f"{ip_address} - {self.service}\n" msg += f"{'=' * (len(ip_address) + len(self.service) + 3)}\n\n" msg += f"{self.port.protocol} port: {self.port.port_number} - {'open' if self.open else 'closed'} - {self.reason}\n" msg += f"product: {self.product} :: {self.product_version}\n" msg += "nse script(s) output:\n" if nse_results is None: # add all nse scripts for nse_result in self.nse_results: msg += f"{pad}{nse_result.script_id}\n" msg += textwrap.indent(nse_result.script_output, pad * 2) msg += "\n" else: # filter used, only return those specified for nse_result in nse_results: if nse_result in self.nse_results: msg += f"{pad}{nse_result.script_id}\n" msg += textwrap.indent(nse_result.script_output, pad * 2) msg += "\n" if commandline: msg += "command used:\n" msg += f"{pad}{self.commandline}\n" return msg __tablename__ = "nmap_result" id = Column(Integer, primary_key=True) open = Column(Boolean) reason = Column(String) service = Column(String) product = Column(String) commandline = Column(String) product_version = Column(String) port = relationship(Port) port_id = Column(Integer, ForeignKey("port.id")) ip_address = relationship(IPAddress) ip_address_id = Column(Integer, ForeignKey("ip_address.id")) target_id = Column(Integer, ForeignKey("target.id")) target = relationship("Target", back_populates="nmap_results") nse_results = relationship("NSEResult", secondary=nse_result_association_table, back_populates="nmap_results") <file_sep>.. _scope-ref-label: Defining Target Scope ===================== **New in v0.9.0**: In the event you're scanning a single ip address or host, simply use ``--target``. It accepts a single target and works in conjunction with ``--exempt-list`` if specified. .. code-block:: console [db-1] recon-pipeline> scan HTBScan --target 10.10.10.183 --top-ports 1000 ... In order to scan more than one host at a time, the pipeline needs a file that describes the target's scope to be provided as an argument to the `--target-file` option. The target file can consist of domains, ip addresses, and ip ranges, one per line. In order to scan more than one host at a time, the pipeline expects a file that describes the target's scope to be provided as an argument to the ``--target-file`` option. The target file can consist of domains, ip addresses, and ip ranges, one per line. Domains, ip addresses and ip ranges can be mixed/matched within the scope file. .. code-block:: console tesla.com tesla.cn teslamotors.com ... Some bug bounty scopes have expressly verboten subdomains and/or top-level domains, for that there is the ``--exempt-list`` option. The exempt list follows the same rules as the target file. .. code-block:: console shop.eu.teslamotors.com energysupport.tesla.com feedback.tesla.com ... <file_sep>from .aquatone import AquatoneScan from .gobuster import GobusterScan from .targets import GatherWebTargets from .webanalyze import WebanalyzeScan from .waybackurls import WaybackurlsScan from .subdomain_takeover import SubjackScan, TKOSubsScan <file_sep>import shutil import tempfile from pathlib import Path from unittest.mock import MagicMock import pytest import pipeline.models.db_manager from pipeline.models.port_model import Port from pipeline.models.target_model import Target from pipeline.models.ip_address_model import IPAddress class TestDBManager: def setup_method(self, tmp_path): self.tmp_path = Path(tempfile.mkdtemp()) self.db_mgr = pipeline.models.db_manager.DBManager(db_location=self.tmp_path / "testdb") def teardown_method(self): shutil.rmtree(self.tmp_path) def create_temp_target(self): tgt = Target( hostname="localhost", ip_addresses=[IPAddress(ipv4_address="127.0.0.1"), IPAddress(ipv6_address="::1")], open_ports=[ Port(port_number=443, protocol="tcp"), Port(port_number=80, protocol="tcp"), Port(port_number=53, protocol="udp"), ], ) return tgt def test_invalid_ip_to_add_ipv4_or_v6_address_to_target(self): retval = self.db_mgr.add_ipv4_or_v6_address_to_target("dummytarget", "not an ip address") assert retval is None def test_get_all_web_targets(self): subdomain = Target(hostname="google.com") ipv4 = Target(ip_addresses=[IPAddress(ipv4_address="172.16.31.10")]) ipv6 = Target(ip_addresses=[IPAddress(ipv6_address="fc00:e968:6179::de52:7100:3c33")]) self.db_mgr.get_and_filter = MagicMock(return_value=[subdomain, ipv4, ipv6]) expected = ["172.16.31.10", "fc00:e968:6179::de52:7100:3c33", "google.com"] actual = self.db_mgr.get_all_web_targets() assert set(actual) == set(expected) @pytest.mark.parametrize("test_input, expected", [("tcp", ["80", "443"]), ("udp", ["53"])]) def test_get_ports_by_ip_or_host_and_protocol_tcp(self, test_input, expected): tgt = self.create_temp_target() self.db_mgr.get_or_create_target_by_ip_or_hostname = MagicMock(return_value=tgt) expectedset = set(expected) actual = self.db_mgr.get_ports_by_ip_or_host_and_protocol("dummy", test_input) assert set(actual) == expectedset <file_sep>from sqlalchemy.orm import relationship from sqlalchemy import Column, Integer, String, Boolean from .base_model import Base from .port_model import port_association_table from .technology_model import technology_association_table class Target(Base): """ Database model that describes a target; This is the model that functions as the "top" model. Relationships: ``ip_addresses``: one to many -> :class:`pipeline.models.ip_address_model.IPAddress` ``open_ports``: many to many -> :class:`pipeline.models.port_model.Port` ``nmap_results``: one to many -> :class:`pipeline.models.nmap_model.NmapResult` ``searchsploit_results``: one to many -> :class:`pipeline.models.searchsploit_model.SearchsploitResult` ``endpoints``: one to many -> :class:`pipeline.models.endpoint_model.Endpoint` ``technologies``: many to many -> :class:`pipeline.models.technology_model.Technology` ``screenshots``: one to many -> :class:`pipeline.models.screenshot_model.Screenshot` """ __tablename__ = "target" id = Column(Integer, primary_key=True) hostname = Column(String, unique=True) is_web = Column(Boolean, default=False) vuln_to_sub_takeover = Column(Boolean, default=False) endpoints = relationship("Endpoint", back_populates="target") ip_addresses = relationship("IPAddress", back_populates="target") screenshots = relationship("Screenshot", back_populates="target") nmap_results = relationship("NmapResult", back_populates="target") searchsploit_results = relationship("SearchsploitResult", back_populates="target") open_ports = relationship("Port", secondary=port_association_table, back_populates="targets") technologies = relationship("Technology", secondary=technology_association_table, back_populates="targets") <file_sep>from sqlalchemy.orm import relationship, relation from sqlalchemy import Column, Integer, ForeignKey, LargeBinary, Table, String from .base_model import Base screenshot_association_table = Table( "screenshot_association", Base.metadata, Column("screenshot_id", Integer, ForeignKey("screenshot.id")), Column("similar_page_id", Integer, ForeignKey("screenshot.id")), ) class Screenshot(Base): """ Database model that describes a screenshot of a given webpage hosted on a ``Target``. Represents aquatone data. Relationships: ``port``: one to one -> :class:`pipeline.models.port_model.Port` ``target``: many to one -> :class:`pipeline.models.target_model.Target` ``endpoint``: one to one -> :class:`pipeline.models.endpoint_model.Endpoint` ``similar_pages``: black magic -> :class:`pipeline.models.screenshot_model.Screenshot` """ __tablename__ = "screenshot" id = Column(Integer, primary_key=True) image = Column(LargeBinary) url = Column(String, unique=True) port = relationship("Port") port_id = Column(Integer, ForeignKey("port.id")) target_id = Column(Integer, ForeignKey("target.id")) target = relationship("Target", back_populates="screenshots") endpoint = relationship("Endpoint") endpoint_id = Column(Integer, ForeignKey("endpoint.id")) similar_pages = relation( "Screenshot", secondary=screenshot_association_table, primaryjoin=screenshot_association_table.c.screenshot_id == id, secondaryjoin=screenshot_association_table.c.similar_page_id == id, backref="similar_to", ) <file_sep>.. _install-ref-label: Installation Instructions ========================= There are two primary phases for installation: * prior to the python dependencies being installed * everything else Manual Steps ############ First, the steps to get python dependencies installed in a virtual environment are as follows (and shown below) Kali ---- .. code-block:: console sudo apt update sudo apt install pipenv Ubuntu 18.04/20.04 ------------------ .. code-block:: console sudo apt update sudo apt install python3-pip pip install --user pipenv echo "PATH=${PATH}:~/.local/bin" >> ~/.bashrc bash Both OSs After ``pipenv`` Install --------------------------------- .. code-block:: console git clone https://github.com/epi052/recon-pipeline.git cd recon-pipeline pipenv install pipenv shell .. raw:: html <script id="asciicast-318395" src="https://asciinema.org/a/318395.js" async></script> Everything Else ############### After installing the python dependencies, the recon-pipeline shell provides its own :ref:`tools_command` command (seen below). A simple ``tools install all`` will handle all installation steps. Installation has **only** been tested on **Kali 2019.4 and Ubuntu 18.04/20.04**. **Ubuntu Note (and newer kali versions)**: You may consider running ``sudo -v`` prior to running ``./recon-pipeline.py``. ``sudo -v`` will refresh your creds, and the underlying subprocess calls during installation won't prompt you for your password. It'll work either way though. Individual tools may be installed by running ``tools install TOOLNAME`` where ``TOOLNAME`` is one of the known tools that make up the pipeline. The installer does not maintain state. In order to determine whether a tool is installed or not, it checks the `path` variable defined in the tool's .yaml file. The installer in no way attempts to be a package manager. It knows how to execute the steps necessary to install and remove its tools. Beyond that, it's like <NAME>, **it knows nothing**. Current tool status can be viewed using ``tools list``. Tools can also be uninstalled using the ``tools uninstall all`` command. It is also possible to individually uninstall them in the same manner as shown above. .. raw:: html <script id="asciicast-343745" src="https://asciinema.org/a/343745.js" async></script> Alternative Distros ################### In v0.8.1, an effort was made to remove OS specific installation steps from the installer. However, if you're using an untested distribution (i.e. not Kali/Ubuntu 18.04/20.04), meeting the criteria below **should** be sufficient for the auto installer to function: - systemd-based system (``luigid`` is installed as a systemd service) - python3.6+ installed With the above requirements met, following the installation steps above starting with ``pipenv install`` should be sufficient. The alternative would be to manually install each tool. Docker ###### If you have Docker installed, you can run the recon-pipeline in a container with the following commands: .. code-block:: console git clone https://github.com/epi052/recon-pipeline.git cd recon-pipeline docker build -t recon-pipeline . docker run -d \ -v ~/docker/recon-pipeline:/root/.local/recon-pipeline \ -p 8082:8082 \ --name recon-pipeline \ recon-pipeline It is important to note that you should not lose any data during an update because all important information is saved to the ``~/docker/recon-pipeline`` location as specified by the ``-v`` option in the ``docker run`` command. If this portion of the command was not executed, data will not persist across container installations. At this point the container should be running and you scan enter the shell with the following command: .. code-block:: console docker exec -it recon-pipeline pipeline Starting & Stopping ------------------- In the event that you need to start or stop the container, you can do so with the following commands after having run the installation commands above once: .. code-block:: console docker start recon-pipeline docker stop recon-pipeline This is useful knowledge because Docker containers do not normally start on their own and executing the ``docker run`` command above again will result in an error if it is already installed. Update ------ To update, you can run the following commands from inside the ``recon-pipeline`` folder cloned in the installation: .. code-block:: console git pull docker stop recon-pipeline docker rm recon-pipeline When complete, execute the inital installation commands again starting with ``docker build``. <file_sep>import os import shutil import tempfile from pathlib import Path from unittest.mock import patch, MagicMock from pipeline.recon.web import WebanalyzeScan, GatherWebTargets from pipeline.tools import tools webanalyze_results = Path(__file__).parent.parent / "data" / "recon-results" / "webanalyze-results" class TestWebanalyzeScan: def setup_method(self): self.tmp_path = Path(tempfile.mkdtemp()) self.scan = WebanalyzeScan( target_file=__file__, results_dir=str(self.tmp_path), db_location=str(self.tmp_path / "testing.sqlite") ) self.scan.exception = False def teardown_method(self): shutil.rmtree(self.tmp_path) def test_scan_requires(self): with patch("pipeline.recon.web.GatherWebTargets"): with patch("pipeline.recon.web.webanalyze.meets_requirements"): retval = self.scan.requires() assert isinstance(retval, GatherWebTargets) def test_scan_creates_results_dir(self): assert self.scan.results_subfolder == self.tmp_path / "webanalyze-results" def test_scan_creates_database(self): assert self.scan.db_mgr.location.exists() assert self.tmp_path / "testing.sqlite" == self.scan.db_mgr.location def test_scan_creates_results(self): self.scan.results_subfolder = webanalyze_results self.scan.parse_results() assert self.scan.output().exists() def test_scan_run(self): with patch("concurrent.futures.ThreadPoolExecutor.map") as mocked_map, patch( "subprocess.run" ) as mocked_run, patch("pathlib.Path.cwd", return_value="/"): self.scan.parse_results = MagicMock() self.scan.db_mgr.get_all_web_targets = MagicMock() self.scan.db_mgr.get_all_web_targets.return_value = [ "172.16.17.32", "2606:fc00:e968:6179::de52:7100:3c33", "google.com", ] self.scan.run() assert mocked_map.called assert mocked_run.called assert self.scan.parse_results.called def test_scan_run_with_wrong_threads(self, caplog): self.scan.threads = "a" retval = self.scan.run() assert retval is None assert "The value supplied to --threads must be a non-negative integer" in caplog.text def test_wrapped_subprocess(self): with patch("subprocess.run") as mocked_run: self.scan.results_subfolder.mkdir() os.chdir(self.scan.results_subfolder) assert len([x for x in self.scan.results_subfolder.iterdir()]) == 0 cmd = [tools.get("webanalyze").get("path"), "-host", "https://google.com", "-output", "csv"] self.scan._wrapped_subprocess(cmd) assert len([x for x in self.scan.results_subfolder.iterdir()]) == 1 assert next(self.scan.results_subfolder.iterdir()).name == "webanalyze-https_google.com.csv" assert mocked_run.called <file_sep>[tool.black] line-length = 120 include = '\.pyi?$' exclude = '.*config.*py$|\.git'<file_sep>import shutil import tempfile from pathlib import Path from unittest.mock import patch, MagicMock import luigi import pytest from luigi.contrib.sqla import SQLAlchemyTarget from pipeline.recon import ThreadedNmapScan, SearchsploitScan, ParseMasscanOutput from pipeline.tools import tools nmap_results = Path(__file__).parent.parent / "data" / "recon-results" / "nmap-results" class TestThreadedNmapScan: def setup_method(self): with patch("pipeline.recon.nmap.which"): self.tmp_path = Path(tempfile.mkdtemp()) shutil.which = MagicMock() shutil.which.return_value = True self.scan = ThreadedNmapScan( target_file=__file__, results_dir=str(self.tmp_path), db_location=str(self.tmp_path / "testing.sqlite") ) self.scan.exception = False def teardown_method(self): shutil.rmtree(self.tmp_path) def test_scan_requires(self): with patch("pipeline.recon.ParseMasscanOutput"): with patch("pipeline.recon.nmap.which"): retval = self.scan.requires() assert isinstance(retval, ParseMasscanOutput) def test_scan_run(self): with patch("concurrent.futures.ThreadPoolExecutor.map") as mocked_run: self.scan.parse_nmap_output = MagicMock() self.scan.db_mgr.get_all_targets = MagicMock() self.scan.db_mgr.get_all_targets.return_value = ["172.16.31.10", "fc00:e968:6179::de52:7100:3c33"] self.scan.db_mgr.get_ports_by_ip_or_host_and_protocol = MagicMock() self.scan.db_mgr.get_ports_by_ip_or_host_and_protocol.return_value = ["135", "80"] self.scan.run() assert mocked_run.called assert self.scan.parse_nmap_output.called def test_scan_run_with_wrong_threads(self, caplog): with patch("concurrent.futures.ThreadPoolExecutor.map"): self.scan.threads = "a" retval = self.scan.run() assert retval is None assert "The value supplied to --threads must be a non-negative integer" in caplog.text def test_parse_nmap_output(self): (self.tmp_path / "nmap-results").mkdir(parents=True, exist_ok=True) shutil.copy(nmap_results / "nmap.13.56.144.135-tcp.xml", self.scan.results_subfolder) shutil.copy(nmap_results / "nmap.fc00:e968:6179::de52:7100:3c33-tcp.xml", self.scan.results_subfolder) assert len([x for x in self.scan.results_subfolder.iterdir()]) == 2 assert "172.16.58.335" not in self.scan.db_mgr.get_all_targets() assert "fc00:e968:6179::de52:7100:3c33" not in self.scan.db_mgr.get_all_targets() self.scan.parse_nmap_output() assert "13.56.144.135" in self.scan.db_mgr.get_all_targets() assert "fc00:e968:6179::de52:7100:3c33" in self.scan.db_mgr.get_all_targets() def test_scan_creates_results_dir(self): assert self.scan.results_subfolder == self.tmp_path / "nmap-results" def test_scan_creates_database(self): assert self.scan.db_mgr.location.exists() assert self.tmp_path / "testing.sqlite" == self.scan.db_mgr.location def test_scan_output_location(self): assert self.scan.output().get("localtarget").path == str(self.tmp_path / "nmap-results") class TestSearchsploitScan: def setup_method(self): self.tmp_path = Path(tempfile.mkdtemp()) self.scan = SearchsploitScan( target_file=__file__, results_dir=str(self.tmp_path), db_location=str(self.tmp_path / "testing.sqlite") ) self.scan.exception = False def teardown_method(self): shutil.rmtree(self.tmp_path) def test_scan_requires(self): with patch("pipeline.recon.ThreadedNmapScan"): with patch("pipeline.recon.nmap.meets_requirements"): with patch("pipeline.recon.nmap.which"): retval = self.scan.requires() assert isinstance(retval, ThreadedNmapScan) def test_scan_output(self): retval = self.scan.output() assert isinstance(retval, SQLAlchemyTarget) def test_scan_creates_database(self): assert self.scan.db_mgr.location.exists() assert self.tmp_path / "testing.sqlite" == self.scan.db_mgr.location def test_scan_creates_results(self): lcl_nmap = self.tmp_path / "nmap-results" lcl_nmap.mkdir(parents=True, exist_ok=True) shutil.copy(nmap_results / "nmap.13.56.144.135-tcp.xml", lcl_nmap) shutil.copy(nmap_results / "nmap.2606:fdf8:f53e:61e4::18:3c33-tcp.xml", lcl_nmap) self.scan.input = lambda: {"localtarget": luigi.LocalTarget(lcl_nmap)} assert len(self.scan.db_mgr.get_all_searchsploit_results()) == 0 if not Path(tools.get("searchsploit").get("path")).exists(): pytest.skip("exploit-db's searchsploit tool not installed") self.scan.run() assert len(self.scan.db_mgr.get_all_searchsploit_results()) > 0 <file_sep>.. toctree:: :maxdepth: 1 :hidden: .. _models-ref-label: Database Models =============== .. image:: ../img/database-design.png Target Model ############ .. autoclass:: pipeline.models.target_model.Target Endpoint Model ############## .. autoclass:: pipeline.models.endpoint_model.Endpoint Header Model ############ .. autoclass:: pipeline.models.header_model.Header IP Address Model ################ .. autoclass:: pipeline.models.ip_address_model.IPAddress Nmap Model ########## .. autoclass:: pipeline.models.nmap_model.NmapResult Nmap Scripting Engine Model ########################### .. autoclass:: pipeline.models.nse_model.NSEResult Port Model ########## .. autoclass:: pipeline.models.port_model.Port Screenshot Model ################ .. autoclass:: pipeline.models.screenshot_model.Screenshot Searchsploit Model ################## .. autoclass:: pipeline.models.searchsploit_model.SearchsploitResult Technology Model ################ .. autoclass:: pipeline.models.technology_model.Technology <file_sep>import sqlite3 from pathlib import Path from urllib.parse import urlparse from cmd2 import ansi from sqlalchemy.orm import sessionmaker from sqlalchemy import exc, or_, create_engine from sqlalchemy.sql.expression import ClauseElement from .base_model import Base from .port_model import Port from .nse_model import NSEResult from .target_model import Target from .nmap_model import NmapResult from .endpoint_model import Endpoint from .ip_address_model import IPAddress from .technology_model import Technology from .searchsploit_model import SearchsploitResult from ..recon.helpers import get_ip_address_version, is_ip_address class DBManager: """ Class that encapsulates database transactions and queries """ def __init__(self, db_location): self.location = Path(db_location).expanduser().resolve() self.connection_string = f"sqlite:///{self.location}" engine = create_engine(self.connection_string) Base.metadata.create_all(engine) # noqa: F405 session_factory = sessionmaker(bind=engine) self.session = session_factory() def get_or_create(self, model, **kwargs): """ Simple helper to either get an existing record if it exists otherwise create and return a new instance """ instance = self.session.query(model).filter_by(**kwargs).first() if instance: return instance else: params = dict((k, v) for k, v in kwargs.items() if not isinstance(v, ClauseElement)) instance = model(**params) return instance def add(self, item): """ Simple helper to add a record to the database """ try: self.session.add(item) self.session.commit() except (sqlite3.IntegrityError, exc.IntegrityError): print(ansi.style("[-] unique key constraint handled, moving on...", fg="bright_white")) self.session.rollback() def get_or_create_target_by_ip_or_hostname(self, ip_or_host): """ Simple helper to query a Target record by either hostname or ip address, whichever works """ # get existing instance instance = ( self.session.query(Target) .filter( or_( Target.ip_addresses.any( or_(IPAddress.ipv4_address.in_([ip_or_host]), IPAddress.ipv6_address.in_([ip_or_host])) ), Target.hostname == ip_or_host, ) ) .first() ) if instance: return instance else: # create new entry tgt = self.get_or_create(Target) if get_ip_address_version(ip_or_host) == "4": tgt.ip_addresses.append(IPAddress(ipv4_address=ip_or_host)) elif get_ip_address_version(ip_or_host) == "6": tgt.ip_addresses.append(IPAddress(ipv6_address=ip_or_host)) else: # we've already determined it's not an IP, only other possibility is a hostname tgt.hostname = ip_or_host return tgt def get_all_hostnames(self) -> list: """ Simple helper to return all hostnames from Target records """ return [x[0] for x in self.session.query(Target.hostname).filter(Target.hostname != None)] # noqa: E711 def get_all_ipv4_addresses(self) -> list: """ Simple helper to return all ipv4 addresses from Target records """ query = self.session.query(IPAddress.ipv4_address).filter(IPAddress.ipv4_address != None) # noqa: E711 return [x[0] for x in query] def get_all_ipv6_addresses(self) -> list: """ Simple helper to return all ipv6 addresses from Target records """ query = self.session.query(IPAddress.ipv6_address).filter(IPAddress.ipv6_address != None) # noqa: E711 return [x[0] for x in query] def close(self): """ Simple helper to close the database session """ self.session.close() def get_all_targets(self): """ Simple helper to return all ipv4/6 and hostnames produced by running amass """ return self.get_all_hostnames() + self.get_all_ipv4_addresses() + self.get_all_ipv6_addresses() def get_all_endpoints(self): """ Simple helper that returns all Endpoints from the database """ return self.session.query(Endpoint).all() def get_all_port_numbers(self): """ Simple helper that returns all Port.port_numbers from the database """ return set(str(x[0]) for x in self.session.query(Port.port_number).all()) def get_endpoint_by_status_code(self, code): """ Simple helper that returns all Endpoints filtered by status code """ return self.session.query(Endpoint).filter(Endpoint.status_code == code).all() def get_endpoints_by_ip_or_hostname(self, ip_or_host): """ Simple helper that returns all Endpoints filtered by ip or hostname """ endpoints = list() tmp_endpoints = self.session.query(Endpoint).filter(Endpoint.url.contains(ip_or_host)).all() for ep in tmp_endpoints: parsed_url = urlparse(ep.url) if parsed_url.hostname == ip_or_host: endpoints.append(ep) return endpoints def get_nmap_scans_by_ip_or_hostname(self, ip_or_host): """ Simple helper that returns all Endpoints filtered by ip or hostname """ scans = list() for result in self.session.query(NmapResult).filter(NmapResult.commandline.contains(ip_or_host)).all(): if result.commandline.split()[-1] == ip_or_host: scans.append(result) return scans def get_status_codes(self): """ Simple helper that returns all status codes found during scanning """ return set(str(x[0]) for x in self.session.query(Endpoint.status_code).all() if x[0] is not None) def get_and_filter(self, model, defaults=None, **kwargs): """ Simple helper to either get an existing record if it exists otherwise create and return a new instance """ return self.session.query(model).filter_by(**kwargs).all() def get_all_nse_script_types(self): """ Simple helper that returns all NSE Script types from the database """ return set(str(x[0]) for x in self.session.query(NSEResult.script_id).all()) def get_all_nmap_reported_products(self): """ Simple helper that returns all products reported by nmap """ return set(str(x[0]) for x in self.session.query(NmapResult.product).all()) def get_all_exploit_types(self): """ Simple helper that returns all exploit types reported by searchsploit """ return set(str(x[0]) for x in self.session.query(SearchsploitResult.type).all()) def add_ipv4_or_v6_address_to_target(self, tgt, ipaddr): """ Simple helper that adds an appropriate IPAddress to the given target """ if not is_ip_address(ipaddr): return if get_ip_address_version(ipaddr) == "4": ip_address = self.get_or_create(IPAddress, ipv4_address=ipaddr) else: ip_address = self.get_or_create(IPAddress, ipv6_address=ipaddr) tgt.ip_addresses.append(ip_address) return tgt def get_all_web_targets(self): """ Simple helper that returns all Targets tagged as having an open web port """ # return set(str(x[0]) for x in self.session.query(Target).all()) web_targets = list() targets = self.get_and_filter(Target, is_web=True) for target in targets: if target.hostname: web_targets.append(target.hostname) for ipaddr in target.ip_addresses: if ipaddr.ipv4_address: web_targets.append(ipaddr.ipv4_address) if ipaddr.ipv6_address: web_targets.append(ipaddr.ipv6_address) return web_targets def get_ports_by_ip_or_host_and_protocol(self, ip_or_host, protocol): """ Simple helper that returns all ports based on the given protocol and host """ tgt = self.get_or_create_target_by_ip_or_hostname(ip_or_host) ports = list() for port in tgt.open_ports: if port.protocol == protocol: ports.append(str(port.port_number)) return ports def get_all_searchsploit_results(self): return self.get_and_filter(SearchsploitResult) def get_all_web_technology_types(self): return set(str(x[0]) for x in self.session.query(Technology.type).all()) def get_all_web_technology_products(self): return set(str(x[0]) for x in self.session.query(Technology.text).all()) <file_sep># Contributor's guide <!-- this guide is a modified version of the guide used by the awesome guys that wrote cmd2 --> First of all, thank you for contributing! Please follow these steps to contribute: 1. Find an issue that needs assistance by searching for the [Help Wanted](https://github.com/epi052/recon-pipeline/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) tag 2. Let us know you're working on it by posting a comment on the issue 3. Follow the [Contribution guidelines](#contribution-guidelines) to start working on the issue Remember to feel free to ask for help by leaving a comment within the Issue. Working on your first pull request? You can learn how from this *free* series [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github). ###### If you've found a bug that is not on the board, [follow these steps](README.md#found-a-bug). --- ## Contribution guidelines - [Prerequisites](#prerequisites) - [Forking the project](#forking-the-project) - [Creating a branch](#creating-a-branch) - [Setting up for recon-pipeline development](#setting-up-for-recon-pipeline-development) - [Making changes](#making-changes) - [Static code analysis](#static-code-analysis) - [Running the test suite](#running-the-test-suite) - [Squashing your commits](#squashing-your-commits) - [Creating a pull request](#creating-a-pull-request) - [How we review and merge pull requests](#how-we-review-and-merge-pull-requests) - [Next steps](#next-steps) - [Other resources](#other-resources) - [Advice](#advice) ### Forking the project #### Setting up your system 1. Install your favorite `git` client 2. Create a parent projects directory on your system. For this guide, it will be assumed that it is `~/projects`. #### Forking recon-pipeline 1. Go to the top-level recon-pipeline repository: <https://github.com/epi052/recon-pipeline> 2. Click the "Fork" button in the upper right hand corner of the interface ([more details here](https://help.github.com/articles/fork-a-repo/)) 3. After the repository has been forked, you will be taken to your copy of the recon-pipeline repo at `your_username/recon-pipeline` #### Cloning your fork 1. Open a terminal / command line / Bash shell in your projects directory (_e.g.: `~/projects/`_) 2. Clone your fork of recon-pipeline, making sure to replace `your_username` with your GitHub username. This will download the entire recon-pipeline repo to your projects directory. ```sh $ git clone https://github.com/your_username/recon-pipeline.git ``` #### Set up your upstream 1. Change directory to the new recon-pipeline directory (`cd recon-pipeline`) 2. Add a remote to the official recon-pipeline repo: ```sh $ git remote add upstream https://github.com/epi052/recon-pipeline.git ``` Now you have a local copy of the recon-pipeline repo! #### Maintaining your fork Now that you have a copy of your fork, there is work you will need to do to keep it current. ##### **Rebasing from upstream** Do this prior to every time you create a branch for a PR: 1. Make sure you are on the `master` branch > ```sh > $ git status > On branch master > Your branch is up-to-date with 'origin/master'. > ``` > If your aren't on `master`, resolve outstanding files and commits and checkout the `master` branch > ```sh > $ git checkout master > ``` 2. Do a pull with rebase against `upstream` > ```sh > $ git pull --rebase upstream master > ``` > This will pull down all of the changes to the official master branch, without making an additional commit in your local repo. 3. (_Optional_) Force push your updated master branch to your GitHub fork > ```sh > $ git push origin master --force > ``` > This will overwrite the master branch of your fork. ### Creating a branch Before you start working, you will need to create a separate branch specific to the issue or feature you're working on. You will push your work to this branch. #### Naming your branch Name the branch something like `23-xxx` where `xxx` is a short description of the changes or feature you are attempting to add and 23 corresponds to the Issue you're working on. #### Adding your branch To create a branch on your local machine (and switch to this branch): ```sh $ git checkout -b [name_of_your_new_branch] ``` and to push to GitHub: ```sh $ git push origin [name_of_your_new_branch] ``` ##### If you need more help with branching, take a look at _[this](https://github.com/Kunena/Kunena-Forum/wiki/Create-a-new-branch-with-git-and-manage-branches)_. ### Setting up for recon-pipeline development For doing recon-pipeline development, it is recommended you create a virtual environment and install both the project dependencies as well as the development dependencies. #### Create a new environment for recon-pipeline using Pipenv `recon-pipeline` has support for using [Pipenv](https://docs.pipenv.org/en/latest/) for development. `Pipenv` essentially combines the features of `pip` and `virtualenv` into a single tool. `recon-pipeline` contains a Pipfile which makes it extremely easy to setup a `recon-pipeline` development environment using `pipenv`. To create a virtual environment and install everything needed for `recon-pipeline` development using `pipenv`, do the following from a GitHub checkout: ```sh pipenv install --dev ``` To create a new virtualenv, using a specific version of Python you have installed (and on your PATH), use the --python VERSION flag, like so: ```sh pipenv install --dev --python 3.7 ``` ### Making changes It's your time to shine! #### How to find code in the recon-pipeline codebase to fix/edit The recon-pipeline project directory structure is pretty simple and straightforward. All actual code for recon-pipeline is located underneath the `pipeline` directory. The code to generate the documentation is in the `docs` directory. Unit tests are in the `tests` directory. There are various other files in the root directory, but these are primarily related to continuous integration and release deployment. #### Changes to the documentation files If you made changes to any file in the `/docs` directory, you need to build the Sphinx documentation and make sure your changes look good: ```sh $ sphinx-build docs/ docs/_build/ ``` In order to see the changes, use your web browser of choice to open `docs/_build/index.html`. ### Static code analysis recon-pipeline uses two code checking tools: 1. [black](https://github.com/psf/black) 2. [flake8](https://github.com/PyCQA/flake8) #### pre-commit setup recon-pipeline uses [pre-commit](https://github.com/pre-commit/pre-commit) to automatically run both of its static code analysis tools. From within your virtual environment's shell, run the following command: ```sh $ pre-commit install pre-commit installed at .git/hooks/pre-commit ``` With that complete, you should be able to run all the pre-commit hooks. ```text ❯ pre-commit run --all-files black....................................................................Passed flake8...................................................................Passed Trim Trailing Whitespace.................................................Passed Debug Statements (Python)................................................Passed run tests................................................................Passed ``` > Please do not ignore any linting errors in code you write or modify, as they are meant to **help** you and to ensure a clean and simple code base. ### Running the test suite When you're ready to share your code, run the test suite: ```sh $ cd ~/projects/recon-pipeline $ python -m pytest tests ``` and ensure all tests pass. Test coverage can be checked using `coverage`: ```sh coverage run --source=pipeline -m pytest tests/test_recon/ tests/test_shell/ tests/test_web/ tests/test_models && coverage report -m ===================================================================================================================================== platform linux -- Python 3.7.5, pytest-5.4.1, py-1.8.1, pluggy-0.13.1 rootdir: /home/epi/PycharmProjects/recon-pipeline, inifile: pytest.ini collected 225 items tests/test_recon/test_amass.py ......... [ 4%] tests/test_recon/test_config.py ........... [ 8%] tests/test_recon/test_helpers.py ............. [ 14%] tests/test_recon/test_masscan.py ....... [ 18%] tests/test_recon/test_nmap.py ........... [ 23%] tests/test_recon/test_parsers.py ............................................................. [ 50%] tests/test_recon/test_targets.py .. [ 51%] tests/test_shell/test_recon_pipeline_shell.py ................................................................ [ 79%] tests/test_web/test_aquatone.py ...... [ 82%] tests/test_web/test_gobuster.py ....... [ 85%] tests/test_web/test_subdomain_takeover.py ................ [ 92%] tests/test_web/test_targets.py ... [ 93%] tests/test_web/test_webanalyze.py ....... [ 96%] tests/test_models/test_db_manager.py .... [ 98%] tests/test_models/test_pretty_prints.py ... [100%] ============================================================================================ 225 passed in 20.35s ============================================================================================ Name Stmts Miss Cover Missing ------------------------------------------------------------------------ pipeline/__init__.py 0 0 100% pipeline/models/__init__.py 0 0 100% pipeline/models/base_model.py 2 0 100% pipeline/models/db_manager.py 123 0 100% pipeline/models/endpoint_model.py 12 0 100% pipeline/models/header_model.py 12 0 100% pipeline/models/ip_address_model.py 10 0 100% pipeline/models/nmap_model.py 47 0 100% pipeline/models/nse_model.py 12 0 100% pipeline/models/port_model.py 12 0 100% pipeline/models/screenshot_model.py 16 0 100% pipeline/models/searchsploit_model.py 34 0 100% pipeline/models/target_model.py 18 0 100% pipeline/models/technology_model.py 28 0 100% pipeline/recon-pipeline.py 388 5 99% 94, 104-105, 356-358 pipeline/recon/__init__.py 9 0 100% pipeline/recon/amass.py 66 2 97% 186-187 pipeline/recon/config.py 7 0 100% pipeline/recon/helpers.py 36 0 100% pipeline/recon/masscan.py 82 24 71% 83-143 pipeline/recon/nmap.py 120 0 100% pipeline/recon/parsers.py 68 0 100% pipeline/recon/targets.py 27 0 100% pipeline/recon/tool_definitions.py 3 0 100% pipeline/recon/web/__init__.py 5 0 100% pipeline/recon/web/aquatone.py 93 0 100% pipeline/recon/web/gobuster.py 72 0 100% pipeline/recon/web/subdomain_takeover.py 87 0 100% pipeline/recon/web/targets.py 27 0 100% pipeline/recon/web/webanalyze.py 70 0 100% pipeline/recon/wrappers.py 34 21 38% 35-70, 97-127 ------------------------------------------------------------------------ TOTAL 1520 52 97% ``` ### Squashing your commits When you make a pull request, it is preferable for all of your changes to be in one commit. Github has made it very simple to squash commits now as it's [available through the web interface](https://stackoverflow.com/a/43858707) at pull request submission time. ### Creating a pull request #### What is a pull request? A pull request (PR) is a method of submitting proposed changes to the recon-pipeline repo (or any repo, for that matter). You will make changes to copies of the files which make up recon-pipeline in a personal fork, then apply to have them accepted by the recon-pipeline team. #### Need help? GitHub has a good guide on how to contribute to open source [here](https://opensource.guide/how-to-contribute/). ##### Editing via your local fork 1. Perform the maintenance step of rebasing `master` 2. Ensure you're on the `master` branch using `git status`: ```sh $ git status On branch master Your branch is up-to-date with 'origin/master'. nothing to commit, working directory clean ``` 1. If you're not on master or your working directory is not clean, resolve any outstanding files/commits and checkout master `git checkout master` 2. Create a branch off of `master` with git: `git checkout -B branch/name-here` 3. Edit your file(s) locally with the editor of your choice 4. Check your `git status` to see unstaged files 5. Add your edited files: `git add path/to/filename.ext` You can also do: `git add .` to add all unstaged files. Take care, though, because you can accidentally add files you don't want added. Review your `git status` first. 6. Commit your edits: `git commit -m "Brief description of commit"`. 7. Squash your commits, if there are more than one 8. Push your commits to your GitHub Fork: `git push -u origin branch/name-here` 9. Once the edits have been committed, you will be prompted to create a pull request on your fork's GitHub page 10. By default, all pull requests should be against the `master` branch 11. Submit a pull request from your branch to recon-pipeline's `master` branch 12. The title (also called the subject) of your PR should be descriptive of your changes and succinctly indicate what is being fixed - Examples: `Add test cases for Unicode support`; `Correct typo in overview documentation` 13. In the body of your PR include a more detailed summary of the changes you made and why - If the PR is meant to fix an existing bug/issue, then, at the end of your PR's description, append the keyword `closes` and #xxxx (where xxxx is the issue number). Example: `closes #1337`. This tells GitHub to close the existing issue if the PR is merged. 14. Indicate what local testing you have done (e.g. what OS and version(s) of Python did you run the unit test suite with) 15. Creating the PR causes our continuous integration (CI) systems to automatically run all of the unit tests on all supported OSes and all supported versions of Python. You should watch your PR to make sure that all unit tests pass. 16. If any unit tests fail, you should look at the details and fix the failures. You can then push the fix to the same branch in your fork. The PR will automatically get updated and the CI system will automatically run all of the unit tests again. ### How we review and merge pull requests 1. If your changes can merge without conflicts and all unit tests pass, then your pull request (PR) will have a big green checkbox which says something like "All Checks Passed" next to it. If this is not the case, there will be a link you can click on to get details regarding what the problem is. It is your responsibility to make sure all unit tests are passing. Generally a Maintainer will not QA a pull request unless it can merge without conflicts and all unit tests pass. 2. If a Maintainer reviews a pull request and confirms that the new code does what it is supposed to do without seeming to introduce any new bugs, and doesn't present any backward compatibility issues, they will merge the pull request. ### Next steps #### If your PR is accepted Once your PR is accepted, you may delete the branch you created to submit it. This keeps your working fork clean. You can do this with a press of a button on the GitHub PR interface. You can delete the local copy of the branch with: `git branch -D branch/to-delete-name` #### If your PR is rejected Don't worry! You will receive solid feedback from the Maintainers as to why it was rejected and what changes are needed. Many pull requests, especially first pull requests, require correction or updating. If you have a local copy of the repo, you can make the requested changes and amend your commit with: `git commit --amend` This will update your existing commit. When you push it to your fork you will need to do a force push to overwrite your old commit: `git push --force` Be sure to post in the PR conversation that you have made the requested changes. ### Other resources - [PEP 8 Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/) - [Searching for your issue on GitHub](https://help.github.com/articles/searching-issues/) - [Creating a new GitHub issue](https://help.github.com/articles/creating-an-issue/) ### Advice Here is some advice regarding what makes a good pull request (PR) from our perspective: - Multiple smaller PRs divided by topic are better than a single large PR containing a bunch of unrelated changes - Good unit/functional tests are very important - Accurate documentation is also important - It's best to create a dedicated branch for a PR, use it only for that PR, and delete it once the PR has been merged - It's good if the branch name is related to the PR contents, even if it's just "fix123" or "add_more_tests" - Code coverage of the unit tests matters, so try not to decrease it - Think twice before adding dependencies to third-party libraries (outside of the Python standard library) because it could affect a lot of users ## Acknowledgement Thanks to the awesome guys at [cmd2](https://github.com/python-cmd2/cmd2) for their fantastic `CONTRIBUTING` file from which we have borrowed heavily. <file_sep>[flake8] max-line-length = 120 select = C,E,F,W,B,B950 ignore = E203, E501, W503 max-complexity = 13 per-file-ignores = pipeline/recon/__init__.py:F401 pipeline/models/__init__.py:F401 pipeline/recon/web/__init__.py:F401 pipeline/luigi_targets/__init__.py:F401 tests/test_recon/test_parsers.py:F405 <file_sep>from sqlalchemy.orm import relationship from sqlalchemy import Column, Integer, ForeignKey, String, Table, UniqueConstraint from .base_model import Base port_association_table = Table( "port_association", Base.metadata, Column("port_id", Integer, ForeignKey("port.id")), Column("target_id", Integer, ForeignKey("target.id")), ) class Port(Base): """ Database model that describes a port (tcp or udp). Relationships: ``targets``: many to many -> :class:`pipeline.models.target_model.Target` """ __tablename__ = "port" __table_args__ = (UniqueConstraint("protocol", "port_number"),) # combination of proto/port == unique id = Column(Integer, primary_key=True) protocol = Column("protocol", String) port_number = Column("port_number", Integer) target_id = Column(Integer, ForeignKey("target.id")) targets = relationship("Target", secondary=port_association_table, back_populates="open_ports") <file_sep><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"> <TITLE>ERROR: The request could not be satisfied</TITLE> </HEAD><BODY> <H1>403 ERROR</H1> <H2>The request could not be satisfied.</H2> <HR noshade size="1px"> Bad request. We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner. <BR clear="all"> If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation. <BR clear="all"> <HR noshade size="1px"> <PRE> Generated by cloudfront (CloudFront) Request ID: uWMKsrTp0Be5vTSEXIVcoeYdLjnC2hylXOIjaVpIYE8uaxmltQIHBA== </PRE> <ADDRESS> </ADDRESS> </BODY></HTML><file_sep>from pathlib import Path import pytest from pipeline.recon import defaults, web_ports, top_tcp_ports, top_udp_ports from pipeline.tools import tools def test_tool_paths_absolute(): for tool in tools.values(): if tool.get("path"): assert Path(tool["path"]).is_absolute() @pytest.mark.parametrize("test_input", ["database-dir", "tools-dir", "gobuster-wordlist"]) def test_defaults_dirs_absolute(test_input): assert Path(defaults.get(test_input)).is_absolute() @pytest.mark.parametrize("test_input", ["threads", "masscan-rate", "aquatone-scan-timeout"]) def test_defaults_are_numeric(test_input): assert defaults.get(test_input).isnumeric() def test_webports_exist(): assert web_ports is not None def test_webports_numeric(): for port in web_ports: assert port.isnumeric() def test_top_tcp_ports_exist(): assert top_tcp_ports is not None assert len(top_tcp_ports) >= 1 def test_top_udp_ports_exist(): assert top_udp_ports is not None assert len(top_udp_ports) >= 1 <file_sep>import re import uuid from http import client from pathlib import Path import yaml from ..recon.config import defaults definitions = Path(__file__).parent tools = {} def join(loader, node): """ yaml tag handler to join a sequence of items into a space-separated string at load time """ seq = loader.construct_sequence(node) return " ".join([str(val) for val in seq]) def join_empty(loader, node): """ yaml tag handler to join a sequence of items into a single string with no separations """ seq = loader.construct_sequence(node) return "".join([str(val) for val in seq]) def join_path(loader, node): """ yaml tag handler to join a sequence of items into a filesystem path at load time """ seq = loader.construct_sequence(node) return "/".join([str(i) for i in seq]) def get_default(loader, node): """ yaml tag handler to access defaults dict at load time """ py_str = loader.construct_python_str(node) return py_str.format(**defaults) def get_tool_path(loader, node): """ yaml tag handler to access tools dict at load time """ py_str = loader.construct_python_str(node) return py_str.format(**tools) def get_go_version(loader=None, node=None): """ download latest version of golang """ arch = defaults.get("arch") err_msg = "Could not find latest go version download url" conn = client.HTTPSConnection("go.dev") conn.request("GET", "/dl/") response = conn.getresponse().read().decode() for line in response.splitlines(): if "linux-amd64.tar.gz" in line: match = re.search(rf"href=./dl/(go.*\.linux-{arch}\.tar\.gz).>", line) if not match: return err_msg.replace("find", "parse") return match.group(1) # go1.16.3.linux- return err_msg yaml.add_constructor("!join", join) yaml.add_constructor("!join_empty", join_empty) yaml.add_constructor("!join_path", join_path) yaml.add_constructor("!get_default", get_default) yaml.add_constructor("!get_tool_path", get_tool_path) yaml.add_constructor("!get_go_version,", get_go_version) def load_yaml(file): try: config = yaml.full_load(file.read_text()) tool_name = str(file.name.replace(".yaml", "")) tools[tool_name] = config except KeyError as error: # load dependencies first dependency = error.args[0] dependency_file = definitions / (dependency + ".yaml") load_yaml(dependency_file) load_yaml(file) for file in definitions.iterdir(): if file.name.endswith(".yaml") and file.name.replace(".yaml", "") not in tools: load_yaml(file) for tool_name, tool_definition in tools.items(): tool_definition["installed"] = Path(tool_definition.get("path", f"/{uuid.uuid4()}")).exists() <file_sep># Landing a Pull Request (PR) Long form explanations of most of the items below can be found in the [CONTRIBUTING](https://github.com/epi052/recon-pipeline/blob/master/CONTRIBUTING.md) guide. ## Branching checklist - [ ] There is an issue associated with your PR (bug, feature, etc.. if not, create one) - [ ] Your PR description references the associated issue (i.e. fixes #123) - [ ] Code is in its own branch - [ ] Branch name is related to the PR contents - [ ] PR targets master ## Static analysis checks - [ ] All python files are formatted using black - [ ] All flake8 checks pass - [ ] All existing tests pass ## Documentation - [ ] Documentation about your PR is included in docs/ and the README, as appropriate ## Additional Tests - [ ] New code is unit tested - [ ] New tests pass <file_sep>from pathlib import Path import luigi from luigi.contrib.sqla import SQLAlchemyTarget import pipeline.models.db_manager from .config import defaults from .helpers import is_ip_address from ..models.target_model import Target class TargetList(luigi.ExternalTask): """ External task. ``TARGET_FILE`` is generated manually by the user from target's scope. Args: results_dir: specifies the directory on disk to which all Task results are written db_location: specifies the path to the database used for storing results """ target_file = luigi.Parameter() db_location = luigi.Parameter() results_dir = luigi.Parameter(default=defaults.get("results-dir")) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.db_mgr = pipeline.models.db_manager.DBManager(db_location=self.db_location) def output(self): """ Returns the target output for this task. target_file.ips || target_file.domains In this case, it expects a file to be present in the local filesystem. By convention, TARGET_NAME should be something like tesla or some other target identifier. The returned target output will either be target_file.ips or target_file.domains, depending on what is found on the first line of the file. Example: Given a TARGET_FILE of tesla where the first line is tesla.com; tesla.domains is written to disk. Returns: luigi.local_target.LocalTarget """ # normally the call is self.output().touch(), however, that causes recursion here, so we grab the target now # in order to call .touch() on it later and eventually return it db_target = SQLAlchemyTarget( connection_string=self.db_mgr.connection_string, target_table="target", update_id=self.task_id ) with open(Path(self.target_file).expanduser().resolve()) as f: for line in f.readlines(): line = line.strip() if is_ip_address(line): tgt = self.db_mgr.get_or_create(Target) tgt = self.db_mgr.add_ipv4_or_v6_address_to_target(tgt, line) else: # domain name assumed if not ip address tgt = self.db_mgr.get_or_create(Target, hostname=line, is_web=True) self.db_mgr.add(tgt) db_target.touch() self.db_mgr.close() return db_target <file_sep>.. _visualization-ref-label: Visualizing Tasks ================= Setup ##### To use the web console, you'll need to :ref:`install the luigid service<install-ref-label>`. Assuming you've already installed ``pipenv`` and created a virtual environment, you can simply run the ``tools install luigi-service`` from within the pipeline. Dashboard ######### If you're using the :ref:`central scheduler<scheduler-ref-label>`, you'll be able to use luigi's web console to see a dashboard style synopsis of your tasks. .. image:: ../img/dashboard.png Dependency Graph ################ You can use the **Dependency Graph** link at the top of the dashboard to view your current task along with any up/downstream tasks that are queued. .. image:: ../img/web-console.png Make it So ########## To view the console from within ``recon-pipeline``, you can run the :ref:`status<status_command>` command or add ``--sausage`` to your scan command at execution time. The web console runs on port **8082** by default, so at any time you can also just use your favorite browser to check it out manually as well. <file_sep>from .loader import tools # noqa: F401,E402 <file_sep>import os import shutil import tempfile from pathlib import Path from unittest.mock import patch, MagicMock from pipeline.recon.web import GobusterScan, GatherWebTargets gobuster_results = Path(__file__).parent.parent / "data" / "recon-results" / "gobuster-results" class TestGobusterScan: def setup_method(self): self.tmp_path = Path(tempfile.mkdtemp()) self.scan = GobusterScan( target_file=__file__, results_dir=str(self.tmp_path), db_location=str(self.tmp_path / "testing.sqlite") ) self.scan.exception = False def teardown_method(self): shutil.rmtree(self.tmp_path) def test_scan_requires(self): with patch("pipeline.recon.web.GatherWebTargets"): with patch("pipeline.recon.web.gobuster.meets_requirements"): retval = self.scan.requires() assert isinstance(retval, GatherWebTargets) def test_scan_run(self): with patch("concurrent.futures.ThreadPoolExecutor.map") as mocked_run: self.scan.parse_results = MagicMock() self.scan.db_mgr.get_all_web_targets = MagicMock() self.scan.db_mgr.get_all_web_targets.return_value = [ "192.168.127.12", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:3c33", "google.com", ] self.scan.extensions = "php" self.scan.proxy = "127.0.0.1:8080" self.scan.run() assert mocked_run.called assert self.scan.parse_results.called def test_scan_recursive_run(self, tmp_path): os.chdir(tmp_path) with patch("concurrent.futures.ThreadPoolExecutor.map") as mocked_run: self.scan.parse_results = MagicMock() self.scan.db_mgr.get_all_web_targets = MagicMock() self.scan.db_mgr.get_all_web_targets.return_value = [ "192.168.127.12", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:3c33", "google.com", ] self.scan.extensions = "php" self.scan.proxy = "127.0.0.1:8080" self.scan.recursive = True self.scan.run() assert mocked_run.called assert self.scan.parse_results.called def test_scan_run_with_wrong_threads(self, caplog): with patch("concurrent.futures.ThreadPoolExecutor.map"): self.scan.threads = "a" retval = self.scan.run() assert retval is None assert "The value supplied to --threads must be a non-negative integer" in caplog.text def test_scan_creates_results_dir(self): assert self.scan.results_subfolder == self.tmp_path / "gobuster-results" def test_scan_creates_database(self): assert self.scan.db_mgr.location.exists() assert self.tmp_path / "testing.sqlite" == self.scan.db_mgr.location def test_scan_creates_results(self): self.scan.results_subfolder = gobuster_results self.scan.parse_results() assert self.scan.output().exists() <file_sep>API Reference ============= .. toctree:: :maxdepth: 1 scanners parsers commands models<file_sep>.. _newwrapper-ref-label: Create a New Wrapper Scan ========================= If for whatever reason you want something other than FullScan, the process for defining a new scan is relatively simple. The ``HTBScan`` is a good example. 1. Define your new class, inheriting from **luigi.WrapperTask** and use the ``inherits`` decorator to include any scan you want to utilize .. code-block:: python @inherits(SearchsploitScan, AquatoneScan, GobusterScan, WebanalyzeScan) class HTBScan(luigi.WrapperTask): ... 2. Include all parameters needed by any of the scans passed to ``inherits`` .. code-block:: python def requires(self): """ HTBScan is a wrapper, as such it requires any Tasks that it wraps. """ args = { "results_dir": self.results_dir, "rate": self.rate, "target_file": self.target_file, "top_ports": self.top_ports, "interface": self.interface, "ports": self.ports, "exempt_list": self.exempt_list, "threads": self.threads, "proxy": self.proxy, "wordlist": self.wordlist, "extensions": self.extensions, "recursive": self.recursive, } ... 3. ``yield`` from each scan, keeping in mind that some of the parameters won't be universal (i.e. need to be removed/added) .. code-block:: python def requires(self): """ HTBScan is a wrapper, as such it requires any Tasks that it wraps. """ ... yield GobusterScan(**args) # remove options that are gobuster specific; if left dictionary unpacking to other scans throws an exception for gobuster_opt in ("proxy", "wordlist", "extensions", "recursive"): del args[gobuster_opt] # add aquatone scan specific option args.update({"scan_timeout": self.scan_timeout}) yield AquatoneScan(**args) del args["scan_timeout"] yield SearchsploitScan(**args) yield WebanalyzeScan(**args) <file_sep>import shutil import tempfile from pathlib import Path from unittest.mock import patch import luigi from pipeline.recon import MasscanScan, ParseMasscanOutput masscan_results = Path(__file__).parent.parent / "data" / "recon-results" / "masscan-results" / "masscan.json" class TestMasscanScan: # can't test run method due to yields from TargetList and ParseAmassOutput def setup_method(self): self.tmp_path = Path(tempfile.mkdtemp()) self.scan = MasscanScan( target_file=__file__, results_dir=str(self.tmp_path), db_location=str(self.tmp_path / "testing.sqlite") ) self.scan.exception = False def teardown_method(self): shutil.rmtree(self.tmp_path) def test_scan_creates_results_dir(self): assert self.scan.results_subfolder == self.tmp_path / "masscan-results" def test_scan_creates_database(self): assert self.scan.db_mgr.location.exists() assert self.tmp_path / "testing.sqlite" == self.scan.db_mgr.location def test_scan_output_location(self): assert self.scan.output().path == str(self.scan.results_subfolder / "masscan.json") class TestParseMasscanOutput: def setup_method(self): self.tmp_path = Path(tempfile.mkdtemp()) self.scan = ParseMasscanOutput( target_file=__file__, results_dir=str(self.tmp_path), db_location=str(self.tmp_path / "testing.sqlite") ) self.scan.input = lambda: luigi.LocalTarget(masscan_results) def teardown_method(self): shutil.rmtree(self.tmp_path) def test_scan_creates_results_dir(self): assert self.scan.results_subfolder == self.tmp_path / "masscan-results" def test_scan_creates_database(self): assert self.scan.db_mgr.location.exists() assert self.tmp_path / "testing.sqlite" == self.scan.db_mgr.location def test_scan_creates_results(self): self.scan.run() assert self.scan.output().exists() def test_scan_bad_json(self, capsys): not_json = self.tmp_path / "not-json" not_json.write_text("I'm definitely not json") self.scan.input = lambda: luigi.LocalTarget(not_json) self.scan.run() assert "Expecting value: line 1 column 1" in capsys.readouterr().out def test_scan_requires(self): with patch("pipeline.recon.MasscanScan"): retval = self.scan.requires() assert isinstance(retval, MasscanScan) <file_sep>import ast import logging import subprocess import concurrent.futures from pathlib import Path from shutil import which from cmd2.ansi import style import luigi import sqlalchemy from luigi.util import inherits from libnmap.parser import NmapParser from luigi.contrib.sqla import SQLAlchemyTarget import pipeline.models.db_manager from .masscan import ParseMasscanOutput from .config import defaults from .helpers import get_ip_address_version, is_ip_address, meets_requirements from ..tools import tools from ..models.port_model import Port from ..models.nse_model import NSEResult from ..models.target_model import Target from ..models.nmap_model import NmapResult from ..models.ip_address_model import IPAddress from ..models.searchsploit_model import SearchsploitResult @inherits(ParseMasscanOutput) class ThreadedNmapScan(luigi.Task): """ Run ``nmap`` against specific targets and ports gained from the ParseMasscanOutput Task. Install: ``nmap`` is already on your system if you're using kali. If you're not using kali, refer to your own distributions instructions for installing ``nmap``. Basic Example: .. code-block:: console nmap --open -sT -sC -T 4 -sV -Pn -p 43,25,21,53,22 -oA htb-targets-nmap-results/nmap.10.10.10.155-tcp 10.10.10.155 Luigi Example: .. code-block:: console PYTHONPATH=$(pwd) luigi --local-scheduler --module recon.nmap ThreadedNmap --target-file htb-targets --top-ports 5000 Args: threads: number of threads for parallel nmap command execution db_location: specifies the path to the database used for storing results *Required by upstream Task* rate: desired rate for transmitting packets (packets per second) *Required by upstream Task* interface: use the named raw network interface, such as "eth0" *Required by upstream Task* top_ports: Scan top N most popular ports *Required by upstream Task* ports: specifies the port(s) to be scanned *Required by upstream Task* target_file: specifies the file on disk containing a list of ips or domains *Required by upstream Task* results_dir: specifes the directory on disk to which all Task results are written *Required by upstream Task* """ threads = luigi.Parameter(default=defaults.get("threads")) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not which("nmap"): raise RuntimeError(style("[!] nmap is not installed", fg="bright_red")) self.db_mgr = pipeline.models.db_manager.DBManager(db_location=self.db_location) self.results_subfolder = (Path(self.results_dir) / "nmap-results").expanduser().resolve() def requires(self): """ ThreadedNmap depends on ParseMasscanOutput to run. TargetList expects target_file, results_dir, and db_location as parameters. Masscan expects rate, target_file, interface, and either ports or top_ports as parameters. Returns: luigi.Task - ParseMasscanOutput """ args = { "results_dir": self.results_dir, "rate": self.rate, "target_file": self.target_file, "top_ports": self.top_ports, "interface": self.interface, "ports": self.ports, "db_location": self.db_location, } return ParseMasscanOutput(**args) def output(self): """ Returns the target output for this task. Naming convention for the output folder is TARGET_FILE-nmap-results. The output folder will be populated with all of the output files generated by any nmap commands run. Because the nmap command uses -oA, there will be three files per target scanned: .xml, .nmap, .gnmap. Returns: luigi.local_target.LocalTarget """ return { "sqltarget": SQLAlchemyTarget( connection_string=self.db_mgr.connection_string, target_table="nmap_result", update_id=self.task_id ), "localtarget": luigi.LocalTarget(str(self.results_subfolder)), } def parse_nmap_output(self): """ Read nmap .xml results and add entries into specified database """ for entry in self.results_subfolder.glob("nmap*.xml"): # relying on python-libnmap here report = NmapParser.parse_fromfile(entry) for host in report.hosts: for service in host.services: port = self.db_mgr.get_or_create(Port, protocol=service.protocol, port_number=service.port) if is_ip_address(host.address) and get_ip_address_version(host.address) == "4": ip_address = self.db_mgr.get_or_create(IPAddress, ipv4_address=host.address) else: ip_address = self.db_mgr.get_or_create(IPAddress, ipv6_address=host.address) if ip_address.target is None: # account for ip addresses identified that aren't already tied to a target # almost certainly ipv6 addresses tgt = self.db_mgr.get_or_create(Target) tgt.ip_addresses.append(ip_address) else: tgt = ip_address.target try: nmap_result = self.db_mgr.get_or_create( NmapResult, port=port, ip_address=ip_address, target=tgt ) except sqlalchemy.exc.StatementError: # one of the three (port/ip/tgt) didn't exist and we're querying on ids that the db doesn't know self.db_mgr.add(port) self.db_mgr.add(ip_address) self.db_mgr.add(tgt) nmap_result = self.db_mgr.get_or_create( NmapResult, port=port, ip_address=ip_address, target=tgt ) for nse_result in service.scripts_results: script_id = nse_result.get("id") script_output = nse_result.get("output") nse_obj = self.db_mgr.get_or_create(NSEResult, script_id=script_id, script_output=script_output) nmap_result.nse_results.append(nse_obj) nmap_result.open = service.open() nmap_result.reason = service.reason nmap_result.service = service.service nmap_result.commandline = report.commandline nmap_result.product = service.service_dict.get("product") nmap_result.product_version = service.service_dict.get("version") nmap_result.target.nmap_results.append(nmap_result) self.db_mgr.add(nmap_result) self.output().get("sqltarget").touch() self.db_mgr.close() def run(self): """ Parses pickled target info dictionary and runs targeted nmap scans against only open ports. """ try: self.threads = abs(int(self.threads)) except (TypeError, ValueError): return logging.error("The value supplied to --threads must be a non-negative integer.") nmap_command = [ # placeholders will be overwritten with appropriate info in loop below "nmap", "--open", "PLACEHOLDER-IDX-2", "-n", "-sC", "-T", "4", "-sV", "-Pn", "-p", "PLACEHOLDER-IDX-10", "-oA", ] commands = list() for target in self.db_mgr.get_all_targets(): for protocol in ("tcp", "udp"): ports = self.db_mgr.get_ports_by_ip_or_host_and_protocol(target, protocol) if ports: tmp_cmd = nmap_command[:] tmp_cmd[2] = "-sT" if protocol == "tcp" else "-sU" # arg to -oA, will drop into subdir off curdir tmp_cmd[10] = ",".join(ports) tmp_cmd.append(str(Path(self.output().get("localtarget").path) / f"nmap.{target}-{protocol}")) if is_ip_address(target) and get_ip_address_version(target) == "6": # got an ipv6 address tmp_cmd.insert(-2, "-6") tmp_cmd.append(target) # target as final arg to nmap commands.append(tmp_cmd) # basically mkdir -p, won't error out if already there self.results_subfolder.mkdir(parents=True, exist_ok=True) with concurrent.futures.ThreadPoolExecutor(max_workers=self.threads) as executor: executor.map(subprocess.run, commands) self.parse_nmap_output() @inherits(ThreadedNmapScan) class SearchsploitScan(luigi.Task): """ Run ``searchcploit`` against each ``nmap*.xml`` file in the **TARGET-nmap-results** directory and write results to disk. Install: ``searchcploit`` is already on your system if you're using kali. If you're not using kali, refer to your own distributions instructions for installing ``searchcploit``. Basic Example: .. code-block:: console searchsploit --nmap htb-targets-nmap-results/nmap.10.10.10.155-tcp.xml Luigi Example: .. code-block:: console PYTHONPATH=$(pwd) luigi --local-scheduler --module recon.nmap Searchsploit --target-file htb-targets --top-ports 5000 Args: threads: number of threads for parallel nmap command execution *Required by upstream Task* db_location: specifies the path to the database used for storing results *Required by upstream Task* rate: desired rate for transmitting packets (packets per second) *Required by upstream Task* interface: use the named raw network interface, such as "eth0" *Required by upstream Task* top_ports: Scan top N most popular ports *Required by upstream Task* ports: specifies the port(s) to be scanned *Required by upstream Task* target_file: specifies the file on disk containing a list of ips or domains *Required by upstream Task* results_dir: specifies the directory on disk to which all Task results are written *Required by upstream Task* """ requirements = ["searchsploit"] exception = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.db_mgr = pipeline.models.db_manager.DBManager(db_location=self.db_location) def requires(self): """ Searchsploit depends on ThreadedNmap to run. TargetList expects target_file, results_dir, and db_location as parameters. Masscan expects rate, target_file, interface, and either ports or top_ports as parameters. ThreadedNmap expects threads Returns: luigi.Task - ThreadedNmap """ meets_requirements(self.requirements, self.exception) args = { "rate": self.rate, "ports": self.ports, "threads": self.threads, "top_ports": self.top_ports, "interface": self.interface, "target_file": self.target_file, "results_dir": self.results_dir, "db_location": self.db_location, } return ThreadedNmapScan(**args) def output(self): """ Returns the target output for this task. Naming convention for the output folder is TARGET_FILE-searchsploit-results. The output folder will be populated with all of the output files generated by any searchsploit commands run. Returns: luigi.local_target.LocalTarget """ return SQLAlchemyTarget( connection_string=self.db_mgr.connection_string, target_table="searchsploit_result", update_id=self.task_id ) def run(self): """ Grabs the xml files created by ThreadedNmap and runs searchsploit --nmap on each one, saving the output. """ for entry in Path(self.input().get("localtarget").path).glob("nmap*.xml"): proc = subprocess.run( [tools.get("searchsploit").get("path"), "-j", "-v", "--nmap", str(entry)], stdout=subprocess.PIPE ) if proc.stdout: # change wall-searchsploit-results/nmap.10.10.10.157-tcp to 10.10.10.157 ipaddr = entry.stem.replace("nmap.", "").replace("-tcp", "").replace("-udp", "") contents = proc.stdout.decode() for line in contents.splitlines(): if "Title" in line: # {'Title': "Nginx (Debian Based Distros + Gentoo) ... } # oddity introduced on 15 Apr 2020 from an exploitdb update # entries have two double quotes in a row for no apparent reason # {"Title":"PHP-FPM + Nginx - Remote Code Execution"", ... # seems to affect all entries at the moment. will remove this line if it # ever returns to normal line = line.replace('""', '"') if line.endswith(","): # result would be a tuple if the comma is left on the line; remove it tmp_result = ast.literal_eval(line.strip()[:-1]) else: # normal dict tmp_result = ast.literal_eval(line.strip()) tgt = self.db_mgr.get_or_create_target_by_ip_or_hostname(ipaddr) ssr_type = tmp_result.get("Type") ssr_title = tmp_result.get("Title") ssr_path = tmp_result.get("Path") ssr = self.db_mgr.get_or_create( SearchsploitResult, type=ssr_type, title=ssr_title, path=ssr_path ) tgt.searchsploit_results.append(ssr) self.db_mgr.add(tgt) self.output().touch() self.db_mgr.close() <file_sep>import shutil import tempfile from pathlib import Path from unittest.mock import patch, MagicMock import luigi from pipeline.recon import AmassScan, ParseAmassOutput, TargetList amass_json = Path(__file__).parent.parent / "data" / "recon-results" / "amass-results" / "amass.json" class TestAmassScan: def setup_method(self): self.tmp_path = Path(tempfile.mkdtemp()) self.scan = AmassScan( target_file=__file__, results_dir=str(self.tmp_path), db_location=str(self.tmp_path / "testing.sqlite") ) def teardown_method(self): shutil.rmtree(self.tmp_path) def test_scan_requires(self): with patch("pipeline.recon.TargetList"): with patch("pipeline.recon.amass.meets_requirements"): retval = self.scan.requires() assert isinstance(retval, TargetList) def test_scan_run(self): with patch("subprocess.run") as mocked_run: self.scan.run() assert mocked_run.called def test_scan_run_with_hostnames(self): with patch("subprocess.run") as mocked_run: self.scan.db_mgr = MagicMock() self.scan.db_mgr.get_all_hostnames.return_value = ["google.com"] self.scan.exempt_list = "stuff" self.scan.run() assert mocked_run.called def test_scan_creates_database(self): assert self.scan.db_mgr.location.exists() assert self.tmp_path / "testing.sqlite" == self.scan.db_mgr.location def test_scan_output_location(self): assert self.scan.output().path == str(Path(self.tmp_path) / "amass-results" / "amass.json") class TestParseAmass: def setup_method(self): self.tmp_path = Path(tempfile.mkdtemp()) self.scan = ParseAmassOutput( target_file=__file__, results_dir=str(self.tmp_path), db_location=str(self.tmp_path / "testing.sqlite") ) self.scan.input = lambda: luigi.LocalTarget(amass_json) self.scan.run() def teardown_method(self): shutil.rmtree(self.tmp_path) def test_scan_requires(self): with patch("pipeline.recon.AmassScan"): retval = self.scan.requires() assert isinstance(retval, AmassScan) def test_scan_results(self): assert self.scan.output().exists() def test_scan_creates_results_dir(self): assert self.scan.results_subfolder.exists() def test_scan_creates_database(self): assert self.scan.db_mgr.location.exists() assert self.tmp_path / "testing.sqlite" == self.scan.db_mgr.location <file_sep>import os import csv import logging import subprocess from pathlib import Path from urllib.parse import urlparse from concurrent.futures import ThreadPoolExecutor import luigi from luigi.util import inherits from luigi.contrib.sqla import SQLAlchemyTarget import pipeline.models.db_manager from ...tools import tools from ..config import defaults from ..helpers import meets_requirements from .targets import GatherWebTargets from ...models.technology_model import Technology from ..helpers import get_ip_address_version, is_ip_address @inherits(GatherWebTargets) class WebanalyzeScan(luigi.Task): """ Use webanalyze to determine the technology stack on the given target(s). Install: .. code-block:: console go get -u github.com/rverton/webanalyze # loads new apps.json file from wappalyzer project webanalyze -update Basic Example: .. code-block:: console webanalyze -host www.tesla.com -output json Luigi Example: .. code-block:: console PYTHONPATH=$(pwd) luigi --local-scheduler --module recon.web.webanalyze WebanalyzeScan --target-file tesla --top-ports 1000 --interface eth0 Args: threads: number of threads for parallel webanalyze command execution db_location: specifies the path to the database used for storing results *Required by upstream Task* exempt_list: Path to a file providing blacklisted subdomains, one per line. *Optional for upstream Task* top_ports: Scan top N most popular ports *Required by upstream Task* ports: specifies the port(s) to be scanned *Required by upstream Task* interface: use the named raw network interface, such as "eth0" *Required by upstream Task* rate: desired rate for transmitting packets (packets per second) *Required by upstream Task* target_file: specifies the file on disk containing a list of ips or domains *Required by upstream Task* results_dir: specifes the directory on disk to which all Task results are written *Required by upstream Task* """ threads = luigi.Parameter(default=defaults.get("threads")) requirements = ["go", "webanalyze", "masscan"] exception = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.db_mgr = pipeline.models.db_manager.DBManager(db_location=self.db_location) self.results_subfolder = Path(self.results_dir) / "webanalyze-results" def requires(self): """ WebanalyzeScan depends on GatherWebTargets to run. GatherWebTargets accepts exempt_list and expects rate, target_file, interface, and either ports or top_ports as parameters Returns: luigi.Task - GatherWebTargets """ meets_requirements(self.requirements, self.exception) args = { "results_dir": self.results_dir, "rate": self.rate, "target_file": self.target_file, "top_ports": self.top_ports, "interface": self.interface, "ports": self.ports, "exempt_list": self.exempt_list, "db_location": self.db_location, } return GatherWebTargets(**args) def output(self): """ Returns the target output for this task. Returns: luigi.contrib.sqla.SQLAlchemyTarget """ return SQLAlchemyTarget( connection_string=self.db_mgr.connection_string, target_table="technology", update_id=self.task_id ) def parse_results(self): """ Reads in the webanalyze's .csv files and updates the associated Target record. """ for entry in self.results_subfolder.glob("webanalyze*.csv"): """ example data http://192.168.3.11,Font scripts,Google Font API, http://192.168.3.11,"Web servers,Reverse proxies",Nginx,1.16.1 http://192.168.3.11,Font scripts,Font Awesome, """ with open(entry, newline="") as f: reader = csv.reader(f) # skip the empty line at the start; webanalyze places an empty line at the top of the file # need to skip that. remove this line if the files have no empty lines at the top next(reader, None) next(reader, None) # skip the headers; keep this one forever and always tgt = None for row in reader: # each row in a file is a technology specific to that target host, category, app, version = row parsed_url = urlparse(host) text = f"{app}-{version}" if version else app technology = self.db_mgr.get_or_create(Technology, type=category, text=text) if tgt is None: # should only hit the first line of each file tgt = self.db_mgr.get_or_create_target_by_ip_or_hostname(parsed_url.hostname) tgt.technologies.append(technology) if tgt is not None: self.db_mgr.add(tgt) self.output().touch() self.db_mgr.close() def _wrapped_subprocess(self, cmd): with open(f"webanalyze-{cmd[2].replace('//', '_').replace(':', '')}.csv", "wb") as f: subprocess.run(cmd, stdout=f) def run(self): """ Defines the options/arguments sent to webanalyze after processing. Returns: list: list of options/arguments, beginning with the name of the executable to run """ try: self.threads = abs(int(self.threads)) except (TypeError, ValueError): return logging.error("The value supplied to --threads must be a non-negative integer.") commands = list() for target in self.db_mgr.get_all_web_targets(): if is_ip_address(target) and get_ip_address_version(target) == "6": target = f"[{target}]" for url_scheme in ("https://", "http://"): command = [tools.get("webanalyze").get("path"), "-host", f"{url_scheme}{target}", "-output", "csv"] commands.append(command) self.results_subfolder.mkdir(parents=True, exist_ok=True) cwd = Path().cwd() os.chdir(self.results_subfolder) if not Path("apps.json").exists(): subprocess.run(f"{tools.get('webanalyze').get('path')} -update".split()) with ThreadPoolExecutor(max_workers=self.threads) as executor: executor.map(self._wrapped_subprocess, commands) os.chdir(str(cwd)) self.parse_results() <file_sep>import json import logging import subprocess from pathlib import Path from urllib.parse import urlparse import luigi from luigi.util import inherits from luigi.contrib.sqla import SQLAlchemyTarget from .targets import GatherWebTargets from ..config import defaults from ...tools import tools import pipeline.models.db_manager from ..helpers import meets_requirements from ...models.port_model import Port from ...models.header_model import Header from ...models.endpoint_model import Endpoint from ...models.screenshot_model import Screenshot @inherits(GatherWebTargets) class AquatoneScan(luigi.Task): """ Screenshot all web targets and generate HTML report. Install: .. code-block:: console mkdir /tmp/aquatone wget -q https://github.com/michenriksen/aquatone/releases/download/v1.7.0/aquatone_linux_amd64_1.7.0.zip -O /tmp/aquatone/aquatone.zip unzip /tmp/aquatone/aquatone.zip -d /tmp/aquatone sudo mv /tmp/aquatone/aquatone /usr/local/bin/aquatone rm -rf /tmp/aquatone Basic Example: ``aquatone`` commands are structured like the example below. ``cat webtargets.tesla.txt | /opt/aquatone -scan-timeout 900 -threads 20`` Luigi Example: .. code-block:: python PYTHONPATH=$(pwd) luigi --local-scheduler --module recon.web.aquatone AquatoneScan --target-file tesla --top-ports 1000 Args: threads: number of threads for parallel aquatone command execution scan_timeout: timeout in miliseconds for aquatone port scans db_location: specifies the path to the database used for storing results *Required by upstream Task* exempt_list: Path to a file providing blacklisted subdomains, one per line. *Optional by upstream Task* top_ports: Scan top N most popular ports *Required by upstream Task* ports: specifies the port(s) to be scanned *Required by upstream Task* interface: use the named raw network interface, such as "eth0" *Required by upstream Task* rate: desired rate for transmitting packets (packets per second) *Required by upstream Task* target_file: specifies the file on disk containing a list of ips or domains *Required by upstream Task* results_dir: specifes the directory on disk to which all Task results are written *Required by upstream Task* """ threads = luigi.Parameter(default=defaults.get("threads", "")) scan_timeout = luigi.Parameter(default=defaults.get("aquatone-scan-timeout", "")) requirements = ["aquatone", "masscan"] exception = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.db_mgr = pipeline.models.db_manager.DBManager(db_location=self.db_location) self.results_subfolder = Path(self.results_dir) / "aquatone-results" def requires(self): """ AquatoneScan depends on GatherWebTargets to run. GatherWebTargets accepts exempt_list and expects rate, target_file, interface, and either ports or top_ports as parameters Returns: luigi.Task - GatherWebTargets """ meets_requirements(self.requirements, self.exception) args = { "results_dir": self.results_dir, "rate": self.rate, "target_file": self.target_file, "top_ports": self.top_ports, "interface": self.interface, "ports": self.ports, "exempt_list": self.exempt_list, "db_location": self.db_location, } return GatherWebTargets(**args) def output(self): """ Returns the target output for this task. Returns: luigi.contrib.sqla.SQLAlchemyTarget """ return SQLAlchemyTarget( connection_string=self.db_mgr.connection_string, target_table="screenshot", update_id=self.task_id ) def _get_similar_pages(self, url, results): # populate similar pages if any exist similar_pages = None for cluster_id, cluster in results.get("pageSimilarityClusters").items(): if url not in cluster: continue similar_pages = list() for similar_url in cluster: if similar_url == url: continue similar_pages.append(self.db_mgr.get_or_create(Screenshot, url=similar_url)) return similar_pages def parse_results(self): """ Read in aquatone's .json file and update the associated Target record """ """ Example data "https://email.assetinventory.bugcrowd.com:8443/": { "uuid": "679b0dc7-02ea-483f-9e0a-3a5e6cdea4b6", "url": "https://email.assetinventory.bugcrowd.com:8443/", "hostname": "email.assetinventory.bugcrowd.com", "addrs": [ "172.16.17.32", "172.16.17.32", "fdf8:f53e:61e4::18:3d33", "fdf8:f53e:61e4::18:3c33" ], "status": "403 Forbidden", "pageTitle": "403 Forbidden", "headersPath": "headers/https__email_assetinventory_bugcrowd_com__8443__42099b4af021e53f.txt", "bodyPath": "html/https__email_assetinventory_bugcrowd_com__8443__42099b4af021e53f.html", "screenshotPath": "screenshots/https__email_assetinventory_bugcrowd_com__8443__42099b4af021e53f.png", "hasScreenshot": true, "headers": [ { "name": "Cf-Ray", "value": "55d396727981d25a-DFW", "decreasesSecurity": false, "increasesSecurity": false }, ... ], "tags": [ { "text": "CloudFlare", "type": "info", "link": "http://www.cloudflare.com", "hash": "9ea92fc7dce5e740ccc8e64d8f9e3336a96efc2a" } ], "notes": null }, ... "pageSimilarityClusters": { "11905c72-fd18-43de-9133-99ba2a480e2b": [ "http://172.16.31.10/", "https://staging.bitdiscovery.com/", "https://172.16.31.10/", ... ], "139fc2c4-0faa-4ae3-a6e4-0a1abe2418fa": [ "https://172.16.17.32:8443/", "https://email.assetinventory.bugcrowd.com:8443/", ... ], """ try: with open(self.results_subfolder / "aquatone_session.json") as f: # results.keys -> dict_keys(['version', 'stats', 'pages', 'pageSimilarityClusters']) results = json.load(f) except FileNotFoundError as e: logging.error(e) return for page, page_dict in results.get("pages").items(): headers = list() url = page_dict.get("url") # one url to one screenshot, unique key # build out the endpoint's data to include headers, this has value whether or not there's a screenshot endpoint = self.db_mgr.get_or_create(Endpoint, url=url) if not endpoint.status_code: status = page_dict.get("status").split(maxsplit=1) if len(status) > 1: endpoint.status_code, _ = status else: endpoint.status_code = status[0] for header_dict in page_dict.get("headers"): header = self.db_mgr.get_or_create(Header, name=header_dict.get("name"), value=header_dict.get("value")) if endpoint not in header.endpoints: header.endpoints.append(endpoint) headers.append(header) endpoint.headers = headers parsed_url = urlparse(url) ip_or_hostname = parsed_url.hostname tgt = self.db_mgr.get_or_create_target_by_ip_or_hostname(ip_or_hostname) endpoint.target = tgt if not page_dict.get("hasScreenshot"): # if there isn't a screenshot, save the endpoint data and move along self.db_mgr.add(endpoint) # This causes an integrity error on insertion due to the task_id being the same for two # different target tables. Could subclass SQLAlchemyTarget and set the unique-ness to be the # combination of update_id + target_table. The question is, does it matter? # TODO: assess above and act # SQLAlchemyTarget( # connection_string=self.db_mgr.connection_string, target_table="endpoint", update_id=self.task_id # ).touch() continue # build out screenshot data port = parsed_url.port if parsed_url.port else 80 port = self.db_mgr.get_or_create(Port, protocol="tcp", port_number=port) image = (self.results_subfolder / page_dict.get("screenshotPath")).read_bytes() screenshot = self.db_mgr.get_or_create(Screenshot, url=url) screenshot.port = port screenshot.endpoint = endpoint screenshot.target = screenshot.endpoint.target screenshot.image = image similar_pages = self._get_similar_pages(url, results) if similar_pages is not None: screenshot.similar_pages = similar_pages self.db_mgr.add(screenshot) self.output().touch() self.db_mgr.close() def run(self): """ Defines the options/arguments sent to aquatone after processing. cat webtargets.tesla.txt | /opt/aquatone -scan-timeout 900 -threads 20 Returns: list: list of options/arguments, beginning with the name of the executable to run """ self.results_subfolder.mkdir(parents=True, exist_ok=True) command = [ tools.get("aquatone").get("path"), "-scan-timeout", self.scan_timeout, "-threads", self.threads, "-silent", "-out", self.results_subfolder, ] aquatone_input_file = self.results_subfolder / "input-from-webtargets" with open(aquatone_input_file, "w") as f: for target in self.db_mgr.get_all_web_targets(): f.write(f"{target}\n") with open(aquatone_input_file) as target_list: subprocess.run(command, stdin=target_list) aquatone_input_file.unlink() self.parse_results() <file_sep>import pytest from unittest.mock import patch from pipeline.recon.helpers import get_ip_address_version, get_scans, is_ip_address, meets_requirements from pipeline.recon import AmassScan, MasscanScan, FullScan, HTBScan, SearchsploitScan, ThreadedNmapScan from pipeline.recon.web import GobusterScan, SubjackScan, TKOSubsScan, AquatoneScan, WaybackurlsScan, WebanalyzeScan def test_get_scans(): with patch("pipeline.recon.helpers.meets_requirements"): scan_names = [ AmassScan, GobusterScan, MasscanScan, SubjackScan, TKOSubsScan, AquatoneScan, FullScan, HTBScan, SearchsploitScan, ThreadedNmapScan, WebanalyzeScan, WaybackurlsScan, ] scans = get_scans() for scan in scan_names: if hasattr(scan, "requirements"): assert scan.__name__ in scans.keys() else: assert scan not in scans.keys() @pytest.mark.parametrize( "requirements, exception, expected", [(["amass"], True, None), (["amass"], False, False), (["aquatone"], False, True)], ) def test_meets_requirements(requirements, exception, expected): mdict = {"amass": {"installed": False}, "aquatone": {"installed": True}} with patch("pipeline.recon.helpers.tools", autospec=dict) as mtools: mtools.get.return_value = mdict.get(requirements[0]) if exception: with pytest.raises(RuntimeError): meets_requirements(requirements, exception) else: assert meets_requirements(requirements, exception) is expected @pytest.mark.parametrize( "test_input, expected", [("127.0.0.1", True), ("::1", True), ("abcd", False), ("", False), (-1, False), (1.0, False)], ) def test_is_ip_address(test_input, expected): assert is_ip_address(test_input) == expected @pytest.mark.parametrize( "test_input, expected", [("127.0.0.1", "4"), ("::1", "6"), ("abcd", None), ("", None), (-1, None), (1.0, None)] ) def test_get_ip_address_version(test_input, expected): assert get_ip_address_version(test_input) == expected <file_sep>import shutil import tempfile from pathlib import Path from unittest.mock import MagicMock, patch import pytest from pipeline.recon.web import SubjackScan, TKOSubsScan, GatherWebTargets subjack_results = Path(__file__).parent.parent / "data" / "recon-results" / "subjack-results" tkosubs_results = Path(__file__).parent.parent / "data" / "recon-results" / "tkosubs-results" class TestTKOSubsScanScan: def setup_method(self): self.tmp_path = Path(tempfile.mkdtemp()) self.scan = TKOSubsScan( target_file=__file__, results_dir=str(self.tmp_path), db_location=str(self.tmp_path / "testing.sqlite") ) self.scan.exception = False def teardown_method(self): shutil.rmtree(self.tmp_path) def test_scan_requires(self): with patch("pipeline.recon.web.GatherWebTargets"): with patch("pipeline.recon.web.subdomain_takeover.meets_requirements"): retval = self.scan.requires() assert isinstance(retval, GatherWebTargets) def test_scan_creates_results_dir(self): assert self.scan.results_subfolder == self.tmp_path / "tkosubs-results" def test_scan_creates_results_file(self): assert self.scan.output_file == self.tmp_path / "tkosubs-results" / "tkosubs.csv" def test_scan_creates_database(self): assert self.scan.db_mgr.location.exists() assert self.tmp_path / "testing.sqlite" == self.scan.db_mgr.location def test_scan_creates_results(self): self.scan.results_subfolder = tkosubs_results self.scan.output_file = self.scan.results_subfolder / "tkosubs.csv" self.scan.parse_results() assert self.scan.output().exists() def test_parse_results(self): myresults = self.tmp_path / "tkosubs-results" / "tkosubs.csv" myresults.parent.mkdir(parents=True, exist_ok=True) content = "Domain,Cname,Provider,IsVulnerable,IsTakenOver,Response\n" content += "google.com,Cname,Provider,true,IsTakenOver,Response\n" content += "maps.google.com,Cname,Provider,false,IsTakenOver,Response\n" myresults.write_text(content) self.scan.output_file = myresults self.scan.db_mgr.get_or_create_target_by_ip_or_hostname = MagicMock() self.scan.db_mgr.get_or_create_target_by_ip_or_hostname.return_value = MagicMock() self.scan.db_mgr.add = MagicMock() self.scan.parse_results() assert self.scan.output().exists() assert self.scan.db_mgr.add.called assert self.scan.db_mgr.get_or_create_target_by_ip_or_hostname.called @pytest.mark.parametrize("test_input", [["google.com"], None]) def test_scan_run(self, test_input): with patch("subprocess.run") as mocked_run: self.scan.parse_results = MagicMock() self.scan.db_mgr.get_all_hostnames = MagicMock() self.scan.db_mgr.get_all_hostnames.return_value = test_input self.scan.run() if test_input is None: assert not mocked_run.called assert not self.scan.parse_results.called else: assert mocked_run.called assert self.scan.parse_results.called class TestSubjackScan: def setup_method(self): self.tmp_path = Path(tempfile.mkdtemp()) self.scan = SubjackScan( target_file=__file__, results_dir=str(self.tmp_path), db_location=str(self.tmp_path / "testing.sqlite") ) self.scan.exception = False def teardown_method(self): shutil.rmtree(self.tmp_path) def test_scan_requires(self): with patch("pipeline.recon.web.GatherWebTargets"): with patch("pipeline.recon.web.subdomain_takeover.meets_requirements"): retval = self.scan.requires() assert isinstance(retval, GatherWebTargets) def test_scan_creates_results_dir(self): assert self.scan.results_subfolder == self.tmp_path / "subjack-results" def test_scan_creates_results_file(self): assert self.scan.output_file == self.tmp_path / "subjack-results" / "subjack.txt" def test_scan_creates_database(self): assert self.scan.db_mgr.location.exists() assert self.tmp_path / "testing.sqlite" == self.scan.db_mgr.location def test_scan_creates_results(self): self.scan.results_subfolder = subjack_results self.scan.output_file = self.scan.results_subfolder / "subjack.txt" self.scan.parse_results() assert self.scan.output().exists() def test_parse_results(self): myresults = self.tmp_path / "subjack-results" / "subjack.txt" myresults.parent.mkdir(parents=True, exist_ok=True) content = "[Not Vulnerable] email.assetinventory.bugcrowd.com\n" content += "[Vulnerable] email.assetinventory.bugcrowd.com\n" content += "[Vulnerable] assetinventory.bugcrowd.com:8080\n" content += "weird input\n" myresults.write_text(content) self.scan.output_file = myresults self.scan.db_mgr.get_or_create_target_by_ip_or_hostname = MagicMock() self.scan.db_mgr.get_or_create_target_by_ip_or_hostname.return_value = MagicMock() self.scan.db_mgr.add = MagicMock() self.scan.parse_results() assert self.scan.output().exists() assert self.scan.db_mgr.add.called assert self.scan.db_mgr.get_or_create_target_by_ip_or_hostname.called @pytest.mark.parametrize("test_input", [["google.com"], None]) def test_scan_run(self, test_input): with patch("subprocess.run") as mocked_run: self.scan.parse_results = MagicMock() self.scan.db_mgr.get_all_hostnames = MagicMock() self.scan.db_mgr.get_all_hostnames.return_value = test_input self.scan.run() if test_input is None: assert not mocked_run.called assert not self.scan.parse_results.called else: assert mocked_run.called assert self.scan.parse_results.called <file_sep>[pytest] filterwarnings = ignore::DeprecationWarning:luigi.*:<file_sep>============== recon-pipeline ============== ``recon-pipeline`` was designed to chain together multiple security tools as part of a Flow-Based Programming paradigm. Each component is part of a network of "black box" processes. These components exchange data between each other and can be reconnected in different ways to form different applications without any internal changes. Getting Started =============== .. include:: overview/summary.rst .. toctree:: :maxdepth: 2 :hidden: overview/index Personalization =============== .. toctree:: :maxdepth: 1 How to personalize the pipeline <modifications/index> API Reference ============= .. toctree:: :maxdepth: 2 api/commands api/manager api/models api/parsers api/scanners Indices and tables ================== * :ref:`genindex` * :ref:`search` <file_sep>from sqlalchemy.orm import relationship from sqlalchemy import Column, Integer, ForeignKey, String from .base_model import Base from .header_model import header_association_table class Endpoint(Base): """ Database model that describes a URL/endpoint. Represents gobuster data. Relationships: ``target``: many to one -> :class:`pipeline.models.target_model.Target` ``headers``: many to many -> :class:`pipeline.models.header_model.Header` """ __tablename__ = "endpoint" id = Column(Integer, primary_key=True) url = Column(String, unique=True) status_code = Column(Integer) target_id = Column(Integer, ForeignKey("target.id")) target = relationship("Target", back_populates="endpoints") headers = relationship("Header", secondary=header_association_table, back_populates="endpoints") <file_sep>import textwrap from pathlib import Path from sqlalchemy.orm import relationship from sqlalchemy import Column, Integer, ForeignKey, String from .base_model import Base class SearchsploitResult(Base): """ Database model that describes results from running searchsploit --nmap TARGET.xml. Represents searchsploit data. Relationships: ``target``: many to one -> :class:`pipeline.models.target_model.Target` """ __tablename__ = "searchsploit_result" def __str__(self): return self.pretty() def pretty(self, fullpath=False): pad = " " type_padlen = 8 filename_padlen = 9 if not fullpath: filename = Path(self.path).name msg = f"{pad}{self.type:<{type_padlen}} | {filename:<{filename_padlen}}" for i, line in enumerate(textwrap.wrap(self.title)): if i > 0: msg += f"{' ' * (type_padlen + filename_padlen + 5)}|{pad * 2}{line}\n" else: msg += f"|{pad}{line}\n" msg = msg[:-1] # remove last newline else: msg = f"{pad}{self.type:<{type_padlen}}" for i, line in enumerate(textwrap.wrap(self.title)): if i > 0: msg += f"{' ' * (type_padlen + 2)}|{pad * 2}{line}\n" else: msg += f"|{pad}{line}\n" msg += f"{' ' * (type_padlen + 2)}|{pad}{self.path}" return msg id = Column(Integer, primary_key=True) title = Column(String, unique=True) path = Column(String) type = Column(String) target_id = Column(Integer, ForeignKey("target.id")) target = relationship("Target", back_populates="searchsploit_results") <file_sep>from sqlalchemy.orm import relationship from sqlalchemy import Column, Integer, ForeignKey, String, UniqueConstraint, Table from .base_model import Base header_association_table = Table( "header_association", Base.metadata, Column("header_id", Integer, ForeignKey("header.id")), Column("endpoint_id", Integer, ForeignKey("endpoint.id")), ) class Header(Base): """ Database model that describes an http header (i.e. Server=cloudflare). Relationships: ``endpoints``: many to many -> :class:`pipeline.models.target_model.Endpoint` """ __tablename__ = "header" __table_args__ = (UniqueConstraint("name", "value"),) # combination of name/value == unique id = Column(Integer, primary_key=True) name = Column(String) value = Column(String) endpoint_id = Column(Integer, ForeignKey("endpoint.id")) endpoints = relationship("Endpoint", secondary=header_association_table, back_populates="headers") <file_sep>import os import logging import subprocess from pathlib import Path from urllib.parse import urlparse from concurrent.futures import ThreadPoolExecutor import luigi from luigi.util import inherits from luigi.contrib.sqla import SQLAlchemyTarget import pipeline.models.db_manager from ...tools import tools from ..config import defaults from ..helpers import meets_requirements from .targets import GatherWebTargets from ...models.endpoint_model import Endpoint from ..helpers import get_ip_address_version, is_ip_address @inherits(GatherWebTargets) class GobusterScan(luigi.Task): """ Use ``gobuster`` to perform forced browsing. Install: .. code-block:: console go get github.com/OJ/gobuster git clone https://github.com/epi052/recursive-gobuster.git Basic Example: .. code-block:: console gobuster dir -q -e -k -t 20 -u www.tesla.com -w /usr/share/seclists/Discovery/Web-Content/common.txt -p http://127.0.0.1:8080 -o gobuster.tesla.txt -x php,html Luigi Example: .. code-block:: console PYTHONPATH=$(pwd) luigi --local-scheduler --module recon.web.gobuster GobusterScan --target-file tesla --top-ports 1000 --interface eth0 --proxy http://127.0.0.1:8080 --extensions php,html --wordlist /usr/share/seclists/Discovery/Web-Content/common.txt --threads 20 Args: threads: number of threads for parallel gobuster command execution wordlist: wordlist used for forced browsing extensions: additional extensions to apply to each item in the wordlist recursive: whether or not to recursively gobust the target (may produce a LOT of traffic... quickly) proxy: protocol://ip:port proxy specification for gobuster exempt_list: Path to a file providing blacklisted subdomains, one per line. *Optional by upstream Task* db_location: specifies the path to the database used for storing results *Required by upstream Task* top_ports: Scan top N most popular ports *Required by upstream Task* ports: specifies the port(s) to be scanned *Required by upstream Task* interface: use the named raw network interface, such as "eth0" *Required by upstream Task* rate: desired rate for transmitting packets (packets per second) *Required by upstream Task* target_file: specifies the file on disk containing a list of ips or domains *Required by upstream Task* results_dir: specifes the directory on disk to which all Task results are written *Required by upstream Task* """ recursive = luigi.BoolParameter(default=False) proxy = luigi.Parameter(default=defaults.get("proxy")) threads = luigi.Parameter(default=defaults.get("threads")) wordlist = luigi.Parameter(default=defaults.get("gobuster-wordlist")) extensions = luigi.Parameter(default=defaults.get("gobuster-extensions")) requirements = ["recursive-gobuster", "go", "gobuster", "masscan"] exception = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.db_mgr = pipeline.models.db_manager.DBManager(db_location=self.db_location) self.results_subfolder = Path(self.results_dir) / "gobuster-results" def requires(self): """ GobusterScan depends on GatherWebTargets to run. GatherWebTargets accepts exempt_list and expects rate, target_file, interface, and either ports or top_ports as parameters Returns: luigi.Task - GatherWebTargets """ meets_requirements(self.requirements, self.exception) args = { "results_dir": self.results_dir, "rate": self.rate, "target_file": self.target_file, "top_ports": self.top_ports, "interface": self.interface, "ports": self.ports, "exempt_list": self.exempt_list, "db_location": self.db_location, } return GatherWebTargets(**args) def output(self): """ Returns the target output for this task. If recursion is disabled, the naming convention for the output file is gobuster.TARGET_FILE.txt Otherwise the output file is recursive-gobuster_TARGET_FILE.log Results are stored in their own directory: gobuster-TARGET_FILE-results Returns: luigi.local_target.LocalTarget """ return SQLAlchemyTarget( connection_string=self.db_mgr.connection_string, target_table="endpoint", update_id=self.task_id ) def parse_results(self): """ Reads in each individual gobuster file and adds each line to the database as an Endpoint """ for file in self.results_subfolder.iterdir(): tgt = None for i, line in enumerate(file.read_text().splitlines()): url, status = line.split(maxsplit=1) # http://somewhere/path (Status:200) if i == 0: # parse first entry to determine ip address -> target relationship parsed_url = urlparse(url) tgt = self.db_mgr.get_or_create_target_by_ip_or_hostname(parsed_url.hostname) if tgt is not None: status_code = status.split(maxsplit=1)[1] ep = self.db_mgr.get_or_create(Endpoint, url=url, status_code=status_code.replace(")", "")) if ep not in tgt.endpoints: tgt.endpoints.append(ep) self.db_mgr.add(tgt) self.output().touch() def run(self): """ Defines the options/arguments sent to gobuster after processing. Returns: list: list of options/arguments, beginning with the name of the executable to run """ try: self.threads = abs(int(self.threads)) except (TypeError, ValueError): return logging.error("The value supplied to --threads must be a non-negative integer.") commands = list() for target in self.db_mgr.get_all_web_targets(): if is_ip_address(target) and get_ip_address_version(target) == "6": target = f"[{target}]" for url_scheme in ("https://", "http://"): if self.recursive: command = [ tools.get("recursive-gobuster").get("path"), "-s", "-w", self.wordlist, f"{url_scheme}{target}", ] else: command = [ tools.get("gobuster").get("path"), "dir", "-q", "-e", "-k", "-u", f"{url_scheme}{target}", "-w", self.wordlist, "-o", self.results_subfolder.joinpath( f"gobuster.{url_scheme.replace('//', '_').replace(':', '')}{target}.txt" ), ] if self.extensions: command.extend(["-x", self.extensions]) if self.proxy: command.extend(["-p", self.proxy]) commands.append(command) self.results_subfolder.mkdir(parents=True, exist_ok=True) if self.recursive: # workaround for recursive gobuster not accepting output directory cwd = Path().cwd() os.chdir(self.results_subfolder) with ThreadPoolExecutor(max_workers=self.threads) as executor: executor.map(subprocess.run, commands) if self.recursive: os.chdir(str(cwd)) self.parse_results() <file_sep># Automated Reconnaissance Pipeline ![version](https://img.shields.io/github/v/release/epi052/recon-pipeline?style=for-the-badge) ![Python application](https://img.shields.io/github/workflow/status/epi052/recon-pipeline/recon-pipeline%20build?style=for-the-badge) ![code coverage](https://img.shields.io/badge/coverage-97%25-blue?style=for-the-badge) ![python](https://img.shields.io/badge/python-3.7-informational?style=for-the-badge) ![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge) There are an [accompanying set of blog posts](https://epi052.gitlab.io/notes-to-self/blog/2019-09-01-how-to-build-an-automated-recon-pipeline-with-python-and-luigi/) detailing the development process and underpinnings of the pipeline. Feel free to check them out if you're so inclined, but they're in no way required reading to use the tool. Check out [recon-pipeline's readthedocs entry](https://recon-pipeline.readthedocs.io/) for some more in depth information than what this README provides. Table of Contents ----------------- - [Installation](#installation) - [Defining Scope](#defining-a-scans-scope) - [Example Scan](#example-scan) - [Existing Results Directories](#existing-results-directories) - [Viewing Results](#viewing-results) - [Chaining Results w/ Commands](#chaining-results-w-commands) - [Choosing a Scheduler](#choosing-a-scheduler) - [Found a Bug?](#found-a-bug) - [Special Thanks](#special-thanks) ## Installation > Automatic installation tested on kali 2019.4 and Ubuntu 18.04/20.04 There are two primary phases for installation: 1. prior to the python dependencies being installed 2. everything else First, the manual steps to get dependencies installed in a virtual environment are as follows, starting with [pipenv](https://github.com/pypa/pipenv) ### Kali ```bash sudo apt update sudo apt install pipenv ``` ### Ubuntu 18.04/20.04 ```bash sudo apt update sudo apt install python3-pip pip install --user pipenv echo "PATH=${PATH}:~/.local/bin" >> ~/.bashrc bash ``` ### Both OSs after pipenv install ```bash git clone https://github.com/epi052/recon-pipeline.git cd recon-pipeline pipenv install pipenv shell ``` ### Docker If you have Docker installed, you can run the recon-pipeline in a container with the following commands: ```bash git clone https://github.com/epi052/recon-pipeline.git cd recon-pipeline docker build -t recon-pipeline . docker run -d \ -v ~/docker/recon-pipeline:/root/.local/recon-pipeline \ -p 8082:8082 \ --name recon-pipeline \ recon-pipeline docker start recon-pipeline docker exec -it recon-pipeline pipeline ``` The `recon-pipeline` should start in the background automatically after the `docker run` command, however, you will have to start it after a reboot. For more information, please see the [Docker](https://recon-pipeline.readthedocs.io/en/latest/overview/installation.html#docker) docs. [![asciicast](https://asciinema.org/a/318395.svg)](https://asciinema.org/a/318395) After installing the python dependencies, the `recon-pipeline` shell provides its own [tools](https://recon-pipeline.readthedocs.io/en/latest/api/commands.html#tools) command (seen below). A simple `tools install all` will handle all additional installation steps. > Ubuntu Note (and newer kali versions): You may consider running `sudo -v` prior to running `./recon-pipeline.py`. `sudo -v` will refresh your creds, and the underlying subprocess calls during installation won't prompt you for your password. It'll work either way though. Individual tools may be installed by running `tools install TOOLNAME` where `TOOLNAME` is one of the known tools that make up the pipeline. The installer does not maintain state. In order to determine whether a tool is installed or not, it checks the `path` variable defined in the tool's .yaml file. The installer in no way attempts to be a package manager. It knows how to execute the steps necessary to install and remove its tools. Beyond that, it's like Jon Snow, **it knows nothing**. [![asciicast](https://asciinema.org/a/343745.svg)](https://asciinema.org/a/343745) ## Defining a Scan's Scope **New as of v0.9.0**: In the event you're scanning a single ip address or host, simply use `--target`. It accepts a single target and works in conjunction with `--exempt-list` if specified. ```text scan HTBScan --target 10.10.10.183 --top-ports 1000 ``` In order to scan more than one host at a time, the pipeline needs a file that describes the target's scope to be provided as an argument to the `--target-file` option. The target file can consist of domains, ip addresses, and ip ranges, one per line. ```text tesla.com tesla.cn teslamotors.com ... ``` Some bug bounty scopes have expressly verboten subdomains and/or top-level domains, for that there is the `--exempt-list` option. The exempt list follows the same rules as the target file. ```text shop.eu.teslamotors.com energysupport.tesla.com feedback.tesla.com ... ``` ## Example Scan Here are the steps the video below takes to scan tesla.com. Create a targetfile ```bash # use virtual environment pipenv shell # create targetfile; a targetfile is required for all scans mkdir /root/bugcrowd/tesla cd /root/bugcrowd/tesla echo tesla.com > tesla-targetfile # create a blacklist (if necessary based on target's scope) echo energysupport.tesla.com > tesla-blacklist echo feedback.tesla.com >> tesla-blacklist echo employeefeedback.tesla.com >> tesla-blacklist echo ir.tesla.com >> tesla-blacklist # drop into the interactive shell /root/PycharmProjects/recon-pipeline/pipeline/recon-pipeline.py recon-pipeline> ``` Create a new database to store scan results ```bash recon-pipeline> database attach 1. create new database Your choice? 1 new database name? (recommend something unique for this target) -> tesla-scan [*] created database @ /home/epi/.local/recon-pipeline/databases/tesla-scan [+] attached to sqlite database @ /home/epi/.local/recon-pipeline/databases/tesla-scan [db-1] recon-pipeline> ``` Scan the target ```bash [db-1] recon-pipeline> scan FullScan --exempt-list tesla-blacklist --target-file tesla-targetfile --interface eno1 --top-ports 2000 --rate 1200 [-] FullScan queued [-] TKOSubsScan queued [-] GatherWebTargets queued [-] ParseAmassOutput queued [-] AmassScan queued [-] ParseMasscanOutput queued [-] MasscanScan queued [-] WebanalyzeScan queued [-] SearchsploitScan queued [-] ThreadedNmapScan queued [-] SubjackScan queued [-] WaybackurlsScan queued [-] AquatoneScan queued [-] GobusterScan queued [db-1] recon-pipeline> ``` The same steps can be seen in realtime in the linked video below. [![asciicast](https://asciinema.org/a/318397.svg)](https://asciinema.org/a/318397) ### Existing Results Directories When running additional scans against the same target, you have a few options. You can either - use a new directory - reuse the same directory If you use a new directory, the scan will start from the beginning. If you choose to reuse the same directory, `recon-pipeline` will resume the scan from its last successful point. For instance, say your last scan failed while running nmap. This means that the pipeline executed all upstream tasks (amass and masscan) successfully. When you use the same results directory for another scan, the amass and masscan scans will be skipped, because they've already run successfully. **Note**: There is a gotcha that can occur when you scan a target but get no results. For some scans, the pipeline may still mark the Task as complete (masscan does this). In masscan's case, it's because it outputs a file to `results-dir/masscan-results/` whether it gets results or not. Luigi interprets the file's presence to mean the scan is complete. In order to reduce confusion, as of version 0.9.3, the pipeline will prompt you when reusing results directory. ``` [db-2] recon-pipeline> scan FullScan --results-dir testing-results --top-ports 1000 --rate 500 --target tesla.com [*] Your results-dir (testing-results) already exists. Subfolders/files may tell the pipeline that the associated Task is complete. This means that your scan may start from a point you don't expect. Your options are as follows: 1. Resume existing scan (use any existing scan data & only attempt to scan what isn't already done) 2. Remove existing directory (scan starts from the beginning & all existing results are removed) 3. Save existing directory (your existing folder is renamed and your scan proceeds) Your choice? ``` ## Viewing Results As of version 0.9.0, scan results are stored in a database located (by default) at `~/.local/recon-pipeline/databases`. Databases themselves are managed through the [database command](https://recon-pipeline.readthedocs.io/en/latest/api/commands.html#database) while viewing their contents is done via [view command](https://recon-pipeline.readthedocs.io/en/latest/api/commands.html#view-command). The view command allows one to inspect different pieces of scan information via the following sub-commands - endpoints (gobuster results) - nmap-scans - ports - searchsploit-results - targets - web-technologies (webanalyze results) Each of the sub-commands has a list of tab-completable options and values that can help drilling down to the data you care about. All of the subcommands offer a `--paged` option for dealing with large amounts of output. `--paged` will show you one page of output at a time (using `less` under the hood). A few examples of different view commands are shown below. [![asciicast](https://asciinema.org/a/KtiV1ihl16DLyYpapyrmjIplk.svg)](https://asciinema.org/a/KtiV1ihl16DLyYpapyrmjIplk) ## Chaining Results w/ Commands All of the results can be **piped out to other commands**. Let’s say you want to feed some results from recon-pipeline into another tool that isn’t part of the pipeline. Simply using a normal unix pipe `|` followed by the next command will get that done for you. Below is an example of piping targets into [gau](https://github.com/lc/gau) ```text [db-2] recon-pipeline> view targets --paged 3.tesla.cn 3.tesla.com api-internal.sn.tesla.services api-toolbox.tesla.com api.mp.tesla.services api.sn.tesla.services api.tesla.cn api.toolbox.tb.tesla.services ... [db-2] recon-pipeline> view targets | gau https://3.tesla.com/pt_PT/model3/design https://3.tesla.com/pt_PT/model3/design?redirect=no https://3.tesla.com/robots.txt https://3.tesla.com/sites/all/themes/custom/tesla_theme/assets/img/icons/favicon-160x160.png?2 https://3.tesla.com/sites/all/themes/custom/tesla_theme/assets/img/icons/favicon-16x16.png?2 https://3.tesla.com/sites/all/themes/custom/tesla_theme/assets/img/icons/favicon-196x196.png?2 https://3.tesla.com/sites/all/themes/custom/tesla_theme/assets/img/icons/favicon-32x32.png?2 https://3.tesla.com/sites/all/themes/custom/tesla_theme/assets/img/icons/favicon-96x96.png?2 https://3.tesla.com/sv_SE/model3/design ... ``` For more examples of view, please see the [documentation](https://recon-pipeline.readthedocs.io/en/latest/overview/viewing_results.html#). ## Choosing a Scheduler The backbone of this pipeline is spotify's [luigi](https://github.com/spotify/luigi) batch process management framework. Luigi uses the concept of a scheduler in order to manage task execution. Two types of scheduler are available, a local scheduler and a central scheduler. The local scheduler is useful for development and debugging while the central scheduler provides the following two benefits: - Make sure two instances of the same task are not running simultaneously - Provide visualization of everything that’s going on While in the `recon-pipeline` shell, running `tools install luigi-service` will copy the `luigid.service` file provided in the repo to its appropriate systemd location and start/enable the service. The result is that the central scheduler is up and running easily. The other option is to add `--local-scheduler` to your `scan` command from within the `recon-pipeline` shell. ## Found a bug? <!-- this section is a modified version of what's used by the awesome guys that wrote cmd2 --> If you think you've found a bug, please first read through the open [Issues](https://github.com/epi052/recon-pipeline/issues). If you're confident it's a new bug, go ahead and create a new GitHub issue. Be sure to include as much information as possible so we can reproduce the bug. At a minimum, please state the following: * ``recon-pipeline`` version * Python version * OS name and version * How to reproduce the bug * Include any traceback or error message associated with the bug ## Special Thanks - [@aringo](https://github.com/aringo) for his help on the precursor to this tool - [@kernelsndrs](https://github.com/kernelsndrs) for identifying a few bugs after initial launch - [@GreaterGoodest](https://github.com/GreaterGoodest) for identifying bugs and the project's first PR! - The [cmd2](https://github.com/python-cmd2/cmd2) team for a lot of inspiration for project layout and documentation <file_sep>FROM python:latest ENV LC_ALL=C.UTF-8 \ LANG=C.UTF-8 # 8082 is the default port for luigi EXPOSE 8082 # Copy in required files COPY pipeline /opt/recon-pipeline/pipeline COPY Pipfile* /opt/recon-pipeline/ COPY luigid.service /opt/recon-pipeline/ # Install dependencies WORKDIR /opt/recon-pipeline/ RUN pip3 install pipenv && \ pipenv install --system --deploy && \ apt update && \ apt install -y chromium less nmap sudo vim # Setup Workarounds # systemctl because systemd is required for luigid setup and is more trouble than it is worth # Moving because default location causes issues with `tools install all` # Symbolic link to more easily enter with `docker exec` # Default interface for Docker Container should be eth0 RUN touch /usr/bin/systemctl && \ chmod 755 /usr/bin/systemctl && \ mv /usr/local/bin/luigid /bin/luigid && \ ln -s /opt/recon-pipeline/pipeline/recon-pipeline.py /bin/pipeline && \ sed -i 's/tun0/eth0/g' /opt/recon-pipeline/pipeline/recon/config.py # Run luigi WORKDIR /root/.local/recon-pipeline/files CMD ["/bin/luigid", "--pidfile", "/var/run/luigid.pid", "--logdir", "/var/log"] <file_sep>import subprocess from pathlib import Path from urllib.parse import urlparse import luigi from luigi.util import inherits from luigi.contrib.sqla import SQLAlchemyTarget from .targets import GatherWebTargets from ...tools import tools from ..helpers import meets_requirements from ...models.endpoint_model import Endpoint import pipeline.models.db_manager @inherits(GatherWebTargets) class WaybackurlsScan(luigi.Task): """ Fetch known URLs from the Wayback Machine, Common Crawl, and Virus Total for historic data about the target. Install: .. code-block:: console go get github.com/tomnomnom/waybackurls Basic Example: ``waybackurls`` commands are structured like the example below. ``cat domains.txt | waybackurls > urls`` Luigi Example: .. code-block:: python PYTHONPATH=$(pwd) luigi --local-scheduler --module recon.web.waybackurls WaybackurlsScan --target-file tesla --top-ports 1000 Args: db_location: specifies the path to the database used for storing results *Required by upstream Task* exempt_list: Path to a file providing blacklisted subdomains, one per line. *Optional by upstream Task* top_ports: Scan top N most popular ports *Required by upstream Task* ports: specifies the port(s) to be scanned *Required by upstream Task* interface: use the named raw network interface, such as "eth0" *Required by upstream Task* rate: desired rate for transmitting packets (packets per second) *Required by upstream Task* target_file: specifies the file on disk containing a list of ips or domains *Required by upstream Task* results_dir: specifes the directory on disk to which all Task results are written *Required by upstream Task* """ requirements = ["go", "waybackurls", "masscan"] exception = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.db_mgr = pipeline.models.db_manager.DBManager(db_location=self.db_location) self.results_subfolder = Path(self.results_dir) / "waybackurls-results" def requires(self): """ WaybackurlsScan depends on GatherWebTargets to run. GatherWebTargets accepts exempt_list and expects rate, target_file, interface, and either ports or top_ports as parameters Returns: luigi.Task - GatherWebTargets """ meets_requirements(self.requirements, self.exception) args = { "results_dir": self.results_dir, "rate": self.rate, "target_file": self.target_file, "top_ports": self.top_ports, "interface": self.interface, "ports": self.ports, "exempt_list": self.exempt_list, "db_location": self.db_location, } return GatherWebTargets(**args) def output(self): """ Returns the target output for this task. Returns: luigi.contrib.sqla.SQLAlchemyTarget """ return SQLAlchemyTarget( connection_string=self.db_mgr.connection_string, target_table="endpoint", update_id=self.task_id ) def run(self): """ Defines the options/arguments sent to waybackurls after processing. """ self.results_subfolder.mkdir(parents=True, exist_ok=True) command = [tools.get("waybackurls").get("path")] waybackurls_input_file = self.results_subfolder / "input-from-webtargets" with open(waybackurls_input_file, "w") as f: for target in self.db_mgr.get_all_hostnames(): f.write(f"{target}\n") with open(waybackurls_input_file) as target_list: proc = subprocess.run(command, stdin=target_list, stdout=subprocess.PIPE) for url in proc.stdout.decode().splitlines(): if not url: continue parsed_url = urlparse(url) # get Target, may exist already or not ip_or_hostname = parsed_url.hostname tgt = self.db_mgr.get_or_create_target_by_ip_or_hostname(ip_or_hostname) endpoint = self.db_mgr.get_or_create(Endpoint, url=url, target=tgt) if endpoint not in tgt.endpoints: tgt.endpoints.append(endpoint) self.db_mgr.add(tgt) self.db_mgr.add(endpoint) self.output().touch() waybackurls_input_file.unlink() <file_sep>import os import pickle import shutil import tempfile import importlib import subprocess from pathlib import Path import pytest from tests import utils recon_pipeline = importlib.import_module("pipeline.recon-pipeline") tools = recon_pipeline.tools class TestUnmockedToolsInstall: def setup_method(self): self.shell = recon_pipeline.ReconShell() self.tmp_path = Path(tempfile.mkdtemp()) self.shell.tools_dir = self.tmp_path / ".local" / "recon-pipeline" / "tools" self.shell.tools_dir.mkdir(parents=True, exist_ok=True) os.chdir(self.shell.tools_dir) def teardown_method(self): def onerror(func, path, exc_info): subprocess.run(f"sudo rm -rf {self.shell.tools_dir}".split()) shutil.rmtree(self.tmp_path, onerror=onerror) def perform_add_remove(self, tools_dict, tool_name, install, exists): if install: pickle.dump(tools_dict, Path(self.shell.tools_dir / ".tool-dict.pkl").open("wb")) tool = Path(tools_dict.get(tool_name).get("path")) if install and exists is False: assert tool.exists() is False elif not install and exists is True: assert tool.exists() is True if install: utils.run_cmd(self.shell, f"tools install {tool_name}") assert tool.exists() is True else: utils.run_cmd(self.shell, f"tools uninstall {tool_name}") assert tool.exists() is False def setup_go_test(self, tool_name, tool_dict): # install go in tmp location dependency = "go" dependency_path = f"{self.shell.tools_dir}/go/bin/go" tmp_path = tempfile.mkdtemp() go_download = tool_dict.get(dependency).get("install_commands")[0].split() go_download[4] = f"{tmp_path}/go.tar.gz" go_download = " ".join(go_download) tool_dict.get(dependency)["path"] = dependency_path tool_dict.get(dependency).get("install_commands")[0] = go_download tool_dict.get(dependency).get("install_commands")[ 1 ] = f"tar -C {self.shell.tools_dir} -xvf {tmp_path}/go.tar.gz" tool_dict.get(dependency).get("uninstall_commands")[0] = f"rm -rvf {self.shell.tools_dir}/go" tool_dict[dependency]["uninstall_commands"].append(f"rm -rvf {tmp_path}") # handle env for local go install if tool_name != "go": tmp_go_path = f"{self.shell.tools_dir}/mygo" Path(tmp_go_path).mkdir(parents=True, exist_ok=True) tool_dict.get(tool_name)["environ"]["GOPATH"] = tmp_go_path tool_path = f"{tool_dict.get(tool_name).get('environ').get('GOPATH')}/bin/{tool_name}" tool_dict.get(tool_name)["path"] = tool_path tool_dict.get(tool_name)["installed"] = False tool_dict.get(dependency)["installed"] = False print(tool_dict.get(tool_name)) print(tool_dict.get(dependency)) return tool_dict def test_install_masscan(self): tool = "masscan" tools_copy = tools.copy() tmp_path = tempfile.mkdtemp() tool_path = f"{self.shell.tools_dir}/{tool}" tools_copy.get(tool)["path"] = tool_path tools_copy.get(tool)["installed"] = False tools_copy.get(tool).get("install_commands")[ 0 ] = f"git clone https://github.com/robertdavidgraham/masscan {tmp_path}/masscan" tools_copy.get(tool).get("install_commands")[1] = f"make -s -j -C {tmp_path}/masscan" tools_copy.get(tool).get("install_commands")[2] = f"mv {tmp_path}/masscan/bin/masscan {tool_path}" tools_copy.get(tool).get("install_commands")[3] = f"rm -rf {tmp_path}/masscan" tools_copy.get(tool).get("install_commands")[4] = f"sudo setcap CAP_NET_RAW+ep {tool_path}" tools_copy.get(tool).get("uninstall_commands")[0] = f"rm {tool_path}" self.perform_add_remove(tools_copy, tool, True, False) self.perform_add_remove(tools_copy, tool, False, True) def test_install_amass(self): tool = "amass" url = "github.com/OWASP/Amass/v3/..." tools_copy = tools.copy() tool_path = f"{self.shell.tools_dir}/mygo/bin/amass" tools_copy.update(self.setup_go_test(tool, tools_copy)) tools_copy.get(tool).get("install_commands")[0] = f"{tools_copy.get('go').get('path')} get {url}" tools_copy.get(tool).get("uninstall_commands")[0] = f"rm {tool_path}" self.perform_add_remove(tools_copy, tool, True, False) self.perform_add_remove(tools_copy, tool, False, True) def test_install_aquatone(self): tool = "aquatone" tools_copy = tools.copy() tool_path = f"{self.shell.tools_dir}/{tool}" tmp_path = tempfile.mkdtemp() tools_copy.get(tool)["path"] = tool_path tools_copy.get(tool).get("install_commands")[0] = f"mkdir /{tmp_path}/aquatone" tools_copy.get(tool).get("install_commands")[ 1 ] = f"wget -q https://github.com/michenriksen/aquatone/releases/download/v1.7.0/aquatone_linux_amd64_1.7.0.zip -O /{tmp_path}/aquatone/aquatone.zip" tools_copy.get(tool).get("install_commands")[ 3 ] = f"unzip /{tmp_path}/aquatone/aquatone.zip -d /{tmp_path}/aquatone" tools_copy.get(tool).get("install_commands")[4] = f"mv /{tmp_path}/aquatone/aquatone {tool_path}" tools_copy.get(tool).get("install_commands")[5] = f"rm -rf /{tmp_path}/aquatone" tools_copy.get(tool).get("uninstall_commands")[0] = f"rm {tool_path}" self.perform_add_remove(tools_copy, tool, True, False) self.perform_add_remove(tools_copy, tool, False, True) def test_install_go(self): tool = "go" tools_copy = tools.copy() tools_copy.update(self.setup_go_test(tool, tools_copy)) self.perform_add_remove(tools_copy, tool, True, False) self.perform_add_remove(tools_copy, tool, False, True) def test_install_gobuster(self): tool = "gobuster" dependency = "go" tools_copy = tools.copy() tool_path = f"{self.shell.tools_dir}/mygo/bin/gobuster" tools_copy.update(self.setup_go_test(tool, tools_copy)) tools_copy.get(tool)["dependencies"] = [dependency] tools_copy.get(tool).get("install_commands")[ 0 ] = f"{tools_copy.get(dependency).get('path')} get github.com/OJ/gobuster" tools_copy.get(tool).get("uninstall_commands")[0] = f"rm {tool_path}" self.perform_add_remove(tools_copy, tool, True, False) self.perform_add_remove(tools_copy, tool, False, True) def pause_luigi(self): proc = subprocess.run("systemctl is-enabled luigid.service".split(), stdout=subprocess.PIPE) if proc.stdout.decode().strip() == "enabled": subprocess.run("sudo systemctl disable luigid.service".split()) proc = subprocess.run("systemctl is-active luigid.service".split(), stdout=subprocess.PIPE) if proc.stdout.decode().strip() == "active": subprocess.run("sudo systemctl stop luigid.service".split()) def test_install_luigi_service(self): luigi_service = Path("/lib/systemd/system/luigid.service") self.pause_luigi() if luigi_service.exists(): subprocess.run(f"sudo rm {luigi_service}".split()) tools_copy = tools.copy() pickle.dump(tools_copy, Path(self.shell.tools_dir / ".tool-dict.pkl").open("wb")) if Path("/usr/local/bin/luigid").exists(): subprocess.run("sudo rm /usr/local/bin/luigid".split()) assert ( subprocess.run("systemctl is-enabled luigid.service".split(), stdout=subprocess.PIPE) .stdout.decode() .strip() != "enabled" ) assert ( subprocess.run("systemctl is-active luigid.service".split(), stdout=subprocess.PIPE).stdout.decode().strip() != "active" ) assert not Path("/usr/local/bin/luigid").exists() utils.run_cmd(self.shell, "tools install luigi-service") assert Path("/lib/systemd/system/luigid.service").exists() proc = subprocess.run("systemctl is-enabled luigid.service".split(), stdout=subprocess.PIPE) assert proc.stdout.decode().strip() == "enabled" proc = subprocess.run("systemctl is-active luigid.service".split(), stdout=subprocess.PIPE) assert proc.stdout.decode().strip() == "active" assert Path("/usr/local/bin/luigid").exists() utils.run_cmd(self.shell, "tools uninstall luigi-service") proc = subprocess.run("systemctl is-enabled luigid.service".split(), stdout=subprocess.PIPE) assert proc.stdout.decode().strip() != "enabled" proc = subprocess.run("systemctl is-active luigid.service".split(), stdout=subprocess.PIPE) assert proc.stdout.decode().strip() != "active" assert luigi_service.exists() is False @pytest.mark.parametrize("test_input", ["install", "update"]) def test_install_recursive_gobuster(self, test_input): tool = "recursive-gobuster" tools_copy = tools.copy() parent = f"{self.shell.tools_dir}/{tool}" tool_path = f"{parent}/recursive-gobuster.pyz" if test_input == "update": subprocess.run(f"git clone https://github.com/epi052/recursive-gobuster.git {parent}".split()) tools_copy.get(tool)["path"] = tool_path tools_copy.get(tool)["dependencies"] = None tools_copy.get(tool).get("install_commands")[0] = f"bash -c 'if [ -d {parent} ]; " tools_copy.get(tool).get("install_commands")[0] += f"then cd {parent} && git fetch --all && git pull; " tools_copy.get(tool).get("install_commands")[ 0 ] += "else git clone https://github.com/epi052/recursive-gobuster.git " tools_copy.get(tool).get("install_commands")[0] += f"{parent} ; fi'" tools_copy.get(tool).get("uninstall_commands")[0] = f"sudo rm -r {parent}" if test_input == "update": self.perform_add_remove(tools_copy, tool, True, True) else: self.perform_add_remove(tools_copy, tool, True, False) self.perform_add_remove(tools_copy, tool, False, True) @pytest.mark.parametrize("test_input", ["install", "update"]) def test_install_searchsploit(self, test_input): tool = "searchsploit" tools_copy = tools.copy() home_path = f"{self.shell.tools_dir}/home" Path(home_path).mkdir(parents=True, exist_ok=True) copied_searchsploit_rc = f"{home_path}/.searchsploit_rc" dependency_path = f"{self.shell.tools_dir}/exploitdb" searchsploit_rc_path = f"{dependency_path}/.searchsploit_rc" tool_path = f"{dependency_path}/{tool}" sed_cmd = f"s#/opt#{self.shell.tools_dir}#g" if test_input == "update": subprocess.run(f"git clone https://github.com/offensive-security/exploitdb.git {dependency_path}".split()) tools_copy.get(tool)["path"] = tool_path first_cmd = "bash -c 'if [ -d /usr/share/exploitdb ]; then ln -fs " first_cmd += f"/usr/share/exploitdb {dependency_path} && ln -fs $(which searchsploit) {tool_path}" first_cmd += f"; elif [ -d {dependency_path} ]; then cd {dependency_path} && git fetch --all && git pull; else " first_cmd += f"git clone https://github.com/offensive-security/exploitdb.git {dependency_path}; fi'" tools_copy.get(tool).get("install_commands")[0] = first_cmd tools_copy.get(tool).get("install_commands")[1] = f"bash -c 'if [ -f {searchsploit_rc_path} ]; " tools_copy.get(tool).get("install_commands")[1] += f"then cp -n {searchsploit_rc_path} {home_path} ; fi'" tools_copy.get(tool).get("install_commands")[2] = f"bash -c 'if [ -f {copied_searchsploit_rc} ]; " tools_copy.get(tool).get("install_commands")[2] += f"then sed -i {sed_cmd} {copied_searchsploit_rc}; fi'" tools_copy.get(tool).get("uninstall_commands")[0] = f"sudo rm -r {dependency_path}" pickle.dump(tools_copy, Path(self.shell.tools_dir / ".tool-dict.pkl").open("wb")) if test_input == "install": assert not Path(tool_path).exists() assert not Path(copied_searchsploit_rc).exists() assert not Path(dependency_path).exists() utils.run_cmd(self.shell, f"tools install {tool}") assert subprocess.run(f"grep {self.shell.tools_dir} {copied_searchsploit_rc}".split()).returncode == 0 assert Path(copied_searchsploit_rc).exists() assert Path(dependency_path).exists() utils.run_cmd(self.shell, f"tools uninstall {tool}") assert Path(dependency_path).exists() is False @pytest.mark.parametrize("test_input", ["install", "update"]) def test_install_seclists(self, test_input): tool = "seclists" tools_copy = tools.copy() tool_path = f"{self.shell.tools_dir}/seclists" tools_copy.get(tool)["path"] = tool_path if test_input == "update": subprocess.run(f"git clone https://github.com/danielmiessler/SecLists.git {tool_path}".split()) first_cmd = f"bash -c 'if [ -d /usr/share/seclists ]; then ln -s /usr/share/seclists {tool_path}; elif " first_cmd += f"[[ -d {tool_path} ]] ; then cd {tool_path} && git fetch --all && git pull; " first_cmd += f"else git clone https://github.com/danielmiessler/SecLists.git {tool_path}; fi'" tools_copy.get(tool).get("install_commands")[0] = first_cmd tools_copy.get(tool).get("uninstall_commands")[0] = f"sudo rm -r {tool_path}" if test_input == "update": self.perform_add_remove(tools_copy, tool, True, True) else: self.perform_add_remove(tools_copy, tool, True, False) self.perform_add_remove(tools_copy, tool, False, True) def test_install_subjack(self): tool = "subjack" url = "github.com/haccer/subjack" tools_copy = tools.copy() tool_path = f"{self.shell.tools_dir}/mygo/bin/subjack" tools_copy.update(self.setup_go_test(tool, tools_copy)) tools_copy.get(tool).get("install_commands")[0] = f"{tools_copy.get('go').get('path')} get {url}" tools_copy.get(tool).get("uninstall_commands")[0] = f"rm {tool_path}" self.perform_add_remove(tools_copy, tool, True, False) self.perform_add_remove(tools_copy, tool, False, True) def test_install_tkosubs(self): tool = "tko-subs" url = "github.com/anshumanbh/tko-subs" tools_copy = tools.copy() tool_path = f"{self.shell.tools_dir}/mygo/bin/tko-subs" tools_copy.update(self.setup_go_test(tool, tools_copy)) tools_copy.get(tool).get("install_commands")[0] = f"{tools_copy.get('go').get('path')} get {url}" tools_copy.get(tool).get("uninstall_commands")[0] = f"rm {tool_path}" self.perform_add_remove(tools_copy, tool, True, False) self.perform_add_remove(tools_copy, tool, False, True) def test_install_waybackurls(self): tool = "waybackurls" url = "github.com/tomnomnom/waybackurls" tools_copy = tools.copy() tool_path = f"{self.shell.tools_dir}/mygo/bin/waybackurls" tools_copy.update(self.setup_go_test(tool, tools_copy)) tools_copy.get(tool).get("install_commands")[0] = f"{tools_copy.get('go').get('path')} get {url}" tools_copy.get(tool).get("uninstall_commands")[0] = f"rm {tool_path}" self.perform_add_remove(tools_copy, tool, True, False) self.perform_add_remove(tools_copy, tool, False, True) def test_install_webanalyze(self): tool = "webanalyze" url = "github.com/rverton/webanalyze/..." tools_copy = tools.copy() tool_path = f"{self.shell.tools_dir}/mygo/bin/webanalyze" tools_copy.update(self.setup_go_test(tool, tools_copy)) tools_copy.get(tool).get("install_commands")[0] = f"{tools_copy.get('go').get('path')} get {url}" tools_copy.get(tool).get("uninstall_commands")[0] = f"rm {tool_path}" self.perform_add_remove(tools_copy, tool, True, False) self.perform_add_remove(tools_copy, tool, False, True) <file_sep>import socket import cmd2 from .config import defaults from .helpers import get_scans from ..tools import tools # options for ReconShell's 'status' command status_parser = cmd2.Cmd2ArgumentParser() status_parser.add_argument( "--port", help="port on which the luigi central scheduler's visualization site is running (default: 8082)", default="8082", ) status_parser.add_argument( "--host", help="host on which the luigi central scheduler's visualization site is running (default: localhost)", default="127.0.0.1", ) # options for ReconShell's 'scan' command scan_parser = cmd2.Cmd2ArgumentParser() scan_parser.add_argument("scantype", choices_function=get_scans, help="which type of scan to run") target_group = scan_parser.add_mutually_exclusive_group(required=True) target_group.add_argument( "--target-file", completer_method=cmd2.Cmd.path_complete, help="file created by the user that defines the target's scope; list of ips/domains", ) target_group.add_argument("--target", help="ip or domain to target") scan_parser.add_argument( "--exempt-list", completer_method=cmd2.Cmd.path_complete, help="list of blacklisted ips/domains" ) scan_parser.add_argument( "--results-dir", default=defaults.get("results-dir"), completer_method=cmd2.Cmd.path_complete, help=f"directory in which to save scan results (default: {defaults.get('results-dir')})", ) scan_parser.add_argument( "--wordlist", completer_method=cmd2.Cmd.path_complete, help=f"path to wordlist used by gobuster (default: {defaults.get('gobuster-wordlist')})", ) scan_parser.add_argument( "--interface", choices_function=lambda: [x[1] for x in socket.if_nameindex()], help=f"which interface masscan should use (default: {defaults.get('masscan-iface')})", ) scan_parser.add_argument( "--recursive", action="store_true", help="whether or not to recursively gobust (default: False)", default=False ) scan_parser.add_argument("--rate", help=f"rate at which masscan should scan (default: {defaults.get('masscan-rate')})") port_group = scan_parser.add_mutually_exclusive_group() port_group.add_argument( "--top-ports", help="ports to scan as specified by nmap's list of top-ports (only meaningful to around 5000)", type=int, ) port_group.add_argument("--ports", help="port specification for masscan (all ports example: 1-65535,U:1-65535)") scan_parser.add_argument( "--threads", help=f"number of threads for all of the threaded applications to use (default: {defaults.get('threads')})", ) scan_parser.add_argument( "--scan-timeout", help=f"scan timeout for aquatone (default: {defaults.get('aquatone-scan-timeout')})" ) scan_parser.add_argument("--proxy", help="proxy for gobuster if desired (ex. 127.0.0.1:8080)") scan_parser.add_argument("--extensions", help="list of extensions for gobuster (ex. asp,html,aspx)") scan_parser.add_argument( "--sausage", action="store_true", default=False, help="open a web browser to Luigi's central scheduler's visualization site (see how the sausage is made!)", ) scan_parser.add_argument( "--local-scheduler", action="store_true", help="use the local scheduler instead of the central scheduler (luigid) (default: False)", default=False, ) scan_parser.add_argument( "--verbose", action="store_true", help="shows debug messages from luigi, useful for troubleshooting (default: False)", ) # top level and subparsers for ReconShell's database command database_parser = cmd2.Cmd2ArgumentParser() database_subparsers = database_parser.add_subparsers( title="subcommands", help="Manage database connections (list/attach/detach/delete)" ) db_list_parser = database_subparsers.add_parser("list", help="List all known databases") db_delete_parser = database_subparsers.add_parser("delete", help="Delete the selected database") db_attach_parser = database_subparsers.add_parser("attach", help="Attach to the selected database") db_detach_parser = database_subparsers.add_parser("detach", help="Detach from the currently attached database") # top level and subparsers for ReconShell's tools command tools_parser = cmd2.Cmd2ArgumentParser() tools_subparsers = tools_parser.add_subparsers( title="subcommands", help="Manage tool actions (install/uninstall/reinstall)" ) tools_install_parser = tools_subparsers.add_parser( "install", help="Install any/all of the libraries/tools necessary to make the recon-pipeline function" ) tools_install_parser.add_argument("tool", help="which tool to install", choices=list(tools.keys()) + ["all"]) tools_uninstall_parser = tools_subparsers.add_parser("uninstall", help="Remove the already installed tool") tools_uninstall_parser.add_argument("tool", help="which tool to uninstall", choices=list(tools.keys()) + ["all"]) tools_reinstall_parser = tools_subparsers.add_parser("reinstall", help="Uninstall and then Install a given tool") tools_reinstall_parser.add_argument("tool", help="which tool to reinstall", choices=list(tools.keys()) + ["all"]) tools_list_parser = tools_subparsers.add_parser("list", help="Show status of pipeline tools") # ReconShell's view command view_parser = cmd2.Cmd2ArgumentParser() view_subparsers = view_parser.add_subparsers(title="result types") target_results_parser = view_subparsers.add_parser( "targets", help="List all known targets (ipv4/6 & domain names); produced by amass", conflict_handler="resolve" ) target_results_parser.add_argument( "--vuln-to-subdomain-takeover", action="store_true", default=False, help="show targets identified as vulnerable to subdomain takeover", ) target_results_parser.add_argument("--type", choices=["ipv4", "ipv6", "domain-name"], help="filter by target type") target_results_parser.add_argument( "--paged", action="store_true", default=False, help="display output page-by-page (default: False)" ) technology_results_parser = view_subparsers.add_parser( "web-technologies", help="List all known web technologies identified; produced by webanalyze", conflict_handler="resolve", ) technology_results_parser.add_argument( "--paged", action="store_true", default=False, help="display output page-by-page (default: False)" ) endpoint_results_parser = view_subparsers.add_parser( "endpoints", help="List all known endpoints; produced by gobuster", conflict_handler="resolve" ) endpoint_results_parser.add_argument( "--headers", action="store_true", default=False, help="include headers found at each endpoint (default: False)" ) endpoint_results_parser.add_argument( "--paged", action="store_true", default=False, help="display output page-by-page (default: False)" ) endpoint_results_parser.add_argument( "--plain", action="store_true", default=False, help="display without status-codes/color (default: False)" ) nmap_results_parser = view_subparsers.add_parser( "nmap-scans", help="List all known nmap scan results; produced by nmap", conflict_handler="resolve" ) nmap_results_parser.add_argument( "--paged", action="store_true", default=False, help="display output page-by-page (default: False)" ) nmap_results_parser.add_argument( "--commandline", action="store_true", default=False, help="display command used to scan (default: False)" ) searchsploit_results_parser = view_subparsers.add_parser( "searchsploit-results", help="List all known searchsploit hits; produced by searchsploit", conflict_handler="resolve", ) searchsploit_results_parser.add_argument( "--paged", action="store_true", default=False, help="display output page-by-page (default: False)" ) searchsploit_results_parser.add_argument( "--fullpath", action="store_true", default=False, help="display full path to exploit PoC (default: False)" ) port_results_parser = view_subparsers.add_parser( "ports", help="List all known open ports; produced by masscan", conflict_handler="resolve" ) port_results_parser.add_argument( "--paged", action="store_true", default=False, help="display output page-by-page (default: False)" ) # all options below this line will be updated with a choices option in recon-pipeline.py's # add_dynamic_parser_arguments function. They're included here primarily to ease auto documentation of the commands port_results_parser.add_argument("--host", help="filter results by host") port_results_parser.add_argument("--port-number", help="filter results by port number") endpoint_results_parser.add_argument("--status-code", help="filter results by status code") endpoint_results_parser.add_argument("--host", help="filter results by host") nmap_results_parser.add_argument("--host", help="filter results by host") nmap_results_parser.add_argument("--nse-script", help="filter results by nse script type ran") nmap_results_parser.add_argument("--port", help="filter results by port scanned") nmap_results_parser.add_argument("--product", help="filter results by reported product") technology_results_parser.add_argument("--host", help="filter results by host") technology_results_parser.add_argument("--type", help="filter results by type") technology_results_parser.add_argument("--product", help="filter results by product") searchsploit_results_parser.add_argument("--host", help="filter results by host") searchsploit_results_parser.add_argument("--type", help="filter results by exploit type") <file_sep>import re import sys import time import pickle import shutil import importlib from pathlib import Path from unittest.mock import MagicMock, patch import pytest from pipeline.models.port_model import Port from pipeline.models.target_model import Target from pipeline.models.db_manager import DBManager from pipeline.tools import tools from pipeline.recon.config import defaults from pipeline.models.ip_address_model import IPAddress recon_shell = importlib.import_module("pipeline.recon-pipeline") existing_db = Path(__file__).parent.parent / "data" / "existing-database-test" class TestReconShell: luigi_logs = [ ( "INFO: Informed scheduler that task SearchsploitScan__home_epi__local_bl_eno1_7c290 has status DONE\n", "SearchsploitScan complete!", ), ( "INFO: Informed scheduler that task SearchsploitScan__home_epi__local_bl_eno1_7c290 has status PENDING\n", "SearchsploitScan queued", ), ("", ""), ( "INFO: [pid 31387] Worker Worker(pid=31387) running FullScan(target_file=bitdiscovery\n", "FullScan running...", ), ("===== Luigi Execution Summary =====", "Luigi Execution Summary"), ] def setup_method(self): self.shell = recon_shell.ReconShell() self.shell.async_alert = print self.shell.poutput = print self.db_location = Path(__file__).parent.parent / "data" / "recon-results" / "updated-tests" self.realdb = DBManager(self.db_location) def create_temp_target(self): tgt = Target( hostname="localhost", ip_addresses=[IPAddress(ipv4_address="127.0.0.1"), IPAddress(ipv6_address="::1")], open_ports=[Port(port_number=443, protocol="tcp"), Port(port_number=80, protocol="tcp")], ) return tgt @pytest.mark.parametrize("test_input", ["tools-dir", "database-dir"]) def test_scan_creates_results_dir(self, test_input): assert Path(defaults.get(test_input)).exists() def test_selector_thread_starts(self): self.shell._preloop_hook() assert self.shell.selectorloop.is_alive() def test_selector_thread_stops(self): with patch("selectors.DefaultSelector.select"), patch("selectors.DefaultSelector.get_map"): self.shell._preloop_hook() assert self.shell.selectorloop.is_alive() time.sleep(0.5) self.shell._postloop_hook() time.sleep(1) assert self.shell.selectorloop.stopped() @pytest.mark.parametrize("test_input", ["tools-dir\n", ""]) def test_install_error_reporter(self, test_input, capsys): stderr = MagicMock() stderr.readline.return_value = test_input.encode() self.shell._install_error_reporter(stderr) if not test_input: assert not capsys.readouterr().out else: assert test_input.strip() in capsys.readouterr().out @pytest.mark.parametrize("test_input, expected", luigi_logs) def test_luigi_pretty_printer(self, test_input, expected, capsys): stderr = MagicMock() stderr.readline.return_value = test_input.encode() self.shell._luigi_pretty_printer(stderr) if not test_input: assert not capsys.readouterr().out else: assert expected in capsys.readouterr().out def test_do_scan_without_db(self, capsys): self.shell.do_scan(f"FullScan --target-file {__file__}") assert "You are not connected to a database" in capsys.readouterr().out def test_get_databases(self): testdb = Path(defaults.get("database-dir")) / "testdb6" testdb.touch() assert testdb in list(recon_shell.ReconShell.get_databases()) try: testdb.unlink() except FileNotFoundError: pass def test_database_list_bad(self, capsys): def empty_gen(): yield from () self.shell.get_databases = empty_gen self.shell.database_list("") assert "There are no databases" in capsys.readouterr().out def test_database_attach_new(self, capsys, tmp_path): testdb = Path(tmp_path) / "testdb1" shell = recon_shell.ReconShell() shell.select = lambda x: "create new database" shell.read_input = lambda x: str(testdb) shell.database_attach("") time.sleep(1) assert "created database @" in capsys.readouterr().out try: testdb.unlink() except FileNotFoundError: pass def test_database_attach_existing(self, capsys, tmp_path): testdb = Path(tmp_path) / "testdb2" shutil.copy(self.db_location, testdb) assert testdb.exists() shell = recon_shell.ReconShell() shell.select = lambda x: str(testdb.expanduser().resolve()) shell.get_databases = MagicMock(return_value=[str(testdb)]) shell.database_attach("") time.sleep(1) assert "attached to sqlite database @" in capsys.readouterr().out try: testdb.unlink() except FileNotFoundError: pass def test_database_detach_connected(self, capsys): self.shell.db_mgr = MagicMock() self.shell.db_mgr.location = "stuff" self.shell.database_detach("") assert "detached from sqlite database @" in capsys.readouterr().out def test_database_detach_not_connected(self, capsys): self.shell.database_detach("") assert "you are not connected to a database" in capsys.readouterr().out def test_database_delete_without_index(self, capsys, tmp_path): testdb = Path(tmp_path) / "testdb3" testdb.touch() self.shell.select = lambda x: str(testdb.expanduser().resolve()) self.shell.get_databases = MagicMock(return_value=[str(testdb)]) self.shell.database_delete("") try: assert not testdb.exists() except AssertionError: try: testdb.unlink() except FileNotFoundError: pass raise AssertionError assert "[+] deleted sqlite database" in capsys.readouterr().out def test_database_delete_with_index(self, capsys): testdb = Path(defaults.get("database-dir")) / "testdb4" testdb.touch() shell = recon_shell.ReconShell() shell.select = lambda x: str(testdb.expanduser().resolve()) shell.prompt = f"[db-1] {recon_shell.DEFAULT_PROMPT}> " shell.db_mgr = MagicMock() shell.db_mgr.location = "stuff" shell.get_databases = MagicMock(return_value=[str(testdb)]) shell.database_delete("") try: assert not testdb.exists() except AssertionError: try: testdb.unlink() except FileNotFoundError: pass raise AssertionError out = capsys.readouterr().out assert "[+] deleted sqlite database" in out @pytest.mark.parametrize( "test_input, expected", [ (None, "you are not connected to a database"), ("", "View results of completed scans"), ("ports", "blog.bitdiscovery.com: 443,80"), ("ports --paged", "blog.bitdiscovery.com: 443,80"), ("ports --host assetinventory.bugcrowd.com", "assetinventory.bugcrowd.com: 8443,8080,443,80"), ("ports --host assetinventory.bugcrowd.com --paged", "assetinventory.bugcrowd.com: 8443,8080,443,80"), ("ports --port-number 8443", "assetinventory.bugcrowd.com: 8443,8080,443,80"), ("endpoints", " https://ibm.bitdiscovery.com/user\n[\x1b[91m403\x1b[39m] https://172.16.31.10/ADMIN"), ("endpoints --host 172.16.31.10", "[\x1b[32m200\x1b[39m] https://172.16.31.10/favicon.ico"), ("endpoints --host 172.16.31.10 --status-code 200", "[\x1b[32m200\x1b[39m] https://172.16.31.10/favicon.ico"), ( "endpoints --host 172.16.31.10 --status-code 200 --paged", "[\x1b[32m200\x1b[39m] https://172.16.31.10/favicon.ico", ), ("endpoints --host 172.16.31.10 --status-code 200 --paged --plain", "https://52.8.186.88/favicon.ico"), ( "endpoints --host 172.16.31.10 --status-code 200 --paged --plain --headers", "http://172.16.31.10/\n Access-Control-Allow-Headers: X-Requested-With", ), ( "endpoints --host 172.16.31.10 --status-code 200 --paged --headers", "[\x1b[32m200\x1b[39m] https://172.16.31.10/\n\x1b[36m Content-Security-Policy:\x1b[39m default-src 'self' https: 'unsafe-inline' 'unsafe-eval' data: client-api.arkoselabs.com", ), ( "nmap-scans", "192.168.127.12 - http\n==================\n\ntcp port: 443 - open - syn-ack\nproduct: nginx :: 1.16.1\nnse script(s) output:\n http-server-header", ), ( "nmap-scans --commandline", "nmap --open -sT -n -sC -T 4 -sV -Pn -p 8443,8080,443,80 -oA /home/epi/PycharmProjects/recon-pipeline/tests/data/updated-tests/nmap-results/nmap.192.168.3.11-tcp 192.168.3.11", ), ( "nmap-scans --host synopsys.bitdiscovery.com", "192.168.127.12 - http\n===================\n\ntcp port: 443 - open - syn-ack", ), ( "nmap-scans --port 443 --product nginx", "192.168.127.12 - http\n==================\n\ntcp port: 443 - open - syn-ack\nproduct: nginx :: 1.16.1", ), ("nmap-scans --port 443 --nse-script http-title", "http-title\n bugcrowd - Asset Inventory"), ( "nmap-scans --host synopsys.bitdiscovery.com", "192.168.127.12 - http\n===================\n\ntcp port: 443 - open - syn-ack", ), ( "searchsploit-results", "==================================================================================", ), ("searchsploit-results --type webapps", "webapps | 37450.txt| Amazon S3"), ("searchsploit-results --host synopsys.bitdiscovery.com --fullpath", "exploits/linux/local/40768.sh"), ("targets", "email.assetinventory.bugcrowd.com"), ("targets --vuln-to-subdomain-takeover --paged", ""), ("targets --type ipv4 --paged", "192.168.3.11"), ("targets --type ipv6", "fc00:e968:6179::de52:7100:3c33"), ("targets --type domain-name --paged", "email.assetinventory.bugcrowd.com"), ("web-technologies", "CloudFlare (CDN)"), ("web-technologies --host blog.bitdiscovery.com --type CDN", "Amazon Cloudfront (CDN)"), ("web-technologies --host blog.bitdiscovery.com --product WordPress", "WordPress (CMS,Blogs)"), ("web-technologies --product WordPress", "172.16.58.3"), ("web-technologies --type Miscellaneous", "192.168.127.12"), ], ) def test_do_view_with_real_database(self, test_input, expected, capsys): if test_input is None: self.shell.do_view("") assert expected in capsys.readouterr().out else: self.shell.db_mgr = self.realdb self.shell.add_dynamic_parser_arguments() self.shell.do_view(test_input) assert expected in capsys.readouterr().out @pytest.mark.parametrize( "test_input, expected", [ (None, "Manage database connections (list/attach/detach/delete)"), ("list", "View results of completed scans"), ], ) def test_do_database(self, test_input, expected, capsys): if test_input is None: self.shell.do_database("") assert expected in capsys.readouterr().out else: testdb = Path(defaults.get("database-dir")) / "testdb5" testdb.touch() self.shell.do_database(test_input) assert str(testdb) in capsys.readouterr().out try: testdb.unlink() except FileNotFoundError: pass @patch("webbrowser.open", autospec=True) def test_do_status(self, mock_browser): self.shell.do_status("--host 127.0.0.1 --port 1111") assert mock_browser.called @pytest.mark.parametrize("test_input, expected", [(None, "Manage tool actions (install/uninstall/reinstall)")]) def test_do_tools(self, test_input, expected, capsys): if test_input is None: self.shell.do_tools("") assert expected in capsys.readouterr().out # after tools moved to DB, update this test @pytest.mark.parametrize( "test_input, expected, return_code", [ ("all", "[-] go queued", 0), ("amass", "check output from the offending command above", 1), ("amass", "has an unmet dependency", 0), ("waybackurls", "[!] waybackurls has an unmet dependency", 0), ("go", "[+] go installed!", 0), ("masscan", "[!] masscan is already installed.", 0), ], ) def test_tools_install(self, test_input, expected, return_code, capsys, tmp_path): process_mock = MagicMock() attrs = {"communicate.return_value": (b"output", b"error"), "returncode": return_code} process_mock.configure_mock(**attrs) tooldir = tmp_path / ".local" / "recon-pipeline" / "tools" tooldir.mkdir(parents=True, exist_ok=True) tools["go"]["installed"] = False tools["waybackurls"]["installed"] = True tools["masscan"]["installed"] = True tools["amass"]["shell"] = False tools["amass"]["installed"] = False pickle.dump(tools, (tooldir / ".tool-dict.pkl").open("wb")) with patch("subprocess.Popen", autospec=True) as mocked_popen: mocked_popen.return_value = process_mock self.shell.tools_dir = tooldir self.shell.do_tools(f"install {test_input}") if test_input != "masscan": assert mocked_popen.called assert expected in capsys.readouterr().out if test_input != "all" and return_code == 0: assert self.shell._get_dict().get(test_input).get("installed") is True # after tools moved to DB, update this test @pytest.mark.parametrize( "test_input, expected, return_code", [ ("all", "waybackurls queued", 0), ("amass", "check output from the offending command above", 1), ("waybackurls", "[+] waybackurls uninstalled!", 0), ("go", "[!] go is not installed", 0), ], ) def test_tools_uninstall(self, test_input, expected, return_code, capsys, tmp_path): process_mock = MagicMock() attrs = {"communicate.return_value": (b"output", b"error"), "returncode": return_code} process_mock.configure_mock(**attrs) tooldir = tmp_path / ".local" / "recon-pipeline" / "tools" tooldir.mkdir(parents=True, exist_ok=True) tools["go"]["installed"] = False tools["waybackurls"]["installed"] = True tools["amass"]["shell"] = False tools["amass"]["installed"] = True pickle.dump(tools, (tooldir / ".tool-dict.pkl").open("wb")) with patch("subprocess.Popen", autospec=True) as mocked_popen: mocked_popen.return_value = process_mock self.shell.tools_dir = tooldir self.shell.do_tools(f"uninstall {test_input}") if test_input != "go": assert mocked_popen.called assert expected in capsys.readouterr().out if test_input != "all" and return_code == 0: assert self.shell._get_dict().get(test_input).get("installed") is False def test_tools_reinstall(self, capsys): self.shell.do_tools("reinstall amass") output = capsys.readouterr().out assert "[*] Removing amass..." in output or "[!] amass is not installed." in output assert "[*] Installing amass..." in output or "[!] amass is already installed." in output def test_tools_list(self, capsys, tmp_path): tooldir = tmp_path / ".local" / "recon-pipeline" / "tools" tooldir.mkdir(parents=True, exist_ok=True) tools["go"]["installed"] = True tools["waybackurls"]["installed"] = True tools["masscan"]["installed"] = False regexes = [r"Installed.*go/bin/go", r"Installed.*bin/waybackurls", r":Missing:.*tools/masscan"] pickle.dump(tools, (tooldir / ".tool-dict.pkl").open("wb")) self.shell.tools_dir = tooldir self.shell.do_tools("list") output = capsys.readouterr().out for regex in regexes: assert re.search(regex, output) @pytest.mark.parametrize( "test_input, expected, db_mgr", [ ( "FullScan --target-file required", "You are not connected to a database; run database attach before scanning", None, ), ( "FullScan --target-file required --sausage --verbose", "If anything goes wrong, rerun your command with --verbose", True, ), ("FullScan --target-file required", "If anything goes wrong, rerun your command with --verbose", True), ("FullScan --target required", "If anything goes wrong, rerun your command with --verbose", True), ], ) def test_do_scan(self, test_input, expected, db_mgr, capsys, tmp_path): process_mock = MagicMock() attrs = {"communicate.return_value": (b"output", b"error"), "returncode": 0} process_mock.configure_mock(**attrs) with patch("subprocess.run", autospec=True) as mocked_popen, patch( "webbrowser.open", autospec=True ) as mocked_web, patch("selectors.DefaultSelector.register", autospec=True) as mocked_selector, patch( "cmd2.Cmd.select" ) as mocked_select, patch( "pipeline.recon-pipeline.get_scans" ) as mocked_scans: mocked_select.return_value = "Resume" mocked_popen.return_value = process_mock test_input += f" --results-dir {tmp_path / 'mostuff'}" mocked_scans.return_value = {"FullScan": ["pipeline.recon.wrappers"]} if db_mgr is None: self.shell.do_scan(test_input) assert expected in capsys.readouterr().out else: self.shell.db_mgr = MagicMock() self.shell.db_mgr.location = tmp_path / "stuff" self.shell.do_scan(test_input) if "--sausage" in test_input: assert mocked_web.called if "--verbose" not in test_input: assert mocked_selector.called def test_cluge_package_imports(self): pathlen = len(sys.path) recon_shell.cluge_package_imports(name="__main__", package=None) assert len(sys.path) > pathlen def test_main(self): with patch("cmd2.Cmd.cmdloop") as mocked_loop, patch("sys.exit"), patch("cmd2.Cmd.select") as mocked_select: mocked_select.return_value = "No" recon_shell.main(name="__main__") assert mocked_loop.called @pytest.mark.parametrize("test_input", ["Yes", "No"]) def test_remove_old_recon_tools(self, test_input, tmp_path): tooldict = tmp_path / ".tool-dict.pkl" tooldir = tmp_path / ".recon-tools" searchsploit_rc = tmp_path / ".searchsploit_rc" tooldict.touch() assert tooldict.exists() searchsploit_rc.touch() assert searchsploit_rc.exists() tooldir.mkdir() assert tooldir.exists() subfile = tooldir / "subfile" subfile.touch() assert subfile.exists() old_loop = recon_shell.ReconShell.cmdloop recon_shell.ReconShell.cmdloop = MagicMock() recon_shell.cmd2.Cmd.select = MagicMock(return_value=test_input) with patch("sys.exit"): recon_shell.main( name="__main__", old_tools_dir=tooldir, old_tools_dict=tooldict, old_searchsploit_rc=searchsploit_rc ) recon_shell.ReconShell.cmdloop = old_loop for file in [subfile, tooldir, tooldict, searchsploit_rc]: if test_input == "Yes": assert not file.exists() else: assert file.exists() @pytest.mark.parametrize( "test_input", [("1", "Resume", True, 1), ("2", "Remove", False, 0), ("3", "Save", False, 1)] ) def test_check_scan_directory(self, test_input, tmp_path): user_input, answer, exists, numdirs = test_input new_tmp = tmp_path / f"check_scan_directory_test-{user_input}-{answer}" new_tmp.mkdir() recon_shell.cmd2.Cmd.select = MagicMock(return_value=answer) print(list(tmp_path.iterdir()), new_tmp) self.shell.check_scan_directory(str(new_tmp)) assert new_tmp.exists() == exists print(list(tmp_path.iterdir()), new_tmp) assert len(list(tmp_path.iterdir())) == numdirs if answer == "Save": assert ( re.search(r"check_scan_directory_test-3-Save-[0-9]{6,8}-[0-9]+", str(list(tmp_path.iterdir())[0])) is not None ) <file_sep>import json import subprocess from pathlib import Path import luigi from luigi.util import inherits from luigi.contrib.sqla import SQLAlchemyTarget import pipeline.models.db_manager from ..tools import tools from .targets import TargetList from .helpers import meets_requirements from ..models.target_model import Target @inherits(TargetList) class AmassScan(luigi.Task): """ Run ``amass`` scan to perform subdomain enumeration of given domain(s). Note: Expects **TARGET_FILE.domains** file to be a text file with one top-level domain per line. Install: .. code-block:: console sudo apt-get install -y -q amass Basic Example: .. code-block:: console amass enum -ip -brute -active -min-for-recursive 3 -df tesla -json amass.tesla.json Luigi Example: .. code-block:: console PYTHONPATH=$(pwd) luigi --local-scheduler --module recon.amass AmassScan --target-file tesla Args: exempt_list: Path to a file providing blacklisted subdomains, one per line. db_location: specifies the path to the database used for storing results *Required by upstream Task* target_file: specifies the file on disk containing a list of ips or domains *Required by upstream Task* results_dir: specifes the directory on disk to which all Task results are written *Required by upstream Task* """ exempt_list = luigi.Parameter(default="") requirements = ["go", "amass"] exception = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.db_mgr = pipeline.models.db_manager.DBManager(db_location=self.db_location) self.results_subfolder = (Path(self.results_dir) / "amass-results").expanduser().resolve() def requires(self): """ AmassScan depends on TargetList to run. TargetList expects target_file as a parameter. Returns: luigi.ExternalTask - TargetList """ meets_requirements(self.requirements, self.exception) args = {"target_file": self.target_file, "results_dir": self.results_dir, "db_location": self.db_location} return TargetList(**args) def output(self): """ Returns the target output for this task. Naming convention for the output file is amass.json. Returns: luigi.local_target.LocalTarget """ results_subfolder = Path(self.results_dir) / "amass-results" new_path = results_subfolder / "amass.json" return luigi.LocalTarget(new_path.expanduser().resolve()) def run(self): """ Defines the options/arguments sent to amass after processing. Returns: list: list of options/arguments, beginning with the name of the executable to run """ self.results_subfolder.mkdir(parents=True, exist_ok=True) hostnames = self.db_mgr.get_all_hostnames() if hostnames: # TargetList generated some domains for us to scan with amass amass_input_file = self.results_subfolder / "input-from-targetlist" with open(amass_input_file, "w") as f: for hostname in hostnames: f.write(f"{hostname}\n") else: return subprocess.run(f"touch {self.output().path}".split()) command = [ tools.get("amass").get("path"), "enum", "-active", "-ip", "-brute", "-min-for-recursive", "3", "-df", str(amass_input_file), "-json", self.output().path, ] if self.exempt_list: command.append("-blf") # Path to a file providing blacklisted subdomains command.append(self.exempt_list) subprocess.run(command) amass_input_file.unlink() @inherits(AmassScan) class ParseAmassOutput(luigi.Task): """ Read amass JSON results and create categorized entries into ip|subdomain files. Args: db_location: specifies the path to the database used for storing results *Required by upstream Task* target_file: specifies the file on disk containing a list of ips or domains *Required by upstream Task* exempt_list: Path to a file providing blacklisted subdomains, one per line. *Optional by upstream Task* results_dir: specifes the directory on disk to which all Task results are written *Required by upstream Task* """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.db_mgr = pipeline.models.db_manager.DBManager(db_location=self.db_location) self.results_subfolder = (Path(self.results_dir) / "amass-results").expanduser().resolve() def requires(self): """ ParseAmassOutput depends on AmassScan to run. TargetList expects target_file as a parameter. AmassScan accepts exempt_list as an optional parameter. Returns: luigi.ExternalTask - TargetList """ args = { "target_file": self.target_file, "exempt_list": self.exempt_list, "results_dir": self.results_dir, "db_location": self.db_location, } return AmassScan(**args) def output(self): """ Returns the target output files for this task. Returns: luigi.contrib.sqla.SQLAlchemyTarget """ return SQLAlchemyTarget( connection_string=self.db_mgr.connection_string, target_table="target", update_id=self.task_id ) def run(self): """ Parse the json file produced by AmassScan and categorize the results into ip|subdomain files. An example (prettified) entry from the json file is shown below { "Timestamp": "2019-09-22T19:20:13-05:00", "name": "beta-partners.tesla.com", "domain": "tesla.com", "addresses": [ { "ip": "172.16.17.32", "cidr": "172.16.58.3/24", "asn": 394161, "desc": "TESLA - Tesla" } ], "tag": "ext", "source": "Previous Enum" } """ self.results_subfolder.mkdir(parents=True, exist_ok=True) if Path(self.input().path).stat().st_size == 0: self.output().touch() return amass_json = self.input().open() with amass_json as amass_json_file: for line in amass_json_file: entry = json.loads(line) tgt = self.db_mgr.get_or_create(Target, hostname=entry.get("name"), is_web=True) for address in entry.get("addresses"): ipaddr = address.get("ip") tgt = self.db_mgr.add_ipv4_or_v6_address_to_target(tgt, ipaddr) self.db_mgr.add(tgt) self.output().touch() self.db_mgr.close() <file_sep>.. toctree:: :maxdepth: 1 :hidden: .. _parsers-ref-label: Parsers ======= Amass Parser ############ .. autoclass:: pipeline.recon.amass.ParseAmassOutput :members: Web Targets Parser ################## .. autoclass:: pipeline.recon.web.targets.GatherWebTargets :members: Masscan Parser ############## .. autoclass:: pipeline.recon.masscan.ParseMasscanOutput :members: <file_sep>from sqlalchemy.orm import relationship from sqlalchemy import Column, Integer, ForeignKey, String, Table, UniqueConstraint from .base_model import Base technology_association_table = Table( "technology_association", Base.metadata, Column("technology_id", Integer, ForeignKey("technology.id")), Column("target_id", Integer, ForeignKey("target.id")), ) class Technology(Base): """ Database model that describes a web technology (i.e. Nginx 1.14). Represents webanalyze data. Relationships: ``targets``: many to many -> :class:`pipeline.models.target_model.Target` """ __tablename__ = "technology" __table_args__ = (UniqueConstraint("type", "text"),) # combination of type/text == unique def __str__(self): return self.pretty() def pretty(self, padlen=0): pad = " " msg = f"{self.text} ({self.type})\n" msg += "=" * len(f"{self.text} ({self.type})") msg += "\n\n" for target in self.targets: if target.hostname: msg += f"{pad * padlen} - {target.hostname}\n" for ipaddr in target.ip_addresses: if ipaddr.ipv4_address: msg += f"{pad * padlen} - {ipaddr.ipv4_address}\n" elif ipaddr.ipv6_address: msg += f"{pad * padlen} - {ipaddr.ipv6_address}\n" return msg id = Column(Integer, primary_key=True) type = Column(String) text = Column(String) target_id = Column(Integer, ForeignKey("target.id")) targets = relationship("Target", secondary=technology_association_table, back_populates="technologies") <file_sep>from .helpers import get_scans from .targets import TargetList from .wrappers import FullScan, HTBScan from .amass import AmassScan, ParseAmassOutput from .masscan import MasscanScan, ParseMasscanOutput from .nmap import ThreadedNmapScan, SearchsploitScan from .config import top_udp_ports, top_tcp_ports, defaults, web_ports from .parsers import ( scan_parser, view_parser, tools_parser, status_parser, database_parser, db_attach_parser, db_delete_parser, db_detach_parser, db_list_parser, tools_list_parser, tools_install_parser, tools_uninstall_parser, tools_reinstall_parser, target_results_parser, endpoint_results_parser, nmap_results_parser, technology_results_parser, searchsploit_results_parser, port_results_parser, ) <file_sep>#!/usr/bin/env python # stdlib imports import os import sys import time import shlex import shutil import tempfile import textwrap import selectors import threading import subprocess import webbrowser from enum import IntEnum from pathlib import Path from typing import List, NewType DEFAULT_PROMPT = "recon-pipeline> " # fix up the PYTHONPATH so we can simply execute the shell from wherever in the filesystem os.environ["PYTHONPATH"] = f"{os.environ.get('PYTHONPATH')}:{str(Path(__file__).expanduser().resolve().parents[1])}" # suppress "You should consider upgrading via the 'pip install --upgrade pip' command." warning os.environ["PIP_DISABLE_PIP_VERSION_CHECK"] = "1" # in case we need pipenv, add its default --user installed directory to the PATH sys.path.append(str(Path.home() / ".local" / "bin")) # third party imports import cmd2 # noqa: E402 from cmd2.ansi import style # noqa: E402 def cluge_package_imports(name, package): """ project's module imports; need to cluge the package to handle relative imports at this level putting into a function for testability """ if name == "__main__" and package is None: file = Path(__file__).expanduser().resolve() parent, top = file.parent, file.parents[1] sys.path.append(str(top)) try: sys.path.remove(str(parent)) except ValueError: # already gone pass import pipeline # noqa: F401 sys.modules[name].__package__ = "pipeline" cluge_package_imports(name=__name__, package=__package__) from .recon.config import defaults # noqa: F401,E402 from .models.nse_model import NSEResult # noqa: F401,E402 from .models.db_manager import DBManager # noqa: F401,E402 from .models.nmap_model import NmapResult # noqa: F401,E402 from .models.technology_model import Technology # noqa: F401,E402 from .models.searchsploit_model import SearchsploitResult # noqa: F401,E402 from .recon import ( # noqa: F401,E402 get_scans, scan_parser, view_parser, tools_parser, status_parser, database_parser, db_attach_parser, db_delete_parser, db_detach_parser, db_list_parser, tools_list_parser, tools_install_parser, tools_uninstall_parser, tools_reinstall_parser, target_results_parser, endpoint_results_parser, nmap_results_parser, technology_results_parser, searchsploit_results_parser, port_results_parser, ) from .tools import tools # noqa: F401,E402 class ToolAction(IntEnum): INSTALL = 0 UNINSTALL = 1 ToolActions = NewType("ToolActions", ToolAction) # select loop, handles async stdout/stderr processing of subprocesses selector = selectors.DefaultSelector() class SelectorThread(threading.Thread): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._stop_event = threading.Event() def stop(self): """ Helper to set the SelectorThread's Event and cleanup the selector's fds """ self._stop_event.set() # close any fds that were registered and still haven't been unregistered for key in selector.get_map(): selector.get_key(key).fileobj.close() # pragma: no cover def stopped(self): """ Helper to determine whether the SelectorThread's Event is set or not. """ return self._stop_event.is_set() def run(self): """ Run thread that executes a select loop; handles async stdout/stderr processing of subprocesses. """ while not self.stopped(): # pragma: no cover for k, mask in selector.select(): callback = k.data callback(k.fileobj) class ReconShell(cmd2.Cmd): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.db_mgr = None self.sentry = False self.self_in_py = True self.selectorloop = None self.continue_install = True self.prompt = DEFAULT_PROMPT self.tools_dir = Path(defaults.get("tools-dir")) self._initialize_parsers() self.tools_dir.mkdir(parents=True, exist_ok=True) Path(defaults.get("database-dir")).mkdir(parents=True, exist_ok=True) Path(defaults.get("gopath")).mkdir(parents=True, exist_ok=True) Path(defaults.get("goroot")).mkdir(parents=True, exist_ok=True) # register hooks to handle selector loop start and cleanup self.register_preloop_hook(self._preloop_hook) self.register_postloop_hook(self._postloop_hook) def _initialize_parsers(self): """ Internal helper to associate methods with the subparsers that use them """ db_list_parser.set_defaults(func=self.database_list) db_attach_parser.set_defaults(func=self.database_attach) db_detach_parser.set_defaults(func=self.database_detach) db_delete_parser.set_defaults(func=self.database_delete) endpoint_results_parser.set_defaults(func=self.print_endpoint_results) target_results_parser.set_defaults(func=self.print_target_results) nmap_results_parser.set_defaults(func=self.print_nmap_results) technology_results_parser.set_defaults(func=self.print_webanalyze_results) searchsploit_results_parser.set_defaults(func=self.print_searchsploit_results) port_results_parser.set_defaults(func=self.print_port_results) tools_install_parser.set_defaults(func=self.tools_install) tools_reinstall_parser.set_defaults(func=self.tools_reinstall) tools_uninstall_parser.set_defaults(func=self.tools_uninstall) tools_list_parser.set_defaults(func=self.tools_list) def _preloop_hook(self) -> None: """ Hook function that runs prior to the cmdloop function starting; starts the selector loop. """ self.selectorloop = SelectorThread(daemon=True) self.selectorloop.start() def _postloop_hook(self) -> None: """ Hook function that runs after the cmdloop function stops; stops the selector loop. """ if self.selectorloop.is_alive(): self.selectorloop.stop() selector.close() def _install_error_reporter(self, stderr): """ Helper to print errors that crop up during any tool installation commands. """ output = stderr.readline() if not output: return output = output.decode().strip() self.async_alert(style(f"[!] {output}", fg="bright_red")) def _luigi_pretty_printer(self, stderr): """ Helper to clean up the VERY verbose luigi log messages that are normally spewed to the terminal. """ output = stderr.readline() if not output: return output = output.decode() if "===== Luigi Execution Summary =====" in output: # header that begins the summary of all luigi tasks that have executed/failed self.async_alert("") self.sentry = True # block below used for printing status messages if self.sentry: # only set once the Luigi Execution Summary is seen self.async_alert(style(output.strip(), fg="bright_blue")) elif output.startswith("INFO: Informed") and output.strip().endswith("PENDING"): # luigi Task has been queued for execution words = output.split() self.async_alert(style(f"[-] {words[5].split('_')[0]} queued", fg="bright_white")) elif output.startswith("INFO: ") and "running" in output: # luigi Task is currently running words = output.split() # output looks similar to , pid=3938074) running MasscanScan( # want to grab the index of the luigi task running and use it to find the name of the scan (i.e. MassScan) scantypeidx = words.index("running") + 1 scantype = words[scantypeidx].split("(", 1)[0] self.async_alert(style(f"[*] {scantype} running...", fg="bright_yellow")) elif output.startswith("INFO: Informed") and output.strip().endswith("DONE"): # luigi Task has completed words = output.split() self.async_alert(style(f"[+] {words[5].split('_')[0]} complete!", fg="bright_green")) def check_scan_directory(self, directory): """ Determine whether or not the results-dir about to be used already exists and prompt the user accordingly. Args: directory: the directory passed to ``scan ... --results-dir`` """ directory = Path(directory) if directory.exists(): term_width = shutil.get_terminal_size((80, 20)).columns warning_msg = ( f"[*] Your results-dir ({str(directory)}) already exists. Subfolders/files may tell " f"the pipeline that the associated Task is complete. This means that your scan may start " f"from a point you don't expect. Your options are as follows:" ) for line in textwrap.wrap(warning_msg, width=term_width, subsequent_indent=" "): self.poutput(style(line, fg="bright_yellow")) option_one = ( "Resume existing scan (use any existing scan data & only attempt to scan what isn't already done)" ) option_two = "Remove existing directory (scan starts from the beginning & all existing results are removed)" option_three = "Save existing directory (your existing folder is renamed and your scan proceeds)" answer = self.select([("Resume", option_one), ("Remove", option_two), ("Save", option_three)]) if answer == "Resume": self.poutput(style("[+] Resuming scan from last known good state.", fg="bright_green")) elif answer == "Remove": shutil.rmtree(Path(directory)) self.poutput(style("[+] Old directory removed, starting fresh scan.", fg="bright_green")) elif answer == "Save": current = time.strftime("%Y%m%d-%H%M%S") directory.rename(f"{directory}-{current}") self.poutput( style(f"[+] Starting fresh scan. Old data saved as {directory}-{current}", fg="bright_green") ) @cmd2.with_argparser(scan_parser) def do_scan(self, args): """ Scan something. Possible scans include AmassScan GobusterScan SearchsploitScan WaybackurlsScan ThreadedNmapScan WebanalyzeScan AquatoneScan FullScan MasscanScan SubjackScan TKOSubsScan HTBScan """ if self.db_mgr is None: return self.poutput( style("[!] You are not connected to a database; run database attach before scanning", fg="bright_red") ) self.check_scan_directory(args.results_dir) self.poutput( style( "If anything goes wrong, rerun your command with --verbose to enable debug statements.", fg="cyan", dim=True, ) ) # get_scans() returns mapping of {classname: [modulename, ...]} in the recon module # each classname corresponds to a potential recon-pipeline command, i.e. AmassScan, GobusterScan ... scans = get_scans() # command is a list that will end up looking something like what's below # luigi --module pipeline.recon.web.webanalyze WebanalyzeScan --target abc.com --top-ports 100 --interface eth0 try: command = ["luigi", "--module", scans.get(args.scantype)[0]] except TypeError: return self.poutput( style(f"[!] {args.scantype} or one of its dependencies is not installed", fg="bright_red") ) tgt_file_path = None if args.target: tgt_file_fd, tgt_file_path = tempfile.mkstemp() # temp file to hold target for later parsing tgt_file_path = Path(tgt_file_path) tgt_idx = args.__statement__.arg_list.index("--target") tgt_file_path.write_text(args.target) args.__statement__.arg_list[tgt_idx + 1] = str(tgt_file_path) args.__statement__.arg_list[tgt_idx] = "--target-file" command.extend(args.__statement__.arg_list) command.extend(["--db-location", str(self.db_mgr.location)]) if args.sausage: # sausage is not a luigi option, need to remove it # name for the option came from @AlphaRingo command.pop(command.index("--sausage")) webbrowser.open("http://127.0.0.1:8082") # hard-coded here, can specify different with the status command if args.verbose: # verbose is not a luigi option, need to remove it command.pop(command.index("--verbose")) subprocess.run(command) else: # suppress luigi messages in favor of less verbose/cleaner output proc = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE) # add stderr to the selector loop for processing when there's something to read from the fd selector.register(proc.stderr, selectors.EVENT_READ, self._luigi_pretty_printer) self.add_dynamic_parser_arguments() def _get_dict(self): """Retrieves tool dict if available""" return tools def _finalize_tool_action(self, tool: str, tool_dict: dict, return_values: List[int], action: ToolActions): """ Internal helper to keep DRY Args: tool: tool on which the action has been performed tool_dict: tools dictionary to save return_values: accumulated return values of subprocess calls action: ToolAction.INSTALL or ToolAction.UNINSTALL """ verb = ["install", "uninstall"][action.value] if all(x == 0 for x in return_values): # all return values in retvals are 0, i.e. all exec'd successfully; tool action has succeeded self.poutput(style(f"[+] {tool} {verb}ed!", fg="bright_green")) tool_dict[tool]["installed"] = True if action == ToolAction.INSTALL else False else: # unsuccessful tool action tool_dict[tool]["installed"] = False if action == ToolAction.INSTALL else True self.poutput( style( f"[!!] one (or more) of {tool}'s commands failed and may have not {verb}ed properly; check output from the offending command above...", fg="bright_red", bold=True, ) ) def tools_install(self, args): """ Install any/all of the libraries/tools necessary to make the recon-pipeline function. """ if args.tool == "all": # show all tools have been queued for installation [ self.poutput(style(f"[-] {x} queued", fg="bright_white")) for x in tools.keys() if not tools.get(x).get("installed") ] for tool in tools.keys(): self.do_tools(f"install {tool}") return if tools.get(args.tool).get("dependencies"): # get all of the requested tools dependencies for dependency in tools.get(args.tool).get("dependencies"): if tools.get(dependency).get("installed"): # already installed, skip it continue self.poutput( style(f"[!] {args.tool} has an unmet dependency; installing {dependency}", fg="yellow", bold=True) ) # install the dependency before continuing with installation self.do_tools(f"install {dependency}") if tools.get(args.tool).get("installed"): return self.poutput(style(f"[!] {args.tool} is already installed.", fg="yellow")) else: # list of return values from commands run during each tool installation # used to determine whether the tool installed correctly or not retvals = list() self.poutput(style(f"[*] Installing {args.tool}...", fg="bright_yellow")) addl_env_vars = tools.get(args.tool).get("environ") if addl_env_vars is not None: addl_env_vars.update(dict(os.environ)) for command in tools.get(args.tool, {}).get("install_commands", []): # run all commands required to install the tool # print each command being run self.poutput(style(f"[=] {command}", fg="cyan")) if tools.get(args.tool).get("shell"): # go tools use subshells (cmd1 && cmd2 && cmd3 ...) during install, so need shell=True proc = subprocess.Popen( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=addl_env_vars ) else: # "normal" command, split up the string as usual and run it proc = subprocess.Popen( shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=addl_env_vars ) out, err = proc.communicate() if err: self.poutput(style(f"[!] {err.decode().strip()}", fg="bright_red")) retvals.append(proc.returncode) self._finalize_tool_action(args.tool, tools, retvals, ToolAction.INSTALL) def tools_uninstall(self, args): """ Uninstall any/all of the libraries/tools used by recon-pipeline""" if args.tool == "all": # show all tools have been queued for installation [ self.poutput(style(f"[-] {x} queued", fg="bright_white")) for x in tools.keys() if tools.get(x).get("installed") ] for tool in tools.keys(): self.do_tools(f"uninstall {tool}") return if not tools.get(args.tool).get("installed"): return self.poutput(style(f"[!] {args.tool} is not installed.", fg="yellow")) else: retvals = list() self.poutput(style(f"[*] Removing {args.tool}...", fg="bright_yellow")) if not tools.get(args.tool).get("uninstall_commands"): self.poutput(style(f"[*] {args.tool} removal not needed", fg="bright_yellow")) return for command in tools.get(args.tool).get("uninstall_commands"): self.poutput(style(f"[=] {command}", fg="cyan")) proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate() if err: self.poutput(style(f"[!] {err.decode().strip()}", fg="bright_red")) retvals.append(proc.returncode) self._finalize_tool_action(args.tool, tools, retvals, ToolAction.UNINSTALL) def tools_reinstall(self, args): """ Reinstall a given tool """ self.do_tools(f"uninstall {args.tool}") self.do_tools(f"install {args.tool}") def tools_list(self, args): """ List status of pipeline tools """ for key, value in tools.items(): status = [style(":Missing:", fg="bright_magenta"), style("Installed", fg="bright_green")] self.poutput(style(f"[{status[value.get('installed')]}] - {value.get('path') or key}")) @cmd2.with_argparser(tools_parser) def do_tools(self, args): """ Manage tool actions (install/uninstall/reinstall) """ func = getattr(args, "func", None) if func is not None: func(args) else: self.do_help("tools") @cmd2.with_argparser(status_parser) def do_status(self, args): """ Open a web browser to Luigi's central scheduler's visualization site """ webbrowser.open(f"http://{args.host}:{args.port}") @staticmethod def get_databases(): """ Simple helper to list all known databases from default directory """ dbdir = defaults.get("database-dir") for db in sorted(Path(dbdir).iterdir()): yield db def database_list(self, args): """ List all known databases """ try: next(self.get_databases()) except StopIteration: return self.poutput(style("[-] There are no databases.", fg="bright_white")) for i, location in enumerate(self.get_databases(), start=1): self.poutput(style(f" {i}. {location}")) def database_attach(self, args): """ Attach to the selected database """ locations = [str(x) for x in self.get_databases()] + ["create new database"] location = self.select(locations) if location == "create new database": location = self.read_input( style("new database name? (recommend something unique for this target)\n-> ", fg="bright_white") ) new_location = str(Path(defaults.get("database-dir")) / location) index = sorted([new_location] + locations[:-1]).index(new_location) + 1 self.db_mgr = DBManager(db_location=new_location) self.poutput(style(f"[*] created database @ {new_location}", fg="bright_yellow")) location = new_location else: index = locations.index(location) + 1 self.db_mgr = DBManager(db_location=location) self.add_dynamic_parser_arguments() self.poutput( style(f"[+] attached to sqlite database @ {Path(location).expanduser().resolve()}", fg="bright_green") ) self.prompt = f"[db-{index}] {DEFAULT_PROMPT}" def add_dynamic_parser_arguments(self): """ Populate command parsers with information from the currently attached database """ port_results_parser.add_argument("--host", choices=self.db_mgr.get_all_targets(), help="filter results by host") port_results_parser.add_argument( "--port-number", choices=self.db_mgr.get_all_port_numbers(), help="filter results by port number" ) endpoint_results_parser.add_argument( "--status-code", choices=self.db_mgr.get_status_codes(), help="filter results by status code" ) endpoint_results_parser.add_argument( "--host", choices=self.db_mgr.get_all_targets(), help="filter results by host" ) nmap_results_parser.add_argument("--host", choices=self.db_mgr.get_all_targets(), help="filter results by host") nmap_results_parser.add_argument( "--nse-script", choices=self.db_mgr.get_all_nse_script_types(), help="filter results by nse script type ran" ) nmap_results_parser.add_argument( "--port", choices=self.db_mgr.get_all_port_numbers(), help="filter results by port scanned" ) nmap_results_parser.add_argument( "--product", help="filter results by reported product", choices=self.db_mgr.get_all_nmap_reported_products() ) technology_results_parser.add_argument( "--host", choices=self.db_mgr.get_all_targets(), help="filter results by host" ) technology_results_parser.add_argument( "--type", choices=self.db_mgr.get_all_web_technology_types(), help="filter results by type" ) technology_results_parser.add_argument( "--product", choices=self.db_mgr.get_all_web_technology_products(), help="filter results by product" ) searchsploit_results_parser.add_argument( "--host", choices=self.db_mgr.get_all_targets(), help="filter results by host" ) searchsploit_results_parser.add_argument( "--type", choices=self.db_mgr.get_all_exploit_types(), help="filter results by exploit type" ) def database_detach(self, args): """ Detach from the currently attached database """ if self.db_mgr is None: return self.poutput(style("[!] you are not connected to a database", fg="magenta")) self.db_mgr.close() self.poutput(style(f"[*] detached from sqlite database @ {self.db_mgr.location}", fg="bright_yellow")) self.db_mgr = None self.prompt = DEFAULT_PROMPT def database_delete(self, args): """ Delete the selected database """ locations = [str(x) for x in self.get_databases()] to_delete = self.select(locations) index = locations.index(to_delete) + 1 Path(to_delete).unlink() if f"[db-{index}]" in self.prompt: self.poutput(style(f"[*] detached from sqlite database at {self.db_mgr.location}", fg="bright_yellow")) self.prompt = DEFAULT_PROMPT self.db_mgr.close() self.db_mgr = None self.poutput( style(f"[+] deleted sqlite database @ {Path(to_delete).expanduser().resolve()}", fg="bright_green") ) @cmd2.with_argparser(database_parser) def do_database(self, args): """ Manage database connections (list/attach/detach/delete) """ func = getattr(args, "func", None) if func is not None: func(args) else: self.do_help("database") def print_target_results(self, args): """ Display all Targets from the database, ipv4/6 and hostname """ results = list() printer = self.ppaged if args.paged else self.poutput if args.type == "ipv4": targets = self.db_mgr.get_all_ipv4_addresses() elif args.type == "ipv6": targets = self.db_mgr.get_all_ipv6_addresses() elif args.type == "domain-name": targets = self.db_mgr.get_all_hostnames() else: targets = self.db_mgr.get_all_targets() for target in targets: if args.vuln_to_subdomain_takeover: tgt = self.db_mgr.get_or_create_target_by_ip_or_hostname(target) if not tgt.vuln_to_sub_takeover: # skip targets that aren't vulnerable continue vulnstring = style("vulnerable", fg="green") vulnstring = f"[{vulnstring}] {target}" results.append(vulnstring) else: results.append(target) if results: printer("\n".join(results)) def print_endpoint_results(self, args): """ Display all Endpoints from the database """ host_endpoints = status_endpoints = None printer = self.ppaged if args.paged else self.poutput color_map = {"2": "green", "3": "blue", "4": "bright_red", "5": "bright_magenta"} if args.status_code is not None: status_endpoints = self.db_mgr.get_endpoint_by_status_code(args.status_code) if args.host is not None: host_endpoints = self.db_mgr.get_endpoints_by_ip_or_hostname(args.host) endpoints = self.db_mgr.get_all_endpoints() for subset in [status_endpoints, host_endpoints]: if subset is not None: endpoints = set(endpoints).intersection(set(subset)) results = list() for endpoint in endpoints: color = color_map.get(str(endpoint.status_code)[0]) if args.plain or endpoint.status_code is None: results.append(endpoint.url) else: results.append(f"[{style(endpoint.status_code, fg=color)}] {endpoint.url}") if not args.headers: continue for header in endpoint.headers: if args.plain: results.append(f" {header.name}: {header.value}") else: results.append(style(f" {header.name}:", fg="cyan") + f" {header.value}") if results: printer("\n".join(results)) def print_nmap_results(self, args): """ Display all NmapResults from the database """ results = list() printer = self.ppaged if args.paged else self.poutput if args.host is not None: # limit by host, if necessary scans = self.db_mgr.get_nmap_scans_by_ip_or_hostname(args.host) else: scans = self.db_mgr.get_and_filter(NmapResult) if args.port is not None or args.product is not None: # limit by port, if necessary tmpscans = scans[:] for scan in scans: if args.port is not None and scan.port.port_number != int(args.port) and scan in tmpscans: del tmpscans[tmpscans.index(scan)] if args.product is not None and scan.product != args.product and scan in tmpscans: del tmpscans[tmpscans.index(scan)] scans = tmpscans if args.nse_script: # grab the specific nse-script, check that the corresponding nmap result is one we care about, and print for nse_scan in self.db_mgr.get_and_filter(NSEResult, script_id=args.nse_script): for nmap_result in nse_scan.nmap_results: if nmap_result not in scans: continue results.append(nmap_result.pretty(nse_results=[nse_scan], commandline=args.commandline)) else: # done filtering, grab w/e is left for scan in scans: results.append(scan.pretty(commandline=args.commandline)) if results: printer("\n".join(results)) def print_webanalyze_results(self, args): """ Display all NmapResults from the database """ results = list() printer = self.ppaged if args.paged else self.poutput filters = dict() if args.type is not None: filters["type"] = args.type if args.product is not None: filters["text"] = args.product if args.host: tgt = self.db_mgr.get_or_create_target_by_ip_or_hostname(args.host) printer(args.host) printer("=" * len(args.host)) for tech in tgt.technologies: if args.product is not None and args.product != tech.text: continue if args.type is not None and args.type != tech.type: continue printer(f" - {tech.text} ({tech.type})") else: for scan in self.db_mgr.get_and_filter(Technology, **filters): results.append(scan.pretty(padlen=1)) if results: printer("\n".join(results)) def print_searchsploit_results(self, args): """ Display all NmapResults from the database """ results = list() targets = self.db_mgr.get_all_targets() printer = self.ppaged if args.paged else self.poutput for ss_scan in self.db_mgr.get_and_filter(SearchsploitResult): tmp_targets = set() if ( args.host is not None and self.db_mgr.get_or_create_target_by_ip_or_hostname(args.host) != ss_scan.target ): continue if ss_scan.target.hostname in targets: # hostname is in targets, so hasn't been reported yet tmp_targets.add(ss_scan.target.hostname) # add to this report targets.remove(ss_scan.target.hostname) # remove from targets list, having been reported for ipaddr in ss_scan.target.ip_addresses: address = ipaddr.ipv4_address or ipaddr.ipv6_address if address is not None and address in targets: tmp_targets.add(address) targets.remove(address) if tmp_targets: header = ", ".join(tmp_targets) results.append(header) results.append("=" * len(header)) for scan in ss_scan.target.searchsploit_results: if args.type is not None and scan.type != args.type: continue results.append(scan.pretty(fullpath=args.fullpath)) if results: printer("\n".join(results)) def print_port_results(self, args): """ Display all Ports from the database """ results = list() targets = self.db_mgr.get_all_targets() printer = self.ppaged if args.paged else self.poutput for target in targets: if args.host is not None and target != args.host: # host specified, but it's not this particular target continue ports = [ str(port.port_number) for port in self.db_mgr.get_or_create_target_by_ip_or_hostname(target).open_ports ] if args.port_number and args.port_number not in ports: continue if ports: results.append(f"{target}: {','.join(ports)}") if results: printer("\n".join(results)) @cmd2.with_argparser(view_parser) def do_view(self, args): """ View results of completed scans """ if self.db_mgr is None: return self.poutput(style("[!] you are not connected to a database", fg="bright_magenta")) func = getattr(args, "func", None) if func is not None: func(args) else: self.do_help("view") def main( name, old_tools_dir=Path().home() / ".recon-tools", old_tools_dict=Path().home() / ".cache" / ".tool-dict.pkl", old_searchsploit_rc=Path().home() / ".searchsploit_rc", ): """ Functionified for testability """ if name == "__main__": if old_tools_dir.exists() and old_tools_dir.is_dir(): # want to try and ensure a smooth transition for folks who have used the pipeline before from # v0.8.4 and below to v0.9.0+ print(style("[*] Found remnants of an older version of recon-pipeline.", fg="bright_yellow")) print( style( f"[*] It's {style('strongly', fg='red')} advised that you allow us to remove them.", fg="bright_white", ) ) print( style( f"[*] Do you want to remove {old_tools_dir}/*, {old_searchsploit_rc}, and {old_tools_dict}?", fg="bright_white", ) ) answer = cmd2.Cmd().select(["Yes", "No"]) print(style(f"[+] You chose {answer}", fg="bright_green")) if answer == "Yes": shutil.rmtree(old_tools_dir) print(style(f"[+] {old_tools_dir} removed", fg="bright_green")) if old_tools_dict.exists(): old_tools_dict.unlink() print(style(f"[+] {old_tools_dict} removed", fg="bright_green")) if old_searchsploit_rc.exists(): old_searchsploit_rc.unlink() print(style(f"[+] {old_searchsploit_rc} removed", fg="bright_green")) print(style("[=] Please run the install all command to complete setup", fg="bright_blue")) rs = ReconShell(persistent_history_file="~/.reconshell_history", persistent_history_length=10000) sys.exit(rs.cmdloop()) main(name=__name__) <file_sep>import json import logging import subprocess from pathlib import Path import luigi from luigi.util import inherits from luigi.contrib.sqla import SQLAlchemyTarget import pipeline.models.db_manager from .targets import TargetList from ..tools import tools from .amass import ParseAmassOutput from ..models.port_model import Port from ..models.ip_address_model import IPAddress from .helpers import meets_requirements from .config import top_tcp_ports, top_udp_ports, defaults, web_ports @inherits(TargetList, ParseAmassOutput) class MasscanScan(luigi.Task): """ Run ``masscan`` against a target specified via the TargetList Task. Note: When specified, ``--top_ports`` is processed and then ultimately passed to ``--ports``. Install: .. code-block:: console git clone https://github.com/robertdavidgraham/masscan /tmp/masscan make -s -j -C /tmp/masscan sudo mv /tmp/masscan/bin/masscan /usr/local/bin/masscan rm -rf /tmp/masscan Basic Example: .. code-block:: console masscan -v --open-only --banners --rate 1000 -e tun0 -oJ masscan.tesla.json --ports 80,443,22,21 -iL tesla.ips Luigi Example: .. code-block:: console PYTHONPATH=$(pwd) luigi --local-scheduler --module recon.masscan Masscan --target-file tesla --ports 80,443,22,21 Args: rate: desired rate for transmitting packets (packets per second) interface: use the named raw network interface, such as "eth0" top_ports: Scan top N most popular ports ports: specifies the port(s) to be scanned db_location: specifies the path to the database used for storing results *Required by upstream Task* target_file: specifies the file on disk containing a list of ips or domains *Required by upstream Task* results_dir: specifes the directory on disk to which all Task results are written *Required by upstream Task* exempt_list: Path to a file providing blacklisted subdomains, one per line. *Optional by upstream Task* """ rate = luigi.Parameter(default=defaults.get("masscan-rate")) interface = luigi.Parameter(default=defaults.get("masscan-iface")) top_ports = luigi.IntParameter(default=0) # IntParameter -> top_ports expected as int ports = luigi.Parameter(default="") requirements = ["masscan"] exception = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.db_mgr = pipeline.models.db_manager.DBManager(db_location=self.db_location) self.results_subfolder = (Path(self.results_dir) / "masscan-results").expanduser().resolve() def output(self): """ Returns the target output for this task. Naming convention for the output file is masscan.TARGET_FILE.json. Returns: luigi.local_target.LocalTarget """ new_path = self.results_subfolder / "masscan.json" return luigi.LocalTarget(new_path.expanduser().resolve()) def run(self): """ Defines the options/arguments sent to masscan after processing. Returns: list: list of options/arguments, beginning with the name of the executable to run """ meets_requirements(self.requirements, self.exception) if not self.ports and not self.top_ports: # need at least one, can't be put into argparse scanner because things like amass don't require ports option logging.error("Must specify either --top-ports or --ports.") exit(2) if self.top_ports: # if --top-ports used, format the top_*_ports lists as strings and then into a proper masscan --ports option top_tcp_ports_str = ",".join(str(x) for x in top_tcp_ports[: self.top_ports]) top_udp_ports_str = ",".join(str(x) for x in top_udp_ports[: self.top_ports]) self.ports = f"{top_tcp_ports_str},U:{top_udp_ports_str}" self.top_ports = 0 self.results_subfolder.mkdir(parents=True, exist_ok=True) yield TargetList(target_file=self.target_file, results_dir=self.results_dir, db_location=self.db_location) if self.db_mgr.get_all_hostnames(): # TargetList generated some domains for us to scan with amass yield ParseAmassOutput( target_file=self.target_file, exempt_list=self.exempt_list, results_dir=self.results_dir, db_location=self.db_location, ) command = [ tools.get("masscan").get("path"), "-v", "--open", "--banners", "--rate", self.rate, "-e", self.interface, "-oJ", self.output().path, "--ports", self.ports, "-iL", ] # masscan only understands how to scan ipv4 ip_addresses = self.db_mgr.get_all_ipv4_addresses() masscan_input_file = None if ip_addresses: # TargetList generated ip addresses for us to scan with masscan masscan_input_file = self.results_subfolder / "input-from-amass" with open(masscan_input_file, "w") as f: for ip_address in ip_addresses: f.write(f"{ip_address}\n") command.append(str(masscan_input_file)) subprocess.run(command) # will fail if no ipv4 addresses were found if masscan_input_file is not None: masscan_input_file.unlink() @inherits(MasscanScan) class ParseMasscanOutput(luigi.Task): """ Read masscan JSON results and create a pickled dictionary of pertinent information for processing. Args: top_ports: Scan top N most popular ports *Required by upstream Task* ports: specifies the port(s) to be scanned *Required by upstream Task* interface: use the named raw network interface, such as "eth0" *Required by upstream Task* rate: desired rate for transmitting packets (packets per second) *Required by upstream Task* db_location: specifies the path to the database used for storing results *Required by upstream Task* target_file: specifies the file on disk containing a list of ips or domains *Required by upstream Task* results_dir: specifes the directory on disk to which all Task results are written *Required by upstream Task* """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.db_mgr = pipeline.models.db_manager.DBManager(db_location=self.db_location) self.results_subfolder = (Path(self.results_dir) / "masscan-results").expanduser().resolve() def requires(self): """ ParseMasscanOutput depends on Masscan to run. Masscan expects rate, target_file, interface, and either ports or top_ports as parameters. Returns: luigi.Task - Masscan """ args = { "results_dir": self.results_dir, "rate": self.rate, "target_file": self.target_file, "top_ports": self.top_ports, "interface": self.interface, "ports": self.ports, "db_location": self.db_location, } return MasscanScan(**args) def output(self): """ Returns the target output for this task. Naming convention for the output file is masscan.TARGET_FILE.parsed.pickle. Returns: luigi.local_target.LocalTarget """ return SQLAlchemyTarget( connection_string=self.db_mgr.connection_string, target_table="port", update_id=self.task_id ) def run(self): """ Reads masscan JSON results and creates a pickled dictionary of pertinent information for processing. """ try: # load masscan results from Masscan Task entries = json.load(self.input().open()) except json.decoder.JSONDecodeError as e: # return on exception; no output file created; pipeline should start again from # this task if restarted because we never hit pickle.dump return print(e) self.results_subfolder.mkdir(parents=True, exist_ok=True) """ populate database from the loaded JSON masscan JSON structure over which we're looping [ { "ip": "10.10.10.146", "timestamp": "1567856130", "ports": [ {"port": 22, "proto": "tcp", "status": "open", "reason": "syn-ack", "ttl": 63} ] } , { "ip": "10.10.10.146", "timestamp": "1567856130", "ports": [ {"port": 80, "proto": "tcp", "status": "open", "reason": "syn-ack", "ttl": 63} ] } ] """ for entry in entries: single_target_ip = entry.get("ip") tgt = self.db_mgr.get_or_create_target_by_ip_or_hostname(single_target_ip) if single_target_ip not in tgt.ip_addresses: tgt.ip_addresses.append(self.db_mgr.get_or_create(IPAddress, ipv4_address=single_target_ip)) for port_entry in entry.get("ports"): protocol = port_entry.get("proto") port = self.db_mgr.get_or_create(Port, protocol=protocol, port_number=port_entry.get("port")) if str(port.port_number) in web_ports: tgt.is_web = True tgt.open_ports.append(port) self.db_mgr.add(tgt) self.output().touch() self.db_mgr.close() <file_sep>.. _scheduler-ref-label: Using a Scheduler ================= The backbone of this pipeline is spotify's `luigi <https://github.com/spotify/luigi>`_ batch process management framework. Luigi uses the concept of a scheduler in order to manage task execution. Two types of scheduler are available, a **local** scheduler and a **central** scheduler. The local scheduler is useful for development and debugging while the central scheduler provides the following two benefits: - Make sure two instances of the same task are not running simultaneously - Provide :ref:`visualization <visualization-ref-label>` of everything that’s going on While in the ``recon-pipeline`` shell, running ``tools install luigi-service`` will copy the ``luigid.service`` file provided in the repo to its appropriate systemd location and start/enable the service. The result is that the central scheduler is up and running easily. The other option is to add ``--local-scheduler`` to your :ref:`scan_command` command from within the ``recon-pipeline`` shell. <file_sep>import shutil import tempfile from pathlib import Path from pipeline.recon import TargetList tfp = Path(__file__).parent.parent / "data" / "bitdiscovery" class TestReconTargets: def setup_method(self): self.tmp_path = Path(tempfile.mkdtemp()) shutil.copy(tfp, self.tmp_path) Path(self.tmp_path / "bitdiscovery").open(mode="a").writelines(["127.0.0.1"]) self.scan = TargetList( target_file=str(self.tmp_path / "bitdiscovery"), results_dir=str(self.tmp_path), db_location=str(self.tmp_path / "testing.sqlite"), ) def teardown_method(self): shutil.rmtree(self.tmp_path) def test_scan_creates_database(self): assert self.scan.db_mgr.location.exists() assert self.tmp_path / "testing.sqlite" == self.scan.db_mgr.location def test_scan_creates_results(self): assert self.scan.output().exists() <file_sep>.. _newscan-ref-label: Add a New Scanner ================= The process of adding a new scanner is relatively simple. The steps are outlined below. Create a tool definition file ----------------------------- This step isn't strictly necessary, but if you want the pipeline to know how to install/uninstall the tool your scanner uses, this is where that is defined. Tool definition files live in the ``pipeline/tools`` directory. .. code-block:: console pipeline/ ... ├── recon-pipeline.py └── tools ├── amass.yaml ├── aquatone.yaml ... Tool Definition Required Fields ******************************* Create a ``.yaml`` file with the following fields. +------------------+------------------+------------------------------------------------------------------------------------------------------------------+----------+ | Field Name | Type | Description | Required | +==================+==================+==================================================================================================================+==========+ | ``commands`` | Array of strings | Which commands to run to install the tool | True | +------------------+------------------+------------------------------------------------------------------------------------------------------------------+----------+ | ``dependencies`` | Array of strings | Each dependency must be defined in a separate definition | False | | | | file, as they'll be installed before the current defintion's tool | | +------------------+------------------+------------------------------------------------------------------------------------------------------------------+----------+ | ``environ`` | Dictionary | Use this if you need to pass information via the | False | | | | environment to your tool (amass.yaml has an example) | | +------------------+------------------+------------------------------------------------------------------------------------------------------------------+----------+ | ``shell`` | Boolean | true means each command in commands will be run via | False | | | | ``/bin/sh -c`` (see `Popen <https://docs.python.org/3.7/library/subprocess.html#subprocess.Popen>`_'s ``shell`` | | | | | argument for more details) | | +------------------+------------------+------------------------------------------------------------------------------------------------------------------+----------+ Useful yaml Helpers ******************* ``pipeline.tools.loader`` defines a few helpful functions to assist with dynamically creating values in yaml files as well as linking user-defined configuration values. Dynamically creating strings and filesystem paths are handled by the following two functions. - ``!join`` - join items in an array with a space character - ``!join_path`` - join items in an array with a ``/`` character In order to get values out of ``pipeline.recon.config.py``, you'll need to use one of the yaml helpers listed below. - ``!get_default`` - get a value from the ``pipeline.recon.config.defaults`` dictionary - ``!get_tool_path`` - get a path value from the ``pipeline.tools.tools`` dictionary Simple Example Tool Definition ****************************** The example below needs go to be installed prior to being installed itself. It then grabs the path to the ``go`` binary from ``pipeline.tools.tools`` by using ``!get_tool_path``. After that, it creates a command using ``!join`` that will look like ``/usr/local/go/bin/go get github.com/tomnomnom/waybackurls``. This command will be run by the ``install waybackurls`` command (or ``install all``). .. code-block:: yaml dependencies: [go] go: &gobin !get_tool_path "{go[path]}" commands: - !join [*gobin, get github.com/tomnomnom/waybackurls] If you're looking for a more complex example, check out ``searchsploit.yaml``. Write Your Scanner Class ------------------------ You can find an abundance of information on how to write your scanner class starting with `Part II <https://epi052.gitlab.io/notes-to-self/blog/2019-09-02-how-to-build-an-automated-recon-pipeline-with-python-and-luigi-part-two/>`_ of the blog posts tied to recon-pipeline's creation. Because scanner classes are covered in so much detail there, we'll only briefly summarize the steps here: - Select ``luigi.Task`` or ``luigi.ExternalTask`` as your base class. Task allows more flexibility while ExternalTask is great for simple scans. - Implement the ``requires``, ``output``, and either ``run`` (Task) or ``program_args`` (ExternalTask) methods Add Your Scan to a Wrapper (optional) ------------------------------------- If you want to run your new scan as part of an existing pipeline, open up ``pipeline.recon.wrappers`` and edit one of the existing wrappers (or add your own) to include your new scan. You should be able to import your new scan, and then add a ``yield MyNewScan(**args)`` in order to add it to the pipeline. The only gotcha here is that depending on what arguments your scan takes, you may need to strategically place your scan within the wrapper in order to ensure it doesn't get any arguments that it doesn't expect. <file_sep>import luigi from luigi.util import inherits from luigi.contrib.sqla import SQLAlchemyTarget import pipeline.models.db_manager from ..config import web_ports from ..amass import ParseAmassOutput from ..masscan import ParseMasscanOutput @inherits(ParseMasscanOutput) class GatherWebTargets(luigi.Task): """ Gather all subdomains as well as any ip addresses known to have a configured web port open. Args: db_location: specifies the path to the database used for storing results *Required by upstream Task* exempt_list: Path to a file providing blacklisted subdomains, one per line. *Optional by upstream Task* top_ports: Scan top N most popular ports *Required by upstream Task* ports: specifies the port(s) to be scanned *Required by upstream Task* interface: use the named raw network interface, such as "eth0" *Required by upstream Task* rate: desired rate for transmitting packets (packets per second) *Required by upstream Task* target_file: specifies the file on disk containing a list of ips or domains *Required by upstream Task* results_dir: specifes the directory on disk to which all Task results are written *Required by upstream Task* """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.db_mgr = pipeline.models.db_manager.DBManager(db_location=self.db_location) def requires(self): """ GatherWebTargets depends on ParseMasscanOutput and ParseAmassOutput to run. ParseMasscanOutput expects rate, target_file, interface, and either ports or top_ports as parameters. ParseAmassOutput accepts exempt_list and expects target_file Returns: dict(str: ParseMasscanOutput, str: ParseAmassOutput) """ args = { "results_dir": self.results_dir, "rate": self.rate, "target_file": self.target_file, "top_ports": self.top_ports, "interface": self.interface, "ports": self.ports, "db_location": self.db_location, } return { "masscan-output": ParseMasscanOutput(**args), "amass-output": ParseAmassOutput( exempt_list=self.exempt_list, target_file=self.target_file, results_dir=self.results_dir, db_location=self.db_location, ), } def output(self): """ Returns the target output for this task. Returns: luigi.contrib.sqla.SQLAlchemyTarget """ return SQLAlchemyTarget( connection_string=self.db_mgr.connection_string, target_table="target", update_id=self.task_id ) def run(self): """ Gather all potential web targets and tag them as web in the database. """ for target in self.db_mgr.get_all_targets(): ports = self.db_mgr.get_ports_by_ip_or_host_and_protocol(target, "tcp") if any(port in web_ports for port in ports): tgt = self.db_mgr.get_or_create_target_by_ip_or_hostname(target) tgt.is_web = True self.db_mgr.add(tgt) self.output().touch() # in the event that there are no web ports for any target, we still want to be able to mark the # task complete successfully. we accomplish this by calling .touch() even though a database entry # may not have happened self.output().touch() self.db_mgr.close() <file_sep>import sys import inspect import pkgutil import importlib import ipaddress from pathlib import Path from cmd2.ansi import style from collections import defaultdict from ..tools import tools def meets_requirements(requirements, exception): """ Determine if tools required to perform task are installed. """ for tool in requirements: if not tools.get(tool).get("installed"): if exception: raise RuntimeError( style(f"[!!] {tool} is not installed, and is required to run this scan", fg="bright_red") ) else: return False return True def get_scans(): """ Iterates over the recon package and its modules to find all of the classes that end in [Ss]can. **A contract exists here that says any scans need to end with the word scan in order to be found by this function.** Example: ``defaultdict(<class 'list'>, {'AmassScan': ['pipeline.recon.amass'], 'MasscanScan': ['pipeline.recon.masscan'], ... })`` Returns: dict containing mapping of ``classname -> [modulename, ...]`` for all potential recon-pipeline commands """ scans = defaultdict(list) file = Path(__file__).expanduser().resolve() web = file.parent / "web" recon = file.parents[1] / "recon" lib_paths = [str(web), str(recon)] # recursively walk packages; import each module in each package # walk_packages yields ModuleInfo objects for all modules recursively on path # prefix is a string to output on the front of every module name on output. for loader, module_name, is_pkg in pkgutil.walk_packages(path=lib_paths, prefix=f"{__package__}."): try: importlib.import_module(module_name) except ModuleNotFoundError: # skipping things like recon.aquatone, not entirely sure why they're showing up... pass # walk all modules, grabbing classes that we've written and add them to the classlist defaultdict # getmembers returns all members of an object in a list of tuples (name, value) for name, obj in inspect.getmembers(sys.modules[__package__]): if inspect.ismodule(obj) and not name.startswith("_"): # we're only interested in modules that don't begin with _ i.e. magic methods __len__ etc... for sub_name, sub_obj in inspect.getmembers(obj): # now we only care about classes that end in [Ss]can if inspect.isclass(sub_obj) and sub_name.lower().endswith("scan"): # final check, this ensures that the tools necessary to AT LEAST run this scan are present # does not consider upstream dependencies try: requirements = sub_obj.requirements exception = False # let meets_req know we want boolean result if not meets_requirements(requirements, exception): continue except AttributeError: # some scan's haven't implemented meets_requirements yet, silently allow them through pass scans[sub_name].append(f"{__package__}.{name}") return scans def is_ip_address(ipaddr): """ Simple helper to determine if given string is an ip address or subnet """ try: ipaddress.ip_interface(ipaddr) return True except ValueError: return False def get_ip_address_version(ipaddr): """ Simple helper to determine whether a given ip address is ipv4 or ipv6 """ if is_ip_address(ipaddr): if isinstance(ipaddress.ip_address(ipaddr), ipaddress.IPv4Address): # ipv4 addr return "4" elif isinstance(ipaddress.ip_address(ipaddr), ipaddress.IPv6Address): # ipv6 return "6" <file_sep>.. toctree:: :maxdepth: 1 :hidden: .. _commands-ref-label: Commands ======== ``recon-pipeline`` provides a handful of commands: - :ref:`tools_command` - :ref:`scan_command` - :ref:`status_command` - :ref:`database_command` - :ref:`view_command` All other available commands are inherited from `cmd2 <https://github.com/python-cmd2/cmd2>`_. .. _tools_command: tools ##### .. argparse:: :module: pipeline.recon :func: tools_parser :prog: tools .. _database_command: database ######## .. argparse:: :module: pipeline.recon :func: database_parser :prog: database .. _scan_command: scan #### .. argparse:: :module: pipeline.recon :func: scan_parser :prog: scan .. _status_command: status ###### .. argparse:: :module: pipeline.recon :func: status_parser :prog: status .. _view_command: view ####### .. argparse:: :module: pipeline.recon :func: view_parser :prog: view <file_sep>from sqlalchemy.orm import relationship from sqlalchemy import Column, Integer, ForeignKey, String from .base_model import Base class IPAddress(Base): """ Database model that describes an ip address (ipv4 or ipv6). Represents amass data or targets specified manually as part of the ``target-file``. Relationships: ``target``: many to one -> :class:`pipeline.models.target_model.Target` """ __tablename__ = "ip_address" id = Column(Integer, primary_key=True) ipv4_address = Column(String, unique=True) ipv6_address = Column(String, unique=True) target_id = Column(Integer, ForeignKey("target.id")) target = relationship("Target", back_populates="ip_addresses") <file_sep>import sys from contextlib import redirect_stdout, redirect_stderr from cmd2.utils import StdSim def normalize(block): """ Normalize a block of text to perform comparison. Strip newlines from the very beginning and very end Then split into separate lines and strip trailing whitespace from each line. """ assert isinstance(block, str) block = block.strip("\n") return [line.rstrip() for line in block.splitlines()] def run_cmd(app, cmd): """ Clear out and err StdSim buffers, run the command, and return out and err """ saved_sysout = sys.stdout sys.stdout = app.stdout # This will be used to capture app.stdout and sys.stdout copy_cmd_stdout = StdSim(app.stdout) # This will be used to capture sys.stderr copy_stderr = StdSim(sys.stderr) try: app.stdout = copy_cmd_stdout with redirect_stdout(copy_cmd_stdout): with redirect_stderr(copy_stderr): app.onecmd_plus_hooks(cmd) finally: app.stdout = copy_cmd_stdout.inner_stream sys.stdout = saved_sysout out = copy_cmd_stdout.getvalue() err = copy_stderr.getvalue() print(out) print(err) return normalize(out), normalize(err) <file_sep>import shutil import tempfile from pathlib import Path from unittest.mock import MagicMock, patch from pipeline.recon.web import GatherWebTargets from pipeline.recon import ParseMasscanOutput, ParseAmassOutput class TestGatherWebTargets: def setup_method(self): self.tmp_path = Path(tempfile.mkdtemp()) self.scan = GatherWebTargets( target_file=__file__, results_dir=str(self.tmp_path), db_location=str(self.tmp_path / "testing.sqlite") ) self.scan.exception = False def teardown_method(self): shutil.rmtree(self.tmp_path) def test_scan_requires(self): with patch("pipeline.recon.ParseMasscanOutput"), patch("pipeline.recon.ParseAmassOutput"): retval = self.scan.requires() assert isinstance(retval.get("masscan-output"), ParseMasscanOutput) assert isinstance(retval.get("amass-output"), ParseAmassOutput) def test_scan_creates_database(self): assert self.scan.db_mgr.location.exists() assert self.tmp_path / "testing.sqlite" == self.scan.db_mgr.location def test_scan_run(self): self.scan.db_mgr.add = MagicMock() self.scan.db_mgr.get_all_targets = MagicMock(return_value=["google.com"]) self.scan.db_mgr.get_ports_by_ip_or_host_and_protocol = MagicMock(return_value=["80", "443"]) self.scan.db_mgr.get_or_create_target_by_ip_or_hostname = MagicMock() self.scan.run() assert self.scan.db_mgr.add.called assert self.scan.db_mgr.get_all_targets.called assert self.scan.db_mgr.get_ports_by_ip_or_host_and_protocol.called assert self.scan.db_mgr.get_or_create_target_by_ip_or_hostname.called <file_sep>import json import shutil import tempfile from pathlib import Path from unittest.mock import patch, MagicMock from pipeline.recon.web import AquatoneScan, GatherWebTargets aquatone_results = Path(__file__).parent.parent / "data" / "recon-results" / "aquatone-results" class TestAquatoneScan: def setup_method(self): self.tmp_path = Path(tempfile.mkdtemp()) self.scan = AquatoneScan( target_file=__file__, results_dir=str(self.tmp_path), db_location=str(self.tmp_path / "testing.sqlite") ) self.scan.exception = False def teardown_method(self): shutil.rmtree(self.tmp_path) def test_scan_requires(self): with patch("pipeline.recon.web.GatherWebTargets"): with patch("pipeline.recon.web.aquatone.meets_requirements"): retval = self.scan.requires() assert isinstance(retval, GatherWebTargets) def test_scan_creates_results_dir(self): assert self.scan.results_subfolder == self.tmp_path / "aquatone-results" def test_scan_creates_database(self): assert self.scan.db_mgr.location.exists() assert self.tmp_path / "testing.sqlite" == self.scan.db_mgr.location def test_scan_creates_results(self): # self.scan.results_subfolder.mkdir() myresults = self.scan.results_subfolder / "aquatone_session.json" shutil.copytree(aquatone_results, self.scan.results_subfolder) with open(myresults) as f: # results.keys -> dict_keys(['version', 'stats', 'pages', 'pageSimilarityClusters']) results = json.load(f) for page, page_dict in results.get("pages").items(): if "hasScreenshot" not in page_dict: continue page_dict["hasScreenshot"] = False break with open(myresults, "w") as f: json.dump(results, f) self.scan.parse_results() assert self.scan.output().exists() # pipeline/recon/web/aquatone.py 83 17 80% 69-79, 183-191, 236-260 def test_scan_parse_results_with_bad_file(self, caplog): self.scan.results_subfolder = Path("/tmp") assert not (self.scan.results_subfolder / "aquatone_session.json").exists() self.scan.parse_results() assert "[Errno 2] No such file or directory:" in caplog.text def test_scan_run(self): with patch("subprocess.run") as mocked_run: self.scan.parse_results = MagicMock() self.scan.db_mgr.get_all_web_targets = MagicMock() self.scan.db_mgr.get_all_web_targets.return_value = ["google.com"] self.scan.run() assert self.scan.parse_results.called assert mocked_run.called <file_sep>sphinx-argparse==0.2.5 sphinx-rtd-theme==0.4.3 sphinxcontrib-napoleon==0.7 cmd2==1.0.1 luigi==2.8.12 python-libnmap==0.7.0 sqlalchemy==1.3.15 pyyaml==5.4.0 <file_sep>.. _scan-ref-label: Running Scans ============= All scans are run from within ``recon-pipeline``'s shell. There are a number of individual scans, however to execute multiple scans at once, ``recon-pipeline`` includes wrappers around multiple commands. As of version |version|, the following individual scans are available - :class:`pipeline.recon.amass.AmassScan` - :class:`pipeline.recon.web.aquatone.AquatoneScan` - :class:`pipeline.recon.web.gobuster.GobusterScan` - :class:`pipeline.recon.masscan.MasscanScan` - :class:`pipeline.recon.nmap.SearchsploitScan` - :class:`pipeline.recon.web.subdomain_takeover.SubjackScan` - :class:`pipeline.recon.nmap.ThreadedNmapScan` - :class:`pipeline.recon.web.subdomain_takeover.TKOSubsScan` - :class:`pipeline.recon.web.waybackurls.WaybackurlsScan` - :class:`pipeline.recon.web.webanalyze.WebanalyzeScan` Additionally, two wrapper scans are made available. These execute multiple scans in a pipeline. - :class:`pipeline.recon.wrappers.FullScan` - runs the entire pipeline - :class:`pipeline.recon.wrappers.HTBScan` - nicety for hackthebox players (myself included) that omits the scans in FullScan that don't make sense for HTB Example Scan ############ Here are the steps the video below takes to scan tesla[.]com. Create a targetfile .. code-block:: console # use virtual environment pipenv shell # create targetfile; a targetfile is required for all scans mkdir /root/bugcrowd/tesla cd /root/bugcrowd/tesla echo tesla.com > tesla-targetfile # create a blacklist (if necessary based on target's scope) echo energysupport.tesla.com > tesla-blacklist echo feedback.tesla.com >> tesla-blacklist echo employeefeedback.tesla.com >> tesla-blacklist echo ir.tesla.com >> tesla-blacklist # drop into the interactive shell /root/PycharmProjects/recon-pipeline/pipeline/recon-pipeline.py recon-pipeline> **New as of v0.9.0**: In the event you're scanning a single ip address or host, simply use ``--target``. It accepts a single target and works in conjunction with ``--exempt-list`` if specified. Create a new database to store scan results .. code-block:: console recon-pipeline> database attach 1. create new database Your choice? 1 new database name? (recommend something unique for this target) -> tesla-scan [*] created database @ /home/epi/.local/recon-pipeline/databases/tesla-scan [+] attached to sqlite database @ /home/epi/.local/recon-pipeline/databases/tesla-scan [db-1] recon-pipeline> Scan the target .. code-block:: console [db-1] recon-pipeline> scan FullScan --exempt-list tesla-blacklist --target-file tesla-targetfile --interface eno1 --top-ports 2000 --rate 1200 [-] FullScan queued [-] TKOSubsScan queued [-] GatherWebTargets queued [-] ParseAmassOutput queued [-] AmassScan queued [-] ParseMasscanOutput queued [-] MasscanScan queued [-] WebanalyzeScan queued [-] SearchsploitScan queued [-] ThreadedNmapScan queued [-] WaybackurlsScan queued [-] SubjackScan queued [-] AquatoneScan queued [-] GobusterScan queued [db-1] recon-pipeline> .. raw:: html <script id="asciicast-318397" src="https://asciinema.org/a/318397.js" async></script> Existing Results Directories and You #################################### When running additional scans against the same target, you have a few options. You can either - use a new directory - reuse the same directory If you use a new directory, the scan will start from the beginning. If you choose to reuse the same directory, ``recon-pipeline`` will resume the scan from its last successful point. For instance, say your last scan failed while running nmap. This means that the pipeline executed all upstream tasks (amass and masscan) successfully. When you use the same results directory for another scan, the amass and masscan scans will be skipped, because they've already run successfully. **Note**: There is a gotcha that can occur when you scan a target but get no results. For some scans, the pipeline may still mark the Task as complete (masscan does this). In masscan's case, it's because it outputs a file to ``results-dir/masscan-results/`` whether it gets results or not. Luigi interprets the file's presence to mean the scan is complete. In order to reduce confusion, as of version 0.9.3, the pipeline will prompt you when reusing results directory. .. code-block:: console [db-2] recon-pipeline> scan FullScan --results-dir testing-results --top-ports 1000 --rate 500 --target tesla.com [*] Your results-dir (testing-results) already exists. Subfolders/files may tell the pipeline that the associated Task is complete. This means that your scan may start from a point you don't expect. Your options are as follows: 1. Resume existing scan (use any existing scan data & only attempt to scan what isn't already done) 2. Remove existing directory (scan starts from the beginning & all existing results are removed) 3. Save existing directory (your existing folder is renamed and your scan proceeds) Your choice? <file_sep>import luigi from luigi.util import inherits from .nmap import SearchsploitScan from .helpers import meets_requirements from .web import AquatoneScan, GobusterScan, SubjackScan, TKOSubsScan, WaybackurlsScan, WebanalyzeScan @inherits(SearchsploitScan, AquatoneScan, TKOSubsScan, SubjackScan, GobusterScan, WebanalyzeScan) class FullScan(luigi.WrapperTask): """ Wraps multiple scan types in order to run tasks on the same hierarchical level at the same time. Note: Because FullScan is a wrapper, it requires all Parameters for any of the Scans that it wraps. Args: threads: number of threads for parallel gobuster command execution wordlist: wordlist used for forced browsing extensions: additional extensions to apply to each item in the wordlist recursive: whether or not to recursively gobust the target (may produce a LOT of traffic... quickly) proxy: protocol://ip:port proxy specification for gobuster exempt_list: Path to a file providing blacklisted subdomains, one per line. top_ports: Scan top N most popular ports ports: specifies the port(s) to be scanned interface: use the named raw network interface, such as "eth0" rate: desired rate for transmitting packets (packets per second) target_file: specifies the file on disk containing a list of ips or domains results_dir: specifes the directory on disk to which all Task results are written """ requirements = [ "amass", "aquatone", "masscan", "tko-subs", "recursive-gobuster", "searchsploit", "subjack", "gobuster", "webanalyze", "waybackurls", "go", ] exception = True def requires(self): """ FullScan is a wrapper, as such it requires any Tasks that it wraps. """ meets_requirements(self.requirements, self.exception) args = { "results_dir": self.results_dir, "rate": self.rate, "target_file": self.target_file, "top_ports": self.top_ports, "interface": self.interface, "ports": self.ports, "exempt_list": self.exempt_list, "threads": self.threads, "proxy": self.proxy, "wordlist": self.wordlist, "extensions": self.extensions, "recursive": self.recursive, "db_location": self.db_location, } yield GobusterScan(**args) # remove options that are gobuster specific; if left dictionary unpacking to other scans throws an exception for gobuster_opt in ("proxy", "wordlist", "extensions", "recursive"): del args[gobuster_opt] # add aquatone scan specific option args.update({"scan_timeout": self.scan_timeout}) yield AquatoneScan(**args) del args["scan_timeout"] yield SubjackScan(**args) yield SearchsploitScan(**args) yield WebanalyzeScan(**args) del args["threads"] yield TKOSubsScan(**args) yield WaybackurlsScan(**args) @inherits(SearchsploitScan, AquatoneScan, GobusterScan, WebanalyzeScan) class HTBScan(luigi.WrapperTask): """ Wraps multiple scan types in order to run tasks on the same hierarchical level at the same time. Note: Because HTBScan is a wrapper, it requires all Parameters for any of the Scans that it wraps. Args: threads: number of threads for parallel gobuster command execution wordlist: wordlist used for forced browsing extensions: additional extensions to apply to each item in the wordlist recursive: whether or not to recursively gobust the target (may produce a LOT of traffic... quickly) proxy: protocol://ip:port proxy specification for gobuster exempt_list: Path to a file providing blacklisted subdomains, one per line. top_ports: Scan top N most popular ports ports: specifies the port(s) to be scanned interface: use the named raw network interface, such as "eth0" rate: desired rate for transmitting packets (packets per second) target_file: specifies the file on disk containing a list of ips or domains results_dir: specifes the directory on disk to which all Task results are written """ requirements = ["aquatone", "go", "masscan", "recursive-gobuster", "searchsploit", "gobuster", "webanalyze"] exception = True def requires(self): """ HTBScan is a wrapper, as such it requires any Tasks that it wraps. """ meets_requirements(self.requirements, self.exception) args = { "results_dir": self.results_dir, "rate": self.rate, "target_file": self.target_file, "top_ports": self.top_ports, "interface": self.interface, "ports": self.ports, "exempt_list": self.exempt_list, "threads": self.threads, "proxy": self.proxy, "db_location": self.db_location, "wordlist": self.wordlist, "extensions": self.extensions, "recursive": self.recursive, } yield GobusterScan(**args) # remove options that are gobuster specific; if left dictionary unpacking to other scans throws an exception for gobuster_opt in ("proxy", "wordlist", "extensions", "recursive"): del args[gobuster_opt] # add aquatone scan specific option args.update({"scan_timeout": self.scan_timeout}) yield AquatoneScan(**args) del args["scan_timeout"] yield SearchsploitScan(**args) yield WebanalyzeScan(**args) <file_sep>from pipeline.models.technology_model import Technology from pipeline.models.searchsploit_model import SearchsploitResult from pipeline.models.nmap_model import NmapResult from pipeline.models.port_model import Port from pipeline.models.ip_address_model import IPAddress def test_technology_pretty(): assert Technology().pretty() == Technology().__str__() def test_searchsploit_pretty(): ssr = SearchsploitResult(path="stuff", type="exploit", title="super cool title") assert ssr.pretty() == ssr.__str__() def test_nmap_pretty(): nmr = NmapResult( ip_address=IPAddress(ipv4_address="127.0.0.1"), service="http", port=Port(port_number="80", protocol="tcp") ) assert nmr.pretty() == nmr.__str__() <file_sep>from sqlalchemy.orm import relationship from sqlalchemy import Column, Integer, ForeignKey, String, UniqueConstraint, Table from .base_model import Base nse_result_association_table = Table( "nse_result_association", Base.metadata, Column("nse_result_id", Integer, ForeignKey("nse_result.id")), Column("nmap_result_id", Integer, ForeignKey("nmap_result.id")), ) class NSEResult(Base): """ Database model that describes the NSE script executions as part of an nmap scan. Represents NSE script data. Relationships: ``NmapResult``: many to many -> :class:`pipeline.models.nmap_model.NmapResult` """ __tablename__ = "nse_result" __table_args__ = (UniqueConstraint("script_id", "script_output"),) # combination of proto/port == unique id = Column(Integer, primary_key=True) script_id = Column(String) script_output = Column(String) nmap_result_id = Column(Integer, ForeignKey("nmap_result.id")) nmap_results = relationship("NmapResult", secondary=nse_result_association_table, back_populates="nse_results") <file_sep>import re import csv import subprocess from pathlib import Path import luigi from luigi.util import inherits from luigi.contrib.sqla import SQLAlchemyTarget import pipeline.models.db_manager from ...tools import tools from ..config import defaults from ..helpers import meets_requirements from .targets import GatherWebTargets @inherits(GatherWebTargets) class TKOSubsScan(luigi.Task): """ Use ``tko-subs`` to scan for potential subdomain takeovers. Install: .. code-block:: console go get github.com/anshumanbh/tko-subs cd ~/go/src/github.com/anshumanbh/tko-subs go build go install Basic Example: .. code-block:: console tko-subs -domains=tesla.subdomains -data=/root/go/src/github.com/anshumanbh/tko-subs/providers-data.csv -output=tkosubs.tesla.csv Luigi Example: .. code-block:: console PYTHONPATH=$(pwd) luigi --local-scheduler --module recon.web.subdomain_takeover TKOSubsScan --target-file tesla --top-ports 1000 --interface eth0 Args: db_location: specifies the path to the database used for storing results *Required by upstream Task* exempt_list: Path to a file providing blacklisted subdomains, one per line. *Optional by upstream Task* top_ports: Scan top N most popular ports *Required by upstream Task* ports: specifies the port(s) to be scanned *Required by upstream Task* interface: use the named raw network interface, such as "eth0" *Required by upstream Task* rate: desired rate for transmitting packets (packets per second) *Required by upstream Task* target_file: specifies the file on disk containing a list of ips or domains *Required by upstream Task* results_dir: specifes the directory on disk to which all Task results are written *Required by upstream Task* """ requirements = ["go", "tko-subs", "masscan"] exception = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.db_mgr = pipeline.models.db_manager.DBManager(db_location=self.db_location) self.results_subfolder = (Path(self.results_dir) / "tkosubs-results").expanduser().resolve() self.output_file = self.results_subfolder / "tkosubs.csv" def requires(self): """ TKOSubsScan depends on GatherWebTargets to run. GatherWebTargets accepts exempt_list and expects rate, target_file, interface, and either ports or top_ports as parameters Returns: luigi.Task - GatherWebTargets """ meets_requirements(self.requirements, self.exception) args = { "results_dir": self.results_dir, "rate": self.rate, "target_file": self.target_file, "top_ports": self.top_ports, "interface": self.interface, "ports": self.ports, "exempt_list": self.exempt_list, "db_location": self.db_location, } return GatherWebTargets(**args) def output(self): """ Returns the target output for this task. Returns: luigi.contrib.sqla.SQLAlchemyTarget """ return SQLAlchemyTarget( connection_string=self.db_mgr.connection_string, target_table="target", update_id=self.task_id ) def parse_results(self): """ Reads in the tkosubs .csv file and updates the associated Target record. """ with open(self.output_file, newline="") as f: reader = csv.reader(f) next(reader, None) # skip the headers for row in reader: domain = row[0] is_vulnerable = row[3] if "true" in is_vulnerable.lower(): tgt = self.db_mgr.get_or_create_target_by_ip_or_hostname(domain) tgt.vuln_to_sub_takeover = True self.db_mgr.add(tgt) self.output().touch() self.db_mgr.close() # make sure task doesn't fail due to no results, it's the last in its chain, so doesn't # affect any downstream tasks self.output().touch() def run(self): """ Defines the options/arguments sent to tko-subs after processing. Returns: list: list of options/arguments, beginning with the name of the executable to run """ self.results_subfolder.mkdir(parents=True, exist_ok=True) domains = self.db_mgr.get_all_hostnames() if not domains: return command = [ tools.get("tko-subs").get("path"), f"-domain={','.join(domains)}", f"-data={tools.get('tko-subs').get('providers')}", f"-output={self.output_file}", ] subprocess.run(command) self.parse_results() @inherits(GatherWebTargets) class SubjackScan(luigi.Task): """ Use ``subjack`` to scan for potential subdomain takeovers. Install: .. code-block:: console go get github.com/haccer/subjack cd ~/go/src/github.com/haccer/subjack go build go install Basic Example: .. code-block:: console subjack -w webtargets.tesla.txt -t 100 -timeout 30 -o subjack.tesla.txt -ssl Luigi Example: .. code-block:: console PYTHONPATH=$(pwd) luigi --local-scheduler --module recon.web.subdomain_takeover SubjackScan --target-file tesla --top-ports 1000 --interface eth0 Args: threads: number of threads for parallel subjack command execution db_location: specifies the path to the database used for storing results *Required by upstream Task* exempt_list: Path to a file providing blacklisted subdomains, one per line. *Optional by upstream Task* top_ports: Scan top N most popular ports *Required by upstream Task* ports: specifies the port(s) to be scanned *Required by upstream Task* interface: use the named raw network interface, such as "eth0" *Required by upstream Task* rate: desired rate for transmitting packets (packets per second) *Required by upstream Task* target_file: specifies the file on disk containing a list of ips or domains *Required by upstream Task* results_dir: specifes the directory on disk to which all Task results are written *Required by upstream Task* """ threads = luigi.Parameter(default=defaults.get("threads")) requirements = ["go", "subjack", "masscan"] exception = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.db_mgr = pipeline.models.db_manager.DBManager(db_location=self.db_location) self.results_subfolder = (Path(self.results_dir) / "subjack-results").expanduser().resolve() self.output_file = self.results_subfolder / "subjack.txt" def requires(self): """ SubjackScan depends on GatherWebTargets to run. GatherWebTargets accepts exempt_list and expects rate, target_file, interface, and either ports or top_ports as parameters Returns: luigi.Task - GatherWebTargets """ meets_requirements(self.requirements, self.exception) args = { "results_dir": self.results_dir, "rate": self.rate, "target_file": self.target_file, "top_ports": self.top_ports, "interface": self.interface, "ports": self.ports, "exempt_list": self.exempt_list, "db_location": self.db_location, } return GatherWebTargets(**args) def output(self): """ Returns the target output for this task. Returns: luigi.contrib.sqla.SQLAlchemyTarget """ return SQLAlchemyTarget( connection_string=self.db_mgr.connection_string, target_table="target", update_id=self.task_id ) def parse_results(self): """ Reads in the subjack's subjack.txt file and updates the associated Target record. """ with open(self.output_file) as f: """ example data [Not Vulnerable] 192.168.3.11:443 [Not Vulnerable] 172.16.58.3 [Not Vulnerable] fc00:db20:35b:7399::5:3d33 [Not Vulnerable] assetinventory.bugcrowd.com """ for line in f: match = re.match(r"\[(?P<vuln_status>.+)] (?P<ip_or_hostname>.*)", line) if not match: continue if match.group("vuln_status") == "Not Vulnerable": continue ip_or_host = match.group("ip_or_hostname") if ip_or_host.count(":") == 1: # ip or host/port ip_or_host, port = ip_or_host.split(":", maxsplit=1) tgt = self.db_mgr.get_or_create_target_by_ip_or_hostname(ip_or_host) tgt.vuln_to_sub_takeover = True self.db_mgr.add(tgt) self.output().touch() self.db_mgr.close() # make sure task doesn't fail due to no results, it's the last in its chain, so doesn't # affect any downstream tasks self.output().touch() def run(self): """ Defines the options/arguments sent to subjack after processing. Returns: list: list of options/arguments, beginning with the name of the executable to run """ self.results_subfolder.mkdir(parents=True, exist_ok=True) hostnames = self.db_mgr.get_all_hostnames() if not hostnames: return subjack_input_file = self.results_subfolder / "input-from-webtargets" with open(subjack_input_file, "w") as f: for hostname in hostnames: f.write(f"{hostname}\n") command = [ tools.get("subjack").get("path"), "-w", str(subjack_input_file), "-t", self.threads, "-a", "-timeout", "30", "-o", str(self.output_file), "-v", "-ssl", "-c", tools.get("subjack").get("fingerprints"), ] subprocess.run(command) self.parse_results() subjack_input_file.unlink() <file_sep>.. toctree:: :maxdepth: 1 :hidden: .. _scanners-ref-label: Scanners ================ Amass Scanner ############# .. autoclass:: pipeline.recon.amass.AmassScan :members: Aquatone Scanner ################ .. autoclass:: pipeline.recon.web.aquatone.AquatoneScan :members: Full Scanner ############ .. autoclass:: pipeline.recon.wrappers.FullScan :members: Gobuster Scanner ################ .. autoclass:: pipeline.recon.web.gobuster.GobusterScan :members: Hackthebox Scanner ################## .. autoclass:: pipeline.recon.wrappers.HTBScan :members: Masscan Scanner ############### .. autoclass:: pipeline.recon.masscan.MasscanScan :members: Searchsploit Scanner #################### .. autoclass:: pipeline.recon.nmap.SearchsploitScan :members: Subjack Scanner ############### .. autoclass:: pipeline.recon.web.subdomain_takeover.SubjackScan :members: ThreadedNmap Scanner #################### .. autoclass:: pipeline.recon.nmap.ThreadedNmapScan :members: TKOSubs Scanner ############### .. autoclass:: pipeline.recon.web.subdomain_takeover.TKOSubsScan :members: WaybackurlsScan Scanner ####################### .. autoclass:: pipeline.recon.web.waybackurls.WaybackurlsScan :members: Webanalyze Scanner ################## .. autoclass:: pipeline.recon.web.webanalyze.WebanalyzeScan :members: <file_sep>Making Changes to the pipeline ############################## .. toctree:: :maxdepth: 1 :hidden: new_scanner new_wrapper There are a few things you can do to modify the pipeline to your own specifications: * :ref:`newscan-ref-label` * :ref:`newwrapper-ref-label` <file_sep># noqa: E405 import pytest from pipeline.recon.parsers import * # noqa: F403 from pipeline.tools import tools @pytest.mark.parametrize("test_input", list(tools.keys()) + ["all"]) def test_tools_parsers_good(test_input): for parser in [tools_install_parser, tools_uninstall_parser, tools_reinstall_parser]: parsed = parser.parse_args([test_input]) assert parsed.tool == test_input @pytest.mark.parametrize( "test_input, expected", [ (1, TypeError), (1.0, TypeError), ("invalid choice", SystemExit), (["all", "-i"], SystemExit), (["all", "--invalid"], SystemExit), ], ) def test_tools_parsers_raises(test_input, expected): for parser in [tools_install_parser, tools_uninstall_parser, tools_reinstall_parser]: with pytest.raises(expected): parser.parse_args([test_input]) @pytest.mark.parametrize( "test_input, expected", [ ((None, None), ("127.0.0.1", "8082")), (("::1", "8000"), ("::1", "8000")), ((None, "8000"), ("127.0.0.1", "8000")), (("10.0.0.1", None), ("10.0.0.1", "8082")), ], ) def test_status_parser_good(test_input, expected): args = list() for arg, ti in zip(("--host", "--port"), test_input): if not ti: continue args += [arg, ti] parsed = status_parser.parse_args(args) exp_host, exp_port = expected assert parsed.host == exp_host assert parsed.port == exp_port @pytest.mark.parametrize( "test_input, expected", [ ((1, None), TypeError), ((1.0, None), TypeError), ((None, None, "invalid_positional"), SystemExit), ((None, None, "-i"), SystemExit), ((None, None, "--invalid"), SystemExit), ], ) def test_status_parser_raises(test_input, expected): with pytest.raises(expected): args = list() for arg, ti in zip(("--host", "--port"), test_input): if not ti: continue args += [arg, ti] if len(test_input) > 2: args += test_input[2:] status_parser.parse_args(args) @pytest.mark.parametrize("test_input", get_scans()) def test_scan_parser_positional_choices(test_input): parsed = scan_parser.parse_args([test_input, "--target-file", "required"]) assert parsed.scantype == test_input @pytest.mark.parametrize("test_input", [x[1] for x in socket.if_nameindex()]) def test_scan_parser_interface_choices(test_input): parsed = scan_parser.parse_args(["FullScan", "--interface", test_input, "--target-file", "required"]) assert parsed.interface == test_input @pytest.mark.parametrize("option_one, option_two", [("--ports", "--top-ports"), ("--target-file", "--target")]) def test_scan_parser_mutual_exclusion(option_one, option_two): with pytest.raises(SystemExit): port_arg = "1111" scan_parser.parse_args(["FullScan", option_one, port_arg, option_two, "target-arg"]) @pytest.mark.parametrize( "test_input, expected", [("verbose", False), ("local_scheduler", False), ("recursive", False), ("sausage", False)] ) def test_scan_parser_defaults(test_input, expected): parsed = scan_parser.parse_known_args(["FullScan", "--target-file", "required"])[0] assert getattr(parsed, test_input) == expected def test_technology_results_parser_defaults(): parsed = technology_results_parser.parse_known_args(["FullScan", "--target-file", "required"])[0] assert not parsed.paged def test_port_results_parser_defaults(): parsed = port_results_parser.parse_known_args(["FullScan", "--target-file", "required"])[0] assert not parsed.paged @pytest.mark.parametrize("test_input, expected", [("headers", False), ("paged", False), ("plain", False)]) def test_endpoint_results_parser_defaults(test_input, expected): parsed = endpoint_results_parser.parse_known_args(["FullScan", "--target-file", "required"])[0] assert getattr(parsed, test_input) == expected @pytest.mark.parametrize("test_input, expected", [("commandline", False), ("paged", False)]) def test_nmap_results_parser_defaults(test_input, expected): parsed = nmap_results_parser.parse_known_args(["FullScan", "--target-file", "required"])[0] assert getattr(parsed, test_input) == expected @pytest.mark.parametrize("test_input, expected", [("fullpath", False), ("paged", False)]) def test_searchsploit_results_parser_defaults(test_input, expected): parsed = searchsploit_results_parser.parse_known_args(["FullScan", "--target-file", "required"])[0] assert getattr(parsed, test_input) == expected <file_sep>import shutil import tempfile from pathlib import Path from unittest.mock import MagicMock, patch from pipeline.recon.web import WaybackurlsScan, GatherWebTargets class TestGatherWebTargets: def setup_method(self): self.tmp_path = Path(tempfile.mkdtemp()) self.scan = WaybackurlsScan( target_file=__file__, results_dir=str(self.tmp_path), db_location=str(self.tmp_path / "testing.sqlite") ) self.scan.exception = False def teardown_method(self): shutil.rmtree(self.tmp_path) def test_scan_requires(self): with patch("pipeline.recon.web.GatherWebTargets"): with patch("pipeline.recon.web.waybackurls.meets_requirements"): retval = self.scan.requires() assert isinstance(retval, GatherWebTargets) def test_scan_creates_database(self): assert self.scan.db_mgr.location.exists() assert self.tmp_path / "testing.sqlite" == self.scan.db_mgr.location def test_scan_creates_results_dir(self): assert self.scan.results_subfolder == self.tmp_path / "waybackurls-results" def test_scan_run(self): with patch("subprocess.run", autospec=True) as mocked_run: self.scan.results_subfolder = self.tmp_path / "waybackurls-results" self.scan.db_mgr.get_all_hostnames = MagicMock() self.scan.db_mgr.get_all_hostnames.return_value = ["google.com"] completed_process_mock = MagicMock() completed_process_mock.stdout.return_value = b"https://drive.google.com\nhttps://maps.google.com\n\n" completed_process_mock.stdout.decode.return_value = "https://drive.google.com\nhttps://maps.google.com\n\n" completed_process_mock.stdout.decode.splitlines.return_value = [ "https://drive.google.com", "https://maps.google.com", ] mocked_run.return_value = completed_process_mock self.scan.db_mgr.add = MagicMock() self.scan.db_mgr.get_or_create = MagicMock() self.scan.db_mgr.get_or_create_target_by_ip_or_hostname = MagicMock() self.scan.run() assert mocked_run.called assert self.scan.db_mgr.add.called assert self.scan.db_mgr.get_or_create.called assert self.scan.db_mgr.get_or_create_target_by_ip_or_hostname.called <file_sep>.. toctree:: :maxdepth: 1 :hidden: .. _db_manager_label: Database Manager ================ .. autoclass:: pipeline.models.db_manager.DBManager :members:
67e7c0f06e8aef9579bf3761ff6af76e5eafb590
[ "HTML", "reStructuredText", "TOML", "Markdown", "INI", "Python", "Text", "Dockerfile" ]
75
reStructuredText
epi052/recon-pipeline
4930f4064ca42c4b3669444b92dee355dd68b81e
d1c711f5fd7ceccc95eda13004287d030452fe90
refs/heads/master
<file_sep># Test MongoDB Connection A console application for testing connection to a MongoDB instance. ## Main This repository contains Sitecore console app, which tests databases' connections in MongoDB using MongoDB .NET\C# Driver. ## Deployment To run the app, perform the following steps on both Content Managment (CM) and Content Delivery (CD) servers: 1. In the `\bin\TestMongoDBConnection.exe.config` file, modify the following connecting strings: * `analytics` * `tracking.live` * `tracking.history` * `tracking.contact` 2. Run the `\bin\TestMongoDBConnection.exe` file. > The log is saved into the `\bin\Sitecore.Log.{Data.Time}.txt` file. ## Content Sitecore Diagnostics app includes the following files: 1. `\bin\MongoDB.Bson.dll` 2. `\bin\MongoDB.Driver.dll` 3. `\bin\TestMongoDBConnection.exe` 4. `\bin\TestMongoDBConnection.exe.config` ## License This tool is licensed under the [Sitecore Corporation A/S License](./LICENSE). ## Download Downloads are available via [GitHub Releases](https://github.com/SitecoreSupport/TestMongoDBConnection/releases). [![Total downloads](https://img.shields.io/github/downloads/SitecoreSupport/TestMongoDBConnection/total.svg)](https://github.com/SitecoreSupport/TestMongoDBConnection/releases) <file_sep>using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Sitecore.Support.TestMongoDBConnection")] [assembly: AssemblyProduct("Sitecore.Support.TestMongoDBConnection")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: AssemblyInformationalVersion("1.1.0 rev. 170501")] [assembly: AssemblyDescription("Sitecore Support Diagnostics")] [assembly: AssemblyCompany("Sitecore Corporation")] [assembly: AssemblyCopyright("Copyright © 2017 Sitecore Corporation")] [assembly: AssemblyTrademark("Sitecore® is a registered trademark of Sitecore Corporation")] [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("893d8b32-7123-47ad-86cd-df5ce60bd4d9")]<file_sep>using MongoDB.Driver; using System; using System.Configuration; using System.Globalization; using System.IO; using System.Linq; using System.Text; namespace TestMongoDBConnection { class Program { private static readonly StringBuilder Log = new StringBuilder(); private static void Main() { foreach (ConnectionStringSettings setting in ConfigurationManager.ConnectionStrings) { if (!setting.Name.Equals("LocalSqlServer")) { TestConnectionString(setting.Name, setting.ConnectionString); } } DumpLog(Log); Console.WriteLine("Press any key to close."); Console.ReadKey(); } private static void TestConnectionString(string name, string connectionString) { Log.AppendLine(); Log.AppendLine($"====== Test Date: {DateTime.Now.ToString(CultureInfo.InvariantCulture)} ======"); Log.AppendLine(); Log.AppendLine($"Connection Name: {name}."); Log.AppendLine($"Connection String: {connectionString}."); try { MongoClient client = new MongoClient(connectionString); var mongoServer = client.GetServer(); // Because of https://jira.mongodb.org/browse/CSHARP-881 mongoServer.Connect(); var buildInfos = mongoServer.Instances.Select(x => x.BuildInfo).Where(w => w != null); var versionStrings = buildInfos.Select(x => x.VersionString); Log.AppendLine(); Log.AppendLine($"MongoDB version: {string.Join(" | ", versionStrings)}."); Log.AppendLine("Connect is successful."); Log.AppendLine(); } catch (Exception exception) { Log.AppendLine($"{exception.Message}{exception.InnerException}{exception.StackTrace}"); } } private static void DumpLog(StringBuilder log) { Console.WriteLine(log); var fileName = $"Support.Log.{DateTime.Now.ToString("yyyyMMdd.hhmmss")}.txt"; using (StreamWriter writer = new StreamWriter(fileName)) { writer.Write(log); } } } }
93060b71f111e87aa16547b4bb32103cec365780
[ "Markdown", "C#" ]
3
Markdown
olegburov/TestMongoDBConnection
19aa0429750a9f287ae25568c71054c77fc4113a
f40828f0c8b69c50f13d676b42d2564c1cfe8fb0
refs/heads/master
<repo_name>caesai/nuland-app<file_sep>/src/reducers/index.js import { combineReducers } from 'redux'; import * as authReducers from './auth'; import * as navReducers from './nav'; import * as popupReducers from './popup'; import * as geoLocation from './geoLocation'; export default combineReducers(Object.assign( authReducers, popupReducers, navReducers, geoLocation )) <file_sep>/android/settings.gradle rootProject.name = 'NuLand' include ':react-native-randombytes' project(':react-native-randombytes').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-randombytes/android') include ':react-native-vector-icons' project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android') include ':react-native-fs' project(':react-native-fs').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fs/android') include ':react-native-camera' project(':react-native-camera').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-camera/android') include ':react-native-fetch-blob' project(':react-native-fetch-blob').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fetch-blob/android') include ':mapbox-react-native-mapbox-gl' project(':mapbox-react-native-mapbox-gl').projectDir = new File(rootProject.projectDir, '../node_modules/@mapbox/react-native-mapbox-gl/android/rctmgl') include ':app' <file_sep>/src/utils/index.js import {PermissionsAndroid} from 'react-native'; // // export const geoClient = { // client: import('../wasm/geoclient.js') // .then(client => { // return client; // }) // } export function checkStatus(response) { if (response.status >= 200 && response.status < 300) { return response } else { var error = new Error(response.statusText) error.response = response throw error } } export function parseJSON(response) { return response.json() } async function requestPermission() { try { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, { 'title': 'Nuland needs your permission.', 'message': `Nuland App needs permission to use your location` } ) if (granted === PermissionsAndroid.RESULTS.GRANTED) { console.log("You can use the camera") } else { console.log("Camera permission denied") } } catch (err) { console.warn(err) } } export default requestPermission <file_sep>/src/actions/index.js import * as AuthActions from './auth'; import * as NavActions from './auth'; export const ActionCreators = Object.assign({}, AuthActions, NavActions); <file_sep>/src/routes/index.js import React from 'react'; import { View } from 'react-native'; import { Route } from 'react-router-native'; import requireAuthentication from '../HOC/AuthenticatedContainer'; import Home from '../views/MainView'; import About from '../views/About'; import Chat from '../views/Chat'; import CameraView from '../views/Camera'; import Account from '../views/Account'; const routes = ( <View> <Route exact path='/' component={Home} /> <Route path='/about' component={About} /> <Route path='/chat' component={requireAuthentication(Chat)} /> <Route path='/camera' component={requireAuthentication(CameraView)} /> <Route path='/account' component={requireAuthentication(Account)} /> </View> ) export default routes; <file_sep>/src/utils/bot.js export function botRequset(command) { return fetch('http://194.58.122.82/bot',{ method: 'post', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({command: command}) }).then((resp)=>{ return resp.json(); }).then((data) =>{ console.log(data) let message; return message = data.message }) } <file_sep>/src/actions/types.js export const OPEN_POPUP = 'OPEN_POPUP'; export const CLOSE_POPUP = 'CLOSE_POPUP'; export const LOGIN = 'LOGIN'; export const LOGOUT = 'LOGOUT'; export const SIGNUP = 'SIGNUP'; export const SIGNIN = 'SIGNIN'; // NULAND BOT ACTIONS export const BOT = 'BOT'; // NULAND BOT ACTIONS END export const GETLOCATION = 'GETLOCATION'; export const SET_TAB = 'SET_TAB'; <file_sep>/src/views/Login/SignUp.js import React from 'react'; import { View, Text, TextInput, Button } from 'react-native'; import _ from 'lodash'; import { connect } from 'react-redux'; import { ActionCreators } from '../../actions'; const bip39 = require('bip39'); const crypto = require('crypto'); const hasher = crypto.createHash('sha256'); const secp256k1 = require('secp256k1'); const bitcoin = require('bitcoinjs-lib'); const ethUtils = require('ethereumjs-util'); const Exonum = require('exonum-client'); class SignUp extends React.Component{ constructor(props) { super(props) this.state = { username: '', privKey: '', pubKey: '', ethAddress: null, mnemonic: null } this.generatePrivateKey = this.generatePrivateKey.bind(this); } generatePrivateKey(){ return new Promise ((resolve, reject) => { crypto.randomBytes(32, (err, buf) => { if (err) reject(err); resolve(buf); }); } ) } componentDidMount() { } render() { return( <View> <Text>Mnemonic seed: {this.state.mnemonic && this.state.mnemonic.map((word, key) =>{ return <Text key={key}>{word} </Text> })}</Text> <TextInput style={{ backgroundColor: '#fff', marginTop: 15, marginBottom: 15, opacity: 0.6, width: 300 }} placeholder="Your name" onChangeText={(e)=>{ this.setState({ 'username': e }) }}/> <Button onPress={()=>{ this.generatePrivateKey().then(rndBts => { const saltKey = hasher.update(rndBts.toString('hex') + this.state.username).digest('hex'); const privKey = new Buffer(saltKey, 'hex'); const pubKey = <KEY>.publicKeyCreate(privKey); let mnemonic = bip39.entropyToMnemonic(privKey).split(' '); let ethAddress = ethUtils.privateToAddress(privKey).toString('hex'); this.setState({ privKey:privKey.toString('hex') + pubKey.toString('hex').substring(0, 64), pubKey: pubKey.toString('hex').substring(0, 64), mnemonic: mnemonic, ethAddress: `0x${ethAddress.toUpperCase()}` }); }).then(() => { console.log(this.state) console.log(this.state.pubKey.length) console.log(this.state.privKey.length) const CreateTransaction = { protocol_version: 0, service_id: 128, message_id: 2, fields: [ { name: 'pub_key', type: Exonum.PublicKey }, { name: 'name', type: Exonum.String } ] } const data = { pub_key: this.state.pubKey, name: this.state.username } const TxCreateWallet = Exonum.newMessage(CreateTransaction); const signature = TxCreateWallet.sign(this.state.privKey, data); TxCreateWallet.signature = signature; const hash = TxCreateWallet.hash(data); TxCreateWallet.send('http://146.185.145.5/api/services/cryptocurrency/v1/wallets/transaction', '/api/explorer/v1/transactions/', data, signature) .then(() => { console.log(data); this.setState({ mnemonic: mnemonic, ethAddress: `0x${ethAddress.toUpperCase()}`, tx_hash : hash }); }); this.props.dispatch(ActionCreators.actions.signup({ username: this.state.username, privKey: this.state.privKey, pubKey: this.state.pubKey, mnemonic: this.state.mnemonic, balance: 0, ethAddress: this.state.ethAddress, tx_hash : this.state.hash })); }); }} title='Create user'/> </View> ) } } const mapStateToProps = (state) => ({ auth: state.logIn.isAuthenticated, name: state.logIn.name, key: state.logIn.key, privKey: state.logIn.privKey, pubKey: state.logIn.pubKey, mnemonic: state.logIn.mnemonic, address: state.logIn.address, ethAddress: state.logIn.ethAddress, tx_hash: state.logIn.tx_hash }) export default connect(mapStateToProps)(SignUp) <file_sep>/src/actions/nav.js export const navActions = { setTab: (payload) => ({ type: 'SET_TAB', payload }) } <file_sep>/src/views/Chat.js import React from 'react'; import { Text, TextInput, View, Button } from 'react-native'; import socketIOClient from 'socket.io-client'; import { connect } from 'react-redux'; import { botRequset } from '../utils/bot'; import Messages from '../components/Chat/Messages'; class Chat extends React.Component{ constructor(props) { super(props); this.state = { username: this.props.name, uid: this.props.public, chat_ready: false, users: [], messages: [], message: '' } } initChat() { this.setState({ chat_ready: true }); this.socket = socketIOClient('ws://172.16.58.3:80', { query : 'username='+this.state.username+'&uid='+this.state.uid }); this.socket.on('message', (message) => { this.setState({ messages : this.state.messages.concat(message) }); }); } botAction(action) { let actionArray = action.substr(action.indexOf("/") + 1).split(' '); let [ botCommand, ...botParams] = actionArray; let actionObject = { botCommand: botCommand, botParams: [...botParams] } botRequset(actionObject) .then((resp) => { console.log('resp: ' + resp) this.setState({ messages : this.state.messages.concat([{ username : 'NulandBot', message : { text: resp }, }]) }) }); } sendMessage(message, e){ if (message.type === 'bot') { this.botAction(message.text) } this.setState({ messages : this.state.messages.concat([{ username : this.props.name, uid : this.props.public, message : message, }]) }); this.socket.emit('message', { username : this.props.name, uid : this.props.public, message : message }); } componentDidMount() { this.initChat(); } render() { const config = { velocityThreshold: 0.3, directionalOffsetThreshold: 80 }; return <Messages sendMessage={this.sendMessage.bind(this)} botAction={this.botAction.bind(this)} messages={this.state.messages} /> } } const mapStateToProps = (state) => ({ auth: state.logIn.isAuthenticated, name: state.logIn.name, public: state.logIn.public, botMessage: state.nulandBot }) export default connect(mapStateToProps)(Chat) <file_sep>/src/reducers/auth.js import createReducer from '../lib/createReducer'; import * as ActionTypes from '../actions/types'; import {AsyncStorage} from 'react-native'; async function setUserData(data) { try { await AsyncStorage.setItem('nuland.storage', JSON.stringify(data)) } catch(err) { console.log(err) } } async function logOutUser() { try { await AsyncStorage.removeItem('nuland.storage') } catch(err) { console.log(err) } } const initialState = { isAuthenticating: false, isAuthenticated: false, token: '', name: '', privKey: null, pubKey: null, ethAddress: null, balance: 0, mnemonic: null, tx_hash: '' }; export const logIn = createReducer(initialState, { [ActionTypes.SIGNIN](state, action) { return { isAuthenticating: false, name: action.payload.username, isAuthenticated: true, token: action.payload.token, key: action.payload.key, privKey: action.payload.privKey, pubKey: action.payload.pubKey, mnemonic: action.payload.mnemonic, address: action.payload.address, ethAddress: action.payload.ethAddress, balance: action.payload.balance, tx_hash: action.payload.tx_hash } }, [ActionTypes.SIGNUP](state, action) { setUserData(action.payload) return { name: action.payload.username, isAuthenticated: true, token: action.payload.token, privKey: action.payload.privKey, mnemonic: action.payload.mnemonic, pubKey: action.payload.pubKey, address: action.payload.address, ethAddress: action.payload.ethAddress, balance: action.payload.balance, tx_hash: action.payload.tx_hash } }, [ActionTypes.LOGOUT](state, action) { logOutUser(); return initialState } }); <file_sep>/src/types/Mnemonic.js export type Mnemonic = Array<String>; <file_sep>/src/components/Nav.js import React from 'react'; import {View, Text, TouchableHighlight} from 'react-native'; import FontAwesome, { Icons } from 'react-native-fontawesome'; import { connect } from 'react-redux' import { navActions } from '../actions/nav'; const mapStateToProps = (state) => ({ tab: state.nav.activeTab }) class Nav extends React.Component{ constructor(props) { super(props); this.state = { activeTab: this.props.tab, tabs: [ { tabName: 'Camera', icon: 'camera' }, { tabName: 'NuLand Bot', icon: 'desktop' }, { tabName: 'Account', icon: 'userCircle' }, { tabName: 'Map/Marks', icon: 'map' }, { tabName: 'Storage', icon: 'folder' } ] } } renderRow(tab, key) { return ( <TouchableHighlight onPress={()=>{ const activeTab = this.props.tab; const newTab = key - activeTab; this.props.dispatch(navActions.setTab({index : key})) this.props.swipe.scrollBy(newTab) }} key={key}> <View style={{ paddingTop: 10, backgroundColor: this.props.tab == key ? '#3b99fc' : '#fff' }}> <FontAwesome style={{ fontSize: 20, textAlign: 'center', color: this.props.tab == key ? '#fff' : '#3b99fc' }}>{Icons[tab.icon]}</FontAwesome> <Text style={{ fontSize: 15, padding: 5, color: this.props.tab == key ? '#fff' : '#3b99fc' }}>{tab.tabName}</Text> </View> </TouchableHighlight> ) } render() { return ( <View style={{flexDirection: 'row'}}> { this.state.tabs.map((tab, key) => { return this.renderRow(tab, key) })} </View> ) } } export default connect(mapStateToProps)(Nav) <file_sep>/src/views/Login/Restore.js import React from 'react'; import { connect } from 'react-redux' import { View, Text, TextInput, Button, Dimensions } from 'react-native'; import { actions } from '../../actions/auth'; const bip39 = require('bip39'); const secp256k1 = require('secp256k1'); const ethUtils = require('ethereumjs-util'); const { width } = Dimensions.get('window'); class Restore extends React.Component { constructor(props) { super(props); this.state = { mnemonic: '', balance: 0 } } restoreKey(mnemonic) { const keyHex = bip39.mnemonicToEntropy(mnemonic); const key = new Buffer(keyHex, 'hex'); const pubKey = secp256k1.publicKeyCreate(key); const ethAddress = ethUtils.privateToAddress(key).toString('hex'); const address = `0x${ethAddress.toUpperCase()}`; console.log({ name: 'Sushka', key: key, private: key.toString('hex'), public: pubKey.toString('hex'), ethAddress: address, }) fetch('http://194.58.122.82/balance',{ method: 'post', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({address: address}) }).then((resp) => { return resp.json(); }).then((data) => { this.props.dispatch(actions.signin({ username: '', key: key, private: key.toString('hex'), public: pubKey.toString('hex'), mnemonic: mnemonic.split(' '), ethAddress: address, balance: data.balance })); }); } render() { return( <View> <TextInput style={{ width: 300 }} value={this.state.mnemonic} ref={(input) => { textInp = input }} placeholder='Enter your mnemonic passphrase' onChangeText={(e)=>{ this.setState({ 'mnemonic': e }) }}/> <Button title='Send' style={{ width: 300 }} onPress={()=>{ this.restoreKey(this.state.mnemonic); }}/> </View> ) } } const mapStateToProps = (state) => ({ auth: state.logIn.isAuthenticated, name: state.logIn.name, key: state.logIn.key, private: state.logIn.private, public: state.logIn.public, mnemonic: state.logIn.mnemonic, address: state.logIn.address, ethAddress: state.logIn.ethAddress }); export default connect(mapStateToProps)(Restore) <file_sep>/src/actions/geo.js export const geoactions = { getLocation: (payload) => ({ type: 'GETLOCATION', payload }) } <file_sep>/src/views/LoginView.js import React from 'react'; import { View, AsyncStorage, NetInfo, Image } from 'react-native'; import { connect } from 'react-redux'; import {actions} from '../actions/auth'; import styled from 'styled-components'; import SignIn from './Login/SignIn'; import SignUp from './Login/SignUp'; import Restore from './Login/Restore'; const Title = styled.Text` font-size: 32px; color: #0073b2; padding-bottom: 5px; `; const SubTitle = styled.Text` color: #1d82bb; font-size: 22px; text-align: center; `; const LoginBtn = styled.Text` background-color: #d1deea; color: #4486b0; height: 50px; padding: 10px; font-size: 18px; width: 80px; text-align:center; margin-right: 15px; `; class LoginView extends React.Component { constructor(props) { super(props); this.state = { activeBtn: 0, auth: false }; this.renderComponent = this.renderComponent.bind(this); } renderComponent(param) { switch(param) { case 0: return <SignIn />; case 1: return <SignUp />; case 2: return <Restore />; default: return; } } componentDidMount() { } render() { let logo = require('../img/logo.png'); return ( <View style={{ flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center', width: 300 }}> <View style={{ flexDirection: 'row', flex: 1, maxHeight: 50 }}> <Image style={{ flexDirection: 'row', alignSelf: 'flex-start' }} source={logo} /> <Title style={{ alignSelf: 'flex-end' }}>NuLand</Title> </View> <SubTitle>Embedding physical reality into cyberspace</SubTitle> <View style={{ flex: 1, flexDirection: 'row', alignSelf: 'flex-start', marginTop: 30, maxHeight: 50 }}> <LoginBtn style={{flexDirection: 'row', alignSelf: 'flex-start'}} onPress={()=>{ this.setState({ activeBtn: 0 }) }}>SignIn</LoginBtn> <LoginBtn style={{color: '#75a1c1'}} onPress={()=>{ this.setState({ activeBtn: 1 }) }}>SignUp</LoginBtn> <LoginBtn style={{color: '#75a1c1'}} onPress={()=>{ this.setState({ activeBtn: 2 }) }}>Restore</LoginBtn> </View> {this.renderComponent(this.state.activeBtn)} </View> ) } } const mapStateToProps = (state) => ({ activeTab: state.nav.activeTab, auth: state.logIn.isAuthenticated }); export default connect(mapStateToProps)(LoginView); <file_sep>/src/views/Account.js import React from 'react'; import { Text, TextInput, View, Button } from 'react-native'; import { connect } from 'react-redux'; import { actions } from '../actions/auth'; class Account extends React.Component{ constructor(props) { super(props); this.state = { latitude: null, longitude: null, error: null } } componentDidMount() { } render() { return( <View style={{ paddingHorizontal: 10 }}> <Text>User: {this.props.name}</Text> <Text>Private: {this.props.privKey}</Text> <Text>Public: {this.props.pubKey}</Text> <Text>Balance: {this.props.balance} NLD</Text> <Text>ETH: {this.props.ethAddress}</Text> <Text>Mnemonic: {this.props.mnemonic.map((word, key) =>{ return <Text key={key}>{word} </Text> })}</Text> <Text>Location:</Text> <Text>Lat: {this.props.geo.lat}</Text> <Text>Lon: {this.props.geo.lon}</Text> {this.state.error ? <Text>Error: {this.state.error}</Text> : null} <Button onPress={()=>{ this.props.dispatch(actions.logout()); }} title='logout'></Button> </View> ) } } const authStateToProps = (state) => ({ auth: state.logIn.isAuthenticated, name: state.logIn.name, geo: state.geoLocation.location, key: state.logIn.key, privKey: state.logIn.privKey, pubKey: state.logIn.pubKey, address: state.logIn.address, mnemonic: state.logIn.mnemonic, ethAddress: state.logIn.ethAddress, balance: state.logIn.balance }); export default connect(authStateToProps)(Account); <file_sep>/__tests__/signup.test.js const Exonum = require('exonum-client'); const crypto = require('crypto'); const secp256k1 = require('secp256k1'); describe('Create transacrion for signing up user', () => { it('should return transaction hash', () => { function generatePrivateKey() { return new Promise ((resolve, reject) => { crypto.randomBytes(32, (err, buf) => { if (err) reject(err); resolve(buf); }); } ) } let privKey; let pubKey; generatePrivateKey().then( key => { privKey = key; pubKey = secp256k1.publicKeyCreate(key); const CreateTransaction = { protocol_version: 0, service_id: 128, message_id: 2, fields: [ { name: 'pub_key', type: Exonum.PublicKey }, { name: 'name', type: Exonum.String } ] } const TxCreateWallet = Exonum.newMessage(CreateTransaction); const data = { pub_key: pubKey.toString('hex'), name: 'username' } const signature = TxCreateWallet.sign(privKey.toString('hex'), data) TxCreateWallet.signature = signature const hash = TxCreateWallet.hash(data) TxCreateWallet.send(TX_URL, '/api/explorer/v1/transactions/', data, signature) .then(() => { expect(data).toBeDefined(); expect(data.tx_hash).toEqual(hash) }) }); }) }) <file_sep>/README.md # Nuland App ## Installation Nuland App is a frontend application based on React-Native framework. To run App while in development you need to download and install Android Studio. Choose a "Custom" setup when prompted to select an installation type. Check: ``` Android SDK Android SDK Platform Android Virtual Device ``` Full guide [is here](https://facebook.github.io/react-native/docs/getting-started.html). Also Java Development Kit needed to be installed. [JDK](http://www.oracle.com/technetwork/java/javase/downloads/index.html) Set your device in development mode, follow instructions and enable all needed options to install apps on your device. To instantiate App on device follow ``` npm install npm run start ``` In another console you should run ``` npm run android ``` Now App is running on your device. To debug open developer console on http://localhost:8081/debugger-ui/, shake your device to use debug menu, set Debug JS Remotely. ## Repository structure 1. /android - Android project folder compiled 2. /ios - Ios project folder compiled 3. /src - sources <file_sep>/src/views/AuthedView.js import React from 'react'; import Swiper from 'react-native-swiper'; import { View, Text, Dimensions } from 'react-native'; import { connect } from 'react-redux' import {navActions} from '../actions/nav'; import Account from './Account'; import Camera from './Camera'; import Map from './Map'; import Chat from './Chat'; import Storage from './Storage'; import Nav from '../components/Nav'; class AuthedView extends React.Component { constructor(props) { super(props); this.state = { visibleSwiper: false, swiper: null }; } componentDidMount() { setTimeout(() => { this.setState({ visibleSwiper: true, swiper: this.refs.swiper }); }, 100); } render() { const { height } = Dimensions.get('window'); const { width } = Dimensions.get('window'); return( <View> <View style={{ flex: 0, flexDirection: 'row' }}> <Nav swipe={this.state.swiper}/> </View> <Swiper ref='swiper' loop={false} height={height} width={width} index={1} showsButtons={false} showsPagination={false} removeClippedSubviews={false} onIndexChanged={(index) => { this.props.dispatch(navActions.setTab({index : index})) }}> <Camera /> <Chat /> <Account /> <Map /> <Storage /> </Swiper> </View> ) } } function mapStateToProps(state) { return { activeTab: state.nav.activeTab } } export default connect(mapStateToProps)(AuthedView) <file_sep>/src/views/Map.js import React from 'react'; import { View, Text, Dimensions } from 'react-native'; import { connect } from 'react-redux'; import Mapbox from '@mapbox/react-native-mapbox-gl'; Mapbox.setAccessToken('<KEY>'); const { height } = Dimensions.get('window'); const { width } = Dimensions.get('window'); const mapStateToProps = (state) => (console.log(state),{ geo: state.geoLocation.location }) class Map extends React.Component { constructor(props){ super(props); this.state = { width: height, height: width, position : { latitude: this.props.geo.lat, longitude: this.props.geo.lon }, zoom: 8 } } componentDidMount() { console.log(this.props) } render() { return( <View> { this.props.geo.lat ? <Mapbox.MapView styleURL={Mapbox.StyleURL.Street} zoomLevel={15} centerCoordinate={[this.props.geo.lon, this.props.geo.lat]} showUserLocation={true} style={{ position: 'absolute', top: 0, left: 0, width: height, height: width, flex: 1 }}> </Mapbox.MapView> : <Text>Loading map...</Text> } </View> ) } } export default connect(mapStateToProps)(Map) <file_sep>/src/reducers/nav.js import createReducer from '../lib/createReducer'; import * as ActionTypes from '../actions/types'; const initialState = { activeTab: 1 } export const nav = createReducer(initialState, { [ActionTypes.SET_TAB](state, action) { return { activeTab: action.payload.index } } }) <file_sep>/src/HOC/AuthenticatedContainer.js import React from 'react'; import { connect } from 'react-redux'; import {AsyncStorage} from 'react-native'; import requestPermission from '../utils'; import {geoactions} from '../actions/geo'; import {actions} from '../actions/auth'; import LoginView from '../views/LoginView'; import AuthedView from '../views/AuthedView'; const Geolocation = navigator.geolocation; function getBalance(ethAddress) { return fetch('http://172.16.31.102/balance',{ method: 'post', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({address: ethAddress}) }).then((resp) => { return resp.json(); }).then((data) => { return data.balance; }); } class AuthenticatedContainer extends React.Component { constructor(props) { super(props); } async getUserData() { try { // Checking if user was authenticated on device const value = await AsyncStorage.getItem('nuland.storage'); // Getting geo data from the device Geolocation.watchPosition( (position) => { this.props.dispatch(geoactions.getLocation({ lat: position.coords.latitude, lon: position.coords.longitude })); }, (error) => this.setState({ error: error.message }) ); if (value !== null){ let userData = JSON.parse(value); // let address = userData.ethAddress; // getBalance(address).then((balance) => { // userData.balance = balance; // this.setState({ // userData // }) // }) this.props.dispatch(actions.signin(userData)); // Checking user balance } } catch (error) { console.log(error); } } componentDidMount() { requestPermission(); this.getUserData(); } componentWillUnmount() { Geolocation.clearWatch(this.watchId); } render() { if (this.props.user) { return <AuthedView /> } else { return <LoginView /> } } } function mapStateToProps(state) { return { user: state.logIn.isAuthenticated } } export default connect(mapStateToProps)(AuthenticatedContainer);
0dce853c5648e21c42bc7e16826f17e6ad94759e
[ "JavaScript", "Markdown", "Gradle" ]
23
JavaScript
caesai/nuland-app
3c8ecb388a23c555a395324c65afb4be57e2453c
e3b0db0ff5ec6a326a5a057df9f0318aa800b47f
refs/heads/master
<repo_name>dadecker/Data_Structures_Homework<file_sep>/MemoryManager.h #include <cassert> #include <iostream> #include <cstdlib> #include "dlUtils.h" #include "MemoryManager.h" MemoryManager::MemoryManager(unsigned int memtotal): memsize(memtotal) { baseptr = new unsigned char[memsize]; blockdata dummyBlock(0,false,0); blockdata originalBlock(memsize,true,baseptr); header = new dlNode<blockdata>(dummyBlock,nullptr,nullptr); trailer = new dlNode<blockdata>(dummyBlock,nullptr,nullptr); header->next = new dlNode<blockdata>(originalBlock,header,trailer); trailer->prev = header->next; } MemoryManager::~MemoryManager() { delete [] baseptr; clearList(header); } void MemoryManager::showBlockList() { printDlList(header,trailer,"->"); } void MemoryManager::splitBlock(dlNode<blockdata> *p, unsigned int request) { unsigned char * newBlockPtr = p->info.blockptr + request; blockdata blockdata1(request,false,p->info.blockptr); blockdata blockdata2(p->info.blocksize - request,true,newBlockPtr); insertAfter(trailer,p->prev,blockdata1); p->info = blockdata2; } unsigned char * MemoryManager::malloc(unsigned int request) { dlNode<blockdata> *p = header->next; while(p != trailer) { if(p->info.free == true && p->info.blocksize > request) { splitBlock(p,request); return p->prev->info.blockptr; } if(p->info.free == true && p->info.blocksize == request) { p->info.free = false; return p->info.blockptr; } p = p->next; } return NULL; } void MemoryManager::mergeForward(dlNode<blockdata> *p) { if(p->next->info.free == true) { blockdata newBlock(p->info.blocksize + p->next->info.blocksize, true, p->info.blockptr); p->next->info.blockptr = NULL; p->info = newBlock; deleteNext(header,trailer,p); } } void MemoryManager::mergeBackward(dlNode<blockdata> *p) { if(p->prev->info.free == true) { blockdata newBlock(p->prev->info.blocksize + p->info.blocksize, true, p->prev->info.blockptr); p->info.blockptr = NULL; p->prev->info = newBlock; deleteNode(header,trailer,p); } } void MemoryManager::free(unsigned char *ptr2block) { dlNode<blockdata>* p = header->next; unsigned char * newBlockptr; while(p != trailer) { if(p->info.blockptr == ptr2block) { p->info.free = true; ptr2block = NULL; newBlockptr = p->prev->info.blockptr + p->prev->info.blocksize; mergeForward(p); mergeBackward(p); return; } p = p->next; } std::cout << "exiting because the pointer was not found"<< std::endl; std::exit(0); } <file_sep>/README.md # Data_Structures_Homework Some class work from Data Structures The code in this course was provided as a framework, and it was the job of the student to complete the missing code segments to achieve the desired functionality The course was instructed by Dr. Tindell and conducted by the University of South Florida <file_sep>/line-3.h // <NAME> // 1/12/2017 #include <iostream> #include "line.h" double Line::intersect(const Line L) const throw(ParallelLines, EqualLines) { double x; //the following formula is from comparing the two lines in slope intercept form which sets up the equation //ax+b = cx+d where the first equation is the lvalue line and the second equation is the line supplied in the argument x = (L.Line::getIntercept()-this->Line::getIntercept())/(this->Line::getSlope()-L.Line::getSlope()); if((L.Line::getSlope() == this->Line::getSlope())&&(L.Line::getIntercept() == this->Line::getIntercept())) throw EqualLines("The lines are equal: infinite intersection");//explicit call of the of the base class constructor //used in the scope of class EqualLines if(L.Line::getSlope() == this->Line::getSlope()) throw ParallelLines("The lines are parallel: no intersection"); return x; } <file_sep>/line-2.h //<NAME> //1/12/2017 #include <string> using namespace std; class RuntimeException { // generic run-time exception private: string errorMsg; public: RuntimeException(const string& err) { errorMsg = err; } string getMessage() const { return errorMsg; } }; // All that is needed for the special exceptions is the inherited constructor and method. class EqualLines: public RuntimeException { public: EqualLines(const string& err):RuntimeException(err){ } }; class ParallelLines: public RuntimeException { public: ParallelLines(const string& err):RuntimeException(err){ } }; class Line { public: Line(double slope, double y_intercept): a(slope), b(y_intercept) {}; double intersect(const Line L) const throw(ParallelLines, EqualLines); double getSlope() const {return a;}; double getIntercept() const {return b;}; private: double a; double b; }; <file_sep>/graph.h #include "graph.h" #include <cassert> #include <stack> graph::graph() { int vertex; cin >> size; adjList.resize(size,NULL); for(int i = 0; i < size; ++i) { cin >> vertex; while(vertex != -1) { adjList[i] = new vnode(vertex,adjList[i]); // insert at begining cin >> vertex; } } } int firstFalse(vector<bool> b) { int i = 0; while(i < b.size() && b[i]) i += 1; return i; } bool all(vector<bool> b) { for(int i = 0; i < b.size(); ++i) if(!b[i]) return false; return true; } void graph::dfs(vector<bool> &visited) { int start = firstFalse(visited); int nbr, current = start; stack<int> S; vnodeptr cursor; visited[start] = true; S.push(start); // Supply the remaining code below while(!S.empty()) { current = S.top(); S.pop(); for(cursor = adjList[current]; cursor != NULL; cursor = cursor->next) { nbr = cursor->vertex; if(visited[nbr] == false) { S.push(nbr); visited[nbr] = true; } } } } bool graph::connected(int excluded = -1) { vector<bool> visited(size,false); if(excluded != -1) visited[excluded] = true; // Supply the remaining code below dfs(visited); return all(visited); } vector<int> graph::get_cutpoints() { vector<int> cutpts; // Supply the remaining code below for(int i = 0; i < size; i++) { if(!this->connected(i)) { cutpts.push_back(i); } } return cutpts; } <file_sep>/dynarr-2.h #include <cassert> #include <iostream> #include <string> class RuntimeException // generic run-time exception { protected: std::string errorMsg; public: RuntimeException(const std::string& err) { errorMsg = err; } std::string getMessage() const { return errorMsg; } }; class InvalidIndex : public RuntimeException { public: InvalidIndex(const std::string& err): RuntimeException(err) {}; }; template <class dynElem> class dynarr { private: int capacity; dynElem *A; public: dynarr() : capacity(0), A(NULL){} dynarr(int N): capacity(N), A(new dynElem[N]){} dynarr(const dynarr<dynElem> &other); ~dynarr(); dynarr<dynElem> & operator=( const dynarr<dynElem> &other); dynElem & operator[](int ndx) throw(InvalidIndex); int getCapacity(); void reserve(int newcap); // if newcap <= capacity, does nothing; // if capacity is 0, allocates a dynamic array of // capacity newcap and makes A point to that array; // otherwise allocates a new dynamic array newA of capacity // newcap, copies values in A to newA, deletes A and sets // A equal to newA }; template <class dynElem>//copy constructor dynarr<dynElem>::dynarr(const dynarr<dynElem> &other) { int i; capacity = other.capacity; A = new dynElem[capacity]; for(i=0; i < capacity; i++)//assigns each element to the newly created array from other { A[i] = other.A[i]; } } template <class dynElem> dynarr<dynElem>::~dynarr() { delete []A; } template <class dynElem> dynarr<dynElem> & dynarr<dynElem>::operator=( const dynarr<dynElem> &other) { if(this != &other) { int i; delete []A; capacity = other.capacity; A = new dynElem[capacity]; for(i=0; i < capacity; i++)//assigns each element to the newly created array other { A[i] = other.A[i]; } return *this; } } template <class dynElem> dynElem & dynarr<dynElem>::operator[](int ndx) throw(InvalidIndex) { if(ndx > capacity) throw InvalidIndex("Array index is too large"); else if(ndx < 0) throw InvalidIndex("Array index is negative"); else { return A[ndx]; } } template <class dynElem> int dynarr<dynElem>::getCapacity() { return capacity; } template <class dynElem> void dynarr<dynElem>::reserve(int newcap) { if(newcap <= capacity) { return; } if(capacity == 0) { A = new dynElem[newcap]; return; } capacity = newcap; dynElem *newA = new dynElem[newcap]; for(int i=0; i<newcap; i++) { newA[i] = A[i]; } delete [] A; A = newA; }
08d7a2dfe902313ec4999155c3561fd1fdec9a32
[ "Markdown", "C++" ]
6
C++
dadecker/Data_Structures_Homework
c706c637e16fc3d8aca9d9bf680a5ac3312383bc
4dfd0bfb2cd3397fdcfe0431e50d16f5b12b7ef5
refs/heads/master
<repo_name>DungTran46/FPS_GT511C3_esp32<file_sep>/Fingerprint_test.ino #include <FPS_GT511C3.h> bool recv=false; FPS_GT511C3 fps(115200, 2); void setup() { Serial.begin(9600); //set up Arduino's hardware serial UART fps.UseSerialDebug = true; // so you can see the messages in the serial debug screen fps.Open(); //send serial command to initialize fps //fps.ChangeBaudRate(115200); delay(100); //Serial.begin(115200); Serial.println("set up"); delay(1000); } void loop() { Serial.println("ON"); // FPS Blink LED Test recv=fps.SetLED(true); // turn on the LED inside the fps Serial.println("ON"); delay(1000); recv=fps.SetLED(false);// turn off the LED inside the fps Serial.println("OFF"); delay(1000); }
f3003d252fb261bb2f986cd6de1ee8461a612988
[ "C++" ]
1
C++
DungTran46/FPS_GT511C3_esp32
c2857213a02d65b4472ddc5ee6975e33a7689835
d6aae747a6f605eb66c2d373dcde93be5b63121b
refs/heads/master
<file_sep>package com.pract.logics; public class SumOfTwoMatrices { public static void main(String[] args) { // TODO Auto-generated method stub int[][] a = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 },{6,7,8} }; int[][] b = { { 10, 11, 12 }, { 13, 14, 15 }, { 16, 17, 18 },{1,2,3} }; SumOfTwoMatrices s = new SumOfTwoMatrices(); int[][] a1 = s.findSumOfTwotrices(a, b); for (int i = 0; i < a1.length; i++) { for (int j = 0; j < a1[i].length; j++) { System.out.print(a1[i][j] + " "); } System.out.println("\n"); } } public int[][] findSumOfTwotrices(int[][] a, int[][] b) { int[][] c = new int[a.length][a[0].length]; for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { c[i][j]=a[i][j]+b[i][j]; } } return c; } } <file_sep>package com.pract.general; public class IfElse{ public static void main(String[] args){ int a=100; int b=200; if(a>=b){ System.out.println("if-block"); } else{ System.out.println("else-block"); } } }<file_sep>package com.pract.general; public class InstanceVar{ int a=10; int b=20; public static void main(String[] args){ InstanceVar v1=new InstanceVar(); System.out.println("v1.a = "+v1.a); System.out.println("v1.b = "+v1.b); InstanceVar v2=new InstanceVar(); System.out.println("v2.a = "+v2.a); System.out.println("v2.b = "+v2.b); v1.a=100; v1.b=200; System.out.println("v1.a = "+v1.a); System.out.println("v1.b = "+v1.b); System.out.println("v2.a = "+v2.a); System.out.println("v2.b = "+v2.b); } }<file_sep>package com.pract.general; public class For{ public static void main(String[] arg){ int n=7; for(int i=1;i<=n;i++){ System.out.println("Hello "+i); } } }<file_sep>package com.pract.general; public class ForEach1{ public static void main(String[] arg){ int[] a={10,20,30}; for(int a1:a){ System.out.println("Element = "+a1); } } }<file_sep>package com.pract.general; import java.util.*; public class TreeSetDemo{ public static void main(String[] ar){ TreeSet<Integer> ts=new TreeSet<Integer>(); ts.add(1); ts.add(3); ts.add(null); ts.add(6); ts.add(2); ts.add(4); ts.add(5); System.out.println("TreeSet : "+ts); } } <file_sep>package com.pract.general; public class EvenNo{ public static void main(String[] arg){ for(int i=1;i<=20;i++){ if(i%2!=0){ continue; } System.out.println(i+" "); } } } <file_sep>package com.pract.search; public class BinarySearch { public static void main(String[] args) { int[] a = { 10, 12, 20, 25, 29, 30 }; int element = 20; int startIndex = 0, endIndex = a.length - 1; boolean binarySearch = BinarySearch.binarySearch(a, element, startIndex, endIndex); if(binarySearch) { System.out.println("element found : "+element); } else { System.out.println("element is not found : "+element); } } public static boolean binarySearch(int[] ar, int element, int startIndex, int endIndex) { if (startIndex == endIndex) { if (element == ar[startIndex]) { return true; } else return false; } int midIndex = (startIndex + endIndex) / 2; if (element == ar[midIndex]) { return true; } else if (element < ar[midIndex]) { return binarySearch(ar, element, startIndex, midIndex - 1); } else { return binarySearch(ar, element, midIndex + 1, endIndex); } } } <file_sep>package com.pract.general; public class IfDemo{ public static void main(String[] arg){ int a=10; int b=20; if(a>b){ System.out.println("Hello"); } } }<file_sep>package com.pract.general; public class StaticVar{ int a=10; static int b=20; public static void main(String[] arg){ StaticVar s1=new StaticVar(); System.out.println("s1.a = "+s1.a); System.out.println("s1.b = "+s1.b); StaticVar s2=new StaticVar(); System.out.println("s2.b = "+s2.b); s1.b=200; System.out.println("s1.b = "+s1.b); System.out.println("s2.b = "+s2.b); StaticVar s3=new StaticVar(); System.out.println("s3.b = "+s3.b); } }<file_sep>package com.pract.logics; public class SumOf2DArray { public static void main(String[] args) { int[][] a= {{1,2,3},{4,5,6},{7,8,9}}; SumOf2DArray array = new SumOf2DArray(); int sum = array.calculateSum(a); System.out.println("sum of 2D array: "+sum); } public int calculateSum(int[][] a) { int sum=0; for(int i=0;i<a.length;i++) { for(int j=0;j<a[i].length;j++) { sum=sum+a[i][j]; } } return sum; } } <file_sep>package com.pract.general; public class AbstractDemo{ public static void main(String[] arg){ Abstract1 abd=new ChildAbstract1(); abd.m2(); } }<file_sep>package com.pract.polindrome; public class StringPolindrome { public static void main(String[] args) { String s="madam"; boolean result=true; for(int i=0,j=s.length()-1;i<j;i++,j--) { if(s.charAt(i)!=s.charAt(j)) { result=false; } } if(!result) { System.out.println(s+ " is not a polindrome"); } else { System.out.println(s+" is a polindrome"); } } } <file_sep>package com.pract.sort; public class CharArraySelectionSort { public static void main(String[] args) { String s = "we have to fight corona"; char[] ch = s.toCharArray(); for (int i = 0; i < ch.length; i++) { for (int j = i + 1; j < ch.length; j++) { if (ch[i] > ch[j]) { char temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; } } } for (char c : ch) { System.out.print(c+" "); } } } <file_sep>package com.pract.general; import java.util.*; public class StudentTreeSet{ public static void main(String[] arg){ TreeSet<Student> ts=new TreeSet<Student>(); ts.add(new Student(1,"shruthi")); ts.add(new Student(2,"abc")); ts.add(new Student(44,"cdf")); ts.add(new Student(30,"sdgh")); System.out.println("student : "+ts); } }<file_sep>package com.pract.sort; public class BubbleSort { public static void main(String[] args) { int[] a = { 2, 5, 11, 4, 1, 10}; int count=0; for (int i = 0; i < a.length; i++) { count++; boolean swap=false; for (int j = a.length - 1; j > i; j--) { if(a[j]<a[j-1]) { int temp=a[j]; a[j]=a[j-1]; a[j-1]=temp; swap=true; } } if(!swap) { break; } } for (int i : a) { System.out.print(i+" "); } System.out.println("\n"); System.out.println("loop count : "+count); } } <file_sep>package com.pract.general; public class Person{ public void name(){ } public void age(){ } }
846e6b46714453b4375790540fc8b89b67b02fc2
[ "Java" ]
17
Java
shruthi202122/CoreJavaPractice
fd08b1167c91f7354d2eb1dc1d9294fb34bcaa82
6f13954fb791734b781eb886fe34a422049bbb17
refs/heads/main
<repo_name>mh3yad/realTimeChatApp<file_sep>/js/realtime.js $(document).load(function(){ $(setInterval(function(){ $('.messages').load('realtime.php') } ,5000 )) })<file_sep>/js/script.js $(document).ready(function(){ // alert('2') // $(':not(.container > )').hide() $('.container').show() $('.after').hide() $('.afterLogin').hide() $('.error').hide() $('#login').submit(function(){ let username = $("#username").val() if(username == ""){ $('.error').show() }else{ data = { 'username':username } $.ajax({ url: 'signinout.php', method: "POST", dataType: "json", data: data, accepts: "application/json; charset=utf-8", }).done(function () { console.log('retrieved') return 1; }) $('.beforeLogin').hide() $('.before').hide() $('.afterLogin').show() $('#username_text').text("welcome "+username) $('.after').show() $('.error').hide() } return false }) $('#logout').submit(function(){ $('.after').hide() $('.afterLogin').hide() $('.before').show() $('.beforeLogin').show() return false }) $('#sendMessage').submit(function(){ let name = $("#username").val() let message = $('#msg').val() let date = new Date($.now()); let time = date.getHours() + ":" + date.getMinutes() ; if(message == ""){ alert("message can't be empty") return false }else{ let data = { 'name':name, 'content':message, 'time':time } $.ajax({ url:'insertM.php', method:'POST', dataType: "json", data: data, accepts: "application/json; charset=utf-8", }).done(function () { console.log('retrieved') return 1; }) $('#messages').css('color',"red") $('.messages').append('<li>'+ '<b> - <span class="mUsername">'+ name +'</span></b><span class="mBody">'+ message +'</span><span class="mTime">'+ time +'</span>'+ '</li>') $('#sendMessage').trigger("reset"); return false } } ); setInterval(function() { $.ajax({ url:'realtime.php', method:'GET', }).done(function(data){ $('.messages').html(data) }) }, 5000); })<file_sep>/index.php <?php include 'connect.php'; // include 'realtime.php'; $stmt=$con->prepare("SELECT * FROM users ORDER BY id DESC LIMIT 1"); $stmt->execute(); $resultSet = $stmt->get_result(); $datas = $resultSet->fetch_all(); // print_r($datas); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv='cache-control' content='no-cache'> <meta http-equiv='expires' content='0'> <meta http-equiv='pragma' content='no-cache'> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <title>Document</title> </head> <body> <?php ?> <div class="container"> <div class="head"> <div class="content"> <div class="beforeLogin"> <form name="login" id="login" onsubmit=""> <span class="error">empty yasta</span> <input type="text" name='username' id="username" placeholder="enter your username"> <input type="submit" value="Login"> </form> </div> <div class="afterLogin"> <form action="" name="logout" id="logout"> <span id="username_text"></span> <input type="submit" value="Logout"> </form> </div> </div> </div> <div class="body"> <ul class="messages"> <!-- <li> ?> </li> --> </ul> </div> <div class="footer"> <div class="after"> <form name="sendMessage" id="sendMessage" onsubmit=""> <textarea placeholder="Enter your Message" id="msg" name="msg" rows="1" cols="60"></textarea> <input type="submit" value="send"> </form> </div> <div class="before"> <label class="please" for="username" style="text-align:center;display: inline-block;width:100%;padding:10px;color:white;background: #112542;border-radius: 10px;">please login first</label> </div> </div> </div> <script src="js/script.js"></script> </body> <script> </script> </html><file_sep>/insertM.php <?php include 'connect.php'; if(isset($_POST['name'])){ $name = $_POST['name']; $content = $_POST['content']; $time = $_POST['time']; $insert = "INSERT INTO `messages` (`id`, `name`,`content`,`time`) VALUES (NULL,'$name','$content','$time')"; if($con->query($insert) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $insert . "<br>" . $con->error; } } $sql = "SELECT name,content,time FROM messages"; $result = mysqli_query($con,$sql); $row = mysqli_fetch_array($result, MYSQLI_NUM); return $row; ?><file_sep>/realtime.php <?php include 'connect.php'; $stmt2=$con->prepare("SELECT * FROM messages"); $stmt2->execute(); $resultSet2 = $stmt2->get_result(); $datas2 = $resultSet2->fetch_all(); foreach($datas2 as $data2){ echo '<li><b> - <span class="mUsername">'.$data2[1].' </span></b><span class="mBody"> '.$data2[2].' </span><span class="mTime"> '.$data2[3].' </span></li>'; } ?><file_sep>/README.md # realTimeChatApp ## technologies: HTML5 CSS3 PHP(native) mysql jQuery Ajax note: um not that big fan of UI design but I tried to do my best 😅😅 <file_sep>/signinout.php <?php include 'connect.php'; if(isset($_POST['username'])){ $username = $_POST['username']; echo $username; $insert = "INSERT INTO `users` (`id`, `name`) VALUES (NULL,'$username')"; if($con->query($insert) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $insert . "<br>" . $con->error; } } $sql = "SELECT name FROM users"; $result = mysqli_query($con,$sql); $row = mysqli_fetch_array($result, MYSQLI_NUM); ?>
4f70c72f0001bfad7cb3d721bdc60bcac6ad97c0
[ "JavaScript", "Markdown", "PHP" ]
7
JavaScript
mh3yad/realTimeChatApp
1d42aaf98507682fdbc20605a21333d3ae36444b
7028f56d32c3dcddc319272c2cf1f60c0e6f822d
refs/heads/master
<repo_name>pacer11/poc<file_sep>/java/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>elasticsearch</groupId> <artifactId>poc</artifactId> <version>1.0-SNAPSHOT</version> <properties> <elasticsearch.groupid>org.elasticsearch.distribution.zip</elasticsearch.groupid> <elasticsearch.version>5.0.0</elasticsearch.version> <skipTests>false</skipTests> <skipIntegTests>false</skipIntegTests> <!-- For integration tests using ANT --> <integ.http.port>9200</integ.http.port> <integ.transport.port>9300</integ.transport.port> </properties> <dependencies> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <version>5.0.0</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.8.2</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>2.8.2</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.8.2</version> </dependency> <dependency> <groupId>com.floragunn</groupId> <artifactId>search-guard-ssl</artifactId> <version>5.0.2-19</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> <scope>test</scope> </dependency> <dependency> <groupId>pl.allegro.tech</groupId> <artifactId>embedded-elasticsearch</artifactId> <version>2.1.0</version> <scope>testCompile</scope> </dependency> <dependency> <groupId>io.searchbox</groupId> <artifactId>jest</artifactId> <version>2.0.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.6</version> </dependency> <dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>io.apptik.json</groupId> <artifactId>json-generator</artifactId> <version>1.0.4</version> </dependency> <dependency> <groupId>io.apptik.json</groupId> <artifactId>json-schema</artifactId> <version>1.0.4</version> </dependency> </dependencies> <build> <plugins> <!-- <plugin> <artifactId>maven-surefire-plugin</artifactId> <configuration> <forkMode>never</forkMode> </configuration> </plugin> --> <!-- <plugin> <groupId>com.github.alexcojocaru</groupId> <artifactId>elasticsearch-maven-plugin</artifactId> --> <!-- REPLACE THE FOLLOWING WITH THE PLUGIN VERSION YOU NEED --> <!-- <version>5.0</version> <configuration> <clusterName>test</clusterName> <transportPort>9300</transportPort> <httpPort>9200</httpPort> <autoCreateIndex>true</autoCreateIndex> <version>5.0.0</version> </configuration> <executions> <execution> <id>start-elasticsearch</id> <phase>process-test-classes</phase> <goals> <goal>runforked</goal> </goals> </execution> <execution> <id>stop-elasticsearch</id> <phase>prepare-package</phase> <goals> <goal>stop</goal> </goals> </execution> </executions> </plugin> --> </plugins> </build> </project><file_sep>/java/src/main/java/JSONGenerator.java import io.apptik.json.JsonElement; import io.apptik.json.JsonObject; import io.apptik.json.generator.JsonGenerator; import io.apptik.json.generator.JsonGeneratorConfig; import io.apptik.json.schema.SchemaV4; import java.io.IOException; /** * */ public class JSONGenerator { public static void main(String[] args) { int numOfObjects = 100; try { SchemaV4 schema = new SchemaV4().wrap(JsonElement.readFrom(getSchema()).asJsonObject()); JsonGeneratorConfig gConf = new JsonGeneratorConfig(); for (int i=0; i<numOfObjects; i++) { JsonObject job = new JsonGenerator(schema, null).generate().asJsonObject(); System.out.println(job.toString()); } } catch (IOException e) { e.printStackTrace(); } } private static String getSchema() { String schemaString = "{\n" + "\"type\" : \"object\"," + "\"properties\" : {" + "\"id\" : {\"type\" : \"string\", \"minimum\": 15, \"maximum\":15 } ," + "\"Address\" : " + "{" + "\"type\" : \"object\"," + "\"properties\" : {" + "\"Line1\" : {\"type\" : \"string\", \"minimum\": 10, \"maximum\":25 }, " + "\"Line2\" : {\"type\" : \"string\", \"minimum\": 10, \"maximum\":50}, " + "\"City\" : {\"type\" : \"string\", \"minimum\": 10, \"maximum\":15}, " + "\"State\" : {\"type\" : \"string\", \"minimum\": 2, \"maximum\":2}, " + "\"ZipCode\" : {\"type\" : \"integer\", \"minimum\": 5, \"maximum\":6 } " + "}" + "}," + "\"Hobbies\" : {\"enum\" : [\"Fishing\", \"Cooking\", \"Tennis\", \"Singing\"] }, " + "\"Age\" : {\"type\" : \"integer\", \"minimum\": 1, \"maximum\":99 }," + "\"Homepage\" : {\"type\" : \"string\", \"format\": \"uri\" }," + "\"EmailAddress\" : {\"type\" : \"string\", \"format\": \"email\" }, " + "\"DateOfBirth\" : {\"type\" : \"string\", \"format\": \"date\" }, " + "\"PhoneNumber\" : {\"type\" : \"string\", \"format\": \"phone\" }, " + "\"ISPIp\" : {\"type\" : \"string\", \"format\": \"ipv4\" }, " + "\"Created\" : {\"type\" : \"string\", \"format\": \"date-time\" } " + "}" + "}" ; return schemaString; } } <file_sep>/docker/apache-flink/Dockerfile FROM centos:latest RUN yum update -y && yum upgrade -y RUN yum install java-1.8.0-openjdk-devel ADD /home/controller-user/flink-1.4.1 /flink-1.4.1 WORKDIR /flink-1.4.1 <file_sep>/README.md # poc playground <file_sep>/java/src/main/java/DateObject.java import org.apache.commons.lang3.builder.EqualsBuilder; import java.util.Date; import java.util.Map; import java.util.TreeMap; /** * Created by jfaniyi on 3/6/17. */ public class DateObject { private String id; private Map<String, Date> documentMap; public DateObject() { documentMap = new TreeMap<String, Date>(); } public DateObject(String id) { this.id = id; documentMap = new TreeMap<String, Date>(); } public DateObject(Map<String, Date> map) { documentMap.putAll(map); } public Date get(String key) { return documentMap.get(key); } public void put(String key, Date value) { documentMap.put(key, value); } @Override public String toString() { return "BasicObject{" + "id='" + id + '\'' + ", documentMap=" + documentMap + '}'; } @Override public boolean equals( Object compare ) { return new EqualsBuilder().append(documentMap, ((DateObject)compare).documentMap).isEquals(); } }
286faa5310d4508ac1455a1ad8d0aa56c95161c9
[ "Markdown", "Java", "Maven POM", "Dockerfile" ]
5
Maven POM
pacer11/poc
ac06fdd76cbba7507d12be2c1ea5ff5d572650e8
ac8f7fca4bfce54045dfb7a697c533dbddac602b
refs/heads/master
<file_sep>#include <iostream> #include <cstdio> #include <cstdlib> #include <vector> #include <queue> #include <SDL.h> #include <SDL_image.h> #include <SDL_mixer.h> using namespace std; #define SCREEN_WIDTH 1280 #define SCREEN_HEIGHT 720 #define SCREEN_FPS 60 #define MAP_SIZE 5 SDL_Window * window = NULL; SDL_Surface * screen = NULL; SDL_Surface * image = NULL; SDL_Renderer * renderer = NULL; SDL_Texture * texture = NULL; SDL_Event event; Mix_Chunk *op = NULL; Mix_Chunk *button = NULL; Mix_Chunk *end = NULL; int type = 0; // 0 for menu, 1 for game play, 2 for option, 3 for staff bool played = false; typedef struct { SDL_Rect rect; SDL_Surface * image; SDL_Texture * texture; } objects; // 0 for nothing , 1 for up is conect, 2 for down is connected, 4 for left is connected, 8 for right is connected int rconnect(int x) { if(x == 0) return 1 | 4; if(x == 1) return 1 | 8; if(x == 2) return 2 | 8; if(x == 3) return 2 | 4; if(x == 4) return 4 | 8; if(x == 5) return 1 | 2; } bool init() { if(SDL_Init(SDL_INIT_VIDEO) == -1) return false; int IMG_Init(IMG_INIT_PNG); if(Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 ) == -1) return false; window = SDL_CreateWindow("Wahaha~ EZ metro~", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, 0); renderer = SDL_CreateRenderer(window, -1, 0); if(window = NULL) return false; else screen = SDL_GetWindowSurface(window); return true; } int play_menu() { if(played == false) { op = Mix_LoadWAV("A_hisa - BloominLights (Callionet - Cherry snow).wav"); button = Mix_LoadWAV("Button.wav"); end = Mix_LoadWAV("end_sp.wav"); Mix_PlayChannel(-1, op, 0); Mix_Volume(0, MIX_MAX_VOLUME/2); played = true; } int type = 0; freopen("menu.in", "r", stdin); int menu_case = 0; scanf("%d", &menu_case); SDL_Rect rect[menu_case]; for(int i = 0; i < menu_case; i++) { char file[100]; int w, h, x, y; scanf("%s%d%d%d%d", &file, &w, &h, &x, &y); rect[i] = {x, y, w, h}; image = IMG_Load(file); texture = SDL_CreateTextureFromSurface(renderer, image); for(int l = 0; l < 256; l += 10) { SDL_SetTextureAlphaMod(texture, l); SDL_RenderCopy(renderer, texture, NULL, &rect[i]); SDL_RenderPresent(renderer); SDL_Delay(1000 / SCREEN_FPS); } //SDL_RenderCopy(renderer, texture, NULL, &rect[i]); //SDL_RenderPresent(renderer); } // make the into play rect smaller rect[0] = { 480, 450, 360, 40}; while(event.type != SDL_QUIT && type == 0) { if(SDL_PollEvent(&event)) { if(event.type == SDL_QUIT) break; else if(event.type == SDL_MOUSEBUTTONDOWN) { if(event.button.button == SDL_BUTTON_LEFT) { Mix_PlayChannel(-1, button, 0); int x = event.button.x; int y = event.button.y; // 0 for play 1 for volumn 2 for staff for(int i = 0; i < menu_case; i++) if(x >= rect[i].x && x <= rect[i].x + rect[i].w && y >= rect[i].y && y <= rect[i].y + rect[i].h) { type = i + 1; cout << "Menu got " << i << endl; } } } } SDL_Delay(1000 / SCREEN_FPS); } return type; } int play_game() { int type = 0; freopen("play.in", "r", stdin); int play_case = 0; scanf("%d", &play_case); SDL_Rect rect[play_case]; for(int i = 0; i < play_case; i++) { char file[100]; int w, h, x, y; scanf("%s%d%d%d%d", &file, &w, &h, &x, &y); rect[i] = {x, y, w, h}; //SDL_Rect rect = {x, y, w, h}; image = IMG_Load(file); texture = SDL_CreateTextureFromSurface(renderer, image); for(int l = 0; l < 256; l += 10) { SDL_SetTextureAlphaMod(texture, l); SDL_RenderCopy(renderer, texture, NULL, &rect[i]); SDL_RenderPresent(renderer); SDL_Delay(1000 / SCREEN_FPS); } //SDL_RenderCopy(renderer, texture, NULL, &rect[i]); //SDL_RenderPresent(renderer); } // read object image int object_number; scanf("%d", &object_number); objects object[object_number]; for(int i = 0; i < object_number; i++) { object[i].image = NULL; object[i].texture = NULL; } for(int i = 0; i < object_number; i++) { char file[100]; int w, h, x, y; scanf("%s%d%d%d%d", &file, &w, &h, &x, &y); object[i].rect = {x, y, w, h}; object[i].image = IMG_Load(file); object[i].texture = SDL_CreateTextureFromSurface(renderer, object[i].image); } // mapt is for checking the rail is connected or not // 0 for nothing. 1 for up. 2 for down. 4 for left. 8 for right d vector<SDL_Rect> orect; objects maps[5][5]; int book[5][5]; int mapt[5][5]; for(int i = 0; i < 5; i++) for(int j = 0; j < 5; j++) { mapt[i][j] = 0; book[i][j] = 0; } // 5 * 5 , map int inix = 390, iniy = 110; for(int i = 0; i < MAP_SIZE; i++) { for(int j = 0; j < MAP_SIZE; j++) { SDL_Rect paste = object[8].rect; maps[i][j] = object[8]; paste.x = inix + i * paste.h; paste.y = iniy + j * paste.w; maps[i][j].rect = paste; orect.push_back(paste); //SDL_RenderCopy(renderer, maps[i][j].texture, NULL, &paste); //SDL_RenderPresent(renderer); } } // garbage can SDL_Rect paste = object[7].rect; paste.x = 11; paste.y = 384; orect.push_back(paste); for(int l = 0; l < 256; l += 60) { SDL_SetTextureAlphaMod(object[7].texture, l); SDL_RenderCopy(renderer, object[7].texture, NULL, &paste); SDL_RenderPresent(renderer); SDL_Delay(1000 / SCREEN_FPS); } //SDL_RenderCopy(renderer, object[7].texture, NULL, &paste); //SDL_RenderPresent(renderer); paste.x = 1168; paste.y = 720 - object[7].rect.h - 236; orect.push_back(paste); for(int l = 0; l < 256; l += 30) { SDL_SetTextureAlphaMod(object[7].texture, l); SDL_RenderCopy(renderer, object[7].texture, NULL, &paste); SDL_RenderPresent(renderer); SDL_Delay(1000 / SCREEN_FPS); } //SDL_RenderCopy(renderer, object[7].texture, NULL, &paste); //SDL_RenderPresent(renderer); // bomb paste = object[6].rect; paste.x = 11; paste.y = 239; orect.push_back(paste); SDL_RenderCopy(renderer, object[6].texture, NULL, &paste); //SDL_RenderPresent(renderer); paste.x = 1167; paste.y = 720 - object[6].rect.h - 381; cout << orect.size() << endl; orect.push_back(paste); for(int l = 0; l < 256; l += 60) { SDL_SetTextureAlphaMod(object[6].texture, l); SDL_RenderCopy(renderer, object[6].texture, NULL, &paste); SDL_RenderPresent(renderer); SDL_Delay(1000 / SCREEN_FPS); } //SDL_RenderCopy(renderer, object[6].texture, NULL, &paste); //SDL_RenderPresent(renderer); objects rails[2][5]; // random rail // state is for checking the rail is connected or not // 0 for nothing , 1 for up is conect, 2 for down is connected, 4 for left is connected, 8 for right is connected int railt[2][5]; int place1x[5] = {65, 140, 162, 140, 65}; int place2x[5] = {1114, 1043, 1018, 1043, 1119}; int placey[5] = {42, 176, 310, 444, 578}; srand(NULL); for(int i = 0; i < 5; i++) { int o = rand() % 6; paste = object[o].rect; paste.x = place1x[i]; paste.y = placey[i]; railt[0][i] = rconnect(o); rails[0][i] = object[o]; rails[0][i].rect = paste; for(int l = 0; l < 256; l += 60) { SDL_SetTextureAlphaMod(rails[0][i].texture, l); SDL_RenderCopy(renderer, rails[0][i].texture, NULL, &paste); SDL_RenderPresent(renderer); SDL_Delay(1000 / SCREEN_FPS); } //SDL_RenderCopy(renderer, rails[0][i].texture, NULL, &paste); //SDL_RenderPresent(renderer); o = rand() % 6; paste = object[o].rect; paste.x = place2x[i]; paste.y = placey[i]; railt[1][i] = rconnect(o); rails[1][i] = object[o]; rails[1][i].rect = paste; for(int l = 0; l < 256; l += 60) { SDL_SetTextureAlphaMod(rails[1][i].texture, l); SDL_RenderCopy(renderer, rails[1][i].texture, NULL, &paste); SDL_RenderPresent(renderer); SDL_Delay(1000 / SCREEN_FPS); } SDL_RenderCopy(renderer, rails[1][i].texture, NULL, &rails[1][i].rect); SDL_RenderPresent(renderer); } // start and end paste = object[9].rect; // s1 int s1x = rand() % 2 * 4, s1y = rand() % 2 * 4; book[s1x][s1y] = -1; mapt[s1x][s1y] = 1 | 2 | 4 | 8; paste.x = inix + s1x * paste.h; paste.y = iniy + s1y * paste.w; orect.push_back(paste); SDL_RenderCopy(renderer, object[9].texture, NULL, &paste); // s2 int s2x = rand() % 2 * 4, s2y = rand() % 2 * 4; while(s1x == s2x && s1y == s2y) { s2x = rand() % 2 * 4; s2y = rand() % 2 * 4; } book[s2x][s2y] = -1; mapt[s2x][s2y] = 1 | 2 | 4 | 8; paste = object[10].rect; paste.x = inix + s2x * paste.h; paste.y = iniy + s2y * paste.w; orect.push_back(paste); for(int l = 0; l < 256; l += 60) { SDL_SetTextureAlphaMod(object[10].texture, l); SDL_RenderCopy(renderer, object[10].texture, NULL, &paste); SDL_RenderPresent(renderer); SDL_Delay(1000 / SCREEN_FPS); } //SDL_RenderCopy(renderer, object[10].texture, NULL, &paste); // e paste = object[11].rect; paste.x = inix + 2 * paste.h; paste.y = iniy + 2 * paste.w; book[2][2] = -2; mapt[2][2] = 1 & 2 & 4 & 8; orect.push_back(paste); for(int l = 0; l < 256; l += 60) { SDL_SetTextureAlphaMod(object[11].texture, l); SDL_RenderCopy(renderer, object[11].texture, NULL, &paste); SDL_RenderPresent(renderer); SDL_Delay(1000 / SCREEN_FPS); } //SDL_RenderCopy(renderer, object[11].texture, NULL, &paste); //SDL_RenderPresent(renderer); //orect: 0 ~ 24 map, 25 26 garbage can, 27 28 bomb, 29 start1, 30 start2, 31 end; //rails: 0 ~ 4 up, 5 ~ 8 down; int select = 0; // gamet: 0 for normal, 1 for bomb, 2 for garbage can int gamet = 0; while(event.type != SDL_QUIT) { if(SDL_PollEvent(&event)) { if(event.type == SDL_QUIT) break; else if(event.type == SDL_MOUSEBUTTONDOWN) { if(event.button.button == SDL_BUTTON_LEFT) { Mix_PlayChannel(-1, button, 0); int x = event.button.x; int y = event.button.y; for(int i = 0; i < 5; i++) { cout << railt[0][i] << " "; } cout << endl; for(int i = 0; i < 5; i++) { cout << railt[1][i] << " "; } cout << endl; // click bomb for(int i = 27; i <= 28; i++) { if(x >= orect[i].x && x <= orect[i].x + orect[i].w && y >= orect[i].y && y <= orect[i].y + orect[i].h) { cout << "Got bomb" << endl; gamet = 1; } } // click garbate can for(int i = 25; i <= 26; i++) { if(x >= orect[i].x && x <= orect[i].x + orect[i].w && y >= orect[i].y && y <= orect[i].y + orect[i].h) { cout << "Got garbage can" << endl; //gamet = 2; for(int j = 1; j < 5; j++) { if(select == 0 && j == 1) SDL_SetRenderDrawColor(renderer, 228, 192, 199, 0); else if(select == 0 && j != 1) SDL_SetRenderDrawColor(renderer, 221, 176, 185, 0); else if(select == 1 && j == 1) SDL_SetRenderDrawColor(renderer, 0xD3, 0xCC, 0xE5, 0); else if(select == 1 && j != 1) SDL_SetRenderDrawColor(renderer, 199, 190, 221, 0); railt[select][j - 1] = railt[select][j]; rails[select][j - 1].texture = rails[select][j].texture; SDL_RenderFillRect(renderer, &rails[select][j - 1].rect); SDL_RenderCopy(renderer, rails[select][j - 1].texture, NULL, &rails[select][j - 1].rect); } int o = rand() % 6; rails[select][4].texture = object[o].texture; railt[select][4] = rconnect(o); SDL_RenderFillRect(renderer, &rails[select][4].rect); SDL_RenderCopy(renderer, rails[select][4].texture, NULL, &rails[select][4].rect); SDL_RenderPresent(renderer); break; } } // click the map for(int i = 0; i < 25; i++) { if((x >= orect[i].x && x <= orect[i].x + orect[i].w && y >= orect[i].y && y <= orect[i].y + orect[i].h)) { cout << "Gamet: " << gamet << " Got " << i / 5 << " " << i % 5 << endl; if(gamet == 0 && book[i / 5][i % 5] == 0) { cout << "Put" << endl; book[i / 5][i % 5] = 1; maps[i / 5][i % 5].texture = rails[select][0].texture; mapt[i / 5][i % 5] = railt[select][0]; SDL_RenderCopy(renderer, maps[i / 5][i % 5].texture, NULL, &maps[i / 5][i % 5].rect); for(int j = 1; j < 5; j++) { if(select == 0 && j == 1) SDL_SetRenderDrawColor(renderer, 228, 192, 199, 0); else if(select == 0 && j != 1) SDL_SetRenderDrawColor(renderer, 221, 176, 185, 0); else if(select == 1 && j == 1) SDL_SetRenderDrawColor(renderer, 0xD3, 0xCC, 0xE5, 0); else if(select == 1 && j != 1) SDL_SetRenderDrawColor(renderer, 199, 190, 221, 0); railt[select][j - 1] = railt[select][j]; rails[select][j - 1].texture = rails[select][j].texture; SDL_RenderFillRect(renderer, &rails[select][j - 1].rect); //else SDL_RenderCopy(renderer, rails[select][j - 1].texture, NULL, &rails[select][j - 1].rect); } int o = rand() % 6; rails[select][4].texture = object[o].texture; railt[select][4] = rconnect(o); SDL_RenderFillRect(renderer, &rails[select][4].rect); SDL_RenderCopy(renderer, rails[select][4].texture, NULL, &rails[select][4].rect); } else if(gamet == 1 && book[i / 5][i % 5] == 1) { cout << "Crashed" << endl; book[i / 5][i % 5] = 0; maps[i / 5][i % 5].texture = object[8].texture; mapt[i / 5][i % 5] = 0; gamet = 0; select ^= 1; SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderFillRect(renderer, &maps[i / 5][i % 5].rect); if(i / 5 >= 1 && i / 5 <= 3 && i % 5 >= 1 && i % 5 <= 3) SDL_SetRenderDrawColor(renderer, 0xD6, 0xEB, 0xD7, 0); else SDL_SetRenderDrawColor(renderer, 0xEB, 0xF5, 0xEB, 0); SDL_Rect temp_rect = {maps[i / 5][i % 5].rect.x + 2, maps[i / 5][i % 5].rect.y + 2, maps[i / 5][i % 5].rect.w - 4, maps[i / 5][i % 5].rect.h - 4 }; SDL_RenderFillRect(renderer, &temp_rect); //SDL_RenderCopy(renderer, maps[i / 5][i % 5].texture, NULL, &maps[i / 5][i % 5].rect); } SDL_RenderPresent(renderer); for(int i = 0; i < 5; i++) { for(int j = 0; j < 5; j++) { cout << mapt[j][i] << " "; } cout << endl; } int walked[5][5]; for(int i = 0; i < 5; i++) for(int j = 0; j < 5; j++) walked[i][j] = 0; walked[s1x][s1y] = 1; walked[s2x][s2y] = 1; int tracex = s1x - 1, tracey = s1y; cout << s1x << " " << s1y << endl; // check finished ? while(tracex != 2 && tracey != 2){ for(int i = 0; i < 5; i++) { for(int j = 0; j < 5; j++){ cout << walked[j][i] << " "; } cout << endl; } cout << "At the :" << tracex << " " << tracey << endl; cout << "The type is :" << mapt[tracex][tracey] << endl; cout << "The book is :" << walked[tracex][tracey] << endl; bool go = false; walked[tracex][tracey] = 1; int which = mapt[tracex][tracey]; if(which == 0) break; switch(which) { case 3: if(tracey + 1 < 5 && walked[tracex][tracey + 1] == 0) { walked[tracex][tracey + 1] = 8; go = true; tracex++; } else if(tracey - 1 >= 0 && walked[tracex][tracey - 1] == 0) { go = true; tracex--; } break; case 5: if(tracey - 1 >= 0 && walked[tracex][tracey - 1] == 0) { go = true; tracey--; } else if(tracex - 1 >= 0 && walked[tracex - 1][tracey] == 0) { go = true; tracex--; } break; case 6: if(tracey - 1 >= 0 && walked[tracex][tracey - 1] == 0) { go = true; tracey--; } else if(tracex + 1 < 5 && walked[tracex + 1][tracey] == 0) { go = true; tracex++; } break; case 9: if(tracey - 1 >= 0 && walked[tracex][tracey - 1] == 0) { go = true; tracey--; } else if(tracex + 1 < 5 && walked[tracex + 1][tracey] == 0) { go = true; tracex++; } break; case 10: if(tracex + 1 < 5 && walked[tracex + 1][tracey] == 0) { go = true; tracex++; } else if(tracey + 1 < 5 && walked[tracex][tracey + 1] == 0) { go = true; tracex++; } break; } if(tracex == 2 && tracey == 2) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Missing file", "Game over.\n Good Game.", NULL); } if(!go) break; } /////////////////// } } select ^= 1; } } } SDL_Delay(1000 / SCREEN_FPS + 10); } return type; } int play_option() { int type = 0; SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Missing file", "I like to PEROPERO.\n Wahahahahaha ~", NULL); return type; } int play_staff() { //SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "The grant staff", "Thank you everybody.", NULL); freopen("staff.in", "r", stdin); int staff_case = 0; scanf("%d", &staff_case); SDL_Rect rect[staff_case]; SDL_Texture *staff; for(int i = 0; i < staff_case; i++) { char file[100]; int w, h, x, y; scanf("%s%d%d%d%d", &file, &w, &h, &x, &y); rect[i] = {x, y, w, h}; image = IMG_Load(file); staff = SDL_CreateTextureFromSurface(renderer, image); //SDL_RenderCopy(renderer, staff, NULL, &rect[i]); SDL_RenderPresent(renderer); } for(int i = 0; i < 256; i += 5) { SDL_SetTextureAlphaMod(staff, i); SDL_RenderCopy(renderer, staff, NULL, &rect[0]); SDL_RenderPresent(renderer); SDL_Delay(1000 / SCREEN_FPS); } while(event.type != SDL_QUIT) { if(SDL_PollEvent(&event)) { if(event.type == SDL_QUIT) break; else if(event.type == SDL_MOUSEBUTTONDOWN) { if(event.button.button == SDL_BUTTON_LEFT) { Mix_PlayChannel(-1, button, 0); break; } } } SDL_Delay(1000 / SCREEN_FPS); } cout << "Type is 0" << endl; return 0; } void clean_up() { Mix_FreeChunk(button); Mix_FreeChunk(op); Mix_FreeChunk(end); SDL_DestroyTexture(texture); SDL_FreeSurface(image); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); } int main(int argc, char * args[]) { if(!init()) return 0; bool quit = false; while(!quit) { SDL_PollEvent(&event); if(event.type == SDL_QUIT) break; switch(type) { // 0 for play 1 for volumn 2 for staff case 0: type = play_menu(); break; case 1: //SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Missing file", "Got play.", NULL); type = play_game(); break; case 2: type = play_option(); break; case 3: type = play_staff(); break; } SDL_Delay(1000 / SCREEN_FPS); } Mix_PlayChannel(-1, end, 0); SDL_Delay(3437); clean_up(); return 0; }
7ed0e5deb0f16433bceffaab2ef365fd03f39d5f
[ "C++" ]
1
C++
s910702s910702/EZ-metro-SDL2
176d677483c7643cb2f4be79307f94d95112a943
0c97158927b5794eb27b55d79c635556df200ca3
refs/heads/master
<file_sep> function Tab(id){ this.box = document.getElementById(id); this.div = this.box.getElementsByTagName('div'); this.btn = this.box.getElementsByTagName('input'); } Tab.prototype.clicks = function(){ var _this = this; for(var i=0;i<this.btn.length;i++){ this.btn[i].index = i; this.btn[i].addEventListener('click',function(){ _this.clear(this.index); }); } } Tab.prototype.clear = function(index){ for(var i=0;i<this.btn.length;i++){ this.btn[i].className = ''; this.div[i].className = ''; } this.btn[index].className = 'active'; this.div[index].className = 'show'; } <file_sep># drag2 拖拽2
7999ad326688de64d782b04fd2d8af7b54d71b99
[ "JavaScript", "Markdown" ]
2
JavaScript
jiaYingp/drag2
5af125a1bdfedb9bbabdd333b305ebb2cda214fb
4d33dceaebc4aa6171f08a9bcd847f6a61550a3c