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>SuperBo/TMEMotorwayProcessor<file_sep>/src/create_txt_anno.cpp /* * Create annotation file for TME Dataset for using with Caffe-SSD * Author: SuperBo <<EMAIL>> */ #include <iostream> #include <fstream> #include <vector> #include "TMEMotorwayProcessor.h" string data_path; string anno_path; using namespace std; /* * Return label * 1: car * 2: truck */ int getLabel(const GTEntry& gt) { return (gt.isTruck()) ? 2 : 1; } bool createTxtAnno(const string& filename, const vector<GTEntry>& GroundTruths) { ofstream txtfile(filename); if (!txtfile.is_open()) { cerr << "Error while writing file " << filename << endl; return false; } // Loop through all of groundtruths boxes of image for (const GTEntry& gt : GroundTruths) { txtfile << getLabel(gt) << ' '; txtfile << gt.ip0.x << ' ' << gt.ip0.y << ' '; txtfile << gt.ip1.x << ' ' << gt.ip1.y << endl; } txtfile.close(); return true; } int processData(TMEMotorwayProcessor& processor) { vector<string> sequences; processor.getSequences(sequences); ofstream listfile(data_path + "/TME_anno_list.txt"); if (!listfile.is_open()) { cerr << "Error while create file " << data_path << "/TME_anno_list.txt"; return -1; } vector<GTEntry> gts; CameraType cams[2] = {RIGHT, LEFT}; for (const string& sequence: sequences) { for (int i = 0; i < 2; i++) { processor.initSequence(cams[i], sequence); if (!processor.isInitialized()) continue; while (processor.hasNextFrame()) { processor.nextFrame(); processor.getGroundTruths(gts); string imgfile = processor.getImageName(); string txtfile = anno_path + '/' + getFilenameWithoutExtension(imgfile) + ".txt"; cout << "Processing " << imgfile << endl; bool status = createTxtAnno(txtfile, gts); if (status) { listfile << imgfile << ' ' << txtfile << endl; } } } } listfile.close(); return 0; } int main(int argc, char* argv[]) { if (argc != 2) { cerr << "Usage: create_txt_anno <path to TME dataset>" << endl; return 1; } data_path = string(argv[1]); anno_path = data_path + "/annotation"; cout << "Data path: " << " " << data_path << endl; // Initialize data processor TMEMotorwayProcessor processor(data_path); int status = processData(processor); if (status == 0) cout << "-------------------" << endl << "Finished Successfully!" << endl; return status; } <file_sep>/src/TMEMotorwayProcessor.cpp // // TMEMotorwayProcessor.cpp // TMEMotorwayProcessor // // Created by <NAME> on 16/02/15. // #include "TMEMotorwayProcessor.h" TMEMotorwayProcessor::TMEMotorwayProcessor(const string& _datasetPath) { datasetPath = _datasetPath + "/"; } void TMEMotorwayProcessor::initSequence(const string& _sequence) { initSequence(RIGHT, _sequence); } void TMEMotorwayProcessor::initSequence(const CameraType& _cameraType, const string& _sequence) { //sequenceType = _sequenceType; cameraType = _cameraType; sequence = _sequence; string imageDirectory = getImageDirectory(); getFilesInDirectory(imageDirectory, imageFiles, "png"); if (imageFiles.empty()) { cout << "Unable to read sequence...EXIT" << endl; return; } // Read calibration parameters (now hardcoded, but can be read from calibration.ini) readCalibrationParameters(); // Read ground truth annotations from file and convert the bounding boxes to screen coordinates readGroundTruths(); currentFrame = -1; // Ground truths are available from frame 80 } void TMEMotorwayProcessor::getSequences(vector<string>& seqs) { getFoldersInDirectory(datasetPath, seqs, "tme"); } void TMEMotorwayProcessor::readCalibrationParameters(const string &calibrationFile) { // Since there is only one calibration file, for now just use hard coded values. calibration.x = -1.70; // POS X_M calibration.y = -0.60; // POS Y_M calibration.z = 1.28; // POS Z_M calibration.h_fov_deg = 32.1; // H_FOV_DEF calibration.pitch_deg = 0.2; // POS PITCH_DEG calibration.yaw_deg = -4.0; // POS YAW_DEF calibration.roll_deg = 0.0; // POS ROLL_DEG calibration.image_width = 1024; calibration.image_height = 768; } void TMEMotorwayProcessor::readGroundTruths() { groundTruths.clear(); string line; int gtCount = 0; // There are 2 GT files: Daylight and Sunset string gtFilename = getGroundTruthFilename(); ifstream gtFile (gtFilename); if (!gtFile.is_open()) { cout << "Unable to read ground truth file." << endl; return; } while (getline(gtFile, line)) { // We only need to read out ground truths for the current sequence if (line.substr(0,5) != sequence) continue; // Use the frame number as key for saving ground truths string frameNr = line.substr(6, 6); frameNr.erase(0, frameNr.find_first_not_of('0')); // remove preceding zeros // Rest of the line containing ground truth boxes line = line.substr(13); boost::trim(line); // Split line on ; character to read all ground truths in the image vector<string> gtLineParts; boost::split(gtLineParts, line, boost::is_any_of(";"), boost::token_compress_on); // Frame ground truths vector<GTEntry> frameGts; for (auto& gtLinePart : gtLineParts) { // Split part of line on space to read out detection values vector<string> gtValues; boost::trim(gtLinePart); boost::split(gtValues, gtLinePart, boost::is_any_of("\t "), boost::token_compress_on); // Ground truth detection contains seven values if (gtValues.size() != 7) continue; // Fill values of GroundTruth object GTEntry gt; gt.ID = stoi(gtValues[0]); gt.wp0.x = stof(gtValues[1]); gt.wp0.y = stof(gtValues[2]); gt.wp1.x = stof(gtValues[3]); gt.wp1.y = stof(gtValues[4]); gt.reconstructed = stoi(gtValues[5]) == 1 ? true : false; gt.estimatedWidth = stof(gtValues[6]); // Save ground truth for this frame frameGts.push_back(gt); gtCount++; } groundTruths[stoi(frameNr)] = frameGts; } // Conversion of world coordinates to screen coordinates // This conversion is done using parameters from calibration.ini computeScreenCoordinates(); gtFile.close(); } void TMEMotorwayProcessor::computeScreenCoordinates() { static const float near = 1.0; static const float far = 100; GLint m_viewPort[4]; GLdouble m_modelViewMatrix[16], m_projMatrix[16]; // Create hidden OpenGL window (just for its context) cv::namedWindow("OpenGL Context", cv::WINDOW_OPENGL); glViewport(0, 0, calibration.image_width, calibration.image_height); glGetIntegerv(GL_VIEWPORT, m_viewPort); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(calibration.h_fov_deg, double(calibration.image_width) / double(calibration.image_height), near, far); glGetDoublev(GL_PROJECTION_MATRIX, m_projMatrix); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0.0,0.0,0.0, 1.0,0.0,0.0, 0.0,0.0,1.0); // This is the only order that works correctly. glRotated(-calibration.roll_deg, 1.0, 0.0, 0.0); glRotated(-calibration.pitch_deg, 0.0, 1.0, 0.0); glRotated(-calibration.yaw_deg, 0.0, 0.0, 1.0); glTranslated(-calibration.x, -calibration.y, -calibration.z); // z = height glGetDoublev(GL_MODELVIEW_MATRIX, m_modelViewMatrix); double z; for(auto &it : groundTruths) { for (auto& gt : it.second) { // 'it.second' is vector<GTEntry> containing GTs for one frame cv::Point2d pointLeft, pointRight; // Convert first (LEFT) point to screen coordinates gluProject(gt.wp0.x, gt.wp1.y, 0.0, m_modelViewMatrix, m_projMatrix, m_viewPort, &(pointLeft.x), &(pointLeft.y), &z); pointLeft.y = calibration.image_height - pointLeft.y; // Convert second (RIGHT) point to screen coordinates gluProject(gt.wp0.x, gt.wp0.y, 0.0, m_modelViewMatrix, m_projMatrix, m_viewPort, &(pointRight.x), &(pointRight.y), &z); pointRight.y = calibration.image_height - pointRight.y; gt.ip0 = pointLeft; gt.ip1 = pointRight; const double pixelHeight = gt.assignedHeight() * gt.meterToPixel(); gt.ip0.y -= pixelHeight; // Check whether bounding box is truncated (out-of-screen) gt.truncated = ((gt.ip0.x < 0 && 1.0 - abs(gt.ip0.x) / gt.pixelWidth() < TRUNCATED_TH) || (gt.ip1.x > calibration.image_width && 1.0 - (gt.ip1.x - calibration.image_width) / gt.pixelWidth() < TRUNCATED_TH) ); // Check whether bounding box is occluded gt.occluded = (isOccluded(gt, it.second)) ? true : false; } } cv::destroyWindow("OpenGL Context"); } bool TMEMotorwayProcessor::isOccluded (const GTEntry& gt, const vector<GTEntry>& otherGts) { for (auto& other : otherGts) { if (gt.ID == other.ID) continue; if (gt.pixelWidth() >= other.pixelWidth()) continue; double overlapScore = computeBoundingBoxOverlap(gt, other); if (overlapScore > 0) return true; } return false; } double TMEMotorwayProcessor::computeBoundingBoxOverlap (const GTEntry& gt1, const GTEntry& gt2) { // get overlapping area double x1 = max(gt1.ip0.x, gt2.ip0.x); double y1 = max(gt1.ip0.y, gt2.ip0.y); double x2 = min(gt1.ip1.x, gt2.ip1.x); double y2 = min(gt1.ip1.y, gt2.ip1.y); // compute width and height of overlapping area double w = x2-x1; double h = y2-y1; // Set invalid entries to 0 overlap if(w <= 0 || h <= 0) return 0; // get overlapping areas double inter = w*h; double b_area = (gt2.ip1.x-gt2.ip0.x) * (gt2.ip1.y-gt2.ip0.y); return (inter / b_area); } void TMEMotorwayProcessor::show (int delay) { string imageDirectory = getImageDirectory(); vector<string> imageFiles; getFilesInDirectory(imageDirectory, imageFiles, "png"); cv::Mat image; cv::namedWindow("TME Motorway Sequence", cv::WINDOW_AUTOSIZE); vector<GTEntry> gts; // ground truths for (int i = 100; i < imageFiles.size(); i++) { // Read ground truths from cache int frameNr = getImageIndex(imageFiles[i]); getGroundTruths(frameNr, gts); image = cv::imread(imageFiles[i], cv::IMREAD_COLOR); for (auto& gt : gts) { cv::Scalar color = (gt.occluded) ? cv::Scalar(0, 0, 255) : cv::Scalar(0, 255, 255); cv::rectangle(image, gt.ip0, gt.ip1, color, 2); } cv::imshow("TME Motorway Sequence", image); cv::waitKey(delay); // recorded @ 20 Hz image.release(); gts.clear(); } } void TMEMotorwayProcessor::readFrame(cv::Mat &image, vector<GTEntry> &gts) { assert(currentFrame >= 0); image = cv::imread(imageFiles[currentFrame], cv::IMREAD_COLOR); getGroundTruths(getImageIndex(imageFiles[currentFrame]), gts); } void TMEMotorwayProcessor::readNextFrame(cv::Mat &image, vector<GTEntry> &gts) { currentFrame++; TMEMotorwayProcessor::readFrame(image, gts); } bool TMEMotorwayProcessor::isInitialized() { if (imageFiles.empty() || groundTruths.empty()) return false; if (calibration.x == 0 || calibration.y == 0) return false; return true; } bool TMEMotorwayProcessor::hasNextFrame () { return (currentFrame < (int) imageFiles.size() - 1); } void TMEMotorwayProcessor::nextFrame() { currentFrame++; } void TMEMotorwayProcessor::resetFrame() { currentFrame = -1; } void TMEMotorwayProcessor::jumpToFrame(int frame) { currentFrame = frame; } string TMEMotorwayProcessor::getImageName() { return imageFiles[currentFrame]; } void TMEMotorwayProcessor::getGroundTruths(vector<GTEntry>& gts) { getGroundTruths(getImageIndex(), gts); } void TMEMotorwayProcessor::getGroundTruths (int frameNr, vector<GTEntry>& gts) { gts.clear(); if (groundTruths.empty()) return; // Map with ground truths filled ? if (groundTruths.find(frameNr) == groundTruths.end()) return; // check key not found gts = groundTruths.at(frameNr); } string TMEMotorwayProcessor::getGroundTruthFilename () { //string lightingSubset = (sequenceType == DAYLIGHT) ? "Daylight" : "Sunset"; //string gtFilename = datasetPath + "ITSC2012gt-" + lightingSubset + ".txt"; //return gtFilename; return (datasetPath + "ITSC2012gt.txt"); } string TMEMotorwayProcessor::getImageDirectory () { //string lightingSubset = (sequenceType == DAYLIGHT) ? "Daylight" : "Sunset"; //string imagePath = datasetPath + lightingSubset + "/" + sequence + "/Right/"; string camPath = (cameraType == RIGHT) ? "/Right/" : "/Left/"; return (datasetPath + sequence + camPath); } int TMEMotorwayProcessor::getImageIndex() { return getImageIndex(getImageName()); } int TMEMotorwayProcessor::getImageIndex (const string& imFilename) { string tmp = getFilenameWithoutExtension(imFilename); // 022562-R tmp.erase(0, tmp.find_first_not_of('0')); // remove preceding zeros tmp.erase(tmp.find_first_of('-'), 2); // remove '-R' return stoi(tmp); } void TMEMotorwayProcessor::convertImagesToRGB (const string& directory) { vector<string> filenames; getFilesInDirectory(directory, filenames, "png"); for (auto& s : filenames) { cv::Mat image = cv::imread(s, cv::IMREAD_UNCHANGED); if (image.type() == CV_8UC3) continue; cout << "Processing " << getFilename(s) << endl; cv::cvtColor(image, image, cv::COLOR_BayerGB2BGR); cv::imwrite(s, image); } } <file_sep>/src/Utilities.h // // Utilities.h // TMEMotorwayProcessor // // Created by <NAME> on 07/02/15. // #ifndef __TMEMotorwayProcessor__Utilities__ #define __TMEMotorwayProcessor__Utilities__ #include <iostream> #include <iomanip> #include <fstream> #include <sstream> #include <dirent.h> #include <algorithm> #include <vector> #include <map> #include <list> #include <string> #include <cstring> #include <unistd.h> using namespace std; namespace utilities { //*************************************************************// //****************** GENERAL HELPER METHODS *******************// //*************************************************************// string toLowerCase(const string& inputString); string getFilename (const string& fullPath); string getFilenameWithoutExtension(const string& fullPath); void getFilesInDirectory(const string& directory, vector<string>& fileNames, const vector<string>& validExtensions); void getFilesInDirectory(const string& directory, vector<string>& fileNames, const string& validExtension); void getFoldersInDirectory(const string& directory, vector<string>& folderNames, const string& prefix); } #endif <file_sep>/Makefile CFLAGS = -Isrc $(shell pkg-config --cflags opencv) LDFLAGS = -lGL -lGLU -lopencv_core -lopencv_highgui -lopencv_imgproc -lopencv_video -lopencv_objdetect -lopencv_imgcodecs .PHONY: clean all all: create_txt_anno convert_to_rgb create_txt_anno: src/create_txt_anno.cpp TMEMotorwayProcessor.o Utilities.o $(CXX) $(CFLAGS) $(LDFLAGS) -o $@ $^ convert_to_rgb: src/convert_to_rgb.cpp TMEMotorwayProcessor.o Utilities.o $(CXX) $(CFLGAS) $(LDFLAGS) -o $@ $^ TMEMotorwayProcessor.o: src/TMEMotorwayProcessor.cpp $(CXX) -c -o $@ $< Utilities.o: src/Utilities.cpp $(CXX) -c -o $@ $< clean: rm -f *.o <file_sep>/src/main.cpp // // main.cpp // TMEMotorwayProcessor // // Created by <NAME> on 20/02/15. // Copyright (c) 2015 TUDelft. All rights reserved. // Modified by <NAME> #include <iostream> #include "Utilities.h" #include "TMEMotorwayProcessor.h" void convertImagesToRGB (TMEMotorwayProcessor& processor, const string& datasetPath) { // Daylight: 08 11 12 16 17 18 32 35 42 // Sunset: 12 16 20 46 processor.convertImagesToRGB(datasetPath + "tme08/Right/"); // ... add other directories if you want. } void showFrames (TMEMotorwayProcessor& processor) { if (!processor.isInitialized()) return; // Ground truth boxes vector<GTEntry> gts; cv::namedWindow("TME Motorway Sequence", cv::WINDOW_AUTOSIZE); cv::Mat image; while (processor.hasNextFrame()) { // Read next frame from sequence processor.readNextFrame(image, gts); // Draw ground truth bounding boxes // Note that the first ~100 frames are not annotated. for (auto& gt : gts) { // Optionally filter occluded objects, trucks or cars too far away //if (gt.isTruck() || gt.occluded || gt.pixelWidth() < 40) continue; cv::rectangle(image, gt.ip0, gt.ip1, cv::Scalar(0, 255, 255), 2); } cv::imshow("TME Motorway Sequence", image); cv::waitKey(5); // Set the delay between frames (ms) image.release(); gts.clear(); } } int main(int argc, const char * argv[]) { // Full path to the location of your TME Motorway Dataset string datasetPath = "data/Daylight"; // Choose a sequence type (Daylight/Sunset) and a sequence number string sequence = "tme08"; // Initialize data processor TMEMotorwayProcessor processor(datasetPath); processor.initSequence(sequence); // Show the images + ground truth bounding boxes showFrames(processor); } <file_sep>/data/calibration.ini H_FOV_DEG = 32.1 POS X_M = -1.7 POS Y_M = -0.60 POS Z_M = 1.28 POS PITCH_DEG = 0.2 POS YAW_DEG = -4.0 POS ROLL_DEG = 0.0 IMAGE WIDTH = 1024 IMAGE HEIGHT = 768 <file_sep>/src/Utilities.cpp // // Utilities.cpp // TMEMotorwayProcessor // // Created by <NAME> on 07/02/15. // #include "Utilities.h" namespace utilities { //*************************************************************// //****************** GENERAL HELPER METHODS *******************// //*************************************************************// // Get current date/time "YYYY-MM-DD HH:mm:ss" string currentDateTime() { time_t now = time(0); struct tm tstruct; char buf[80]; tstruct = *localtime(&now); strftime(buf, sizeof(buf), "%Y-%m-%d_%X", &tstruct); return string(buf); } string toLowerCase(const string& inputString) { string t; for (string::const_iterator i = inputString.begin(); i != inputString.end(); ++i) { t += tolower(*i); } return t; } string getFilename(const string& fullPath) { unsigned pos = (unsigned)fullPath.find_last_of("/\\"); string filename = fullPath.substr(pos+1); return filename; } string getFilenameWithoutExtension(const string& fullPath) { string withExtension = getFilename(fullPath); int lastDot = withExtension.find_last_of("."); if (lastDot == string::npos) return fullPath; return withExtension.substr(0, lastDot); } void getFilesInDirectory(const string& directory, vector<string>& fileNames, const vector<string>& validExtensions) { struct dirent* ep; size_t extensionLocation; DIR* dp = opendir(directory.c_str()); if (dp != NULL) { while ((ep = readdir(dp))) { // Ignore (sub-)directories like if (ep->d_type & DT_DIR) { continue; } extensionLocation = string(ep->d_name).find_last_of("."); // Assume the last point marks beginning of extension like file.ext // Check if extension is matching the wanted ones string tempExt = toLowerCase(string(ep->d_name).substr(extensionLocation + 1)); // Check for matching file if (find(validExtensions.begin(), validExtensions.end(), tempExt) != validExtensions.end()) { fileNames.push_back((string)directory + ep->d_name); } } (void)closedir(dp); } // Make sture the filenames are sorted sort(fileNames.begin(), fileNames.end()); } void getFilesInDirectory(const string& directory, vector<string>& fileNames, const string& validExtension) { getFilesInDirectory(directory, fileNames, vector<string>{validExtension}); } void getFoldersInDirectory(const string& directory, vector<string>& folderNames, const string& prefix) { int pre_len = prefix.length(); const char* pre_str = prefix.c_str(); struct dirent* entry; DIR* dir = opendir(directory.c_str()); folderNames.clear(); while ((entry = readdir(dir)) != NULL) { if (entry->d_type == DT_DIR && entry->d_name[0] != '.' && strncmp(entry->d_name, pre_str, pre_len) == 0) { folderNames.push_back(string(entry->d_name)); } } closedir(dir); // Sort Folder Name sort(folderNames.begin(), folderNames.end()); } } <file_sep>/src/TMEMotorwayProcessor.h // // TMEMotorwayProcessor.h // TMEMotorwayProcessor // // Created by <NAME> on 16/02/15. // #ifndef __TMEMotorwayProcessor__TMEMotorwayProcessor__ #define __TMEMotorwayProcessor__TMEMotorwayProcessor__ #include <iostream> #include <fstream> #include <vector> #include <map> #include <string> // Only tested on OS X 10.9 #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #else #ifdef _WIN32 #include <windows.h> #endif #include <GL/gl.h> #include <GL/glu.h> #endif #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/video/tracking.hpp> #include <opencv2/objdetect/objdetect.hpp> // Only used for string.trim() and string.split() #include <boost/algorithm/string.hpp> #include "Utilities.h" using namespace std; using namespace utilities; static const double CAR_TRUCK_WIDTH_BOUNDARY_TH = 2.1; static const double CAR_HEIGHT = 1.5; static const double TRUCK_HEIGHT = 2.1; static const double TRUNCATED_TH = 0.75; static const double OVERLAP_TH = 0.2; static const double OCCLUSION_TH = 0.2; enum SequenceType { DAYLIGHT, SUNSET }; enum CameraType { RIGHT, LEFT }; struct CalibrationParameters { double x; double y; double z; double roll_deg; double yaw_deg; double pitch_deg; double h_fov_deg; int image_width; int image_height; inline double Roll_rad() const { return roll_deg *M_PI/180; } inline double Yaw_rad() const { return yaw_deg*M_PI/180; } inline double Pitch_rad() const { return pitch_deg*M_PI/180; } inline double H_fov_rad() const { return h_fov_deg*M_PI/180; } }; struct GTEntry { unsigned long ID; cv::Point2d wp0; // World coordinate cv::Point2d wp1; // World coordinate bool reconstructed; // Sample was not detected at this frame, but interpolated from previous and successive detection double estimatedWidth; // Estimated across all the observation time of this target // Variables computed from the static calibration cv::Point2d ip0; // Screen coordinates cv::Point2d ip1; // Screen coordinates bool truncated; bool occluded; bool truck; inline double assignedHeight() const { return (estimatedWidth > CAR_TRUCK_WIDTH_BOUNDARY_TH) ? TRUCK_HEIGHT : CAR_HEIGHT; } inline double meterWidth() const { return (wp1.y - wp0.y); } inline double pixelWidth() const { return (ip1.x - ip0.x); } inline double pixelHeight() const { return (ip1.y - ip0.y); } inline double ImageArea() const { return pixelWidth() * pixelHeight(); } inline bool isTruck () const { return (estimatedWidth > CAR_TRUCK_WIDTH_BOUNDARY_TH) ? true : false; } inline double meterToPixel() const { if (meterWidth()) return pixelWidth() / meterWidth(); else return 0.0; } inline double PixelToMeter() const { if (pixelWidth()) return meterWidth() / (pixelWidth()); else return 0.0; } void print () { printf("ID = %i\n", (int)ID); printf("wp0 = (%2.2f, %2.2f)\n", wp0.x, wp0.y); printf("wp1 = (%2.2f, %2.2f)\n", wp1.x, wp1.y); printf("reconsructed = %i\n", reconstructed); printf("estimated width = %3.2f\n", estimatedWidth); } }; class TMEMotorwayProcessor { public: TMEMotorwayProcessor (); TMEMotorwayProcessor (const string& _datasetPath); void initSequence (const string& _sequence); void initSequence (const CameraType& _cameraType, const string& _sequence); void getSequences (vector<string>& seqs); void readCalibrationParameters (const string& calibrationFile = "calibration.ini"); void readGroundTruths (); void getGroundTruths (vector<GTEntry>& groundTruths); void getGroundTruths (int frame, vector<GTEntry>& groundTruths); string getGroundTruthFilename (); string getImageDirectory (); string getImageName(); int getImageIndex (); int getImageIndex (const string& imFilename); void show(int delay = 5); void readFrame(cv::Mat& image, vector<GTEntry>& gts); void readNextFrame(cv::Mat& image, vector<GTEntry>& gts); void jumpToFrame (int frame); bool hasNextFrame(); void nextFrame(); void resetFrame(); bool isInitialized(); void computeScreenCoordinates (); double computeBoundingBoxOverlap (const GTEntry& gt1, const GTEntry& gt2); bool isOccluded (const GTEntry& gt, const vector<GTEntry>& otherGts); void convertImagesToRGB (const string& directory); private: string datasetPath; string sequence; //SequenceType sequenceType; CameraType cameraType; CalibrationParameters calibration; // This map stores ground truths for each frame (key = frame number) map<int, vector<GTEntry>> groundTruths; // List of images in the stream vector<string> imageFiles; int currentFrame; }; #endif /* defined(__TMEMotorwayProcessor__TMEMotorwayProcessor__) */ <file_sep>/src/convert_to_rgb.cpp #include <iostream> #include "TMEMotorwayProcessor.h" using namespace std; int main(int argc, char* argv[]) { if (argc != 2) { cerr << "Usage: convert_to_rgb <path to TME dataset>" << endl; return 1; } string data_path = string(argv[1]); TMEMotorwayProcessor processor (data_path); cout << "TME Dataset path: data_path" << endl; vector<string> seqs; processor.getSequences(seqs); CameraType cams[2] = {RIGHT, LEFT}; for (const string& seq : seqs) { for (int i = 0; i < 2; i++) { processor.initSequence(cams[i], seq); if (! processor.isInitialized()) continue; string imgDir = processor.getImageDirectory(); cout << "Converting " << imgDir << " to RGB" << endl; processor.convertImagesToRGB(imgDir); } } return 0; }
6d9e51092706600ba788c14f0c7ab3f046fc1cfc
[ "Makefile", "C++", "INI" ]
9
C++
SuperBo/TMEMotorwayProcessor
74983be8ea66ee33d0af005fa0197ff4e15f714d
a578e01794b7e9da45f06906c079ff501d61bd84
refs/heads/master
<repo_name>outofjungle/knife-info<file_sep>/spec/unit/info_spec.rb require File.expand_path('../../spec_helper', __FILE__) describe KnifeInfo::Info do let(:username) do 'user' end let(:host) do 'test' end let(:domain) do 'chef.org' end let(:organization) do 'org' end let(:url) do "https://#{host}.#{domain}/organizations/#{organization}" end let(:config_file) do "/home/#{username}/.chef/knife.rb" end before :each do @knife = Chef::Knife::Info.new Chef::Knife.stub(:locate_config_file).and_return(config_file) @knife.stub(:server_url).and_return(url) @knife.stub(:username).and_return(username) end context 'if env user DOES NOT match' do before :each do ENV['USER'] = 'none' end it 'and tiny=true should print concise info in oneline' do @knife.config[:tiny] = true @knife.ui.should_receive(:msg).with("#{username}@#{host}/#{organization}") @knife.run end it 'and medium=true should print info in oneline' do @knife.config[:medium] = true @knife.ui.should_receive(:msg).with("#{username}@#{host}.#{domain}/#{organization}") @knife.run end end context 'if env user match' do before :each do ENV['USER'] = username end it 'and tiny=true should print concise info without username' do @knife.config[:tiny] = true @knife.ui.should_receive(:msg).with("#{host}/#{organization}") @knife.run end it 'and medium=true should print concise info without username' do @knife.config[:medium] = true @knife.ui.should_receive(:msg).with("#{host}.#{domain}/#{organization}") @knife.run end end it 'if long=true should print info in multi-line' do @knife.config[:long] = true expected = [ "Host: #{host}.#{domain}", "Username: #{username}", "Organization: #{organization}", "Config File: #{config_file}", "" ] @knife.ui.should_receive(:msg).with(expected.join("\n")) @knife.run end context 'if config file is not found' do before :each do Chef::Knife.stub(:locate_config_file).and_return(nil) end it 'should print nothing' do @knife.ui.should_receive(:msg).exactly(0).times @knife.run end end end <file_sep>/spec/spec_helper.rb $:.unshift File.expand_path('../../lib', __FILE__) require 'coveralls' Coveralls.wear! require 'chef/knife' require 'chef/knife/info' class Chef::Knife include KnifeInfo end <file_sep>/README.md # knife Info [![Gem Version](https://badge.fury.io/rb/knife-info.png)](http://badge.fury.io/rb/knife-info) [![Build Status](https://travis-ci.org/outofjungle/knife-info.png?branch=master)](https://travis-ci.org/outofjungle/knife-info) [![Code Climate](https://codeclimate.com/github/outofjungle/knife-info.png)](https://codeclimate.com/github/outofjungle/knife-info) [![Dependency Status](https://gemnasium.com/outofjungle/knife-info.png)](https://gemnasium.com/outofjungle/knife-info) [![Coverage Status](https://coveralls.io/repos/outofjungle/knife-info/badge.png)](https://coveralls.io/r/outofjungle/knife-info) ## Description This is an EXPERIMENTAL knife plugin that displays information from `knife.rb` config file in knife's configuration file search path. ## Installation This knife plugin is packaged as a gem. To install it, clone this git repository and run the following command: rake install ## Subcommands ### `knife info [options]` *Options* * `--tiny`: Show concise information in oneline * `--medium`: Show important information in oneline * `--long`: Show all information in multi-lines ## TODO * Support for `--[no-]color` option * Support for `json` output <file_sep>/Rakefile lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'rubygems/package_task' require 'knife-info/version' GEM_NAME = 'knife-info' GEM_VERSION = KnifeInfo::VERSION task :clean => :clobber_package spec = eval(File.read('knife-info.gemspec')) Gem::PackageTask.new(spec) do |pkg| pkg.gem_spec = spec end desc 'install gem' task :install => :package do sh %{gem install pkg/#{GEM_NAME}-#{GEM_VERSION}.gem --no-rdoc --no-ri} end desc 'uninstall gem' task :uninstall do sh %{gem uninstall #{GEM_NAME} -x -v #{GEM_VERSION} } end begin require 'rspec/core/rake_task' task :default => :spec desc 'Run all specs in spec directory' RSpec::Core::RakeTask.new(:spec) do |t| t.pattern = 'spec/unit/**/*_spec.rb' end rescue LoadError STDERR.puts "\n*** RSpec not available. (sudo) gem install rspec to run unit tests. ***\n\n" end<file_sep>/lib/chef/knife/info.rb require 'chef/knife' require 'uri' module KnifeInfo class Info < Chef::Knife category 'CHEF KNIFE INFO' banner 'knife info' option :tiny, :long => '--tiny', :description => 'Print concise information in oneline', :boolean => true | false option :medium, :long => '--medium', :description => 'Print important information in oneline', :boolean => true | false option :long, :long => '--long', :description => 'Print all information in multiple lines', :boolean => true | false, :default => true def run read_config_data unless @config_file.nil? case when config[:tiny] then ui.msg(tiny_print) when config[:medium] then ui.msg(medium_print) else ui.msg(long_print) end end end def read_config_data @config_file = Chef::Knife.locate_config_file uri = URI(server_url) @host = uri.host %r(.*/organizations/(?<org>.*)$) =~ uri.path @organization = org || '' end def user_string (username != ENV['USER']) ? "#{username}@" : '' end def tiny_print %r(^(?<host>[a-zA-Z0-9-]+)\..*$) =~ @host "#{user_string}#{host}/#{@organization}" end def medium_print "#{user_string}#{@host}/#{organization}" end def long_print <<-VERBOSE.gsub(/^\s+/, '') Host: #{@host} Username: #{username} Organization: #{@organization} Config File: #{@config_file} VERBOSE end attr_reader :host, :organization, :user, :config_file_location end end <file_sep>/knife-info.gemspec $:.push File.expand_path("../lib", __FILE__) require 'knife-info/version' Gem::Specification.new do |spec| spec.name = 'knife-info' spec.version = KnifeInfo::VERSION spec.summary = 'knife info' spec.description = 'Displays which .chef config dir knife will be using' spec.authors = ['<NAME>'] spec.email = '<EMAIL>' spec.homepage = 'https://github.com/outofjungle/knife-info' spec.files = %w(README.md) + Dir.glob('lib/**/*') + Dir.glob('bin/*') spec.require_path = 'lib' spec.required_ruby_version = '>= 1.9' spec.add_dependency 'chef' spec.add_development_dependency 'bundler', '~> 1.3' spec.add_development_dependency 'rake' spec.add_development_dependency 'rspec' spec.add_development_dependency 'coveralls' spec.license = 'MIT' end
253aa4135194f39278c16827a45873154f9e2c40
[ "Markdown", "Ruby" ]
6
Ruby
outofjungle/knife-info
43807c75c25f5bd34699441d28d6fb366ce70c53
11cd9cc2c97ab8c9bef6e7a83bd1409ca793f68b
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using Internship.DAL; using Internship.Models; namespace Internship.Controllers { public class TicketsController : Controller { private InternshipContext db = new InternshipContext(); // GET: Tickets public ActionResult Index() { var tickets = db.Tickets.Include(t => t.Order); return View(tickets.ToList()); } // GET: Tickets/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Ticket ticket = db.Tickets.Find(id); if (ticket == null) { return HttpNotFound(); } return View(ticket); } // GET: Tickets/Create public ActionResult Create() { ViewBag.orderKey = new SelectList(db.Orders, "orderKey", "firstName"); return View(); } // POST: Tickets/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "ticketKey,ticketNumber,eventDate,orderKey")] Ticket ticket) { if (ModelState.IsValid) { db.Tickets.Add(ticket); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.orderKey = new SelectList(db.Orders, "orderKey", "firstName", ticket.orderKey); return View(ticket); } // GET: Tickets/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Ticket ticket = db.Tickets.Find(id); if (ticket == null) { return HttpNotFound(); } ViewBag.orderKey = new SelectList(db.Orders, "orderKey", "firstName", ticket.orderKey); return View(ticket); } // POST: Tickets/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "ticketKey,ticketNumber,eventDate,orderKey")] Ticket ticket) { if (ModelState.IsValid) { db.Entry(ticket).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.orderKey = new SelectList(db.Orders, "orderKey", "firstName", ticket.orderKey); return View(ticket); } // GET: Tickets/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Ticket ticket = db.Tickets.Find(id); if (ticket == null) { return HttpNotFound(); } return View(ticket); } public ActionResult DeleteAll() { IList<Ticket> removeTickets = db.Tickets.ToList(); db.Tickets.RemoveRange(removeTickets); db.SaveChanges(); return RedirectToAction("Index"); } // POST: Tickets/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Ticket ticket = db.Tickets.Find(id); db.Tickets.Remove(ticket); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } } <file_sep>using Internship.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.IO; using Internship.DAL; namespace Internship.Controllers { public class HomeController : Controller { private InternshipContext ordersDatabase = new InternshipContext(); [HttpGet] public ActionResult Index() { return View(new List<FullOrder>()); } [HttpPost] public ActionResult Index(HttpPostedFileBase postedFile) { List<FullOrder> fullOrders = new List<FullOrder>(); string filePath = string.Empty; if (postedFile != null) { string path = Server.MapPath("~/Uploads/"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } filePath = path + Path.GetFileName(postedFile.FileName); string extension = Path.GetExtension(postedFile.FileName); postedFile.SaveAs(filePath); //Read the contents of CSV file. string csvData = System.IO.File.ReadAllText(filePath); int i = 0; //Execute a loop over the rows. foreach (string row in csvData.Split('\n')) { if (!string.IsNullOrEmpty(row) && i != 0) { fullOrders.Add(new FullOrder { Key = i + 1, ID = Convert.ToInt32(row.Split(',')[0]), FName = row.Split(',')[1], LName = row.Split(',')[2], TicketNumber = row.Split(',')[3], EventDate = Convert.ToDateTime(row.Split(',')[4]) }); } i++; } foreach(FullOrder order in fullOrders) { ordersDatabase.Orders.Add(new Order { orderID = order.ID, firstName = order.FName, lastName = order.LName }); ordersDatabase.SaveChanges(); ordersDatabase.Tickets.Add(new Ticket { orderKey = ordersDatabase.Orders.ToList().Last().orderKey, ticketNumber = order.TicketNumber, eventDate = order.EventDate }); ordersDatabase.SaveChanges(); } } return View(fullOrders); } public ActionResult DisplayAll() { List<FullOrder> allOrders = new List<FullOrder>(); foreach(Order order in ordersDatabase.Orders.ToList()) { Ticket ticket = ordersDatabase.Tickets.Where(tkt => tkt.orderKey == order.orderKey).FirstOrDefault(); allOrders.Add(new FullOrder { Key = order.orderKey, ID = order.orderID, FName = order.firstName, LName = order.lastName, TicketNumber = ticket.ticketNumber, EventDate = ticket.eventDate }); } return View(allOrders); } public ActionResult DeleteAll() { IList<Order> removeOrders = ordersDatabase.Orders.ToList(); ordersDatabase.Orders.RemoveRange(removeOrders); ordersDatabase.SaveChanges(); IList<Ticket> removeTickets = ordersDatabase.Tickets.ToList(); ordersDatabase.Tickets.RemoveRange(removeTickets); ordersDatabase.SaveChanges(); return RedirectToAction("DisplayAll"); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace Internship.Models { [Table("Ticket")] public class Ticket { [Key] public int ticketKey { get; set; } public string ticketNumber { get; set; } public DateTime eventDate { get; set; } [ForeignKey("Order")] public virtual int? orderKey { get; set; } public virtual Order Order { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Internship.Models { public class FullOrder { public int Key { get; set; } public int ID { get; set; } public string FName { get; set; } public string LName { get; set; } public string TicketNumber { get; set; } public DateTime EventDate { get; set; } } }<file_sep>using Internship.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace Internship.DAL { public class InternshipContext : DbContext { public InternshipContext() : base("InternshipContext") { } public DbSet<Order> Orders { get; set; } public DbSet<Ticket> Tickets { get; set; } public System.Data.Entity.DbSet<Internship.Models.FullOrder> FullOrders { get; set; } } }
7f4b3917b0bd9c611bcec7aaa7e762916a6130c9
[ "C#" ]
5
C#
johnnyataisg/Internship
193e7e3949ecfc29a6c2eea18c05501de76e0fb4
8b7a2f9089b4ce1807262d104e2b8b6460702bd4
refs/heads/master
<file_sep><?php require_once './autoload.php'; $logout = filter_input(INPUT_GET, 'logout'); if ($logout == 1) { $_SESSION['user_id'] = null; } if (!isset($_SESSION['user_id'])) { header('Location: index.php'); } else if (isset($_SESSION['user_id'])) { echo '<div class="logout"><a href="?logout=1">Logout</a></div>'; } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Admin</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="css/styles.css"> </head> <body> <div class="wrapper"><p>You are on the admin page<p></div> </body> </html> <file_sep><!DOCTYPE html> <!-- 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. --> <html> <head> <meta charset="UTF-8"> <title>Show Flash Message</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="style.css"> </head> <body> <div class="bg-warning message-box"> <?php session_start(); include './models/IMessage.php'; include './models/Message.php'; include './models/FlashMessage.php'; $flashMessage = new FlashMessage(); $messages = $flashMessage->getAllMessages(); print_r($messages); ?> </div> </body> </html> <file_sep><?php include './autoload.php'; include './templates/login_signup.html.php'; ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>View Page</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="css/styles.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <?php include './templates/errors.html.php'; ?> <?php include './templates/messages.html.php'; ?> <!--for facebook share--> <div id="fb-root"></div> <script>(function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.5"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> <?php $logout = filter_input(INPUT_GET, 'logout'); if ($logout == 1) { $_SESSION['user_id'] = null; } if (!isset($_SESSION['user_id'])) { echo'<div id="header_right">'; echo '<input type="button" value="Log in" id="login" />'; echo '<input type="button" value="Sign up" id="sign_up" />'; echo '</div>'; } else if (isset($_SESSION['user_id'])) { echo '<div class="logout button"><a href="?logout=1">Logout</a></div>'; echo '<div class="action_btn button"><a href="add_image.php">Upload Image</a></div>'; } ?> <?php $files = array(); $directory = '.' . DIRECTORY_SEPARATOR . 'uploads'; $dir = new DirectoryIterator($directory); foreach ($dir as $fileInfo) { if ($fileInfo->isFile()) { $files[$fileInfo->getMTime()] = $fileInfo->getPathname(); } } //sort the files by latest upload first krsort($files); ?> <?php if (!isset($_SESSION['user_id'])) { echo '<div class="view_table">'; foreach ($files as $key => $path) { echo '<div class=meme>'; echo '<img src="' . $path . '" /> <br />'; echo date("l F j, Y, g:i a", $key); echo '<div class="g-plus" data-action="share" data-href="' . $path . '"></div>'; echo '<div class="mail"> <a href="mailto:?subject=I wanted you to see this image&amp;body=Check out this site"' . $path . '"title="Share by Email"> <img src="http://png-2.findicons.com/files/icons/573/must_have/48/mail.png"> </a> </div>'; echo '<div class="fb-share-button" data-href="' . $path . '" data-layout="button_count"></div>'; echo '</div>'; } echo '</div>'; } else if (isset($_SESSION['user_id'])) { $util = new Util(); if ($util->isPostRequest()) { $filename = filter_input(INPUT_POST, 'filename'); $removeFromFolder = new Remove(); $removeFromFolder->removeFile($filename); $removeFromDB = new Login(); $removeFromDB->removeUserPhotos($filename); } $results = new Login(); $userPhotos = array(); $userPhotos = $results->getUserPhotos($_SESSION['user_id']); if ($userPhotos) { echo '<div class="view_table">'; foreach ($userPhotos as $uPhoto) { echo '<div class="meme">'; //echo '<p>User ID ' . $stuff['user_id'] . '<br />'; //echo 'Photo ID ' . $stuff['photo_id'] . '<br />'; echo '<img src="' . $directory . '\\' . $uPhoto['filename'] . '."/> <br />'; echo '<div class="g-plus" data-action="share" data-href="' . $directory . '\\' . $uPhoto['filename'] . '"></div>'; echo '<div class="mail"> <a href="mailto:?subject=I wanted you to see this image&amp;body=Check out this site"' . $directory . '\\' . $uPhoto['filename'] . 'title="Share by Email">' . '<img src="http://png-2.findicons.com/files/icons/573/must_have/48/mail.png"> </a> </div>'; echo '<div class="fb-share-button" data-href="' . $directory . '\\' . $uPhoto['filename'] . '" data-layout="button_count"></div><br /><br />'; echo '<form action="#" method="POST"> <input class="btn" type="submit" value="Delete" /> <input type="hidden" value="' . $uPhoto['filename'] . '" name="filename"/> </form>'; echo '</div>'; } echo '</div>'; } } ?> <!-- Place this tag in your head or just before your close body tag. --> <script src="https://apis.google.com/js/platform.js" async defer></script> <script> $("#login").on("click", function () { $("#login_popup").css({"top": $("#login").position().top + 40, "right": 15}).show(); }); $("#sign_up").on("click", function () { $("#signup_popup").css({"top": $("#sign_up").position().top + 40, "right": 15}).show(); }); </script> </body> </html><file_sep><!--default form--> <div class="form"> <form action="#" method="post" name="login_form"> <div id="login_popup" class="login_popup"> <div class="form_row"> <label>Email:</label> <span class="input_container"> <input type="text" name="email" value="<?php echo $email; ?>" /> </span> </div> <div class="form_row"> <label>Password:</label> <span class="input_container"> <input type="<PASSWORD>" name="password" value="" /> </span> </div> <div class="text_right"> <input type="submit" name="login" value="Submit" class="btn btn-primary" /> </div> </div> </form> </div><file_sep><?php include_once './autoload.php'; $restServer = new RestServer(); try { $restServer->setStatus(200); $resource = $restServer->getResource(); $verb = $restServer->getVerb(); $id = $restServer->getId(); $data = $restServer->getServerData(); if ('corporations' === $resource) { $corps = new Corporations(); $results = null; if ('GET' === $verb) { if (is_null($id)) { $results = $corps->getAll(); } else { $results = $corps->get($id); } } if ('DELETE' === $verb) { if (is_null($id)) { throw new InvalidArgumentException('missing ID'); } else { if ($corps->delete($id)) { $restServer->setMessage('Deleted successfully'); } else { throw new InvalidArgumentException('Delete unsuccessful for id ' . $id); } } } if ('PUT' === $verb) { if (is_null($id)) { throw new InvalidArgumentException('missing ID'); } else { $results = $corps->put($data, $id); } } if ('POST' === $verb) { if ($corps->post($data)) { $restServer->setMessage('Post successful'); $restServer->setStatus(201); } else { throw new Exception('Post unsuccessful'); } } $restServer->setData($results); } } catch (InvalidArgumentException $e) { $restServer->setErrors($e->getMessage()); $restServer->setStatus(400); } catch (Exception $e) { $restServer->setErrors($e->getMessage()); $restServer->setStatus(500); } $restServer->outputResponse(); <file_sep><?php // include necessary files require_once '../functions/dbconnect.php'; require_once '../functions/util.php'; //get fields from the post and set them to variables $fullname = filter_input(INPUT_POST, 'fullname'); $email = filter_input(INPUT_POST, 'email'); $address = filter_input(INPUT_POST, 'address'); $city = filter_input(INPUT_POST, 'city'); $state = filter_input(INPUT_POST, 'state'); $zip = filter_input(INPUT_POST, 'zip'); $birthday = filter_input(INPUT_POST, 'birthday'); //set regex validation $zipRegex = '/^[0-9]{5}(?:-[0-9]{4})?$/'; $nameRegex = '/^[A-Z][-a-zA-Z]+$/'; $addressRegex = '/^([0-9]+ )?[a-zA-Z ]+$/'; $cityRegex = '/^[a-zA-Z]+(?:[\s-][a-zA-Z]+)*$/'; $isValid = true; $error = array(); //validate the information if (isPostRequest()) { if (empty($fullname)) { $error[] = 'Full name is required.'; } else if (!preg_match($nameRegex, $fullname)) { $error[] = 'Name is in an invalid format.'; } if (empty($email)) { $error[] = 'Email is required.'; } else if (filter_var($email, FILTER_VALIDATE_EMAIL) == false) { $error[] = 'Invalid email address.'; } if (empty($address)) { $error[] = 'Adress Line 1 is required.'; } else if (!preg_match($addressRegex, $address)) { $error[] = 'Addreess Line 1 is in an invalid format.'; } if (empty($city)) { $error[] = 'City is required.'; } else if (!preg_match($cityRegex, $city)) { $error[] = 'City is in an invalid format.'; } if (empty($state)) { $error[] = 'State is required.'; } if (empty($zip)) { $error[] = 'ZIP is required.'; } else if (!preg_match($zipRegex, $zip)) { $error[] = 'ZIP code is in an invalid format.'; } if (empty($birthday)) { $error[] = 'Birthday is a required field.'; } else if (!is_null($birthday)) { date("F j, Y, g:i a", strtotime($birthday)); } if (is_array($error) && count($error) > 0) { $isValid = false; foreach ($error as $err) { echo '<div class="alert alert-warning alert-size"><p>', $err, '</p></div>'; } } //if the data is valid, add the data to the db, output success, clear variables if ($isValid) { addAddress($fullname, $email, $address, $city, $state, $zip, $birthday); echo '<div class="alert alert-success alert-size"><p>Address Added</p></div>'; $fullname = ''; $email = ''; $address = ''; $city = ''; $state = ''; $zip = ''; $birthday = ''; } } ?> <!-- form--> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="../main.css" type="text/css"> <div class="main"> <h1>Add an Address</h1> <div class="shift"> <a href="../index.php">Click here</a> to go back to the main page. </div> <form action="#" method="post" role="form"> <div class="form-group">Full Name:</div> <input name="fullname" value="<?php echo $fullname ?>" class="form-control" /> <div class="form-group">Email:</div> <input name="email" value="<?php echo $email ?>" class="form-control"/> <br /> <div class="form-group">Address Line 1:</div> <input name="address" value="<?php echo $address ?>" class="form-control"/> <div class="form-group">City:</div> <input name="city" value="<?php echo $city ?>" class="form-control"/> <div class="form-group">State:</div> <input name="state" value="<?php echo $state ?>" class="form-control"/> <div class="form-group">ZIP:</div> <input name="zip" value="<?php echo $zip ?>" class="form-control"/> <div class="form-group">Birthday:</div> <input type="date" name="birthday" value="<?php echo $birthday ?>" class="form-control"/> <input type="submit" value="submit" class="btn btn-primary btn-move" /> </form> </div> <file_sep><html> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="../main.css" type="text/css"> </head> <body> <?php //include necessary files require_once '../functions/dbconnect.php'; require_once '../functions/util.php'; //get all the address records from the db and set them to an array $addresses = getAllAddresses(); echo '<div class="main"><h1>Addresses </h1> <div class="shift"> <a href="../index.php">Click here</a> to go back to the main page. </div>'; //if there are address records display them in a table if (count($addresses) > 0) { echo '<table class="table table-bordered">'; echo '<tr>'; echo '<th>' . 'Full Name' . '</th>'; echo '<th>' . 'Email' . '</th>'; echo '<th>' . 'Address Line 1' . '</th>'; echo '<th>' . 'City' . '</th>'; echo '<th>' . 'State' . '</th>'; echo '<th>' . 'ZIP' . '</th>'; echo '<th>' . 'Birthday' . '</th>'; echo '</tr>'; foreach ($addresses as $value) { echo '<tr>'; echo '<td>' . $value["fullname"] . '</td>'; echo '<td>' . $value["email"] . '</td>'; echo '<td>' . $value["addressline1"] . '</td>'; echo '<td>' . $value["city"] . '</td>'; echo '<td>' . $value["state"] . '</td>'; echo '<td>' . $value["zip"] . '</td>'; echo '<td>' . $value["birthday"] . '</td>'; echo '</tr>'; } echo '</table></div>'; } else { echo 'No results found'; } ?> </body> </html> <file_sep><?php $email = filter_input(INPUT_POST, 'email'); $password = filter_input(INPUT_POST, '<PASSWORD>'); $loginField = filter_input(INPUT_POST, 'login'); $util = new Util(); $validtor = new Validator(); $login = new Login(); $errors = array(); if ($util->isPostRequest() && $loginField !== null) { if (!$validtor->emailIsValid($email)) { $errors[] = 'Email is not valid'; } if (!$validtor->passwordIsValid($password)) { $errors[] = 'Password cannot be empty'; } if (count($errors) <= 0) { $user_id = $login->verify($email, $password); if ($user_id > 0) { $_SESSION['user_id'] = $user_id; header('Location:add_image.php'); } else { $message = 'Log in failed'; } } } $signupField = filter_input(INPUT_POST, 'signup'); $signup = new Signup(); if ($util->isPostRequest() && $signupField !== null) { if (!$validtor->emailIsValid($email)) { $errors[] = 'Email is not valid'; } if ($signup->emailExists($email)) { $errors[] = 'Email already exists'; } if (!$validtor->passwordIsValid($password)) { $errors[] = 'Password cannot be empty'; } if (count($errors) <= 0) { if ($signup->save($email, $password)) { $message = 'Signup complete. Please log in to upload an image.'; } else { $message = 'Signup failed'; } } } include './templates/login-form.html.php'; include './templates/signup-form.php'; ?><file_sep><?php require_once './autoload.php'; ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Log In</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="css/styles.css"> </head> </head> <body> <?php $email = filter_input(INPUT_POST, 'email'); $password = filter_input(INPUT_POST, 'password'); $util = new Util(); $validtor = new Validator(); $login = new Login(); $errors = array(); if ($util->isPostRequest()) { if (!$validtor->emailIsValid($email)) { $errors[] = 'Email is not valid'; } if (!$validtor->passwordIsValid($password)) { $errors[] = 'Password cannot be empty'; } if (count($errors) <= 0) { $user_id = $login->verify($email, $password); if ($user_id > 0) { $_SESSION['user_id'] = $user_id; header('Location:admin.php'); } else { $message = 'Log in failed'; } } } ?> <?php include './templates/errors.html.php'; ?> <?php include './templates/messages.html.php'; ?> <h1>Login Form</h1> <?php include './templates/login-form.html.php'; ?> <div class="nav">Click <a href="./signup.php">here</a> to sign up.</div> </body> </html> <file_sep><?php /* * 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. */ /** * Description of Remove * * @author jmorriseau */ class Remove { public function removeFile($file){ unlink('./uploads/' . $file); } } <file_sep><!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Error Messages</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="style.css"> </head> <body> <div class="bg-danger message-box"> <?php include './models/IMessage.php'; include './models/Message.php'; include './models/ErrorMessage.php'; $errorMessage = new ErrorMessage(); $errorMessage->addMessage('test', 'my test message'); var_dump($errorMessage->getAllMessages()); var_dump($errorMessage instanceof IMessage); var_dump($errorMessage->removeMessage('test')); var_dump($errorMessage->getAllMessages()); ?> </div> </body> </html> <file_sep><!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Success Messages</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="style.css"> </head> <body> <div class="bg-success message-box"> <?php include './models/IMessage.php'; include './models/Message.php'; include './models/SuccessMessage.php'; $successMessage = new SuccessMessage(); $successMessage->addMessage('test', 'my test message'); var_dump($successMessage->getAllMessages()); var_dump($successMessage instanceof IMessage); var_dump($successMessage->removeMessage('test')); var_dump($successMessage->getAllMessages()); ?> </div> </body> </html>
bd22c8a0942db1b550486433bc93f11105368fc8
[ "PHP" ]
12
PHP
jmorriseau/PHPAdvClassFall2015
fe632484ac35b4105dd1536f02d8fa5d53b8697a
68dc01514986d57ce4290e19ae159d3cd614abe4
refs/heads/master
<repo_name>abraeva98/pairexExercise_nodeShell<file_sep>/cat.js const fs = require('fs'); module.exports = function (fullPath){ fs.readFile(fullPath, (err, data) => { if (err) throw err; process.stdout.write(data) process.stdout.write ('\nprompt > ') }) }
d1009a03b67552c622245f0eafe3aa0b236b868a
[ "JavaScript" ]
1
JavaScript
abraeva98/pairexExercise_nodeShell
80440b2edbd48d21d56a3c8a603cecc60770d85b
aca35d4191d718ea76ae3fb3b70a5fb7894c29a4
refs/heads/master
<file_sep>package AAR; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.TreeMap; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; import org.mcavallo.opencloud.Cloud; import org.mcavallo.opencloud.Tag; public class GUI { public static List<String> NameList = new ArrayList<String>(); public static List<String> WordList = new ArrayList<String>(); public static TreeMap<String,Integer> dictionary = new TreeMap<String,Integer>(); protected void initUI() { JFrame frame = new JFrame(String_Load.class.getSimpleName()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); Cloud cloud = new Cloud(); Random random = new Random(); int j = 0; for (int i = 0; i < WordList.size(); i++) { cloud.addTag(WordList.get(i)); } System.out.println(cloud.size()); for (Tag tag : cloud.tags()) { final JLabel label = new JLabel(tag.getName()); label.setOpaque(false); label.setFont(label.getFont().deriveFont((float) tag.getWeight() * 50)); panel.add(label); j++; } System.out.println(j); frame.add(panel); frame.setSize(800, 600); frame.setVisible(true); } public static void main(String [ ] args) { String f = "myfile.txt"; String_Load.ReadDoc(f, NameList); Text_Analysis.Run(NameList, WordList, dictionary); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new GUI().initUI(); } }); } } <file_sep>package AAR; import java.sql.*; public class SQLiteJDBC { public static String name; public static Connection c; public static Statement stmt; public static void main( String args[] ) { name = "somename2"; createTable(name); insert(name); select(name); } public static void createTable(String name) { c = null; stmt = null; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:test.db"); System.out.println("Opened database successfully"); stmt = c.createStatement(); String sql = "CREATE TABLE " + name + "(ID INT PRIMARY KEY NOT NULL," + " NAME TEXT NOT NULL, " + " AGE INT NOT NULL, " + " ADDRESS CHAR(50), " + " SALARY REAL)"; stmt.executeUpdate(sql); stmt.close(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } System.out.println("Table created successfully"); } public static void insert(String name) { c = null; stmt = null; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:test.db"); c.setAutoCommit(false); System.out.println("Opened database successfully"); stmt = c.createStatement(); String sql = "INSERT INTO " + name + " (ID,NAME,AGE,ADDRESS,SALARY) " + "VALUES (1, 'Paul', 32, 'California', 20000.00 );"; stmt.executeUpdate(sql); sql = "INSERT INTO " + name + " (ID,NAME,AGE,ADDRESS,SALARY) " + "VALUES (2, 'Allen', 25, 'Texas', 15000.00 );"; stmt.executeUpdate(sql); sql = "INSERT INTO " + name + " (ID,NAME,AGE,ADDRESS,SALARY) " + "VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );"; stmt.executeUpdate(sql); sql = "INSERT INTO " + name + " (ID,NAME,AGE,ADDRESS,SALARY) " + "VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );"; stmt.executeUpdate(sql); stmt.close(); c.commit(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } System.out.println("Records created successfully"); } public static void select(String name) { c = null; stmt = null; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:test.db"); c.setAutoCommit(false); System.out.println("Opened database successfully"); stmt = c.createStatement(); ResultSet(); stmt.close(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } System.out.println("Operation done successfully"); } public static void update(String name) { c = null; stmt = null; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:test.db"); c.setAutoCommit(false); System.out.println("Opened database successfully"); stmt = c.createStatement(); String sql = "UPDATE " + name + " set SALARY = 25000.00 where ID=1;"; stmt.executeUpdate(sql); c.commit(); ResultSet(); stmt.close(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } System.out.println("Operation done successfully"); } public static void delete(String name) { c = null; stmt = null; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:test.db"); c.setAutoCommit(false); System.out.println("Opened database successfully"); stmt = c.createStatement(); String sql = "DELETE from " + name + " where ID=2;"; stmt.executeUpdate(sql); c.commit(); ResultSet(); stmt.close(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } System.out.println("Operation done successfully"); } public static String insertPos(int ID, String Name, int Age, String Address, float Salary) throws SQLException { String sql = "INSERT INTO " + name + " (ID,NAME,AGE,ADDRESS,SALARY) " + "VALUES (" + ID +"," + Name + "," + Age + "," + Address + "," + Salary + " );"; stmt.executeUpdate(sql); return sql; } public static void printoutPos(int id, String Name, int age, String address, float salary) { System.out.println( "ID = " + id ); System.out.println( "NAME = " + Name ); System.out.println( "AGE = " + age ); System.out.println( "ADDRESS = " + address ); System.out.println( "SALARY = " + salary ); System.out.println(); } public static void ResultSet() throws SQLException { ResultSet rs = stmt.executeQuery( "SELECT * FROM " + name + ";" ); while ( rs.next() ) { int id = rs.getInt("id"); String Name = rs.getString("name"); int age = rs.getInt("age"); String address = rs.getString("address"); float salary = rs.getFloat("salary"); printoutPos(id, Name, age, address, salary); } rs.close(); } }<file_sep>package AAR; public class Filter { static int LevenshteinDistance(String s, String t) { // degenerate cases if (s == t) return 0; if (s.length() == 0) return t.length(); if (t.length() == 0) return s.length(); // create two work vectors of integer distances int[] v0 = new int[t.length() + 1]; int[] v1 = new int[t.length() + 1]; // initialize v0 (the previous row of distances) // this row is A[0][i]: edit distance for an empty s // the distance is just the number of characters to delete from t for (int i = 0; i < v0.length; i++) v0[i] = i; for (int i = 0; i < s.length(); i++) { // calculate v1 (current row distances) from the previous row v0 // first element of v1 is A[i+1][0] // edit distance is delete (i+1) chars from s to match empty t v1[0] = i + 1; // use formula to fill in the rest of the row for (int j = 0; j < t.length(); j++) { int cost; if (s.charAt(i) == t.charAt(j)) cost = 0; else cost = 1; v1[j + 1] = Minimum(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost); } // copy v1 (current row) to v0 (previous row) for next iteration for (int j = 0; j < v0.length; j++) v0[j] = v1[j]; } return v1[t.length()]; } static int Minimum(int a, int b) { if (a>=b) return b; else return a; } static int Minimum(int a, int b, int c) { int temp = Minimum(a,b); return Minimum(temp, c); } static String DeleteNumbers(String s) { String s1 = s.replaceAll("[0-9!@#$%^&*()><?=|№]", ""); s1 = s1.replaceAll("'", ""); s1 = s1.replaceAll("\"", ""); s1 = s1.replaceAll("\\+", ""); s1 = s1.replaceAll("\\\\", ""); s1 = s1.toLowerCase(); if ((s1 == " ") || (s1 == " ") || (s1 == " ") || (s1 == " ")) s1 = ""; if (s1.length() == 1) s1 = ""; return s1; } static String Token(String s) { String s1 = s.replaceAll("[,.:;-]", " "); s1 = s1.replaceAll("\\/", " "); s1 = s1.replaceAll("-", " "); return s1; } static boolean isCyrillic(char c) { return Character.UnicodeBlock.CYRILLIC.equals(Character.UnicodeBlock.of(c)); } static boolean isCyrillic(String s) { int latin = 0; int cyrillic = 0; for (int i = 0; i < s.length(); i++) { if (isCyrillic(s.charAt(i))) cyrillic++; else latin++; } if (cyrillic > 0) return true; else return false; } static String makeCyrillic(String s) { String s1; s1 = s.replaceAll("a", "а"); s1 = s1.replaceAll("b", "в"); s1 = s1.replaceAll("c", "с"); s1 = s1.replaceAll("e", "е"); s1 = s1.replaceAll("h", "н"); s1 = s1.replaceAll("k", "к"); s1 = s1.replaceAll("m", "м"); s1 = s1.replaceAll("o", "о"); s1 = s1.replaceAll("p", "р"); s1 = s1.replaceAll("t", "т"); s1 = s1.replaceAll("x", "х"); s1 = s1.replaceAll("y", "у"); s1 = s1.replaceAll("u", "и"); return s1; } }
05118f8a127de1642aa895062129510431452fac
[ "Java" ]
3
Java
Nik0l/Valuation
ab98db28686d67ec85f33bbee48b2db028355d4b
cc0f34871eff4c59fbc18fab630b4857d68adb89
refs/heads/master
<file_sep>package br.com.isaccanedo; import com.amazon.sqs.javamessaging.ProviderConfiguration; import com.amazon.sqs.javamessaging.SQSConnectionFactory; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.regions.Regions; import com.amazonaws.services.sqs.AmazonSQSClientBuilder; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.aws.core.region.RegionProvider; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jms.annotation.JmsListenerConfigurer; import org.springframework.jms.config.DefaultJmsListenerContainerFactory; import org.springframework.jms.config.JmsListenerEndpointRegistrar; import org.springframework.messaging.converter.MappingJackson2MessageConverter; import org.springframework.messaging.converter.MessageConverter; import org.springframework.messaging.handler.annotation.support.DefaultMessageHandlerMethodFactory; import java.util.Optional; import javax.jms.ConnectionFactory; /** * Configures JMS {@link ConnectionFactory} for Amazon SQS. * Automatically deserialises JSON messages into objects using Jackson 2.x {@link ObjectMapper}. */ @Configuration @EnableConfigurationProperties(SqsProperties.class) class SqsJmsConfiguration implements JmsListenerConfigurer { private final Optional<ObjectMapper> objectMapper; SqsJmsConfiguration(Optional<ObjectMapper> objectMapper) { this.objectMapper = objectMapper; } @Bean ProviderConfiguration providerConfiguration(SqsProperties sqsProperties) { return new ProviderConfiguration().withNumberOfMessagesToPrefetch(sqsProperties.getPrefetch()); } @Bean SQSConnectionFactory sqsConnectionFactory(RegionProvider regionProvider, AWSCredentialsProvider awsCredentialsProvider, ProviderConfiguration providerConfiguration) { return new SQSConnectionFactory(providerConfiguration, AmazonSQSClientBuilder.standard() .withRegion(Regions.fromName(regionProvider.getRegion().getName())) .withCredentials(awsCredentialsProvider) .build()); } @Bean public DefaultJmsListenerContainerFactory jmsListenerContainerFactory( DefaultJmsListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); configurer.configure(factory, connectionFactory); // SQS does not support transactions factory.setSessionTransacted(false); return factory; } // beans defined below enables automatic message deserialization in @JmsListeners using MessageConverter @Bean public DefaultMessageHandlerMethodFactory handlerMethodFactory() { DefaultMessageHandlerMethodFactory factory = new DefaultMessageHandlerMethodFactory(); factory.setMessageConverter(messageConverter()); return factory; } @Bean public MessageConverter messageConverter() { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); objectMapper.ifPresent(converter::setObjectMapper); return converter; } @Override public void configureJmsListeners(JmsListenerEndpointRegistrar registrar) { registrar.setMessageHandlerMethodFactory(handlerMethodFactory()); } } <file_sep># Amazon SQS with Spring Cloud AWS and JMS sample Este repositório é um projeto de amostra de como configurar o cliente Spring Boot + Spring Cloud AWS + SQS JMS para ler e enviar mensagens ao SQS. Usos: - https://github.com/awslabs/amazon-sqs-java-messaging-lib - para integração SQS e JMS - [Spring Cloud AWS](https://github.com/spring-cloud/spring-cloud-aws) para região e configuração de credenciais AWS <file_sep>cloud.aws.region.static=eu-west-1 spring.cloud.aws.sqs.prefetch=1
235b332b662d1b176a80361b0ec6f44444594eac
[ "Markdown", "Java", "INI" ]
3
Java
isaccanedo/spring-cloud-aws-sqs-jms
9be0d8d1f74a9b127dc1dbfa3166c941f39eb0bd
51feb9efe8480fe271baea21997cd1bd5d9a2975
refs/heads/master
<repo_name>MeyCry/flux-template<file_sep>/source/js/app.js // Generated by CoffeeScript 1.10.0 var $, Category, Main, React, ReactDOM, ReactRouter, Route, Router; $ = require("jquery"); React = require("react"); ReactDOM = require('react-dom'); Main = require("./flux/views/Main"); Category = require("./flux/views/Category"); ReactRouter = require('react-router'); Router = ReactRouter.Router, Route = ReactRouter.Route; $(function() { return ReactDOM.render(( <Router> <Route path="/" component={Main}></Route> <Route path="category" component={Category}/> </Router> ), document.getElementById("app")); }); <file_sep>/gulpfile.js // Generated by CoffeeScript 1.10.0 var autoprefixer, browserify, compass, concat, filter, gulp, imagemin, minifyCss, paths, reactify, sourcemaps, styledown, svg2png, svgSprite, uglify; gulp = require("gulp"); compass = require("gulp-compass"); autoprefixer = require("gulp-autoprefixer"); minifyCss = require('gulp-minify-css'); concat = require("gulp-concat"); uglify = require("gulp-uglify"); sourcemaps = require('gulp-sourcemaps'); reactify = require("reactify"); browserify = require("gulp-browserify"); imagemin = require('gulp-imagemin'); filter = require('gulp-filter'); svgSprite = require("gulp-svg-sprites"); svg2png = require('gulp-svg2png'); styledown = require("gulp-styledown"); paths = { cssSource: "source/css", cssDist: "public/css" }; gulp.task("css", function() { return gulp.src(paths.cssSource + "/**/*.scss").pipe(compass({ config_file: "./config.rb", css: paths.cssSource, sass: paths.cssSource })).pipe(autoprefixer({ browsers: ["last 6 version", "> 1%", "ie 8", "Opera 12.1"] })).pipe(minifyCss({ compatibility: 'ie8' })).pipe(gulp.dest(paths.cssDist)); }); gulp.task("js", function() { return gulp.src("source/js/app.js").pipe(browserify({ transform: reactify })).pipe(concat("app.js")).pipe(gulp.dest("./public/js")); }); gulp.task("img", function() { return gulp.src('source/image/**/*').pipe(imagemin({ progressive: true })).pipe(gulp.dest('public/image')); }); gulp.task('sprites', function() { return gulp.src('source/image/svg/*.svg').pipe(svgSprite({ cssFile: "css/sprite.css", padding: 1 })).pipe(gulp.dest("source/image/svg/sprite")).pipe(filter("**/*.svg")).pipe(svg2png()).pipe(gulp.dest("source/image/svg/sprite")); }); gulp.task("cssdoc", function() { return gulp.src('source/css/**/*.scss').pipe(styledown({ config: './cssDOC/styledown.md', filename: 'zeo-css-doc.html' })).pipe(gulp.dest('./cssDOC/')); }); gulp.task("watch", function() { gulp.watch("source/css/**/*.scss", ["css"]); gulp.watch("source/js/**/*.js", ["js"]); return gulp.watch("source/image/**/*", ["img"]); }); gulp.task("default", ["css", "js", "img"]); gulp.task("w", ["css", "js", "watch"]); <file_sep>/source/js/appServer.js // Generated by CoffeeScript 1.10.0 exports.Main = require("./flux/views/Main"); <file_sep>/index.js var express = require('express'); var app = express(); var jsx = require('node-jsx'); jsx.install(); var React = require("react"); var ReactDOM = require('react-dom/server'); var ReactApp = require("./source/js/appServer"); var reactHtml = React.createFactory(ReactApp.Main); app.set('view engine', 'ejs'); app.use(express.static('public')); app.get('/', function (req, res) { console.log(reactHtml); res.render("index", {reactOutput: ReactDOM.renderToString(reactHtml())}) }); var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log('Example app listening at http://%s:%s', host, port) });
cf88b4b2099dd705cca5ec429bf06b7094bbf396
[ "JavaScript" ]
4
JavaScript
MeyCry/flux-template
911d36f1123b5cd8c47ab61b77e7499ddb64f574
b6d9aa2da3325ff8b5ca5c28eaae7c48b8e2a701
refs/heads/master
<file_sep>/*jshint esversion: 6 */ // Подключаем необходимые модули const { series, parallel, src, dest, watch } = require('gulp'); const concat = require('gulp-concat'); const autoprefixer = require('gulp-autoprefixer'); const babel = require("gulp-babel"); const cleanCSS = require('gulp-clean-css'); const uglify = require('gulp-uglify'); const del = require('del'); const browserSync = require('browser-sync').create(); const sourcemaps = require('gulp-sourcemaps'); const sass = require('gulp-sass'); const imagemin = require('gulp-imagemin'); const rename = require('gulp-rename'); // Private task подготовки CSS-определений к развёртыванию // jsFiles привязка указывающая на порядок обработки файлов scss, sass и css const sassFiles = [ "./src/sass/main.scss", // "./src/sass/**/*.scss", "./src/sass/**/*.sass" ]; const cssFiles = [ "./src/css/main.css", // "./src/css/sass-to.css", "./src/css/**/*.css" ]; function styles() { return src(sassFiles, cssFiles) .pipe(sourcemaps.init()) .pipe(sass()) .pipe(concat("styles.css")) .pipe(autoprefixer({ cascade: false })) .pipe(cleanCSS({ level: 2 })) .pipe(rename({ suffix: '.min' })) .pipe(sourcemaps.write('./')) .pipe(dest("./build/css")) .pipe(browserSync.stream()); // auto-inject into browsers } // jsFiles привязка указывающая на порядок объединения файлов js const jsFiles = [ "./src/libsJS/**/*.min.js", "./src/js/lib.js", "./src/js/main.js", "./src/js/**/*.js" ]; // Private task подготовки JS-скриптов к развёртыванию function scripts() { return src(jsFiles) .pipe(concat("scripts.js")) .pipe(sourcemaps.init()) .pipe(babel({ presets: ['@babel/env'] })) .pipe(uglify({ toplevel: true })) .pipe(rename({ suffix: '.min' })) .pipe(sourcemaps.write('maps')) .pipe(dest("./build/js")) .pipe(browserSync.stream()); // auto-inject into browsers } // Private task сжатия изображений function imgCompress() { return src(['./src/img/**', '!src/img/README.md']) .pipe(imagemin({ progressive: true })) .pipe(dest('./build/img/')); } // Private task очистки папки build function clean() { return del(['./build/**/*']); } // Private task наблюдения за изменеями в файлах function overwatch() { browserSync.init({ server: { baseDir: "./" } }); watch('./src/img/**', imgCompress); // Следить за изображениями watch('./src/css/**/*.css', styles); // Следить за CSS файлами watch('./src/sass/**/*.scss', styles); // Следить за CSS файлами watch('./src/sass/**/*.sass', styles); // Следить за CSS файлами watch('./src/js/**/*.js', scripts); // Следить за JS файлами watch('./*.html').on('change', browserSync.reload); // Следить за изменением HTML файлов } // Public tasks // exports.styles = styles; exports.scripts = scripts; // exports.clean = clean; // exports.overwatch = overwatch; build = series(clean, parallel(styles, scripts, imgCompress)); exports.default = series(build, overwatch);<file_sep>Autor: <NAME> This is the directory for images by the Front-Project-Template.<file_sep>Autor: <NAME> This is the directory for third-party JavaScript libraries by the Front-Project-Template.<file_sep># Template for web-front-end development projects This is the repository of the project template for web-front-end development. --- ## Install 1. Create folder for new project. 2. In the terminal, run the following command: ``` $ git clone https://github.com/RZ3DDD/front-project-template <new_project_full_path> ``` 3. Go to the folder of the new project and delete the entire .git directory. and .gitignore. file. For example: ``` $ rm -R .git $ rm .gitignore ``` If necessary, then later organize the version control as usual. 4. Run the command: ``` $ npm i ``` To execute this command, node.js and gulp must be installed globally. 5. Run the command: ``` $ gulp ``` The browser should open the welcome page for a new project. 6. Work on a new project with pleasure. ---
247a58fbee70786f2b598f4fe15474b245da3a0a
[ "JavaScript", "Markdown" ]
4
JavaScript
RZ3DDD/front-project-template
dfdff276da97caba315d8eb51365a1ff4ff7d8f0
cb0e7783e1b3c3f416d983c5fc422f670d5fa455
refs/heads/master
<file_sep>const Engine = Matter.Engine; const World = Matter.World; const Bodies = Matter.Bodies; const Constraint = Matter.Constraint; var engine, world; var ball, rope var rope2,rope3,rope4,rope5; var ball2,ball3,ball4,ball5; function preload(){ // background = loadImage(Newton.jpg); } function setup() { createCanvas(800, 800); engine = Engine.create(); world = engine.world; ball = new Ball(200, 200, 80, 80); ball2 = new Ball(300,200,80,80); ball3 = new Ball(400,200,80,80); ball4 = new Ball(500,200,80,80); ball5 = new Ball(600,200,80,80); rope = new Rope(ball.body, { x: 200, y: 50 }); rope2 = new Rope(ball2.body, { x: 300, y: 50}); rope3 = new Rope(ball3.body, { x: 400, y: 50}); rope4 = new Rope(ball4.body, { x: 500, y: 50}); rope5 = new Rope(ball5.body, { x: 600, y: 50}); } function draw() { Engine.update(engine); ball.display(); ball2.display(); ball3.display(); ball4.display(); ball5.display(); rope.display(); rope2.display(); rope3.display(); rope4.display(); rope5.display(); } function mouseDragged() { Matter.Body.setPosition(ball.body, { x: mouseX, y: mouseY }); }
3b7755a6e4f3458e50abb63ff6048f061a98bb33
[ "JavaScript" ]
1
JavaScript
Aditya-Srivastava105/project34
3de4da50e1fd4ddf7040f361a1aae8c7a39ec658
8dfb03d4a492a062b4c84201686d0374abc17563
refs/heads/master
<file_sep>package gmailSpam.webdriver; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; // Singletone pattern example public class Browser { public static WebDriver driver; //private Browser (){}; public static WebDriver getInstance(){ if (driver==null) { driver = new ChromeDriver(); driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS); driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); driver.manage().deleteAllCookies(); return driver; } return driver; } public static void closeBrowser() { driver.quit(); //driver = null; //commented to avoid warnings on Commit } } <file_sep>package gmailSpam.utilities; import gmailSpam.webdriver.Browser; import org.apache.commons.io.FileUtils; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import java.io.File; import java.io.IOException; public class PageHighlightAndScreenShot { public static void takeScreenShot(String label){ //ChromeDriver driver = (ChromeDriver) Browser.getInstance(); //File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); ChromeDriver driver = (ChromeDriver) Browser.getInstance(); File screenshotFile = driver.getScreenshotAs(OutputType.FILE); try { String fileName = label+".png"; FileUtils.copyFile(screenshotFile, new File (fileName)); } catch (IOException e) { e.printStackTrace(); } } public static void highlightAreaAndScreenShot(WebDriver driver, WebElement element){ JavascriptExecutor jsexecutor = ((JavascriptExecutor)driver); String color = element.getCssValue("backgroundColor"); jsexecutor.executeScript("arguments[0].style.backgroundColor = '"+ "yellow"+"'", element); takeScreenShot("highlight"); jsexecutor.executeScript("arguments[0].style.backgroundColor = '"+ color + "'", element); //takeScreenShot("afterhighlight"); } }
ce4fc2f11ba069a6f625f670c48b3f059a5774c5
[ "Java" ]
2
Java
Alex-Galavach/GmailSpamBDD
15461ca4a4aa09147461c0cf601bef74a525f07b
fc777704cd068555aef868790d0b11e30a32436a
refs/heads/master
<repo_name>barce/exclusive_scope<file_sep>/README.md exclusive_scope =============== <file_sep>/app/models/post.rb class Post < ActiveRecord::Base # TODO: Look into not even using ActiveRecord def self.default_scope raise "Must use .secure_* methods" end def self.secure_by_letter(letter) with_exclusive_scope{Post.where("title like '%#{letter}%'")} end end
558389c05258ffff81d2c904dad9fb0deabb6375
[ "Markdown", "Ruby" ]
2
Markdown
barce/exclusive_scope
f76131f9239fdeab6e75e57719fcd97b84f5b94c
7af109feae042ec185f159a09841a222949b0b32
refs/heads/master
<repo_name>linyjme/snake<file_sep>/Snake/Snake/snake.h #pragma once #include <iostream> #include "wall.h" #include "food.h" using namespace std; class Snake { public: Snake(Wall& tempWall, Food & food); // 节点 enum { UP = 'w', DOWN = 's', LEFT = 'a', RIGHT = 'd' }; struct Point { // 数据域 int x; int y; // 指针域 Point* next; }; void initSnake(); // 销毁节点 void destroyPoint(); // 添加节点 void addPoint(int x, int y); // 删除节点 void delPoint(); // 蛇的移动 bool move(char key); // 设定难度 // 获取刷屏时间 int getSleepTime(); // 获取蛇的身段 int countList(); // 获取分数 int getScore(); Point * pHead; Wall & wall; Food& food; bool isRoll; // 判断循环标示 };<file_sep>/Snake/Snake/food.h #pragma once #include <iostream> #include "wall.h" using namespace std; class Food { public: // ΙθΦΓΚ³Ξο Food(Wall& tempWall); void setFood(); int foodX; int foodY; Wall& wall; };<file_sep>/Snake/Snake/snake.cpp #include "snake.h" #include<Windows.h> void gotoxy1(HANDLE hOut1, int x, int y) { COORD pos; pos.X = x; //横坐标 pos.Y = y; //纵坐标 SetConsoleCursorPosition(hOut1, pos); } HANDLE hOut1 = GetStdHandle(STD_OUTPUT_HANDLE);//定义显示器句柄变量 Snake::Snake(Wall & tempWall, Food & tempFood):wall(tempWall), food(tempFood) { pHead = NULL; isRoll = false; } void Snake::initSnake() { destroyPoint(); addPoint(5, 3); addPoint(5, 4); addPoint(5, 5); } void Snake::destroyPoint() { Point* pCur = pHead; while (pHead != NULL) { pCur = pHead->next; delete pHead; pHead = pCur; } } void Snake::addPoint(int x, int y) { // 创建新的节点 Point* newPoint = new Point; newPoint->x = x; newPoint->y = y; newPoint->next = NULL; // 如果原来的头不为空,改为身子 if (pHead != NULL) { wall.setWall(pHead->x, pHead->y, '='); gotoxy1(hOut1, pHead->y * 2, pHead->x); cout << "="; } newPoint->next = pHead; pHead = newPoint; // 更新头部 wall.setWall(pHead->x, pHead->y, '@'); gotoxy1(hOut1, pHead->y * 2, pHead->x); cout << "@"; } void Snake::delPoint() { // 判断两个节点以上才做删除 if (pHead == NULL || pHead->next == NULL) { return; } Point* pCur = pHead->next; Point* pPre = pHead; while (pCur->next != NULL) { pPre = pPre->next; pCur = pCur->next; } // 删除尾节点 wall.setWall(pCur->x, pCur->y, ' '); gotoxy1(hOut1, pCur->y * 2, pCur->x); cout << " "; delete pCur; pCur = NULL; pPre->next = NULL; } bool Snake::move(char key) { int x = pHead->x; int y = pHead->y; switch (key) { case UP: x--; break; case DOWN: x++; break; case LEFT: y--; break; case RIGHT: y++; break; default: break; } // 判断如果是下一步碰到尾巴,不应该死亡 Point* pCur = pHead->next; Point* pPre = pHead; while (pCur->next != NULL) { pPre = pPre->next; pCur = pCur->next; } if (pCur->x == x && pCur->y == y) { // 碰到尾巴,循环 isRoll = true; } else { // 判断用户要到达的位置是否成功 if (wall.getWall(x, y) == '*' || wall.getWall(x, y) == '=') { addPoint(x, y); delPoint(); system("cls"); wall.drawWall(); cout << "Score : " << getScore() << "分" << endl; cout << "GAME OVER !!!" << endl; return false; } } // 移动成功,分两种 // 吃到食物,未迟到食物 if (wall.getWall(x, y) == '#') { addPoint(x, y); // 重新设置食物 food.setFood(); } else { addPoint(x, y); delPoint(); if (isRoll == true) { wall.setWall(x, y, '@'); gotoxy1(hOut1, y * 2, x); cout << "@"; } } return true; } int Snake::getSleepTime() { int sleepTime = 0; int size = countList(); if (size < 5) { sleepTime = 300; } else if (size >= 5 && size <= 8) { sleepTime = 200; } else { sleepTime = 100; } return sleepTime; } int Snake::countList() { int size = 0; Point* curPoint = pHead; while (curPoint != NULL) { size++; curPoint = curPoint->next; } return size; } int Snake::getScore() { int size = countList(); int score = (size - 3) * 100; return score; } <file_sep>/README.md # 基于c++写的贪吃蛇程序
85930e983afa49c84d5c78a6b424f691c22d7260
[ "Markdown", "C++" ]
4
C++
linyjme/snake
fb77a768c3078ac0d7a88f040a9522c36289f579
ae7182cdadd0434cadcd5b5caebf137793627da2
refs/heads/master
<repo_name>moonstar-x/react-twitch-embed<file_sep>/src/types.ts export interface OnPlayData { sessionId: string } export interface OnSeekData { position: number } export interface OnAuthenticateData { displayName: string id: string profileImageURL: string } export interface PlayerQuality { bitrate: number codecs: string group: string height: number framerate?: number isDefault: boolean name: string width: number } export interface PlaybackStats { /** * The version of the Twitch video player backend. */ backendVersion: string /** * The size of the video buffer in seconds. */ bufferSize: number /** * Codecs currently in use, comma-separated (video,audio). */ codecs: string /** * The current size of the video player element (eg. 850x480). */ displayResolution: string /** * The video playback rate in frames per second. Not available on all browsers. */ fps: number /** * Current latency to the broadcaster in seconds. Only available for live content. */ hlsLatencyBroadcaster: number /** * The playback bitrate in Kbps. */ playbackRate: number /** * The number of dropped frames. */ skippedFrames: number /** * The native resolution of the current video (eg. 640x480). */ videoResolution: string } export interface PlayerState { channelID: string channelName: string collectionID: string currentTime: number duration: number ended: boolean muted: boolean playback: 'Idle' | 'Ready' | 'Buffering' | 'Playing' | 'Ended' qualitiesAvailable: string[] quality: string stats: { videoStats: PlaybackStats } videoID: string volume: number } export interface TwitchPlayerInstance extends EventTarget { /** * Disables display of Closed Captions. */ disableCaptions: () => void /** * Enables display of Closed Captions. Note captions will only display if they are included in the video content being played. * See the CAPTIONS JavaScript Event for more info. */ enableCaptions: () => void /** * Pauses the player. */ pause: () => void /** * Begins playing the specified video. */ play: () => void /** * Seeks to the specified timestamp (in seconds) in the video. Does not work for live streams. */ seek: (timestamp: number) => void /** * Sets the channel to be played. * @param channel */ setChannel: (channel: string) => void /** * Sets the collection to be played. * * Optionally also specifies the video within the collection, from which to start playback. * If a video ID is not provided here or the specified video is not part of the collection * playback starts with the first video in the collection. * @param collection * @param videoId */ setCollection: (collection: string, videoId?: string) => void /** * Sets the quality of the video. quality should be a string value returned by getQualities. * @param quality */ setQuality: (quality: string) => void /** * Sets the video to be played to be played and starts playback at timestamp (in seconds). * @param video * @param timestamp */ setVideo: (video: string, timestamp: number) => void /** * Returns true if the player is muted; otherwise, false. */ getMuted: () => boolean /** * If true, mutes the player; otherwise, unmutes it. This is independent of the volume setting. * @param muted */ setMuted: (muted: boolean) => void /** * Returns the volume level, a value between 0.0 and 1.0. */ getVolume: () => number /** * Sets the volume to the specified volume level, a value between 0.0 and 1.0. * @param volumeLevel */ setVolume: (volumeLevel: number) => void /** * Returns an object with statistics on the embedded video player and the current live stream or VOD. * See below for more info. */ getPlaybackStats: () => PlaybackStats /** * Returns the channel’s name. Works only for live streams, not VODs. */ getChannel: () => string | undefined /** * Returns the current video’s timestamp, in seconds. Works only for VODs, not live streams. */ getCurrentTime: () => number /** * Returns the duration of the video, in seconds. Works only for VODs,not live streams. */ getDuration: () => number /** * Returns true if the live stream or VOD has ended; otherwise, false. */ getEnded: () => boolean /** * Returns the available video qualities. For example, chunked (pass-through of the original source). */ getQualities: () => PlayerQuality[] /** * Returns the current quality of video playback. */ getQuality: () => string /** * Returns the video ID. Works only for VODs, not live streams. */ getVideo: () => string | undefined /** * Returns true if the video is paused; otherwise, false. Buffering or seeking is considered playing. */ isPaused: () => boolean /** * UNDOCUMENTED. Get the ID of the channel being played. */ getChannelId: () => string | undefined /** * UNDOCUMENTED. Get the collection being played. */ getCollection: () => string | undefined /** * UNDOCUMENTED. Get the current state of the player. */ getPlayerState: () => PlayerState /** * UNDOCUMENTED. Set the ID of the channel to play. * @param channelId */ setChannelId: (channelId: string) => void addEventListener: (event: string, callback: (...args: any[]) => void) => void } export interface TwitchPlayerConstructorOptions { allowfullscreen?: boolean autoplay?: boolean channel?: string collection?: string controls?: boolean height?: string | number muted?: boolean parent?: string[] playsinline?: boolean time?: string video?: string width?: string | number } export interface TwitchPlayerConstructor { new (id: string, options: TwitchPlayerConstructorOptions): TwitchPlayerInstance /** * Closed captions are found in the video content being played. * This event will be emitted once for each new batch of captions, * in sync with the corresponding video content. * The event payload is a string containing the caption content. */ CAPTIONS: string /** * Video or stream ends. */ ENDED: string /** * Player is paused. Buffering and seeking is not considered paused. */ PAUSE: string /** * Player just unpaused, will either start video playback or start buffering. */ PLAY: string /** * Player playback was blocked. Usually fired after an unmuted autoplay or unmuted programmatic call on play(). */ PLAYBACK_BLOCKED: string /** * Player started video playback. */ PLAYING: string /** * Loaded channel goes offline. */ OFFLINE: string /** * Loaded channel goes online. */ ONLINE: string /** * Player is ready to accept function calls. */ READY: string /** * User has used the player controls to seek a VOD, the seek() method has been called, * or live playback has seeked to sync up after being paused. */ SEEK: string } export interface TwitchEmbedInstance extends TwitchPlayerInstance { /** * To provide additional functionality to our API, access specific components with getPlayer(), * which retrieves the current video player instance from the embed and provides full programmatic access to the video player API. */ getPlayer: () => TwitchPlayerInstance } export interface TwitchEmbedConstructorOptions { allowfullscreen?: boolean autoplay?: boolean channel?: string collection?: string controls?: boolean height?: string | number layout?: 'video-with-chat' | 'video' muted?: boolean parent?: string[] | null theme?: 'light' | 'dark' time?: string video?: string width?: string | number } export interface TwitchEmbedConstructor { new (id: string, options: TwitchEmbedConstructorOptions): TwitchEmbedInstance /** * UNDOCUMENTED. The embed instance has been authenticated with the user's stored credentials. * This callback receives an object with displayName, id and profileImageURL properties. */ AUTHENTICATE: string /** * The video started playing. This callback receives an object with a sessionId property. */ VIDEO_PLAY: string /** * UNDOCUMENTED. The video player has been paused. */ VIDEO_PAUSE: string /** * The video player is ready for API commands. */ VIDEO_READY: string } export interface TwitchWindow extends Window { Twitch?: { Embed?: TwitchEmbedConstructor Player?: TwitchPlayerConstructor } } <file_sep>/src/stories/documentation/TwitchChat.stories.mdx import { Meta } from '@storybook/addon-docs'; <Meta title="Documentation/TwitchChat" /> # TwitchChat This component frames a channel's chat window. ## Props The following props are supported by this component: | Name | Type | Required | Default | Description | |------------|----------------------------|----------|----------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------| | `channel` | **string** | ✅ | | The name of the channel to embed the chat. | | `parent` | **string &#124; string[]** | ❌ | `window.location.hostname` | The URL of the site that is embedding this chat. Multiple values can be added. You don't need to specify this as the current hostname is already picked up. | | `darkMode` | **boolean** | ❌ | `true` | Whether the chat embed should be displayed in a dark or light theme. | | `title` | **string** | ❌ | `TwitchChat` | The name of the `iframe` that embeds the chat. Useful for accessibility reasons. | | `height` | **string &#124; number** | ❌ | `550` | The height of the chat embed. Percentage values can be used (i.e `100%`). | | `width` | **string &#124; number** | ❌ | `350` | The width of the chat embed. Percentage values can be used (i.e `100%`). | | `...props` | | | | The rest of the props are passed to the underlying `iframe` node. | ## Example ```jsx import React from 'react'; import { TwitchChat } from 'react-twitch-embed'; const MyComponent = () => { return ( <TwitchChat channel="moonstar_x" darkMode /> ); }; export default MyComponent; ``` <file_sep>/src/utils/TwitchChat.spec.ts import { generateUrl } from './TwitchChat'; import { URLS } from '../constants'; const channel = 'channel'; const parent = 'localhost'; describe('Utils -> TwitchChat', () => { describe('generateUrl()', () => { it('should return a string with the correct URL.', () => { const url = generateUrl(channel, parent); expect(url).toContain(URLS.TWITCH_CHAT_URL); }); it('should return a string with the provided channel.', () => { const url = generateUrl('channel', parent); expect(url).toContain('/channel/chat'); }); it('should return a string with dark mode if enabled.', () => { const url = generateUrl(channel, parent, { darkMode: true }); expect(url).toContain('?darkpopout&'); }); it('should return a string without dark mode if disabled.', () => { const url = generateUrl(channel, parent, { darkMode: false }); expect(url).not.toContain('?darkpopout&'); }); it('should return a string with a single parent if parent is a string.', () => { const url = generateUrl(channel, 'localhost'); expect(url).toContain('parent=localhost'); }); it('should return a string with multiple parents if parent is an array.', () => { const parents = ['host1', 'host2', 'host3']; const url = generateUrl(channel, parents); parents.forEach((parent) => { expect(url).toContain(`parent=${parent}`); }); }); it('should return a string with all the default options if no options are provided.', () => { const url = generateUrl(channel, parent); expect(url).toContain('?darkpopout&'); }); }); }); <file_sep>/src/stories/documentation/TwitchPlayer.stories.mdx import { Meta } from '@storybook/addon-docs'; <Meta title="Documentation/TwitchPlayer" /> # TwitchPlayer This component frames a player that can embed a stream, VODs and collections. It is an interactive component, meaning that it exposes its underlying API through the `onReady` event that can be used to control the player from the outside (i.e. custom control components). ## Props The following props are supported by this component: | Name | Type | Required | Default | Description | |---------------------|------------------------------------------------------|----------|----------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `channel` | **string** | ❌ | | The name of the channel to embed their stream. | | `video` | **string** | ❌ | | The ID of the video to embed. | | `collection` | **string** | ❌ | | The ID of collection to embed. If both `video` and `collection` are provided, the player will play the provided collection while starting with the provided video. | | `parent` | **string &#124; string[]** | ❌ | `window.location.hostname` | The URL of the site that is embedding this player. Multiple values can be added. You don't need to specify this as the current hostname is already picked up by the underlying API. | | `autoplay` | **boolean** | ❌ | `true` | Whether the content should autoplay on load. Keep in mind that the audio might not play unless the user has focused at least once on the player. | | `muted` | **boolean** | ❌ | `false` | Whether the content should start muted when playing. The user can still change the volume later. | | `time` | **string** | ❌ | `0h0m0s` | The timestamp from where the content should play. If a `channel` is provided then this setting is ignored. Should be a string formatted like `XhYmZs` for an X hour, Y minute and Z second timestamp. | | `allowFullscreen` | **boolean** | ❌ | `true` | Whether the player allows fullscreen to be played in fullscreen mode. Disabling this also removes the fullscreen button from the player. | | `playsInline` | **boolean** | ❌ | `true` | Whether the embedded player plays inline for mobile iOS apps. This setting is undocumented so its functionality is unknown. | | `onCaptions` | **(p: TwitchPlayerInstance, d: string) => void** | ❌ | `() => void` | This event is fired when a batch of captions is received by the player. The type of the data payload might not be accurate as I couldn't find any stream or VOD that had captions enabled. The documentation mentions that this should be a string. | | `onEnded` | **(p: TwitchPlayerInstance) => void** | ❌ | `() => void` | This event is fired when the content that was being played in the player ends. | | `onPause` | **(p: TwitchPlayerInstance) => void** | ❌ | `() => void` | This event is fired when the player pauses. | | `onPlay` | **(p: TwitchPlayerInstance, d: OnPlayData) => void** | ❌ | `() => void` | This event is fired when the player starts playing or resumes content. | | `onPlaybackBlocked` | **(p: TwitchPlayerInstance) => void** | ❌ | `() => void` | This event is fired when the player playback is blocked, possibly due to an unmuted programmatic call to `play()`. | | `onPlaying` | **(p: TwitchPlayerInstance) => void** | ❌ | `() => void` | This event is fired when the player starts playing content. | | `onOffline` | **(p: TwitchPlayerInstance) => void** | ❌ | `() => void` | This event is fired when the channel being streamed has gone offline. | | `onOnline` | **(p: TwitchPlayerInstance) => void** | ❌ | `() => void` | This event is fired when the channel being streamed has gone online. | | `onReady` | **(p: TwitchPlayerInstance) => void** | ❌ | `() => void` | This event is fired when the player is ready. Use this if you need to keep track of the player instance. Updating certain props might trigger a recreation of the player, so this event should keep track of those changes. | | `onSeek` | **(p: TwitchPlayerInstance, d: OnSeekData) => void** | ❌ | `() => void` | This event is fired when the user uses the seek functionality in the player. | | `id` | **string** | ❌ | `twitch-embed` | The ID of the `div` node where the player will be mounted. The underlying API uses this. You should not use an ID that depends on the channel name because it will trigger recreations of the player unnecessarily. | | `height` | **string &#124; number** | ❌ | `480` | The height of the embed. Percentage values can be used (i.e `100%`). | | `width` | **string &#124; number** | ❌ | `940` | The width of the embed. Percentage values can be used (i.e `100%`). | | `...props` | | | | The rest of the props are passed to the underlying `div` node. | > **Note**: If `channel`, `video` and `collection` are provided, only `channel` is taken into account. > If `collection` and `video` are provided, the player will play the videos in the collection starting from the video that was provided. > If the collection doesn't contain the video, the player might enter an undefined state where one of the following may happen. > > 1. The player might start playing the video provided while saying that is playing the collection provided, even if the video isn't part of the collection. > 2. The player might start playing the collection provided while ignoring the video (the official docs mention that this is the default behavior, but I've seen the others happen, so it isn't 100% certain). > 3. The player might remain black and not play anything. ## Example ```jsx import React, { useRef } from 'react'; import { TwitchPlayer } from 'react-twitch-embed'; const MyComponent = () => { const embed = useRef(); // We use a ref instead of state to avoid rerenders. const handleReady = (e) => { embed.current = e; }; return ( <TwitchPlayer channel="moonstar_x" autoplay muted onReady={handleReady} /> ); }; export default MyComponent; ``` <file_sep>/src/stories/documentation/TwitchPlayerNonInteractive.stories.mdx import { Meta } from '@storybook/addon-docs'; <Meta title="Documentation/TwitchPlayerNonInteractive" /> # TwitchPlayerNonInteractive This component frames a non-interactive player for streams, VODs and collections. This component does not contain an underlying API, and it's just a simple `iframe`. Using this or the interactive player component is up to you. They both do the same thing, but the key difference is that updating the `channel`, `video` and or `collection` props will still recreate the embed, while this does not happen on the interactive player. ## Props The following props are supported by this component: | Name | Type | Required | Default | Description | |--------------|----------------------------|----------|------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `parent` | **string &#124; string[]** | ❌ | `window.location.hostname` | The URL of the site that is embedding this player. Multiple values can be added. You don't need to specify this as the current hostname is already picked up. | | `channel` | **string** | ❌ | | The name of the channel to embed their stream. | | `video` | **string** | ❌ | | The ID of the video to embed. | | `collection` | **string** | ❌ | | The ID of collection to embed. If both `video` and `collection` are provided, the player will play the provided collection while starting with the provided video. | | `autoplay` | **boolean** | ❌ | `true` | Whether the content should autoplay on load. Keep in mind that the audio might not play unless the user has focused at least once on the player. | | `muted` | **boolean** | ❌ | `false` | Whether the content should start muted when playing. The user can still change the volume later. | | `time` | **string** | ❌ | `0h0m0s` | The timestamp from where the content should play. If a `channel` is provided then this setting is ignored. Should be a string formatted like `XhYmZs` for an X hour, Y minute and Z second timestamp. | | `title` | **string** | ❌ | `TwitchPlayerNonInteractive` | The name of the `iframe` that embeds the player. Useful for accessibility reasons. | | `height` | **string &#124; number** | ❌ | `480` | The height of the player embed. Percentage values can be used (i.e `100%`). | | `width` | **string &#124; number** | ❌ | `940` | The width of the player embed. Percentage values can be used (i.e `100%`). | | `...props` | | | | The rest of the props are passed to the underlying `iframe` node. | > **Note**: If `channel`, `video` and `collection` are provided, only `channel` is taken into account. > If `collection` and `video` are provided, the player will play the videos in the collection starting from the video that was provided. > If the collection doesn't contain the video, the player might enter an undefined state where one of the following may happen. > > 1. The player might start playing the video provided while saying that is playing the collection provided, even if the video isn't part of the collection. > 2. The player might start playing the collection provided while ignoring the video (the official docs mention that this is the default behavior, but I've seen the others happen, so it isn't 100% certain). > 3. The player might remain black and not play anything. ## Example ```jsx import React from 'react'; import { TwitchPlayerNonInteractive } from 'react-twitch-embed'; const MyComponent = () => { return ( <TwitchPlayerNonInteractive channel="moonstar_x" autoplay muted /> ); }; export default MyComponent; ``` <file_sep>/src/constants/index.ts export const URLS = { TWITCH_EMBED_URL: 'https://embed.twitch.tv/embed/v1.js', TWITCH_CHAT_URL: 'https://www.twitch.tv/embed', TWITCH_CLIP_URL: 'https://clips.twitch.tv/embed', TWITCH_PLAYER_URL: 'https://player.twitch.tv/js/embed/v1.js', TWITCH_PLAYER_NON_INTERACTIVE_URL: 'https://player.twitch.tv' }; export const DEFAULTS = { CHAT: { HEIGHT: 550, WIDTH: 350 }, MEDIA: { HEIGHT: 480, WIDTH: 940 }, ID: { TWITCH_EMBED: 'twitch-embed', TWITCH_PLAYER: 'twitch-player' }, TITLE: { TWITCH_CHAT: 'TwitchChat', TWITCH_CLIP: 'TwitchClip', TWITCH_PLAYER_NON_INTERACTIVE: 'TwitchPlayerNonInteractive' }, ALLOW_FULLSCREEN: true, AUTOPLAY: true, WITH_CHAT: true, MUTED: false, DARK_MODE: true, TIME: '0h0m0s', HIDE_CONTROLS: false, INLINE: true }; export const STORYBOOK_DEFAULTS = { channel: 'moonstar_x', channels: ['moonstar_x', 'minibambu', 'LCS', 'LLA', 'ibai'], clips: [ 'AdventurousBusyWormTwitchRaid-7vDEE8L5ur9j9dzi', 'ColdbloodedSavagePterodactylTheTarFu-nB9EPedzd7eI1Rih' ], video: '260075663', videos: ['260075663', '503792888', '443327254'], videoInCollection: '444741819', collection: 'pFPJIZ6FORWE5g', collections: ['pFPJIZ6FORWE5g', '4B-kpic7DRc5ww'] }; <file_sep>/.github/PULL_REQUEST_TEMPLATE.md ### :pencil: Checklist Make sure that your PR fulfills these requirements: - [ ] Tests have been added for this feature. - [ ] Code is properly documented in Storybook. - [ ] All tests pass on your local machine. - [ ] Code has been linted with the proper rules. ### :page_facing_up: Description > Add a brief description of your PR. ### :pushpin: Does this PR address any issue? > If so, add the # of the issue this is addressing. <file_sep>/src/index.ts import TwitchChat, { TwitchChatProps } from './components/TwitchChat'; import TwitchClip, { TwitchClipProps } from './components/TwitchClip'; import TwitchEmbed, { TwitchEmbedProps } from './components/TwitchEmbed'; import TwitchPlayer, { TwitchPlayerProps } from './components/TwitchPlayer'; import TwitchPlayerNonInteractive, { TwitchPlayerNonInteractiveProps } from './components/TwitchPlayerNonInteractive'; import { OnPlayData, OnSeekData, OnAuthenticateData, PlayerQuality, PlaybackStats, PlayerState, TwitchPlayerInstance, TwitchPlayerConstructorOptions, TwitchPlayerConstructor, TwitchEmbedInstance, TwitchEmbedConstructorOptions, TwitchEmbedConstructor, TwitchWindow } from './types'; export { TwitchChat, TwitchChatProps, TwitchClip, TwitchClipProps, TwitchEmbed, TwitchEmbedProps, TwitchPlayer, TwitchPlayerProps, TwitchPlayerNonInteractive, TwitchPlayerNonInteractiveProps, OnPlayData, OnSeekData, OnAuthenticateData, PlayerQuality, PlaybackStats, PlayerState, TwitchPlayerInstance, TwitchPlayerConstructorOptions, TwitchPlayerConstructor, TwitchEmbedInstance, TwitchEmbedConstructorOptions, TwitchEmbedConstructor, TwitchWindow }; <file_sep>/src/stories/Home.stories.mdx import { Meta } from '@storybook/addon-docs'; <Meta title="Home" /> [![ci-build-status](https://img.shields.io/github/workflow/status/moonstar-x/react-twitch-embed/On%20Push%20%28Master%29?logo=github)](https://github.com/moonstar-x/react-twitch-embed) [![issues](https://img.shields.io/github/issues/moonstar-x/react-twitch-embed?logo=github)](https://github.com/moonstar-x/react-twitch-embed) [![bundle-size](https://img.shields.io/bundlephobia/min/react-twitch-embed)](https://www.npmjs.com/package/react-twitch-embed) [![version](https://img.shields.io/npm/v/react-twitch-embed?logo=npm)](https://www.npmjs.com/package/react-twitch-embed) [![downloads-week](https://img.shields.io/npm/dw/react-twitch-embed?logo=npm)](https://www.npmjs.com/package/react-twitch-embed) [![downloads-total](https://img.shields.io/npm/dt/react-twitch-embed?logo=npm)](https://www.npmjs.com/package/react-twitch-embed) # react-twitch-embed A collection of components to embed Twitch. For more information, visit the [Embedding Twitch](https://dev.twitch.tv/docs/embed) documentation page. Make sure to check out the [Demo and Documentation](https://docs.moonstar-x.dev/react-twitch-embed) page for more information on the usage of the components, alongside a description on all the supported props for each component. ## Installation ```text npm install react-twitch-embed ``` ## A Note on Typings This package includes some typings for the `Embed` and `Player` constructors that are downloaded automatically into the browser's `window` object. These are unofficial typings that I made empirically, some of them might not be accurate. The documentation on Twitch's official page is incomplete in various aspects, and a lot of the functionality included in this package was found by arbitrarily and through trial and error. If you find any inconsistency with the typings provided by this package, feel free to open a [Pull Request](https://github.com/moonstar-x/react-twitch-embed). ## A Note on the `parent` Prop Twitch requires that any embeds include the URL of the parent site that embeds their content. These components will get this parent URL through `window.location.hostname` for non-interactive components (those components that are essentially just an `iframe`), while the interactive ones get the parent automatically (possible through the same property) by their respective constructor. As such, you shouldn't need to specify this prop for any of the components, unless you run a particular setup with multiple domains. ## FAQ * **Between `TwitchEmbed`, `TwitchPlayer` and `TwitchPlayerNonInteractive`, which component should I choose?** > Out of these components, `TwitchEmbed` and `TwitchPlayer` are both interactive components, meaning that they expose the internal > instance through their respective events. Both of these components support streams, VODs and collections, and they both react > efficiently when their `channel`, `video`, or `collection` props change by using the internal API instead of recreating the embed > when they change. The key difference is that `TwitchEmbed` can include the live chat on streams. At the end of the day, it depends > on which one you prefer. > > As for `TwitchPlayerNonInteractive`, this component can embed streams, VODs and collections too, but it does not include an internal > API. This means that channel, video or collection switching is not "smooth" and will recreate the embed. However, this component does > not download anything extra, it does not create any additional nodes on the body document, so it is probably less resource heavy. * **Why are there `TwitchClip` and `TwitchPlayer`?** > `TwitchClip` will only work for clips whereas`TwitchPlayer` will work for VODs, collections and streams. * **I'm using multiple embeds simultaneously, why are they sticking next to each other?** > In the case of `TwichEmbed` and `TwitchPlayer`, these components need an `id` prop to work because the internal API > mounts its respective `iframe` inside a `div` queried by its `id`. These components will use a default `id` if it's not > provided in their props. If you're displaying multiple embeds simultaneously then you should provide a static `id`. Try > not to use the name of the channel as an `id` because in the case that this prop changes, the embed will be recreated and > the internal API won't be used for the channel switching. * **What does smooth switching mean?** > For the `TwitchEmbed` and `TwitchPlayer` components, when updating their `channel`, `video` and/or `collection` props, > the player will not be recreated and instead the internal API will be used to update this data. ## Testing You can run the tests for this package by running: ```text npm test ``` Or leave the watcher running with: ```text npm run test:watch ``` ## Developing When developing, you can use Storybook as a way to check the components and test them. You can run the Storybook server with: ```text npm run storybook:serve ``` Also, make sure that your code is linter properly with: ```text npm run lint ``` ## Author This component package was made by [moonstar-x](https://github.com/moonstar-x). <file_sep>/src/utils/TwitchPlayerNonInteractive.spec.ts import { generateUrl } from './TwitchPlayerNonInteractive'; import { URLS } from '../constants'; const channel = 'channel'; const parent = 'localhost'; describe('Utils -> TwitchPlayerNonInteractive', () => { describe('generateUrl()', () => { it('should return a string with the correct URL.', () => { const url = generateUrl({ channel }, parent); expect(url).toContain(URLS.TWITCH_PLAYER_NON_INTERACTIVE_URL); }); it('should return a string with the provided channel.', () => { const url = generateUrl({ channel: 'channel' }, parent); expect(url).toContain('channel=channel'); }); it('should return a string with the provided video.', () => { const url = generateUrl({ video: 'video' }, parent); expect(url).toContain('video=video'); }); it('should return a string with the provided collection.', () => { const url = generateUrl({ collection: 'collection' }, parent); expect(url).toContain('collection=collection'); }); it('should return a string with the provided video and collection.', () => { const url = generateUrl({ video: 'video', collection: 'collection' }, parent); expect(url).toContain('video=video'); expect(url).toContain('collection=collection'); }); it('should return a string with only the channel if all media are provided.', () => { const url = generateUrl({ channel: 'channel', video: 'video', collection: 'collection' }, parent); expect(url).toContain('channel=channel'); expect(url).not.toContain('video=video'); expect(url).not.toContain('collection=collection'); }); it('should return a string with autoplay true if enabled.', () => { const url = generateUrl({ channel }, parent, { autoplay: true }); expect(url).toContain('autoplay=true'); }); it('should return a string with autoplay false if disabled.', () => { const url = generateUrl({ channel }, parent, { autoplay: false }); expect(url).toContain('autoplay=false'); }); it('should return a string with muted true if enabled.', () => { const url = generateUrl({ channel }, parent, { muted: true }); expect(url).toContain('muted=true'); }); it('should return a string with muted false if disabled.', () => { const url = generateUrl({ channel }, parent, { muted: false }); expect(url).toContain('muted=false'); }); it('should return a string with time if provided.', () => { const url = generateUrl({ channel }, parent, { time: '4m20s' }); expect(url).toContain('time=4m20s'); }); it('should return a string with time 0h0m0s if not provided.', () => { const url = generateUrl({ channel }, parent); expect(url).toContain('time=0h0m0s'); }); it('should return a string with a single parent if parent is a string.', () => { const url = generateUrl({ channel }, 'localhost'); expect(url).toContain('parent=localhost'); }); it('should return a string with multiple parents if parent is an array.', () => { const parents = ['host1', 'host2', 'host3']; const url = generateUrl({ channel }, parents); parents.forEach((parent) => { expect(url).toContain(`parent=${parent}`); }); }); it('should return a string with all the default options if no options are provided.', () => { const url = generateUrl({ channel }, parent); expect(url).toContain('autoplay=true'); expect(url).toContain('muted=false'); expect(url).toContain('time=0h0m0s'); }); }); }); <file_sep>/src/utils/object.spec.ts import { objectCompareWithIgnoredKeys } from './object'; describe('Utils -> object', () => { describe('objectCompareWithIgnoredKeys()', () => { it('should return true if properties other than ignored have changed.', () => { const o1 = { a: 1, b: 2, c: 3 }; const o2 = { a: 1, b: 3, c: 2 }; const keys = ['b']; const result = objectCompareWithIgnoredKeys(o1, o2, keys); expect(result).toBe(true); }); it('should return false if no properties have changed.', () => { const obj = { a: 1, b: 2, c: 3 }; const keys = ['a']; const result = objectCompareWithIgnoredKeys(obj, obj, keys); expect(result).toBe(false); }); it('should return false if only properties that are ignored have changed.', () => { const o1 = { a: 1, b: 2, c: 3 }; const o2 = { a: 1, b: 3, c: 2 }; const keys = ['b', 'c']; const result = objectCompareWithIgnoredKeys(o1, o2, keys); expect(result).toBe(false); }); }); }); <file_sep>/src/utils/document.spec.ts import { clearElementById } from './document'; const id = 'my-id'; const div = document.createElement('div'); div.id = id; div.innerHTML = 'Full of html'; Object.defineProperty(document, 'getElementById', { value: jest.fn().mockReturnValue(div) }); describe('Utils -> document', () => { beforeEach(() => { div.innerHTML = 'Full of html'; }); describe('clearElementById()', () => { it('should clear the html content of the container if found.', () => { expect(div.innerHTML).not.toHaveLength(0); clearElementById(id); expect(div.innerHTML).toHaveLength(0); }); }); }); <file_sep>/src/utils/misc.ts /* eslint-disable no-empty-function */ export const noop = () => {}; export const typedNoop = <T>() => (_: T) => {}; export const typedNoop2 = <T1, T2>() => (_1: T1, _2: T2) => {}; <file_sep>/src/utils/TwitchClip.ts import { URLS, DEFAULTS } from '../constants'; export interface TwitchClipGenerateUrlOptions { autoplay?: boolean muted?: boolean } const generateUrlDefaultOptions: TwitchClipGenerateUrlOptions = { autoplay: DEFAULTS.AUTOPLAY, muted: DEFAULTS.MUTED }; export const generateUrl = ( clip: string, parent: string | string[], options = generateUrlDefaultOptions ): string => { const fullOptions = { ...generateUrlDefaultOptions, ...options }; const params = new URLSearchParams(); params.append('clip', clip); params.append('autoplay', fullOptions.autoplay!.toString()); params.append('muted', fullOptions.muted!.toString()); if (Array.isArray(parent)) { parent.forEach((parent) => params.append('parent', parent)); } else { params.append('parent', parent); } return `${URLS.TWITCH_CLIP_URL}?${params.toString()}`; }; <file_sep>/src/stories/documentation/TwitchEmbed.stories.mdx import { Meta } from '@storybook/addon-docs'; <Meta title="Documentation/TwitchEmbed" /> # TwitchEmbed This component frames an embed that can embed a stream with its chat, VODs and collections. It is an interactive component, meaning that it exposes its underlying API through the `onVideoReady` event that can be used to control the player from the outside (i.e. custom control components). ## Props The following props are supported by this component: | Name | Type | Required | Default | Description | |-------------------|-------------------------------------------------------------|----------|----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `allowFullscreen` | **boolean** | ❌ | `true` | Whether the player allows fullscreen to be played in fullscreen mode. Disabling this also removes the fullscreen button from the player. | | `autoplay` | **boolean** | ❌ | `true` | Whether the content should autoplay on load. Keep in mind that the audio might not play unless the user has focused at least once on the player. | | `channel` | **string** | ❌ | | The name of the channel to embed their stream. | | `video` | **string** | ❌ | | The ID of the video to embed. | | `collection` | **string** | ❌ | | The ID of collection to embed. If both `video` and `collection` are provided, the player will play the provided collection while starting with the provided video. | | `withChat` | **boolean** | ❌ | `true` | Whether the embed should include the live chat or not. This setting is only applied when `channel` is provided. There are no chat options for VODs. | | `muted` | **boolean** | ❌ | `false` | Whether the content should start muted when playing. The user can still change the volume later. | | `parent` | **string &#124; string[]** | ❌ | `window.location.hostname` | The URL of the site that is embedding this player. Multiple values can be added. You don't need to specify this as the current hostname is already picked up by the underlying API. | | `darkMode` | **boolean** | ❌ | `true` | Whether the chat embed should be displayed in a dark or light theme. | | `time` | **string** | ❌ | `0h0m0s` | The timestamp from where the content should play. If a `channel` is provided then this setting is ignored. Should be a string formatted like `XhYmZs` for an X hour, Y minute and Z second timestamp. | | `hideControls` | **boolean** | ❌ | `false` | Whether the player controls should be hidden. | | `onAuthenticate` | **(e: TwitchEmbedInstance, d: OnAuthenticateData) => void** | ❌ | `() => void` | This event is fired when the embed authenticates the client through their stored credentials in the browser. | | `onVideoPlay` | **(e: TwitchEmbedInstance, d: OnPlayData) => void** | ❌ | `() => void` | This event is fired when the player starts playing or resumes content. | | `onVideoPause` | **(e: TwitchEmbedInstance) => void** | ❌ | `() => void` | This event is fired when the player pauses. | | `onVideoReady` | **(e: TwitchEmbedInstance) => void** | ❌ | `() => void` | This event is fired when the player embed is ready. Use this if you need to keep track of the embed instance. Updating certain props might trigger a recreation of the embed, so this event should keep track of those changes. | | `id` | **string** | ❌ | `twitch-embed` | The ID of the `div` node where the player will be mounted. The underlying API uses this. You should not use an ID that depends on the channel name because it will trigger recreations of the player unnecessarily. | | `height` | **string &#124; number** | ❌ | `480` | The height of the embed. Percentage values can be used (i.e `100%`). | | `width` | **string &#124; number** | ❌ | `940` | The width of the embed. Percentage values can be used (i.e `100%`). | | `...props` | | | | The rest of the props are passed to the underlying `div` node. | > **Note**: If `channel`, `video` and `collection` are provided, only `channel` is taken into account. > If `collection` and `video` are provided, the player will play the videos in the collection starting from the video that was provided. > If the collection doesn't contain the video, the player might enter an undefined state where one of the following may happen. > > 1. The player might start playing the video provided while saying that is playing the collection provided, even if the video isn't part of the collection. > 2. The player might start playing the collection provided while ignoring the video (the official docs mention that this is the default behavior, but I've seen the others happen, so it isn't 100% certain). > 3. The player might remain black and not play anything. ## Example ```jsx import React, { useRef } from 'react'; import { TwitchEmbed } from 'react-twitch-embed'; const MyComponent = () => { const embed = useRef(); // We use a ref instead of state to avoid rerenders. const handleReady = (e) => { embed.current = e; }; return ( <TwitchEmbed channel="moonstar_x" autoplay muted withChat darkMode={false} hideControls onVideoReady={handleReady} /> ); }; export default MyComponent; ``` <file_sep>/src/utils/object.ts export const objectCompareWithIgnoredKeys = ( o1: Record<string, unknown>, o2: Record<string, unknown>, keysToIgnore: string[] ): boolean => { for (const key in o1) { const v1 = o1[key]; const v2 = o2[key]; if (v1 !== v2 && !keysToIgnore.includes(key)) { return true; } } return false; }; <file_sep>/src/utils/TwitchChat.ts import { URLS, DEFAULTS } from '../constants'; export interface TwitchChatGenerateUrlOptions { darkMode?: boolean } const generateUrlDefaultOptions: TwitchChatGenerateUrlOptions = { darkMode: DEFAULTS.DARK_MODE }; export const generateUrl = ( channel: string, parent: string | string[], options = generateUrlDefaultOptions ): string => { const fullOptions = { ...generateUrlDefaultOptions, ...options }; const params = new URLSearchParams(); if (Array.isArray(parent)) { parent.forEach((parent) => params.append('parent', parent)); } else { params.append('parent', parent); } const startOfQuery = fullOptions.darkMode ? '?darkpopout&' : '?'; return `${URLS.TWITCH_CHAT_URL}/${channel}/chat${startOfQuery}${params.toString()}`; }; <file_sep>/src/utils/document.ts export const clearElementById = (id: string) => { const container = document.getElementById(id); if (container) { container.innerHTML = ''; } }; <file_sep>/src/stories/documentation/TwitchClip.stories.mdx import { Meta } from '@storybook/addon-docs'; <Meta title="Documentation/TwitchClip" /> # TwitchClip This component frames a player for clips. ## Props The following props are supported by this component: | Name | Type | Required | Default | Description | |------------|----------------------------|----------|----------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------| | `clip` | **string** | ✅ | | The ID of the clip to embed. | | `parent` | **string &#124; string[]** | ❌ | `window.location.hostname` | The URL of the site that is embedding this clip. Multiple values can be added. You don't need to specify this as the current hostname is already picked up. | | `autoplay` | **boolean** | ❌ | `true` | Whether the clip should autoplay on load. Keep in mind that the audio might not play unless the user has focused at least once on the player. | | `muted` | **boolean** | ❌ | `false` | Whether the clip should start muted when playing. The user can still change the volume later. | | `title` | **string** | ❌ | `TwitchClip` | The name of the `iframe` that embeds the player. Useful for accessibility reasons. | | `height` | **string &#124; number** | ❌ | `480` | The height of the player embed. Percentage values can be used (i.e `100%`). | | `width` | **string &#124; number** | ❌ | `940` | The width of the player embed. Percentage values can be used (i.e `100%`). | | `...props` | | | | The rest of the props are passed to the underlying `iframe` node. | ## Example ```jsx import React from 'react'; import { TwitchClip } from 'react-twitch-embed'; const MyComponent = () => { return ( <TwitchClip clip="AdventurousBusyWormTwitchRaid-7vDEE8L5ur9j9dzi" autoplay muted /> ); }; export default MyComponent; ``` <file_sep>/src/utils/TwitchPlayerNonInteractive.ts import { URLS, DEFAULTS } from '../constants'; export interface TwitchPlayerNonInteractiveMedia { channel?: string video?: string collection?: string } export interface TwitchPlayerNonInteractiveOptions { autoplay?: boolean muted?: boolean time?: string } const generateUrlDefaultOptions: TwitchPlayerNonInteractiveOptions = { autoplay: DEFAULTS.AUTOPLAY, muted: DEFAULTS.MUTED, time: DEFAULTS.TIME }; export const generateUrl = ( media: TwitchPlayerNonInteractiveMedia, parent: string | string[], options = generateUrlDefaultOptions ): string => { const fullOptions = { ...generateUrlDefaultOptions, ...options }; const params = new URLSearchParams(); if (media.channel) { params.append('channel', media.channel); } else { if (media.video) { params.append('video', media.video); } if (media.collection) { params.append('collection', media.collection); } } Object.entries(fullOptions).forEach(([key, value]) => { params.append(key, value.toString()); }); if (Array.isArray(parent)) { parent.forEach((parent) => params.append('parent', parent)); } else { params.append('parent', parent); } return `${URLS.TWITCH_PLAYER_NON_INTERACTIVE_URL}/?${params.toString()}`; }; <file_sep>/src/utils/TwitchClip.spec.ts import { generateUrl } from './TwitchClip'; import { URLS } from '../constants'; const clip = 'clip'; const parent = 'localhost'; describe('Utils -> TwitchClip', () => { describe('generateUrl()', () => { it('should return a string with the correct URL.', () => { const url = generateUrl(clip, parent); expect(url).toContain(URLS.TWITCH_CLIP_URL); }); it('should return a string with the provided clip.', () => { const url = generateUrl('clip', parent); expect(url).toContain('clip=clip'); }); it('should return a string with autoplay true if enabled.', () => { const url = generateUrl(clip, parent, { autoplay: true }); expect(url).toContain('autoplay=true'); }); it('should return a string with autoplay false if disabled.', () => { const url = generateUrl(clip, parent, { autoplay: false }); expect(url).toContain('autoplay=false'); }); it('should return a string with muted true if enabled.', () => { const url = generateUrl(clip, parent, { muted: true }); expect(url).toContain('muted=true'); }); it('should return a string with muted false if disabled.', () => { const url = generateUrl(clip, parent, { muted: false }); expect(url).toContain('muted=false'); }); it('should return a string with a single parent if parent is a string.', () => { const url = generateUrl(clip, 'localhost'); expect(url).toContain('parent=localhost'); }); it('should return a string with multiple parents if parent is an array.', () => { const parents = ['host1', 'host2', 'host3']; const url = generateUrl(clip, parents); parents.forEach((parent) => { expect(url).toContain(`parent=${parent}`); }); }); it('should return a string with all the default options if no options are provided.', () => { const url = generateUrl(clip, parent); expect(url).toContain('autoplay=true'); expect(url).toContain('muted=false'); }); }); });
612811ddcc1da4f958a2ab2d40dfdb088a584d40
[ "Markdown", "TypeScript" ]
21
TypeScript
moonstar-x/react-twitch-embed
c198a9f4f08eb58fcb68e06fb59c520cc51fc5db
0e88f530c57bd074dc19d3cda88c5420e3a1e8a3
refs/heads/master
<file_sep>import os import csv month_count = 0 total_revenue = 0 this_month_revenue = 0 last_month_revenue = 0 revenue_change = 0 revenue_changes = [] months = [] # Read and open CSV file csv_path = os.path.join('PayBank', 'Resources', 'budget_data.csv') with open(csv_path, newline="") as csvfile: csvreader=csv.reader(csvfile,delimiter=',') print (csvreader) # print the Header csv_header=next(csvreader) # gather monthly changes in revenue for row in csvreader: month_count = month_count + 1 months.append(row[0]) this_month_revenue = int(row[1]) total_revenue = total_revenue + this_month_revenue if month_count > 1: revenue_change = this_month_revenue - last_month_revenue revenue_changes.append(revenue_change) last_month_revenue = this_month_revenue # analyze the month by month results sum_rev_changes = sum(revenue_changes) average_change = sum_rev_changes / (month_count - 1) max_change = max(revenue_changes) min_change = min(revenue_changes) max_month_index = revenue_changes.index(max_change) min_month_index = revenue_changes.index(min_change) max_month = months[max_month_index] min_month = months[min_month_index] # print summary to user print("Financial Analysis") print("----------------------------------------") print(f"Total Months: {month_count}") print(f"Total Revenue: ${total_revenue}") print(f"Average Revenue Change: ${average_change}") print(f"Greatest Increase in Revenue: {max_month} (${max_change})") print(f"Greatest Decrease in Revenue: {min_month} (${min_change})") # save summary to txt output_path = os.path.join("PayBank", "output", "new_analysis_data.csv") with open(output_path,'w') as text: text.write("Financial Analysis" + "\n") text.write("----------------------------------------" + "\n") text.write(f"Total Months: {month_count}" + "\n") text.write(f"Total Revenue: ${total_revenue}" + "\n") text.write(f"Average Revenue Change: ${average_change}" + "\n") text.write(f"Greatest Increase in Revenue: {max_month} (${max_change})" + "\n") text.write(f"Greatest Decrease in Revenue: {min_month} (${min_change})" + "\n")
7285a0d10c94fefa5a45d069a75a7e61750c9ceb
[ "Python" ]
1
Python
nmansoorabadi/python-challenge
1d85eecb3e39a4a8df601da51ded692e3927cb1f
e17a13f7cb23ffa0058622e32fc9d9749ef60552
refs/heads/master
<repo_name>yarynakor/COVID-19-vs-Pollution<file_sep>/static/logic.js function numberWithCommas(x) { return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ","); } // Retrieve data from the CSV file and execute everything below d3.json("http://127.0.0.1:5000/data", function(covidData) { console.log(covidData) covidDates = []; covidDatesSlider = []; begDate = new Date("2020-03-01"); curDate = begDate; covidData.data.forEach(function(data) { myDate = new Date(data.Date); if(!covidDates.includes(data.Date) && myDate.getDay() == 6 && myDate.getTime() >= curDate.getTime()){ var mydate = new Date(data.Date); //console.log(mydate.toDateString()); month = (myDate.getMonth() + 1); day = myDate.getDate(); year = myDate.getYear()-100; if (month.length < 2) month = '0' + month; if (day.length < 2) day = '0' + day; dateString = month + "/" + day + "/" + year covidDates.push(data.Date); covidDatesSlider.push(dateString); } }); // covidDates.reverse(); // covidDatesSlider.reverse(); function getTotalCases(state, d){ totalcases = 0; covidData.data.forEach(function(data) { dateLimit = new Date(d); dateLimit.setDate(dateLimit.getDate() + 7); dataFile = new Date(data["Date"]); if(dataFile.getTime() < dateLimit.getTime()){ if (data.State == state){ data["Positive_Cases"] = +data["Positive_Cases"] totalcases = data["Positive_Cases"] } } }); return totalcases; } // Creating map object var map = L.map("map", { center: [39.09, -95.71], zoom: 4 }); // Adding tile layer L.tileLayer("https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}", { 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>", maxZoom: 18, id: "mapbox.streets", accessToken: API_KEY }).addTo(map); var link = "static/States.json"; function getColor(d) { return d > 200000 ? '#800026' : d > 100000 ? '#BD0026' : d > 75000 ? '#E31A1C' : d > 50000 ? '#FC4E2A' : d > 25000 ? '#FD8D3C' : d > 10000 ? '#FEB24C' : d > 1000 ? '#FED976' : '#FFEDA0'; } // Function that will determine the color of the state function chooseColor(state, label) { totalcases = getTotalCases(state, label); return getColor(totalcases); } // Grabbing our GeoJSON data. d3.json(link, function(data) { // Creating a geoJSON layer with the retrieved data getDataAddMarkers = function( {label, value, map, exclamation} ) { var removeMarkers = function() { map.eachLayer( function(layer) { if ( layer.myTag && layer.myTag === "myGeoJSON") { map.removeLayer(layer) } }); } removeMarkers(); slider_date = label; L.geoJson(data, { // Style each feature (in this case a neighborhood) style: function(feature) { return { color: "white", // Call the chooseColor function to decide which color to color our state fillColor: chooseColor(feature.properties.NAME, slider_date), fillOpacity: 0.5, weight: 1.5 }; }, // Called on each feature onEachFeature: function(feature, layer) { // Set mouse events to change map styling layer.myTag = "myGeoJSON"; layer.on({ // When a user's mouse touches a map feature, the mouseover event calls this function, that feature's opacity changes to 90% so that it stands out mouseover: function(event) { layer = event.target; layer.setStyle({ fillOpacity: 0.9 }); }, // When the cursor no longer hovers over a map feature - when the mouseout event occurs - the feature's opacity reverts back to 50% mouseout: function(event) { layer = event.target; layer.setStyle({ fillOpacity: 0.5 }); }, // When a feature (state) is clicked, it is enlarged to fit the screen click: function(event) { // map.fitBounds(event.target.getBounds()); } }); // Giving each feature a pop-up with information pertinent to it needs to be fixed to attach to the CSV layer.bindPopup("<h3>" + feature.properties.NAME + "</h3> <hr> <h4>" + "Cases: " + numberWithCommas(getTotalCases(feature.properties.NAME, slider_date)) + "</h4>"); } }).addTo(map); } L.control.timelineSlider({ timelineItems: covidDatesSlider, changeMap: getDataAddMarkers, extraChangeMapParams: {exclamation: "Extra data"} }) .addTo(map); var legend = L.control({position: 'bottomleft'}); legend.onAdd = function (map) { var div = L.DomUtil.create('div', 'info legend'), grades = [0, 1000, 10000, 25000, 50000, 75000, 100000, 200000], labels = []; // loop through our density intervals and generate a label with a colored square for each interval for (var i = 0; i < grades.length; i++) { div.innerHTML += '<i style="background:' + getColor(grades[i] + 1) + '"></i> ' + grades[i] + (grades[i + 1] ? '&ndash;' + grades[i + 1] + '<br>' : '+'); } return div; }; legend.addTo(map); }); }); d3.json('http://127.0.0.1:5000/plotly', function(data) { var data = data.data var layout = data.layout Plotly.plot('line', data,layout) }); // d3.json('/mapCovid', function(data) { // var data = data.data // var layout = data.layout // Plotly.plot('line', data,layout) // });<file_sep>/app.py from flask import Flask, jsonify, render_template,request import sqlite3 import plotly.express as px import pandas as pd import numpy as np import json from flask_cors import CORS, cross_origin app = Flask(__name__) CORS(app) @app.route("/") def index(): return render_template('map.html') @app.route("/plotly") def plotly(): conn = sqlite3.connect('covid.db') #Creates the plotly object. corona_df = pd.read_sql('SELECT * FROM covid', con=conn) fig = px.line(corona_df, x='Date', y='Positive_Cases', color='State') fig.update_xaxes(tickangle=90) fig.update_layout( title = 'COVID-19 Confirmed Cases over Time', xaxis_tickformat = '%m/%d/%y') #Returns the fig object with the data and layout return jsonify(json.loads(fig.to_json())) @app.route('/data') # @cross_origin() def covid(): conn = sqlite3.connect('covid.db') corona_df=pd.read_sql('SELECT * FROM covid', con=conn) data=corona_df.to_json(orient='table') return jsonify(json.loads(data)) if __name__ == "__main__": app.run(debug=True) <file_sep>/README.md # COVID-19-vs-Pollution In this project we decided to look if there's any relation between the COVID-19 cases (lockdowns) and the air pollution in the USA. We wrote the code that pulls the json COVID-19 in the USA data from the https://covidtracking.com/api/states/daily and convert it to the csv file. We cleaned up the the data to contain the date, number of positive cases and the states and loaded it to the sqlite db. Further on, we have created an app.py to load the data by going to the api endpoint and visualize it with the map. By using the scroller on the map we could track how number of positive cases has grown over time, in particular every states color is changing to a darker color the higher the number of positvie cases grew. We have also created a graph that showed the same data giving a comparison day by day in each state when hovering over the lines. The bubble map has an automated play button that when clicked by the user goes day by day and the bubbles grow over each state that had positive cases based on how the number grew. To show the impact on the air pollution we have pulled the pictures of comparison that showed the amount of air pollution over the certain states and cities on March, 2019 and March, 2020. Adding a slider to it made it an interactive visual that helps to see the impact of the lockdown on the air pollution. Finally, we have put all the visuals together to a responsive website that contained all of the mentioned above interactvie graphs and maps.
28905bbdaeac47cde89a19e9897d4fe8c6b8fc73
[ "JavaScript", "Python", "Markdown" ]
3
JavaScript
yarynakor/COVID-19-vs-Pollution
0f72e03de101d35c1953804585083b6aa6c783f0
e5e90537e1be3df6671b1eacc49a75a9190d0f3b
refs/heads/master
<repo_name>dheeraj510/722f04ad85d64cdee6e5<file_sep>/README.md # README This README would normally document whatever steps are necessary to get the application up and running. Things you may want to cover: * Ruby version * System dependencies * Configuration * Database creation * Database initialization * How to run the test suite * Services (job queues, cache servers, search engines, etc.) * Deployment instructions # API GET /api/users - api/users#index POST /api/users(.:format) - api/users#create GET /api/users/:id(.:format) - api/users#show PATCH /api/users/:id(.:format) - api/users#update PUT /api/users/:id(.:format) - api/users#update DELETE /api/users/:id(.:format) - api/users#destroy GET /api/users/typeahead/:input(.:format) - api/users#typeahead * ... <file_sep>/config/routes.rb Rails.application.routes.draw do namespace :api do resources :users get 'users/typeahead/:input' => 'users#typeahead' end # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
4ca31fbf5e20db1a2c3717d542dc3f4d2a22450b
[ "Markdown", "Ruby" ]
2
Markdown
dheeraj510/722f04ad85d64cdee6e5
e093a8c343c48a1ef4cf18668d54e87127a4ae6f
8bb2202178379639455142fbc115e1076b0ade75
refs/heads/master
<file_sep>package com.cs.constants; /** * Created by olgac on 31/05/2017. */ public enum PaymentMethod { CREDITCARD, CUP, IDEAL, GIROPAY, MISTERCASH, STORED, PAYTOCARD } <file_sep>package com.cs.controller; import com.cs.constants.Status; import com.cs.model.error.Error; import com.cs.model.request.ClientRequest; import com.cs.model.request.ListRequest; import com.cs.model.request.MerchantRequest; import com.cs.model.request.ReportRequest; import com.cs.model.request.TransactionRequest; import com.cs.model.response.ClientResponse; import com.cs.model.response.ListResponse; import com.cs.model.response.MerchantResponse; import com.cs.model.response.ReportResponse; import com.cs.model.response.TransactionResponse; import com.cs.service.TransactionService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.util.Optional; import java.util.concurrent.Callable; import java.util.concurrent.Future; /** * Created by olgac on 31/05/2017. */ @RestController @Api(description = "Transaction Operations") @RequestMapping("/transaction") public class TransactionController { @Autowired private TransactionService transactionService; @ApiOperation("List End-Point") @PostMapping("/list") public Callable<ResponseEntity<ListResponse>> retrieveList(@RequestHeader(HttpHeaders.AUTHORIZATION) String token, @Valid @RequestBody ListRequest listRequest, @RequestParam(value = "page", required = false) Integer page) { return () -> { Future<Optional<ListResponse>> future = transactionService.retrieveList(token, listRequest, page); Optional<ListResponse> optional = future.get(); return new ResponseEntity<>(optional.orElseThrow(() -> new Error(0, Status.ERROR, "List not retrieved!")), HttpStatus.OK); }; } @ApiOperation("Report End-Point") @PostMapping("/report") public Callable<ResponseEntity<ReportResponse>> retrieveReport(@RequestHeader(HttpHeaders.AUTHORIZATION) String token, @Valid @RequestBody ReportRequest reportRequest) { return () -> { Future<Optional<ReportResponse>> future = transactionService.retrieveReport(token, reportRequest); Optional<ReportResponse> optional = future.get(); return new ResponseEntity<>(optional.orElseThrow(() -> new Error(0, Status.ERROR, "Report not retrieved!")), HttpStatus.OK); }; } @ApiOperation("Client End-Point") @PostMapping("/client") public Callable<ResponseEntity<ClientResponse>> retrieveClient(@RequestHeader(HttpHeaders.AUTHORIZATION) String token, @Valid @RequestBody ClientRequest clientRequest) { return () -> { Future<Optional<ClientResponse>> future = transactionService.retrieveClient(token, clientRequest); Optional<ClientResponse> optional = future.get(); return new ResponseEntity<>(optional.orElseThrow(() -> new Error(0, Status.ERROR, "Client not retrieved!")), HttpStatus.OK); }; } @ApiOperation("Merchant End-Point") @PostMapping("/merchant") public Callable<ResponseEntity<MerchantResponse>> retrieveMerchant(@RequestHeader(HttpHeaders.AUTHORIZATION) String token, @Valid @RequestBody MerchantRequest merchantRequest) { return () -> { Future<Optional<MerchantResponse>> future = transactionService.retrieveMerchant(token, merchantRequest); Optional<MerchantResponse> optional = future.get(); return new ResponseEntity<>(optional.orElseThrow(() -> new Error(0, Status.ERROR, "Merchant not retrieved!")), HttpStatus.OK); }; } @ApiOperation("Transaction End-Point") @PostMapping public Callable<ResponseEntity<TransactionResponse>> retrieveTransaction(@RequestHeader(HttpHeaders.AUTHORIZATION) String token, @Valid @RequestBody TransactionRequest transactionRequest) { return () -> { Future<Optional<TransactionResponse>> future = transactionService.retrieveTransaction(token, transactionRequest); Optional<TransactionResponse> optional = future.get(); return new ResponseEntity<>(optional.orElseThrow(() -> new Error(0, Status.ERROR, "Transaction not retrieved!")), HttpStatus.OK); }; } }<file_sep>package com.cs.serializer; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import org.springframework.util.StringUtils; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class JsonDateTimeDeserializer extends JsonDeserializer<Date> { @Override public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { JsonToken jsonToken = jsonParser.getCurrentToken(); if (jsonToken == JsonToken.VALUE_STRING) { String text = jsonParser.getText().trim(); if (StringUtils.isEmpty(text)) { return null; } try { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(text); } catch (ParseException e) { throw new IOException(e); } } else if (jsonToken == JsonToken.VALUE_NUMBER_INT) { return new Date(jsonParser.getLongValue()); } else { throw new IOException("Expecting String for Date Deserializing Token:" + jsonToken); } } }<file_sep># cs-api The Reporting API gives you access to most of the report data in PSP Used Techs: >* Java 8 >* Spring Boot >* Maven >* [Swagger](https://agile-caverns-39115.herokuapp.com/swagger-ui.html) >* Docker >* JUnit >* Mockito >* [Sonar Report](https://sonarcloud.io/organizations/olgac/projects) <file_sep>package com.cs.constants; import lombok.AllArgsConstructor; /** * Created by olgac on 31/05/2017. */ @AllArgsConstructor public enum ErrorCode { CS01("Do not honor"), CS02("Invalid Transaction"), CS03("Invalid Card"), CS04("Not sufficient funds"), CS05("Incorrect PIN"), CS06("Invalid country association"), CS07("3-D Secure Transport Error"), CS08("Transaction not permitted to cardholder"); private String name; } <file_sep>package com.cs.constants; /** * Created by olgac on 31/05/2017. */ public enum Status { APPROVED, WAITING, DECLINED, ERROR }<file_sep>package com.cs.service; import com.cs.model.request.ClientRequest; import com.cs.model.request.ListRequest; import com.cs.model.request.MerchantRequest; import com.cs.model.request.ReportRequest; import com.cs.model.request.TransactionRequest; import com.cs.model.response.ClientResponse; import com.cs.model.response.ListResponse; import com.cs.model.response.MerchantResponse; import com.cs.model.response.ReportResponse; import com.cs.model.response.TransactionResponse; import java.util.Optional; import java.util.concurrent.Future; /** * Created by olgac on 31/05/2017. */ public interface TransactionService { Future<Optional<ListResponse>> retrieveList(String token, ListRequest listRequest, Integer page); Future<Optional<ReportResponse>> retrieveReport(String token, ReportRequest reportRequest); Future<Optional<ClientResponse>> retrieveClient(String token, ClientRequest clientRequest); Future<Optional<MerchantResponse>> retrieveMerchant(String token, MerchantRequest merchantRequest); Future<Optional<TransactionResponse>> retrieveTransaction(String token, TransactionRequest transactionRequest); }<file_sep>package com.cs.model.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; /** * Created by olgac on 01/06/2017. */ @Data @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class TransactionDto implements Serializable { private static final long serialVersionUID = 2060782769472203031L; private TransactionMerchantDto merchant; } <file_sep>package com.cs.model.request; import com.cs.serializer.JsonDateDeserializer; import com.cs.serializer.JsonDateSerializer; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; /** * Created by olgac on 31/05/2017. */ @Data @Builder @AllArgsConstructor @NoArgsConstructor public class ReportRequest { @JsonDeserialize(using = JsonDateDeserializer.class) @JsonSerialize(using = JsonDateSerializer.class) private Date fromDate; @JsonDeserialize(using = JsonDateDeserializer.class) @JsonSerialize(using = JsonDateSerializer.class) private Date toDate; private Integer merchant; private Integer acquirer; } <file_sep>package com.cs.model.dto; import com.cs.constants.Status; import com.cs.serializer.JsonDateTimeDeserializer; import com.cs.serializer.JsonDateTimeSerializer; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.Date; /** * Created by olgac on 01/06/2017. */ @Data @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class TransactionMerchantDto implements Serializable { private static final long serialVersionUID = 3144081124787429490L; private Integer id; private String referenceNo; private Integer merchantId; private Integer fxTransactionId; private Integer agentInfoId; private Status status; private String operation; private String type; private String chainId; private String returnUrl; private Integer acquirerTransactionId; private String code; private String message; private String channel; private String customData; private Integer parentId; @JsonDeserialize(using = JsonDateTimeDeserializer.class) @JsonSerialize(using = JsonDateTimeSerializer.class) @JsonProperty("created_at") private Date createdAt; @JsonDeserialize(using = JsonDateTimeDeserializer.class) @JsonSerialize(using = JsonDateTimeSerializer.class) @JsonProperty("updated_at") private Date updatedAt; @JsonDeserialize(using = JsonDateTimeDeserializer.class) @JsonSerialize(using = JsonDateTimeSerializer.class) @JsonProperty("deleted_at") private Date deletedAt; private String transactionId; }<file_sep>package com.cs.model.dto; import com.cs.constants.Status; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.math.BigDecimal; /** * Created by olgac on 01/06/2017. */ @Data @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class DataIpnMerchantDto implements Serializable { private static final long serialVersionUID = -7046681452927990306L; private String transactionId; private String referenceNo; private BigDecimal amount; private String currency; private BigDecimal convertedAmount; private String convertedCurrency; private Long date; private String code; private String message; private String operation; private String type; private Status status; private String customData; private String chainId; private String paymentType; private String descriptor; private String token; @JsonProperty("IPNUrl") private String IPNUrl; private String ipnType; }
4990a7e94ad926dfd3dd5ee3994e32abbbfd50bc
[ "Markdown", "Java" ]
11
Java
olgac/cs-api
d709de9ea460ce27f31f2594e41cd8d116345f72
86c688aedd3c467ba45e0f47d1a53ca32cb7c10e
refs/heads/master
<file_sep>import React, { Component } from 'react'; import { Text, StyleSheet, View, TouchableOpacity, Image } from 'react-native'; import ClubView from './ClubView'; import * as axios from 'axios'; import PropTypes from "prop-types"; import { update } from 'tcomb'; import Overlay from 'react-native-modal-overlay'; export default class ClubDiv extends Component{ constructor(props){ super(props); this.state={ clubName:[], clubLogo:[], }; } static propTypes = { school: PropTypes.string.isRequired, }; componentWillMount = () => { this._getDatas(); }; _getDatas = () => { const { clubName, clubLogo } = this.state; const { school, clubKind } = this.props; this.setState({school : school}) // 데이터 가져오기 axios.post('http://dkstkdvkf00.cafe24.com/FindClubs.php',{ school:school, clubKind: clubKind, }) .then((result) => { const response = result.data; var clubNameArray = new Array(); var clubLogoArray = new Array(); response.forEach(row => { clubNameArray.push(row.clubName); clubLogoArray.push(row.clubLogo); }); this.setState({ clubName: clubName.concat(clubNameArray), clubLogo: clubLogo.concat(clubLogoArray), }); }); } _gotoClubIntroduce = () => { console.log() } render(){ const {clubName, clubLogo} = this.state; const { school, clubKind } = this.props; // console.log(count); return ( <View style={styles.container}> <Text style={styles.menuTitle}>{clubKind}</Text> {clubName.map((name, i) => { return ( <ClubView clubName={clubName[i]} clubLogo={clubLogo[i]} school={school} key={i} navigation={this.props.navigation} /> ); })} </View> ) } } const styles = StyleSheet.create({ container:{ width:'100%', borderTopWidth:1, borderColor: '#bebebe', marginBottom: 10 }, menuTitle:{ marginBottom: 7, paddingTop:15, paddingLeft:25, color: '#828282', fontSize: 15 }, });<file_sep>import React, { Component } from 'react'; import { TouchableOpacity, Text, StyleSheet, } from 'react-native'; import { scale, moderateScale, verticalScale} from '../components/Scaling'; export default class MainButton extends Component{ static defaultProps = { title: 'untitled', buttonColor: '#000', titleColor: '#fff', onPress: () => null, } constructor(props){ super(props); } render(){ return ( <TouchableOpacity style={[styles.button,{backgroundColor: this.props.buttonColor}]} onPress={this.props.onPress}> <Text style={[styles.title,{color: this.props.titleColor, fontSize: moderateScale(15),}]}> {this.props.title} </Text> </TouchableOpacity> ) } } const styles = StyleSheet.create({ button: { width: moderateScale(300), alignItems: 'center', justifyContent: 'center', marginBottom: 10, borderRadius: 30, height:moderateScale(50, 0.25), }, title: { fontSize: 18, }, });<file_sep>import React, {Component} from 'react'; import {StyleSheet, Platform, Text, View, ScrollView, TouchableOpacity} from 'react-native'; import RecordFalse from '../components/RecordFalse'; import RecordTrue from '../components/RecordTrue'; import { Header, Icon } from 'react-native-elements'; import MasonryList from "react-native-masonry-list"; import * as axios from 'axios'; export default class SignUpRecord extends React.Component { static navigationOptions = { title: "기록추가", style: {elevation: 0, shadowOpacity: 0,}, headerStyle: { height: Platform.OS === 'ios' ? 70 : 10, elevation: 0,shadowColor: 'transparent', borderBottomWidth:0, paddingBottom:10, paddingTop: Platform.OS === 'ios' ? 40 : 5}, headerTitleStyle: { color:"#2eaeff", fontSize:Platform.OS === 'ios' ? 25 : 18, textAlign:"center", flex:1 , fontWeight: "bold" }, tintColor: "#2eaeff" } constructor(props){ super(props); this.state={ records:[], showImage:[], school:'', }; this.props.navigation.addListener('didFocus', () => { this._getDatas() }); } componentWillMount = () => { this._getSchool(); }; // 이미지들 가져오기 _getDatas = () => { //userNo 가지고 오기 const { navigation } = this.props; const {records} = this.state; var userNo = navigation.getParam('userNo', 'NO-ID'); // console.log(userNo); // var userNo = 27; const t = this; // 데이터 가져오기 axios.post('http://dkstkdvkf00.cafe24.com/GetImages.php',{ userNo:userNo, }) .then((result) => { // t._setDatas(response); const response = result.data; var recordArray = new Array(); response.forEach(row => { recordArray.push({ uri : row.recordPicture}); }); t.setState({ records: records.concat(recordArray), }); }); } _RecordRegister = item => { this.props.navigation.navigate('RecordRegister', { item: item.uri, userNo: this.props.userNo }) } _getSchool = () => { const { navigation } = this.props; var userNo = navigation.getParam('userNo', 'NO-ID'); const t = this; // 데이터 가져오기 axios.post('http://dkstkdvkf00.cafe24.com/GetSchool.php',{ userNo:userNo, }) .then(function (response) { var str = JSON.stringify(response.data.message.school);; var school = str.substring(1, str.length-1); t.setState({ school: school }); }); } render() { const { navigation } = this.props; var name = navigation.getParam('recordName', 'NO-ID'); var userNo = navigation.getParam('userNo', 'NO-ID'); const {records, showImage} = this.state; console.log(this.state.school) return ( <> <View style={styles.container}> <Icon raised reverse name='plus' type='entypo' color='#2eaeff' containerStyle={{ position: 'absolute', bottom:100, right: 10, zIndex:999 }} onPress={() => this.props.navigation.navigate('RecordRegister',{ userNo: userNo })} /> {/* 사진들 들어갈 곳 */} <MasonryList imageContainerStyle={{borderRadius:17, right:12}} spacing={7} images={records} onPressImage = {(item, index) => { this._RecordRegister(item.uri) }} /> {/* 완료버튼 */} <View style={styles.footer}> {/* true면 <RecordTrue /> false면 <RecordFalse /> */} <RecordTrue onPress={ () => this.props.navigation.navigate('FindClub',{ schoolName : this.state.school }) // () => console.log(records) } /> </View> </View> </> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor:'#fff' }, header:{ width:'100%', height:70, // backgroundColor:'#A0AFFF', flexDirection:"row", justifyContent: "flex-end" }, content:{ flex: 1 }, footer:{ width: '100%', height: 70, // backgroundColor: '#5CEEE6', borderTopWidth:0 }, button:{ backgroundColor: '#0064FF', width:50, height:50, marginTop:10, alignItems: 'center', justifyContent: 'center', marginRight: 20, borderRadius: 50 }, text:{ fontSize: 25, color: '#fff' } });<file_sep>import React, { Component } from 'react'; import { TouchableOpacity, Text, StyleSheet, View, Image } from 'react-native'; import * as axios from 'axios'; import ClubChars from './ClubChars'; import Overlay from 'react-native-modal-overlay'; export default class ClubView extends Component{ state = {modalVisible: false} constructor(props){ super(props); this.state={ clubChar: [], } } showOverlay() { this.setState({modalVisible: true}) } hideOverlay() { this.setState({modalVisible: false}) } onClose = () => this.setState({ modalVisible: false}); componentWillMount = () => { this._getDatas(); }; _getDatas = () => { const { clubName, school } = this.props; const { clubChar } = this.state; // 데이터 가져오기 axios.post('http://dkstkdvkf00.cafe24.com/GetClubChars.php',{ clubName: clubName, school: school, }) .then((result) => { const response = result.data; var clubCharArray = new Array(); response.forEach(row => { clubCharArray.push(row.chars); }); this.setState({ clubChar: clubChar.concat(clubCharArray), }); }); } _gotoClubIntroduce = () => { this.onClose() this.props.navigation.navigate('ClubIntroduce', { clubName: this.props.clubName, school: this.props.school }) } _gotoRecord = () => { this.onClose() this.props.navigation.navigate('Record', { clubName: this.props.clubName, school: this.props.school }) } render(){ let {clubLogo, clubName} = this.props; let {clubChar} = this.state; return ( <View style={styles.container}> <TouchableOpacity onPress={this.showOverlay.bind(this)}> <View style={styles.logo}> <Image style={styles.Image} source={{ uri: clubLogo }}/> </View> </TouchableOpacity> <TouchableOpacity onPress={this.showOverlay.bind(this)} style={styles.club}> <Text style={styles.clubTitle}>{clubName}</Text> <Text style={styles.clubChar}> {clubChar.map((chars, i) => { return (<ClubChars chars={clubChar[i]} key={i}/>); })} </Text> </TouchableOpacity> <Overlay visible={this.state.modalVisible} onClose={this.onClose} closeOnTouchOutside animationType="zoomIn" animationDuration={200} childrenWrapperStyle={{width:'100%', backgroundColor: 'white', borderRadius: 15,}} containerStyle={{backgroundColor: 'rgba(50, 50, 50, 0.78)'}} > <View style={{flexDriection:'column', }}> <View style={{flexDirection:'row',}}> <View style={styles.logo}> { clubLogo === null ? <Image source={require('../images/momo.jpg')} style={styles.Image} /> : {clubLogo} && <Image source={{uri: clubLogo}} style={styles.Image} /> } </View> <View style={{marginBottom:30, flex:1}}> <Text style={styles.clubTitle}>{clubName}</Text> <Text style={styles.clubChar}> {clubChar.map((chars, i) => { return (<ClubChars chars={clubChar[i]} key={i}/>); })} </Text> </View> </View> <View style={{flexDirection:'row', justifyContent:'center', alignItems:'center'}}> <TouchableOpacity style={styles.button} onPress={this._gotoClubIntroduce} > <Image style={styles.ImageR} source={require('../images/introduce.png')}/> <Text style={{textAlign:'center',fontSize:15}}>소개</Text> </TouchableOpacity> <TouchableOpacity style={styles.button} onPress={this._gotoRecord} > <Image style={styles.ImageR} source={require('../images/record.png')}/> <Text style={{textAlign:'center', fontSize:15}}>기록</Text> </TouchableOpacity> </View> </View> </Overlay> </View> ) } } const styles = StyleSheet.create({ container:{ width:'100%', height:70, // backgroundColor:'#FAFABE', flexDirection:"row", justifyContent: "flex-start", padding:15, paddingLeft:25, alignItems:'center' }, logo:{ height:50, width:50, borderRadius:25, backgroundColor:'#fff', marginRight:25 }, Image:{ height:50, width:50, resizeMode:'cover', backgroundColor: '#fff', borderRadius: 25, borderColor:'#0064FF', borderWidth:1, }, ImageR:{ left:-5, height:60, width:60, resizeMode:'contain', }, club:{ flex:1, // backgroundColor: '#DCEBFF', }, clubTitle:{ fontSize:20, fontWeight: '500', marginBottom: 8 }, clubChar:{ fontSize: 14, color: '#828282' }, button:{ top:-40, margin:30, height:70, width:50, zIndex:999, // backgroundColor:'red' }, });<file_sep>import React, {Component} from 'react'; import {StyleSheet, Text, View, ScrollView, TouchableOpacity} from 'react-native'; import RecordFalse from '../components/RecordFalse'; import RecordTrue from '../components/RecordTrue'; import { Header, Icon } from 'react-native-elements'; import MasonryList from "react-native-masonry-list"; export default class Record extends React.Component { constructor(props){ super(props); this.state={ records:[], showImage:[], }; } _RecordRegister = picture => { this.props.navigation.navigate('RecordPictures_dLite', { picture: picture.uri, userNo: this.props.userNo }) } render() { return ( <> <MasonryList imageContainerStyle={{borderRadius:17, right:12}} spacing={7} images={[ { uri: 'http://etoland.co.kr//data/daumeditor02/190221/thumbnail3/33687715507189160.jpg', }, { uri: 'http://etoland.co.kr/data/file0207/star/1743390505_TfphHEzC_U1NCbtMH6.jpg' }, { uri: 'http://etoland.co.kr/data/file0207/star/1743390505_2H1RX0k7_kiuMHutnZ.jpg' }, { uri: 'http://etoland.co.kr/data/file0207/star/thumbnail3/2041774303_gHOKcVMt_Screenshot_20190217-032858_Instagram.jpg' }, { uri: 'http://etoland.co.kr/data/daumeditor02/190120/15479464870.jpg' }, { uri: 'http://etoland.co.kr/data/mw.cheditor/190101/thumbnail3/1c7fa003a62cf5552d2788ed0ff73d07_PFpsIeTnwvCLkCbXu.jpg' }, { uri: 'http://dimg.donga.com/wps/NEWS/IMAGE/2016/05/27/78352163.1.jpg' }, { uri: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQKaqws0tnHsY_jePJqGz3iltCjnitigbnTlghg4ciUjGe7RsYb' }, { uri: 'https://image.fmkorea.com/files/attach/new/20180517/3655109/48834235/1060661020/4c23a9fce45cd3e205b686d32b3b0324.jpg' }, ]} onPressImage = {(item, index) => { this._RecordRegister(item.uri) }} /> </> ); } } const styles = StyleSheet.create({ container:{ flex:1, padding:20 } });<file_sep>import React, {Component,Fragment} from 'react'; import {StyleSheet, Text, View, ScrollView, TouchableOpacity, TextInput, AsyncStorage, Dimensions,KeyboardAvoidingView, Platform, Image, TouchableWithoutFeedback, Keyboard} from 'react-native'; import { ImagePicker, Constants, Permissions } from 'expo'; import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'; import * as axios from 'axios'; import RegisterButton from '../components/RegisterButton'; import RegisterButtonN from '../components/RegisterButtonN'; import { scale, moderateScale, verticalScale} from '../components/Scaling'; const DismissKeyboard = ({ children }) => ( <TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}> {children} </TouchableWithoutFeedback> ); const { width, height } = Dimensions.get("window"); export default class RecordRegister extends React.Component { static navigationOptions = { title: "기록생성", style: {elevation: 0, shadowOpacity: 0,}, headerStyle: { height: Platform.OS === 'ios' ? 70 : 10, elevation: 0,shadowColor: 'transparent', borderBottomWidth:0, paddingBottom:10, paddingTop: Platform.OS === 'ios' ? 40 : 5}, headerTitleStyle: { color:"#2eaeff", fontSize:Platform.OS === 'ios' ? 25 : 18, textAlign:"center", flex:1 , fontWeight: "bold" }, tintColor: "#2eaeff" } constructor(props){ super(props); this.state={ image:null, disabled: false, count:0, text: '', plds: [], comment:'', name:'', }; } _pickImage = async () => { const permissions = Permissions.CAMERA_ROLL; const { status } = await Permissions.askAsync(permissions); console.log(permissions, status); if(status === 'granted') { let result = await ImagePicker.launchImageLibraryAsync({ allowsEditing: true, aspect: [4, 3], }); if (!result.cancelled) { this.setState({ image: result.uri }); } } } _ButtonPress = () => { const { name, image, comment } = this.state; const { navigation } = this.props; var userNo = navigation.getParam('userNo', 'NO-ID'); // console.log(userNo) // for(let i=0; i<images.length; i++){ // 데이터베이스에 넣기 axios.post('http://dkstkdvkf00.cafe24.com/SetRecord.php',{ recordName: name, recordPicture: image, recordContent: comment, userNo: userNo }) .then(function (response) { ms = response.data.message; }); // } this.setState({image: null}) this.props.navigation.navigate('SignUpRecord') } componentDidMount = () => { AsyncStorage.getItem("plds").then(data => { const plds = JSON.parse(data || '[]'); this.setState({ plds }); }); }; removePld = (index) => { let plds = [...this.state.plds] plds.splice(index,1) this.setState({ plds: plds, }) } addPld = (pld) => { // 새로운 특성(char) 객체 생성 const newPld = { id: Date.now(), // 등록시간 text: pld, // 특성 내용 } // state 업데이트 this.setState(prevState => { prevState.plds.push(newPld); return prevState; }); // 콘솔창에 출력해보자~ console.log(this.state.plds); } componentWillMount(){ this.setState({ text:'', plds:[], }) } state={ count:0 } _updateCount = () => { this.setState({ count:this.state.count+1 }); }; render() { const {image} = this.state; return ( <> <DismissKeyboard> <ScrollView> <View style={styles.container}> <KeyboardAvoidingView behavior="padding" keyboardVerticalOffset={Platform.OS=== 'ios' ? '200' : '10'} > {/* 밑에 완료버튼 빼고 나머지 화면 스크롤 */} {/* 맨 위 활동 내용 적는 곳 */} {/* 사진 넣는 곳 */} <View style={styles.contentBackground}> <TouchableOpacity onPress={this._pickImage}> <View style={styles.content}> { image === null ? <Image style={{height:'50%',width:'55%',resizeMode:'contain'}} source={require('../images/addPhoto.png')}/> : <Image style={{height:'100%',width:'100%',resizeMode:'cover'}} source={{ uri : image}}/> } </View> </TouchableOpacity> <TextInput style={styles.commentInput} placeholder={"간단한 코멘트를 입력해주세요"} placeholderTextColor={"#bebebe"} multiline={false} onChangeText={(comment) => this.setState({comment})} /> </View> <View style={styles.coment}> </View> {/* 완료버튼 */} </KeyboardAvoidingView> </View> </ScrollView> <View style={styles.footer}> {this.state.name.length==0 && this.state.image==null ? <RegisterButtonN title={'확인'}/> : this.state.name.length==0? <RegisterButtonN title={'확인'}/> : this.state.image==null? <RegisterButtonN title={'확인'}/> : <RegisterButton title={'확인'}/> } </View> </DismissKeyboard> </> ); } } const styles = StyleSheet.create({ container: { flex:1, backgroundColor:'#fff', padding:20, justifyContent:'center', alignItems:'center' }, scroll:{ flex:1, padding:10 }, header:{ width: moderateScale(300), height:50, backgroundColor:'#32AAFF', justifyContent: "center", alignItems:'center', borderRadius: 10, marginBottom: 40, textAlign:'center' }, footer:{ width: '100%', height: 70, }, button:{ flex:1, backgroundColor: '#50C8FF', alignItems: 'center', justifyContent: 'center' }, text:{ fontSize: 20, color: '#fff' }, titleInput:{ color: '#fff', // backgroundColor: '#32AAFF', fontSize: 20, textAlign:'center' }, buttonStyle: { width: 150, height: 75, backgroundColor: 'ivory', borderRadius: 5, justifyContent: 'center', alignItems: 'center', marginVertical: 15, }, contentBackground:{ marginTop:scale(50), backgroundColor: '#f2f2f2', marginBottom: 15, width: moderateScale(310), height: verticalScale(360), borderRadius:10, alignItems: 'center', justifyContent: 'center', //그림자효과 shadowColor: "#dbdbdb", shadowOpacity: 0.8, shadowRadius: 5, shadowOffset: { height: 5, width: 5 }, elevation: 3, }, content:{ backgroundColor:'#fff', width: moderateScale(270), height:moderateScale(280), borderRadius: 10, alignItems: "center", justifyContent:"center", marginTop:10 }, coment:{ width: '100%', height: height*0.01, // backgroundColor: '#c98cc9', paddingTop:10, paddingLeft:10 }, commentInput:{ fontSize:21, textAlign: 'center', paddingTop:30, paddingBottom:5 } });<file_sep>import React, {Component} from 'react'; import {StyleSheet, Text, View, TextInput, Platform} from 'react-native'; import SchoolButton from '../components/SchoolButton'; import ConfirmButtonN from '../components/ConfirmButtonN'; import { Header } from 'react-native-elements'; import { scale, moderateScale, verticalScale} from '../components/Scaling'; export default class InputSchool extends React.Component { static navigationOptions = { title: "학교 선택", style: {elevation: 0, shadowOpacity: 0,}, headerStyle: { height: Platform.OS === 'ios' ? 70 : 10, elevation: 0,shadowColor: 'transparent', borderBottomWidth:0, paddingBottom:10, paddingTop: Platform.OS === 'ios' ? 40 : 5}, headerTitleStyle: { color:"#2eaeff", fontSize:Platform.OS === 'ios' ? 25 : 18, textAlign:"center", flex:1 , fontWeight: "bold" }, tintColor: "#2eaeff" } constructo render() { return ( <> <View style={styles.container}> <View style={styles.select}> <SchoolButton title={'울산대학교'} onPress={() => this.props.navigation.navigate('FindClub', { schoolName: '울대' })}/> </View> </View> </> ); } } const styles = StyleSheet.create({ container: { flex: 1, padding: 15, backgroundColor: 'white', }, select: { flex:1, justifyContent:'center', width:'100%', // backgroundColor: '#1ad657', flexDirection:'row', alignItems:'center', }, });<file_sep>import React, {Component} from 'react'; import {StyleSheet, Text, View, TextInput} from 'react-native'; import ConfirmButton from '../components/ConfirmButton'; export default class PhoneNumber extends React.Component { render() { return ( <View style={styles.container}> <View style={styles.header} /> <View style={styles.title}> <Text style={styles.text}>동아리원 모집을 위해 회장님의 전화번호가 공개됩니다.</Text> <Text style={styles.text}>전화번호는 최초 1회만 입력하시면 됩니다.</Text> <TextInput style={styles.input} placeholder={"전화번호"} placeholderTextColor={"#999"} /> </View> <View style={styles.content}/> <View style={styles.footer}> <ConfirmButton style={styles.button} title={'확인'}/> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, padding: 15, backgroundColor: 'white', }, header: { width:'100%', height:'10%', // backgroundColor: '#ff9a9a', }, title: { width:'100%', height:'30%', flexDirection: "column", alignItems:"center" // backgroundColor: '#9aa9ff' }, content: { flex: 1, // backgroundColor: '#d6ca1a', }, footer: { width:'100%', height:150, // backgroundColor: '#1ad657', paddingTop: 40, paddingBottom: 40 }, input: { width:'100%', padding: 7, borderColor: "#32B8FF", borderWidth: 1, fontSize: 17, marginTop:13 }, text: { fontSize: 13, color:"#c8c8c8" } });<file_sep>import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { TouchableOpacity, Text, StyleSheet } from 'react-native'; import {Icon} from 'react-native-elements' class CSButton extends Component { render() { const { text, onPress} = this.props; return ( <> <Icon name='plus' type='entypo' color='#2eaeff' onPress={() => onPress()} reverse raised containerStyle={{zIndex: 999, position: 'absolute', bottom:120, right: 20 }} /> </> ); } } CSButton.propTypes = { onPress: PropTypes.func.isRequired }; const styles = StyleSheet.create({ textStyle: { fontSize:20, color: '#ffffff', textAlign: 'center' }, buttonStyle: { flex:1, zIndex: 999, borderWidth:1, borderColor:'rgba(0,0,0,0.2)', alignItems:'center', justifyContent:'center', width:50, height:50, backgroundColor:'#0083f0', borderRadius:100, position: 'absolute', bottom:120, right: 20, shadowColor: 'rgba(0,0,0, .4)', // IOS shadowOffset: { height: 1, width: 1 }, // IOS shadowOpacity: 1, // IOS shadowRadius: 1, //IOS elevation: 2, // Android } }); export default CSButton;<file_sep>import React, {Component} from 'react'; import {StyleSheet, AsyncStorage, Text, View, KeyboardAvoidingView, TouchableWithoutFeedback, Keyboard, ScrollView,BackHandler,Platform} from 'react-native'; import ConfirmButton from '../components/ConfirmButton'; import ConfirmButtonN from '../components/ConfirmButtonN'; import CharButton from '../components/CharButton'; import CharInput from '../components/CharInput'; import CharGoal from '../components/CharGoal'; import * as axios from 'axios'; import { scale, moderateScale, verticalScale} from '../components/Scaling'; const DismissKeyboard = ({ children }) => ( <TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}> {children} </TouchableWithoutFeedback> ); export default class CharChoice extends React.Component { static navigationOptions = { headerLeft: null, gesturesEnabled: false, header: null } constructor(props){ super(props); this.state={ clubChars:[], chars:[], count:0, }; } componentDidMount = () => { AsyncStorage.getItem("chars").then(data => { const chars = JSON.parse(data || '[]'); this.setState({ chars }); }); }; removeChar = (index) => { let clubChars = [...this.state.clubChars]; let chars = [...this.state.chars] let {count} = this.state chars.splice(index,1) clubChars.splice(index,1) this.setState({ chars: chars, clubChars: clubChars, count: count-1, }) } addChar = (char) => { let {count} = this.state; this.setState({count: count+1}) // 새로운 특성(char) 객체 생성 const newChar = { id: Date.now(), // 등록시간 text: char, // 특성 내용 } // state 업데이트 this.setState(prevState => { prevState.clubChars.push(char); prevState.chars.push(newChar); return prevState; }); } _ButtonPress = () => { // console.log(this.state.count); const { navigation } = this.props; var userNo = navigation.getParam('userNo', 'NO-ID'); this._setClubChars(); this.props.navigation.navigate('SignUpRecord', { userNo: userNo }) } _setClubChars = () => { const { navigation } = this.props; const { clubChars } = this.state; var userNo = navigation.getParam('userNo', 'NO-ID'); for(let i=0; i<clubChars.length; i++){ // 데이터베이스에 넣기 axios.post('http://dkstkdvkf00.cafe24.com/SetClubChars.php',{ chars: clubChars[i], userNo: userNo }) .then(function (response) { ms = response.data.message; }); } } componentWillMount(){ BackHandler.addEventListener('hardwareBackPress', function () { return true }) this.setState({ text:'', chars:[], }) } clear = () => { this.setState({text:""}) } render() { return ( <> <DismissKeyboard> <View style={styles.container}> <KeyboardAvoidingView behavior="padding" keyboardVerticalOffset={Platform.OS=== 'ios' ? '200' : '10'} > <View style={styles.header} > {/* 제목 */} <View style={styles.title}> <Text style={styles.text_1}>특징선택</Text> <Text style={styles.text_2}>중복 선택 가능</Text> </View> </View> {/* 샾버튼 모아놓은거 */} {/* 위에 샾버튼 클릭했을 때 생긴 샾버튼 들어가는 곳 */} <View style={styles.contain}> <CharGoal chars={this.state.chars} removeChar={this.removeChar}/> </View> { this.state.count >= 10 ? <View style={styles.dd}></View> : <CharInput addChar={this.addChar} /> } {/* 완료버튼 */} <View style={styles.footer}> {(this.state.chars ==0 )?<ConfirmButtonN title={'선택완료'}/>:<ConfirmButton title={'선택완료'} onPress={this._ButtonPress} /> } </View> </KeyboardAvoidingView> </View> </DismissKeyboard> </> ); } } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', paddingTop: 10, padding:10, paddingBottom:10, backgroundColor: "white", }, header: { width:'100%', height:'50%', paddingTop:20 // backgroundColor: '#ff9a9a', }, title: { width:'100%', paddingTop: scale(10), flexDirection: "row", alignItems:"flex-end", // backgroundColor: '#9aa9ff', paddingLeft: 15 }, dd: { height:'5%' }, content: { // backgroundColor: '#d6ca1a', padding:15, paddingTop:30, flexDirection: "row", flexWrap: "wrap", paddingBottom:50 }, inputView:{ width:'100%', height:110, flexDirection: "column", alignItems: "flex-start", marginTop:30 }, footer: { flex:1, width:"100%", // backgroundColor: '#1ad657', paddingTop: 10, justifyContent: 'center', alignItems:'center' }, text_1: { fontSize: moderateScale(25), color:"#0A6EFF", marginRight:3 }, text_2: { fontSize: moderateScale(12), color: "#aaaaaa" }, selectView:{ flexDirection: "row", }, STBT:{ paddingLeft: 50, marginLeft:50, }, AB:{ backgroundColor:"red" }, contain:{ height:'25%', flexDirection: "row", flexWrap: "wrap", alignItems: "flex-end" } });<file_sep>import React, {Component} from 'react'; import {StyleSheet, Text, View, ScrollView, TouchableOpacity} from 'react-native'; import RecordFalse from '../components/RecordFalse'; import RecordTrue2 from '../components/RecordTrue2'; import { Header, Icon } from 'react-native-elements'; import MasonryList from "react-native-masonry-list"; import * as axios from 'axios'; export default class SignUpRecord extends React.Component { constructor(props){ super(props); this.state={ records:[], }; this.props.navigation.addListener('didFocus', () => { this._getDatas() }); } componentWillMount = () => { this._getDatas(); }; // 이미지들 가져오기 _getDatas = () => { //userNo 가지고 오기 const { navigation } = this.props; const {records} = this.state; var userNo = navigation.getParam('userNo', 'NO-ID'); // console.log(userNo); // var userNo = 27; const t = this; // 데이터 가져오기 axios.post('http://dkstkdvkf00.cafe24.com/GetImages.php',{ userNo:userNo, }) .then((result) => { // t._setDatas(response); const response = result.data; var recordArray = new Array(); response.forEach(row => { recordArray.push({ uri : row.recordPicture}); }); t.setState({ records: records.concat(recordArray) }); }); } _RecordRegister = item => { this.props.navigation.navigate('RecordRegister', { item: item.uri, userNo: this.props.userNo }) } render() { const { navigation } = this.props; var userNo = navigation.getParam('userNo', 'NO-ID'); const {records} = this.state; // console.log(userNo) return ( <> <View style={styles.container}> <Icon raised reverse name='plus' type='entypo' color='#2eaeff' containerStyle={{ position: 'absolute', bottom:100, right: 10, zIndex:999 }} onPress={() => this.props.navigation.navigate('RecordRegister',{ userNo: userNo })} /> {/* 사진들 들어갈 곳 */} <MasonryList imageContainerStyle={{borderRadius:17, right:12}} spacing={7} images={records} onPressImage = {(item, index) => { this._RecordRegister(item) }} /> {/* 완료버튼 */} <View style={styles.footer}> {/* true면 <RecordTrue /> false면 <RecordFalse /> */} <TouchableOpacity style={styles.true} onPress={() => this.props.navigation.navigate('Main')} > <Text style={styles.text1}>완료</Text> </TouchableOpacity> </View> </View> </> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor:'#fff' }, header:{ width:'100%', height:70, // backgroundColor:'#A0AFFF', flexDirection:"row", justifyContent: "flex-end" }, content:{ flex: 1 }, footer:{ width: '100%', height: 70, // backgroundColor: '#5CEEE6', borderTopWidth:1 }, button:{ backgroundColor: '#0064FF', width:50, height:50, marginTop:10, alignItems: 'center', justifyContent: 'center', marginRight: 20, borderRadius: 50 }, text:{ fontSize: 25, color: '#fff' }, true:{ flex:1, backgroundColor:'#1478FF', alignItems:'center', justifyContent: 'center' }, text1:{ fontSize:25, color:'#fff', fontWeight:'700' } });<file_sep>import React, {Component} from 'react'; import {StyleSheet, Text, View, TextInput, ScrollView, TouchableOpacity, Button, image, Image} from 'react-native'; import ConfirmButton from '../components/ConfirmButton'; import ClubPicker from '../components/ClubPicker'; import ConfirmButtonN from '../components/ConfirmButtonN'; import { Avatar } from 'react-native-elements'; import * as axios from 'axios'; import { ImagePicker, Constants, Permissions } from 'expo'; import { scale, moderateScale, verticalScale} from '../components/Scaling'; export default class SignUp extends Component { static navigationOptions = { header : null, }; constructor(props){ super(props); this.state={ clubName:'', clubKind:'예술 공연', clubWellcome:'', clubPhoneNumber:'', clubIntroduce:'', clubMainPicture: null, userNo:'', clubLogo: null, }; } myCallback = (dataFromChild) => { this.setState({ clubKind: dataFromChild }); } //테두리 색변경 효과 state = { isFocused: false, isFocused1: false, isFocused2: false, isFocused3: false } handleFocus = () => this.setState({isFocused: true}) handleBlur = () => this.setState({isFocused: false}) handleFocus1 = () => this.setState({isFocused1: true}) handleBlur1 = () => this.setState({isFocused1: false}) handleFocus2 = () => this.setState({isFocused2: true}) handleBlur2 = () => this.setState({isFocused2: false}) handleFocus3 = () => this.setState({isFocused3: true}) handleBlur3 = () => this.setState({isFocused3: false}) render() { let { clubLogo, clubMainPicture } = this.state; return ( <> <ScrollView> <View style={styles.container}> <Text style={styles.blank}>ㅁㅁㅁㅁ</Text> <View style={styles.block}> <Text style={[styles.text,{ color: this.state.isFocused ? '#000000' : '#8d97a5', }]} >동아리 이름</Text> <TextInput onFocus={this.handleFocus} onBlur={this.state.clubName.length==0?this.handleBlur:null} style={[styles.input,{ borderColor: this.state.isFocused ? '#8ad1ff' : '#dbf1ff', borderWidth: 1, }]} onChangeText={(clubName) => this.setState({clubName})} maxLength={20} /> </View> <View style={styles.block}> <Text style={styles.text}>동아리 종류</Text> <View style={{width:160,}}> <ClubPicker callbackFromParent={this.myCallback} /> </View> </View> <View style={styles.block}> <Text style={[styles.text,{ color: this.state.isFocused1 ? '#000000' : '#8d97a5', }]} >동아리 소개</Text> <TextInput onFocus={this.handleFocus1} onBlur={this.state.clubIntroduce.length==0?this.handleBlur1:null} style={[styles.input, styles.introduce,{ borderColor: this.state.isFocused1 ? '#8ad1ff' : '#dbf1ff', borderWidth: 1, }]} multiline={true} onChangeText={(clubIntroduce) => this.setState({clubIntroduce})} maxLength={100} /> </View> <View style={styles.block}> <Text style={[styles.text,{ color: this.state.isFocused2 ? '#000000' : '#8d97a5', }]} >이런 신입생 와라</Text> <TextInput onFocus={this.handleFocus2} onBlur={this.state.clubWellcome.length==0?this.handleBlur2:null} style={[styles.input, styles.introduce,{ borderColor: this.state.isFocused2 ? '#8ad1ff' : '#dbf1ffed', borderWidth: 1, }]} multiline={true} onChangeText={(clubWellcome) => this.setState({clubWellcome})} placeholder={"ex. 상큼한 새내기들 환영"} placeholderTextColor={"#d1d1d1"} maxLength={100} /> </View> <View style={styles.block}> <Text style={[styles.text,{ color: this.state.isFocused3 ? '#000000' : '#8d97a5', }]} >연락 가능 연락처</Text> <TextInput onFocus={this.handleFocus3} onBlur={this.state.clubPhoneNumber.length==0?this.handleBlur3:null} style={[styles.input,{ borderColor: this.state.isFocused3 ? '#8ad1ff' : '#dbf1ffed', borderWidth: 1, }]} multiline={true} onChangeText={(clubPhoneNumber) => this.setState({clubPhoneNumber})} maxLength={100} /> </View> <View style={styles.block}> <Text style={styles.text}>동아리 로고</Text> <TouchableOpacity style={{alignItems :'center'}} onPress={this._pickLogo}> { clubLogo === null ? <Image source={require('../images/logoEdit.png')} style={{ width: 100, height: 100, alignItems :'center',flex:1, marginTop:20 }} /> : clubLogo && <Image source={{ uri: clubLogo }} style={{ width: 100, height: 100 }} /> } </TouchableOpacity> </View> <View style={styles.block}> <Text style={styles.text}>동아리 메인사진</Text> <TouchableOpacity style={{alignItems :'center'}} onPress={this._pickMainPicture}> { clubMainPicture === null ? <Image source={require('../images/pictureEdit.png')} style={{ width:moderateScale(210), height:verticalScale(160), marginTop:20 }} /> : clubMainPicture && <Image source={{ uri: clubMainPicture }} style={{width:moderateScale(210), height:verticalScale(160), marginTop:20 }} /> } </TouchableOpacity> </View> <View style={styles.button}> {(this.state.clubName.length==0 && this.state.clubWellcome.length==0 && this.state.clubPhoneNumber.length==0) ? <ConfirmButtonN title={'확인'}/> : <ConfirmButton title={'확인'} onPress={() => this._insertRegister()}/> } </View> </View> </ScrollView> </> ); } // 로고 가져오기 _pickLogo = async () => { const permissions = Permissions.CAMERA_ROLL; const { status } = await Permissions.askAsync(permissions); console.log(permissions, status); if(status === 'granted') { let result = await ImagePicker.launchImageLibraryAsync({ allowsEditing: true, aspect: [4, 3], }); if (!result.cancelled) { this.setState({ clubLogo: result.uri }); } } } // 메인사진 가져오기 _pickMainPicture = async () => { const permissions = Permissions.CAMERA_ROLL; const { status } = await Permissions.askAsync(permissions); console.log(permissions, status); if(status === 'granted') { let result = await ImagePicker.launchImageLibraryAsync({ allowsEditing: true, aspect: [4, 3], }); console.log(result); if (!result.cancelled) { this.setState({ clubMainPicture: result.uri }); } } } _pickImage = async () => { let result = await ImagePicker.launchImageLibraryAsync({ allowsEditing: true, aspect: [4, 3], }); console.log(result); if (!result.cancelled) { this.setState({ image: result.uri }); } }; _userNo = userNo => { this.setState({ userNo: userNo }); }; _insertRegister = () => { //userNo 가지고 오기 const { navigation } = this.props; var getUserNo = navigation.getParam('userNo', 'NO-ID'); var getSchool = navigation.getParam('school', 'NO-ID'); getUserNo = getUserNo.replace(/[^0-9]/g,''); getSchool = getSchool.substring(1, getSchool.length-1); const {clubName, clubKind, clubWellcome, clubPhoneNumber, clubIntroduce, clubLogo, clubMainPicture} = this.state; // 데이터베이스에 넣기 axios.post('http://dkstkdvkf00.cafe24.com/UserRegister.php',{ clubName:clubName, clubKind:clubKind, clubWellcome:clubWellcome, clubPhoneNumber:clubPhoneNumber, clubIntroduce:clubIntroduce, clubLogo:clubLogo, clubMainPicture:clubMainPicture, userNo:getUserNo, school:getSchool, }) .then(function (response) { ms = response.data.message; }); this.props.navigation.navigate('CharChoice', { userNo: getUserNo }) } } const styles = StyleSheet.create({ container: { flex: 1, padding: 25, backgroundColor: 'white', }, input: { borderRadius:8, width:'100%', padding: 7, borderColor: "#32B8FF", borderWidth: 1, fontSize: 17, marginTop: 5 }, text: { fontSize: 13 }, toDos: { alignItems: "center" }, block: { paddingBottom: 30 }, introduce: { height: 120 }, button: { height:60, marginTop:30 }, blank: { fontSize: 40, color:'white' } }); <file_sep>import React from 'react'; import { Button, View, Text,StatusBar } from 'react-native'; import { createAppContainer, createStackNavigator } from 'react-navigation'; import Main from './src/Main'; import codeConfirm from './src/codeConfirm'; import PhoneNumber from './src/PhoneNumber'; import SignUp from './src/SignUp'; import CharChoice from './src/CharChoice'; import SignUpRecord from './src/SignUpRecord'; import RecordRegister from './src/RecordRegister'; import FindClub from './src/FindClub'; import InputSchool from './src/InputSchool'; import ClubSearch from './src/ClubSearch'; import ClubIntroduce from './src/ClubIntroduce'; import ClubFix from './src/ClubFix'; import RecordPictures from './src/RecordPictures'; import SchoolChoice from './src/SchoolChoice'; import ClubModify from './src/ClubModify'; import ModifySignUp from './src/ModifySignUp'; import ModifyChar from './src/ModifyChar'; import ModifyRecord from './src/ModifyRecord'; import Record from './src/Record'; import SignUpRecord2 from './src/SignUpRecord2'; const RootStack = createStackNavigator( { Main: { screen: Main, }, codeConfirm: { screen: codeConfirm, }, PhoneNumber: { screen: PhoneNumber, }, SignUp: { screen: SignUp, }, CharChoice: { screen: CharChoice, }, SignUpRecord: { screen: SignUpRecord, }, RecordRegister: { screen: RecordRegister, }, FindClub: { screen: FindClub, }, InputSchool: { screen: InputSchool, }, ClubSearch: { screen: ClubSearch, }, ClubIntroduce: { screen: ClubIntroduce, }, ClubFix: { screen: ClubFix, }, RecordPictures: { screen: RecordPictures, }, SchoolChoice: { screen: SchoolChoice, }, ClubModify: { screen: ClubModify, }, ModifySignUp: { screen: ModifySignUp, }, ModifyChar: { screen: ModifyChar, }, ModifyRecord: { screen: ModifyRecord, }, Record: { screen: Record, }, SignUpRecord2: { screen: SignUpRecord2, } }, { initialRouteName: 'ClubIntroduce', }, ); const AppContainer = createAppContainer(RootStack); export default class App extends React.Component { render() { return ( <> <AppContainer /> <StatusBar barStyle = "dark-content" // dark-content, light-content and default hidden = {false} //To hide statusBar backgroundColor = "white" //Background color of statusBar only works for Android translucent = {false} //allowing light, but not detailed shapes networkActivityIndicatorVisible = {true} /> </> ) } }<file_sep>import React, {Component} from 'react'; import {StyleSheet, Text, View, TextInput, ScrollView, TouchableOpacity, Image, image, Button} from 'react-native'; import ConfirmButton from '../components/ConfirmButton'; import ClubPicker from '../components/ClubPicker'; import ConfirmButtonN from '../components/ConfirmButtonN'; import { Avatar } from 'react-native-elements'; import * as axios from 'axios'; import { ImagePicker, Constants, Permissions } from 'expo'; export default class ModifySignUp extends Component { static navigationOptions = { header : null, }; constructor(props){ super(props); this.state={ clubName:'', clubKind:'', clubWellcome:'', clubPhoneNumber:'', clubIntroduce:'', clubLogo:null, clubMainPicture:null, userNo:'', }; } componentWillMount = () => { this._getDatas(); }; render() { let { clubLogo, clubMainPicture } = this.state; console.log(clubMainPicture); return ( <View style={styles.container}> <Text style={styles.blank}>ㅁㅁㅁㅁ</Text> <ScrollView> <View style={styles.block}> <Text style={styles.text}>동아리 이름</Text> <TextInput style={styles.input} onChangeText={(clubName) => this.setState({clubName})} maxLength={20} value={this.state.clubName} /> </View> <View style={styles.block}> <Text style={styles.text}>동아리 종류</Text> <View style={{width:160,}}> <ClubPicker /> </View> </View> <View style={styles.block}> <Text style={styles.text}>이런 신입생 와라</Text> <TextInput style={[styles.input, styles.introduce]} multiline={true} onChangeText={(clubWellcome) => this.setState({clubWellcome})} placeholder={"ex. 상큼한 새내기들 환영"} placeholderTextColor={"#d1d1d1"} maxLength={100} value={this.state.clubWellcome} /> </View> <View style={styles.block}> <Text style={styles.text}>연락 가능 연락처</Text> <TextInput style={[styles.input, styles.introduce]} multiline={true} onChangeText={(clubPhoneNumber) => this.setState({clubPhoneNumber})} maxLength={100} value={this.state.clubPhoneNumber} /> </View> <View style={styles.block}> <Text style={styles.text}>동아리 소개</Text> <TextInput style={[styles.input, styles.introduce]} multiline={true} onChangeText={(clubIntroduce) => this.setState({clubIntroduce})} maxLength={100} value={this.state.clubIntroduce} /> </View> <View style={styles.block}> <Text style={styles.text}>동아리 로고</Text> <TouchableOpacity onPress={this._pickLogo}> { clubLogo === null ? <Avatar size="large" icon={{ name: 'questioncircle' }} containerStyle={{flex: 1, marginTop:20, width:'100%'}} showEditButton /> : {clubLogo} && <Image source={{ uri: clubLogo }} style={{ width: 100, height: 100 }} /> } </TouchableOpacity> </View> <View style={styles.block}> <Text style={styles.text}>동아리 메인사진</Text> <TouchableOpacity onPress={this._pickMainPicture}> { clubMainPicture === null ? <Avatar size="large" icon={{ name: 'questioncircle' }} containerStyle={{flex: 1, marginTop:20, width:'100%'}} showEditButton /> : {clubMainPicture} && <Image source={{ uri: clubMainPicture }} style={{ width: '100%', height: 100 }} /> } </TouchableOpacity> </View> <View style={styles.button}> {(this.state.clubName.length==0 && this.state.clubWellcome.length==0 && this.state.clubPhoneNumber.length==0) ? <ConfirmButtonN title={'확인'}/> : <ConfirmButton title={'확인'} onPress={() => this._updatRegister()}/> } </View> </ScrollView> </View> ); } // 로고 가져오기 _pickLogo = async () => { const permissions = Permissions.CAMERA_ROLL; const { status } = await Permissions.askAsync(permissions); console.log(permissions, status); if(status === 'granted') { let result = await ImagePicker.launchImageLibraryAsync({ allowsEditing: true, aspect: [4, 3], }); console.log(result); if (!result.cancelled) { this.setState({ clubLogo: result.uri }); } } } // 메인사진 가져오기 _pickMainPicture = async () => { const permissions = Permissions.CAMERA_ROLL; const { status } = await Permissions.askAsync(permissions); console.log(permissions, status); if(status === 'granted') { let result = await ImagePicker.launchImageLibraryAsync({ allowsEditing: true, aspect: [4, 3], }); console.log(result); if (!result.cancelled) { this.setState({ clubMainPicture: result.uri }); } } } // 데이터 가져오는 함수 _getDatas = () => { //userNo 가지고 오기 const { navigation } = this.props; var userNo = navigation.getParam('userNo', 'NO-ID'); const t = this; // 데이터 가져오기 axios.post('http://dkstkdvkf00.cafe24.com/GetRegister.php',{ userNo:userNo, }) .then(function (response) { // clubName = tt.subString(1,tt.length-1); t._setDatas(response); var str = JSON.stringify(response.data.message.clubName);; var clubName = str.substring(1, str.length-1); t.setState({ clubName: clubName }); var str = JSON.stringify(response.data.message.clubWellcome);; var clubWellcome = str.substring(1, str.length-1); t.setState({ clubWellcome: clubWellcome }); }); } // 데이터 넣기 _setDatas = response => { var str = JSON.stringify(response.data.message.clubName);; var clubName = str.substring(1, str.length-1); this.setState({ clubName: clubName }); var str = JSON.stringify(response.data.message.clubWellcome);; var clubWellcome = str.substring(1, str.length-1); this.setState({ clubWellcome: clubWellcome }); var str = JSON.stringify(response.data.message.clubPhoneNumber);; var clubPhoneNumber = str.substring(1, str.length-1); this.setState({ clubPhoneNumber: clubPhoneNumber }); var str = JSON.stringify(response.data.message.clubIntroduce);; var clubIntroduce = str.substring(1, str.length-1); this.setState({ clubIntroduce: clubIntroduce }); var str = JSON.stringify(response.data.message.clubLogo);; var clubLogo = str.substring(1, str.length-1); this.setState({ clubLogo: clubLogo }); var str = JSON.stringify(response.data.message.clubMainPicture);; var clubMainPicture = str.substring(1, str.length-1); this.setState({ clubMainPicture: clubMainPicture }); } // 정보 수정 함수 _updatRegister = () => { //userNo 가지고 오기 const { navigation } = this.props; var userNo = navigation.getParam('userNo', 'NO-ID'); const {clubName, clubKind, clubWellcome, clubPhoneNumber, clubIntroduce, clubLogo, clubMainPicture} = this.state; // 데이터베이스에 넣기 axios.post('http://dkstkdvkf00.cafe24.com/ModifySignUp.php',{ clubName:clubName, clubKind:clubKind, clubWellcome:clubWellcome, clubPhoneNumber:clubPhoneNumber, clubIntroduce:clubIntroduce, clubLogo:clubLogo, clubMainPicture:clubMainPicture, userNo:userNo, }) .then(function (response) { ms = response.data.message; }); this.props.navigation.navigate('Main') } } const styles = StyleSheet.create({ container: { flex: 1, padding: 25, backgroundColor: 'white', }, input: { width:'100%', padding: 7, borderColor: "#32B8FF", borderWidth: 1, fontSize: 17, marginTop: 5 }, text: { fontSize: 13 }, toDos: { alignItems: "center" }, block: { paddingBottom: 30 }, introduce: { height: 120 }, button: { height:60, marginTop:30 }, blank: { fontSize: 40, color:'white' } }); <file_sep>import React, {Component} from 'react'; import {StyleSheet, Text, View, ScrollView} from 'react-native'; import Picture from '../components/Picture'; import * as axios from 'axios'; export default class RecordPictures extends React.Component { constructor(props){ super(props); this.state={ recordName:'', recordContent:'', picture: null, }; } componentWillMount = () => { this._getDatas() } _getDatas = () => { const { navigation } = this.props; var picture = navigation.getParam('picture', 'NO-ID'); const t = this; this.setState({picture: picture}) // 데이터 가져오기 axios.post('http://dkstkdvkf00.cafe24.com/GetRecordPicture.php',{ recordPicture:picture, }) .then(function (response) { t._setDatas(response); }); } _setDatas = response => { var str = JSON.stringify(response.data.message.recordName);; var recordName = str.substring(1, str.length-1); this.setState({ recordName: recordName }); var str = JSON.stringify(response.data.message.recordContent);; var recordContent = str.substring(1, str.length-1); this.setState({ recordContent: recordContent }); } render() { const {recordName, recordContent, picture} = this.state; return ( <ScrollView style={styles.container}> {/* 제목부분 */} <View style={styles.header}> <Text style={styles.title}>{recordName}</Text> </View> {/* 회색부분 */} <Picture picture={picture} text={recordContent}/> </ScrollView> ); } } const styles = StyleSheet.create({ container: { flex: 1, padding: 15, backgroundColor: 'white', }, header: { width:'100%', height:40, backgroundColor: '#3296FF', borderRadius:10, justifyContent: 'center', alignItems: 'center', marginBottom:15 }, title: { fontSize: 23, color: '#fff' }, });
daaa20f9e8e772634591abe88efb4749d1d76e7f
[ "JavaScript" ]
15
JavaScript
sangeunAhn/dLite_Prototype
5594ab3cd7649bb61bf4316d288df0eee252536a
026f6a74e680e2a219c529f112a8f68144fbf3db
refs/heads/master
<repo_name>drawwithcode/2019-09-DoksaVPC<file_sep>/sketch_start.js //variable for the start button var startButton; function setup() { frameRate(12); createCanvas(windowWidth, windowHeight); //creating the button startButton = createButton("DONE"); } function draw() { background("RosyBrown"); //drawing welcome text textAlign(CENTER); textSize(20); text("Please, be sure you turned OFF", width / 2, height / 3.8); text("the auto-rotate setting of your device", width / 2, height / 3); text("before starting.", width / 2, height / 2.5); //setting the button's position and on touch event startButton.position(width / 2 - 100, height / 2); startButton.touchEnded(startGame); } // prevent dragging the screen function touchMoved() { return false; } //sending a request permission to detect the device orientation on ios function touchStarted(event) { DeviceOrientationEvent.requestPermission(); } //opens the game's page function startGame() { window.open("ketchup.html", "_self"); } //resizes the canvas when the window is resized function windowResized() { resizeCanvas(windowWidth, windowHeight); } <file_sep>/sketch_ketchup.js //variable for the img of the bottle var bottle; //variable for the img of the top of the bottle var bottleTop; //variable for the img of the opening part of the top var bottleTopOpen; //array that contains all the drops of ketchup created when pouring it var allTheDrops = []; function setup() { frameRate(12); createCanvas(windowWidth, windowHeight); angleMode(DEGREES); ellipseMode(CENTER); //creating an img element for each section of the ketchup bottle bottle = createImg("./assets/bottle.svg", "bottle"); bottleTop = createImg("./assets/top.svg", "top"); bottleTopOpen = createImg("./assets/top_open.svg", "top open"); } function draw() { background("RosyBrown"); //setting height and width of the image for the main part of the bottle according to the window height. These two sizes will be used as units of measure for the size of the other elements too var bottleHeight = height * 0.6; var bottleWidth = bottleHeight * 0.6; //styling and positioning the images bottle.style("height", bottleHeight + "px"); bottleTop.style("width", bottleWidth * 0.8 + "px"); bottleTopOpen.style("width", bottleWidth * 0.8 + "px"); //setting a transform-origin to the upper part of the top to rotate it around a choosen corner bottleTopOpen.style("transform-origin", "3% 40%"); bottle.position(width / 2 - bottleWidth / 2, height - bottleHeight - 10); bottleTop.position(width / 2 - (bottleWidth * 0.8) / 2, height / 4 - 10); bottleTopOpen.position(width / 2 - (bottleWidth * 0.8) / 2, height / 4 - 10); //displaying and moving all the existing drops of ketchup for (var i = 0; i < allTheDrops.length; i++) { allTheDrops[i].display(); allTheDrops[i].drop(); } //opening the top when the smartphone is flipped if (rotationZ > 130 && rotationZ < 220) { openTop(); } } // prevent dragging the screen function touchMoved() { return false; } //sending a request permission to detect the device orientation on ios function touchEnded(event) { DeviceOrientationEvent.requestPermission(); } //resizes the canvas when the window is resized function windowResized() { resizeCanvas(windowWidth, windowHeight); } //opens the top if it isn't already open function openTop() { if (bottleTopOpen.hasClass("topOpen") === false) { bottleTopOpen.toggleClass("topOpen"); } } //creates a new drop with slightly random size and x-position, then adds it in allTheDrops array function pour() { if (bottleTopOpen.hasClass("topOpen") === true) { var ketchupDrop = new KetchupDrop((height / 30) * random(1, 1.5), random(0, 4)); allTheDrops.push(ketchupDrop); } } //calls the pour function when the device is shaken function deviceShaken() { pour(); } //constructor for the ketchup drop object function KetchupDrop(_size, _xOffset) { this.x = width / 2 -2 + _xOffset; this.y = height / 3; this.size = _size; this.display = function() { noStroke(); fill(144, 18, 13); ellipse(this.x, this.y, _size); }; this.drop = function() { this.y -= 15; }; }
6d4f61c80a96ec72e67d0d8c5893d03aac27f1ba
[ "JavaScript" ]
2
JavaScript
drawwithcode/2019-09-DoksaVPC
3568ce0033d7cc22ae826720d5c767f369744280
f0c7a6c91aa3b6701d9b1f212c435dc73729bf73
refs/heads/master
<repo_name>izelnakri/bookshelf<file_sep>/index.js var express = require('express'); var pug = require('pug'); var fs = require('fs'); var app = express(); var dataInMemory = JSON.parse(fs.readFileSync('data.json').toString())['books']; function findBook(slug) { // iterate through the slugs in the array of object // if the iterated object holds the same slug as the parameter of this function return the object for (var i = 0; i < dataInMemory.length; i++) { if (dataInMemory[i].slug === slug) { return dataInMemory[i]; } } } // lets us access files inside the public folder via http: app.use(express.static('public')); app.get('/', function(request, response) { response.redirect('/books'); }); app.get('/books', function(req, res) { console.log('Requesting /books'); res.send(pug.renderFile('views/index.pug', { books: dataInMemory })); }); app.get('/books/*', function(req, res) { var foundBook = findBook(req.params[0]); res.send(pug.renderFile('views/book.pug', { book: foundBook })); }); app.listen(3001, function() { console.log('Web server is now running on port 3001'); });
bfdc95c30f361201c79a608321a4c5ad67695a89
[ "JavaScript" ]
1
JavaScript
izelnakri/bookshelf
ea6845fddaa6d286769a73edf8cc0f43894fe282
829c5407d5ed5e456ecd8947c9dcdb9c223737aa
refs/heads/main
<file_sep>const stringName="<NAME>"; console.log(stringName.length);
5d8c3e58cd3deff5d0cdc90c56af0b31485cd9c1
[ "JavaScript" ]
1
JavaScript
masum-diucse/string-method
afe172e6c5c0597f23373e8725f3917df60de6cd
1d07809e93fc6edad8ada3d92a803277f207a2e7
refs/heads/master
<file_sep># vue-transition-demo 一些 Vue 官方的 tarnsition 组件案例,以及和第三方库结合的使用方式。 <file_sep># 第一次关联两个仓库 git init git add . git commit -m "first commit" git remote add github <EMAIL>:uphg/vue-transition-demo.git git remote add gitee <EMAIL>:uphg/vue-transition-demo.git git push github master:master git push gitee master:master <file_sep>#!/usr/bin/env sh set -e yarn build cd dist git init git add -A git commit -m 'deploy' git push -f <EMAIL>:uphg/vue-transition-demo.git master:gh-pages git push -f <EMAIL>:uphg/vue-transition-demo.git master:gh-pages cd -
e98097346c30ae97a7c37fb76dbc95acffe58691
[ "Markdown", "Shell" ]
3
Markdown
uphg/vue-transition-demo
a9853c14f09edb66cf85a001c3d121339e75df81
d4df28363278eb30acb6f41c5b1c0075bf577b4a
refs/heads/master
<repo_name>pawel-prochniak/StateMachine<file_sep>/StateMachine.playground/Contents.swift import Foundation public class StateMachine<S: State, E: Event> { public typealias EventToState = (E, S) public private(set) var state: S private var eventsTransitions: [E : [Transition<S>]] = [:] private var conditionMappings: [EventToTransition<E, S> : Condition] = [:] private var handlers: [Transition<S>: Handler] = [:] let dispatchQueue: DispatchQueue public init(initialState: S, workQueue: DispatchQueue? = nil) { self.dispatchQueue = workQueue ?? DispatchQueue(label: "statemachine", qos: .background, attributes: .concurrent, autoreleaseFrequency: .workItem, target: nil) state = initialState } public func addTransition(_ eventToTransition: EventToTransition<E, S>, condition: Condition? = nil, handler: @escaping Handler) { addTransition(eventToTransition.transition, onEvent: eventToTransition.event, condition: condition, handler: handler) } public func addTransition(from: S, to: S, onEvent event: E, condition: Condition? = nil, handler: @escaping Handler) { addTransition(Transition(fromState: from, toState: to), onEvent: event, condition: condition, handler: handler) } public func addTransition(_ transition: Transition<S>, onEvent event: E, condition: Condition? = nil, handler: @escaping Handler) { if eventsTransitions[event] == nil { eventsTransitions[event] = [] } let conditionsKey = EventToTransition(event: event, transition: transition) guard conditionMappings[conditionsKey] == nil else { fatalError("\(transition) on event: \(event) - this transition is already defined") } conditionMappings[conditionsKey] = condition ?? { true } eventsTransitions[event]!.append(transition) handlers[transition] = handler } public func addTransitions(from: S, _ transitions: AvailableTransition<E, S>...) { transitions.forEach { addTransition(from: from, to: $0.to, onEvent: $0.event, condition: $0.condition, handler: $0.handler) } } public func addTransitions(start: S, @AvailableTransitionBuilder transitions: () -> [AvailableTransition<E, S>]) { transitions().forEach { addTransition(from: start, to: $0.to, onEvent: $0.event, condition: $0.condition, handler: $0.handler) } } private func findTransition(for event: E) -> Transition<S>? { guard let eventTransitions = eventsTransitions[event] else { return nil } return eventTransitions.first { let key = EventToTransition(event: event, transition: $0) return $0.fromState == self.state && (conditionMappings[key]?() ?? true ) } } public func event(_ event: E) -> Bool { guard let transition = findTransition(for: event) else { return false } if let handler = handlers[transition] { dispatchQueue.async { handler() } } self.state = transition.toState return true } @resultBuilder public struct AvailableTransitionBuilder { public static func buildBlock(_ components: AvailableTransition<E, S>...) -> [AvailableTransition<E, S>] { components } } } public struct AvailableTransition<E: Event, S: State> { let to: S let event: E let condition: Condition? let handler: Handler public init(_ to: S, _ event: E, _ condition: Condition? = nil, _ handler: @escaping Handler) { self.to = to self.event = event self.condition = condition self.handler = handler } public init(availableTransition: AvailableTransition<E,S>, _ handler: @escaping Handler) { self.to = availableTransition.to self.event = availableTransition.event self.condition = availableTransition.condition self.handler = handler } } public struct EventToTransition<E: Event, S: State>: Hashable { public let event: E public let transition: Transition<S> init(event: E, transition: Transition<S>) { self.event = event self.transition = transition } public func hash(into hasher: inout Hasher) { hasher.combine(event.hashValue) hasher.combine(transition.hashValue) } } public func ~> <S>(fromState: S, toState: S) -> Transition<S> { return Transition(fromState: fromState, toState: toState) } //infix operator ==> : MultiplicationPrecedence infix operator ==> : AdditionPrecedence public func ==> <S, E>(event: E, toState: S) -> AvailableTransition<E, S> { AvailableTransition(toState, event, nil) { } } infix operator ?! : AdditionPrecedence public func ?! <S, E>(eventToState: AvailableTransition<E, S>, condition: @escaping Condition) -> AvailableTransition<E, S> { AvailableTransition(eventToState.to, eventToState.event, condition) { } } //infix operator | : AdditionPrecedence public func | <E, S>(availableTransition: AvailableTransition<E, S>, handler: @escaping Handler) -> AvailableTransition<E, S> { AvailableTransition(availableTransition: availableTransition, handler) } public func ==> <E, S>(availableTransition: AvailableTransition<E, S>, handler: @escaping Handler) -> AvailableTransition<E, S> { AvailableTransition(availableTransition: availableTransition, handler) } enum TransferState: State { case start, fromSelection, toSelection, setAmount, confirm, complete } enum TransferEvent: Event { var payload: Any? { return nil } case onFromAccountChosen case onToAccountChosen case onChangeFromAccount case onChangeToAccount case onAmountSet case onConfirm } class TransferLogicController: CoordinatorDelegate { var from: String? var to: String? var amount: Double? var fromChosen: Bool { from != nil } var toChosen: Bool { to != nil } let machine = StateMachine<TransferState, TransferEvent>(initialState: .start) lazy var navigator = Coordinator(delegate: self) init() { configureStateMachine() } private func configureStateMachine() { machine.addTransitions(from: .start, .onFromAccountChosen ==> .toSelection | navigator.showToSelection, .onToAccountChosen ==> .fromSelection | navigator.showFromSelection ) machine.addTransitions(from: .toSelection, .onToAccountChosen ==> .setAmount ?! { self.fromChosen } | navigateToAmountSelection, .onToAccountChosen ==> .fromSelection ?! { !self.fromChosen } | navigator.showFromSelection ) machine.addTransitions(from: .fromSelection, .onFromAccountChosen ==> .setAmount ?! { self.toChosen } | navigateToAmountSelection, .onFromAccountChosen ==> .toSelection ?! { !self.toChosen } | navigator.showToSelection ) machine.addTransitions(from: .setAmount, .onAmountSet ==> .confirm | navigateToConfirm, .onChangeFromAccount ==> .fromSelection | navigator.showFromSelection, .onChangeToAccount ==> .toSelection | navigator.showToSelection ) machine.addTransitions(from: .confirm, .onConfirm ==> .complete | navigator.showSuccess ) } private func navigateToAmountSelection() { navigator.showAmountSelection(SelectAmountModel(from: from!, to: to!)) } private func navigateToConfirm() { navigator.showConfirm(ConfirmModel(from: from!, to: to!, amount: amount!)) } func onFromSelected(_ from: String) { self.from = from machine.event(.onFromAccountChosen) } func onToSelected(_ to: String) { self.to = to machine.event(.onToAccountChosen) } func onAmountSelected(_ amount: Double) { self.amount = amount machine.event(.onAmountSet) } func onConfirmTransfer() { machine.event(.onConfirm) } } let controller = TransferLogicController() controller.onFromSelected("From") // //var fromChosen = false //var toChosen = false //let machine = StateMachine<TransferState, TransferEvent>(initialState: .start) //machine.addTransition(.start ~> .toSelection, onEvent: .onFromAccountChosen) { // fromChosen = true // print("start->to") //} // //machine.addTransition(from: .start, to: .fromSelection, onEvent: .onToAccountChosen) { // toChosen = true // print("start->from") //} // ////machine.addTransition(from: .toSelection, //// to: .setAmount, //// onEvent: .onToAccountChosen, //// condition: { fromChosen }) { //// toChosen = true //// print("to->amount") ////} //// ////machine.addTransition(from: .toSelection, to: .fromSelection, onEvent: .onToAccountChosen, condition: { !fromChosen }) { //// toChosen = true //// print("to->from") ////} // //machine.addTransitions(from: .toSelection, // .onToAccountChosen ==> .setAmount ?! { print("onToAccountChosen: \(fromChosen)"); return fromChosen } // | { toChosen = true; print("to->amount") }, // .onToAccountChosen ==> .fromSelection ?! { print("onToAccountChosen: \(fromChosen)"); return !fromChosen } // | { toChosen = true; print("to->from") } //) // //machine.addTransition(from: .fromSelection, to: .setAmount, onEvent: .onFromAccountChosen, condition: { toChosen }) { // fromChosen = true // print("from->amount") //} // //machine.addTransition(from: .fromSelection, to: .toSelection, onEvent: .onFromAccountChosen, condition: { !toChosen }) { // fromChosen = true // print("from->amount") //} // //machine.addTransition(from: .setAmount, to: .fromSelection, onEvent: .onChangeFromAccount) { // print("amount->from") //} // //machine.addTransition(from: .setAmount, to: .toSelection, onEvent: .onChangeToAccount) { // print("amount->from") //} // //machine.addTransition(from: .setAmount, to: .confirm, onEvent: .onAmountSet) { // print("amount->confirm") //} // //machine.addTransition(from: .confirm, to: .complete, onEvent: .onConfirm) { // print("confirm->complete") //} // ////// to -> from -> amount -> confirm ////machine.event(.onToAccountChosen) ////machine.event(.onFromAccountChosen) ////machine.event(.onAmountSet) ////machine.event(.onConfirm) ////machine.state //// ////// from -> to -> amount -> confirm ////machine.event(.onFromAccountChosen) ////machine.event(.onToAccountChosen) ////machine.event(.onAmountSet) ////machine.event(.onConfirm) ////machine.state //// ////// to -> from -> amount -> from -> amount -> confirm ////machine.event(.onToAccountChosen) ////machine.event(.onFromAccountChosen) ////machine.event(.onChangeFromAccount) ////machine.event(.onFromAccountChosen) ////machine.event(.onAmountSet) ////machine.event(.onConfirm) ////machine.state // //// to -> from -> amount -> from -> amount -> confirm //machine.event(.onFromAccountChosen) //machine.event(.onToAccountChosen) //machine.event(.onChangeToAccount) //machine.event(.onToAccountChosen) //machine.event(.onAmountSet) //machine.event(.onConfirm) //machine.state <file_sep>/StateMachine.playground/Sources/Coordinator.swift import Foundation public protocol TransferStateModel { } public class Empty: TransferStateModel { public init() {} } public struct SelectAmountModel: TransferStateModel { let from: String let to: String public init(from: String, to: String) { self.from = from self.to = to } } public struct ConfirmModel: TransferStateModel { let from: String let to: String let amount: Double public init(from: String, to: String, amount: Double) { self.from = from self.to = to self.amount = amount } } public protocol CoordinatorDelegate { func onFromSelected(_ from: String) func onToSelected(_ to: String) func onAmountSelected(_ amount: Double) func onConfirmTransfer() } public class Coordinator { private let delegate: CoordinatorDelegate public init(delegate: CoordinatorDelegate) { self.delegate = delegate } public func showFromSelection() { delegate.onFromSelected("From") } public func showToSelection() { delegate.onToSelected("To") } public func showAmountSelection(_ model: SelectAmountModel) { delegate.onAmountSelected(10.0) } public func showConfirm(_ model: ConfirmModel) { delegate.onConfirmTransfer() } public func showSuccess() { print("Success") } } <file_sep>/StateMachine.playground/Sources/Graveyard.swift import Foundation //@StateMachine<TransferState, TransferEvent>.AvailableTransitionBuilder var transitions: [AvailableTransition<TransferEvent, TransferState>] { // AvailableTransition<TransferEvent, TransferState>(.toSelection, .onFromAccountChosen, nil, { // fromChosen = true // print("start->to") // }) // AvailableTransition<TransferEvent, TransferState>(.toSelection, .onFromAccountChosen, nil, { // fromChosen = true // print("start->to") // }) //} // ////// resultBuilder //machine.addTransitions(start: .start) { // .onFromAccountChosen ==> .toSelection //// { //// fromChosen = true //// print("start->to") //// } // .init(.fromSelection, .onToAccountChosen, nil, { // toChosen = true // print("start->to") // }) //} //// AvailableTransition<E, S>... //machine.addTransitions(from: .start, // .init(.toSelection, // .onFromAccountChosen) { // fromChosen = true // print("start->to") // }, // .init(.fromSelection, // .onToAccountChosen) { // toChosen = true // print("start->from") // } //) //machine.addTransition(from: .start, // .onToAccountChosen ==> .fromSelection ~! { true } //// { // toChosen = true // print("start->from") //} //) // // //var fromChosen = false //var toChosen = false //let machine = StateMachine<TransferState, TransferEvent>(initialState: .start) //machine.addTransition(.start ~> .toSelection, onEvent: .onFromAccountChosen) { // fromChosen = true // print("start->to") //} // //machine.addTransition(from: .start, // to: .fromSelection, // onEvent: .onToAccountChosen) { // toChosen = true // print("start->from") //} // //machine.addTransition(from: .start, // to: .toSelection, // onEvent: .onFromAccountChosen) { // toChosen = true // print("start->from") //} // //machine.addTransition(from: .toSelection, // to: .setAmount, // onEvent: .onToAccountChosen, // condition: { fromChosen }) { // toChosen = true // print("to->amount") //} // //machine.addTransition(from: .toSelection, to: .fromSelection, onEvent: .onToAccountChosen, condition: { !fromChosen }) { // toChosen = true // print("to->from") //} // //machine.addTransition(from: .fromSelection, to: .setAmount, onEvent: .onFromAccountChosen, condition: { toChosen }) { // fromChosen = true // print("from->amount") //} // //machine.addTransition(from: .fromSelection, to: .toSelection, onEvent: .onFromAccountChosen, condition: { !toChosen }) { // fromChosen = true // print("from->amount") //} // //machine.addTransition(from: .setAmount, to: .fromSelection, onEvent: .onChangeFromAccount) { // print("amount->from") //} // //machine.addTransition(from: .setAmount, to: .toSelection, onEvent: .onChangeToAccount) { // print("amount->from") //} // //machine.addTransition(from: .setAmount, to: .confirm, onEvent: .onAmountSet) { // print("amount->confirm") //} // //machine.addTransition(from: .confirm, to: .complete, onEvent: .onConfirm) { // print("confirm->complete") //} // //// to -> from -> amount -> confirm //machine.event(.onToAccountChosen) //machine.event(.onFromAccountChosen) //machine.event(.onAmountSet) //machine.event(.onConfirm) //machine.state //// from -> to -> amount -> confirm //machine.event(.onFromAccountChosen) //machine.event(.onToAccountChosen) //machine.event(.onAmountSet) //machine.event(.onConfirm) //machine.state // //// to -> from -> amount -> from -> amount -> confirm //machine.event(.onToAccountChosen) //machine.event(.onFromAccountChosen) //machine.event(.onChangeFromAccount) //machine.event(.onFromAccountChosen) //machine.event(.onAmountSet) //machine.event(.onConfirm) //machine.state //// to -> from -> amount -> from -> amount -> confirm //machine.event(.onFromAccountChosen) //machine.event(.onToAccountChosen) //machine.event(.onChangeToAccount) //machine.event(.onToAccountChosen) //machine.event(.onAmountSet) //machine.event(.onConfirm) //machine.state <file_sep>/StateMachine.playground/Sources/StateMachine.swift public protocol State: Hashable {} public protocol Event: Hashable { var payload: Any? { get } } public struct Transition<S: State>: Hashable { public let fromState: S public let toState: S public init(fromState: S, toState: S) { self.fromState = fromState self.toState = toState } public static func == (lhs: Transition<S>, rhs: Transition<S>) -> Bool { lhs.fromState == rhs.fromState && lhs.toState == rhs.toState } public func hash(into hasher: inout Hasher) { hasher.combine(fromState.hashValue) hasher.combine(toState.hashValue) } } extension Transition: CustomStringConvertible { public var description: String { "Transition \(fromState) -> \(toState)" } } public typealias Handler = () -> Void public typealias Condition = () -> Bool //public class StateMachine<S: State, E: Event> { // public typealias EventToState = (E, S) // public private(set) var state: S // private var eventsTransitions: [E : [Transition<S>]] = [:] // private var conditionMappings: [EventToTransition<E, S> : Condition] = [:] // private var handlers: [Transition<S>: Handler] = [:] // // public init(initialState: S) { // state = initialState // } // // public func addTransition(_ eventToTransition: EventToTransition<E, S>, condition: Condition? = nil, handler: @escaping Handler) { // addTransition(eventToTransition.transition, onEvent: eventToTransition.event, condition: condition, handler: handler) // } // // public func addTransition(from: S, to: S, onEvent event: E, condition: Condition? = nil, handler: @escaping Handler) { // addTransition(Transition(fromState: from, toState: to), onEvent: event, condition: condition, handler: handler) // } // // public func addTransition(_ transition: Transition<S>, onEvent event: E, condition: Condition? = nil, handler: @escaping Handler) { // if eventsTransitions[event] == nil { // eventsTransitions[event] = [] // } // let conditionsKey = EventToTransition(event: event, transition: transition) // guard conditionMappings[conditionsKey] == nil else { // fatalError("\(transition) on event: \(event) - this transition is already defined") // } // conditionMappings[conditionsKey] = condition ?? { true } // eventsTransitions[event]!.append(transition) // handlers[transition] = handler // } // // public func addTransitions(from: S, _ transitions: AvailableTransition<E, S>...) { // transitions.forEach { // addTransition(from: from, to: $0.to, onEvent: $0.event, condition: $0.condition, handler: $0.handler) // } // } // // public func addTransitions(start: S, @AvailableTransitionBuilder transitions: () -> [AvailableTransition<E, S>]) { // transitions().forEach { // addTransition(from: start, to: $0.to, onEvent: $0.event, condition: $0.condition, handler: $0.handler) // } // } // // private func findTransition(for event: E) -> Transition<S>? { // guard let eventTransitions = eventsTransitions[event] else { // return nil // } // return eventTransitions.first { // let key = EventToTransition(event: event, transition: $0) // return $0.fromState == self.state // && (conditionMappings[key]?() ?? true ) // } // } // // public func event(_ event: E) -> Bool { // guard let transition = findTransition(for: event) else { // return false // } // if let handler = handlers[transition] { // handler() // } // self.state = transition.toState // return true // } // // @resultBuilder // public struct AvailableTransitionBuilder { // public static func buildBlock(_ components: AvailableTransition<E, S>...) -> [AvailableTransition<E, S>] { // components // } // } //} // //public struct AvailableTransition<E: Event, S: State> { // let to: S // let event: E // let condition: Condition? // let handler: Handler // // public init(_ to: S, _ event: E, _ condition: Condition? = nil, _ handler: @escaping Handler) { // self.to = to // self.event = event // self.condition = condition // self.handler = handler // } // // public init(availableTransition: AvailableTransition<E,S>, _ handler: @escaping Handler) { // self.to = availableTransition.to // self.event = availableTransition.event // self.condition = availableTransition.condition // self.handler = handler // } //} // //public struct EventToTransition<E: Event, S: State>: Hashable { // public let event: E // public let transition: Transition<S> // init(event: E, transition: Transition<S>) { // self.event = event // self.transition = transition // } // // public func hash(into hasher: inout Hasher) { // hasher.combine(event.hashValue) // hasher.combine(transition.hashValue) // } //} // //public func ~> <S>(fromState: S, toState: S) -> Transition<S> { // return Transition(fromState: fromState, toState: toState) //} // ////infix operator ==> : MultiplicationPrecedence //infix operator ==> : AdditionPrecedence // //public func ==> <S, E>(event: E, toState: S) -> AvailableTransition<E, S> { // AvailableTransition(toState, event, nil) { } //} // //infix operator ?! : AdditionPrecedence // //public func ?! <S, E>(eventToState: AvailableTransition<E, S>, condition: @escaping Condition) -> AvailableTransition<E, S> { // AvailableTransition(eventToState.to, eventToState.event, condition) { } //} // ////infix operator | : AdditionPrecedence // //public func | <E, S>(availableTransition: AvailableTransition<E, S>, handler: @escaping Handler) -> AvailableTransition<E, S> { // AvailableTransition(availableTransition: availableTransition, handler) //} // //public func ==> <E, S>(availableTransition: AvailableTransition<E, S>, handler: @escaping Handler) -> AvailableTransition<E, S> { // AvailableTransition(availableTransition: availableTransition, handler) //}
1fd592574fc5e1a0baf82ade3f50146c68c56a04
[ "Swift" ]
4
Swift
pawel-prochniak/StateMachine
ceacc45a733eac083f3be7d98bfba11528b68631
b94d0db68835aef88cb7dd36953a1df4def623dc
refs/heads/master
<repo_name>AlexanderC/DiseaseControl<file_sep>/Dockerfile FROM mhart/alpine-node:12 WORKDIR /web COPY package*.json ./ RUN npm ci --only=production COPY . . RUN mv .docker.env .env EXPOSE 8000 CMD [ "node", "./web/server.js" ] <file_sep>/web/server.js const path = require('path'); const fs = require('fs-extra'); const Hapi = require('@hapi/hapi'); const Boom = require('boom'); const dotenv = require('dotenv'); const origDebug = require('debug'); const Kernel = require('../src/kernel'); const debug = (...args) => process.env.DEBUG ? origDebug('dc')(...args) : undefined; const init = async () => { // Configure environment let configFile = path.resolve(process.cwd(), '.env'); if (!(await fs.exists(configFile))) { configFile = path.resolve(process.cwd(), 'sample.env'); } dotenv.config({ path: configFile }); // Configure server and initialize kernel const server = Hapi.server({ port: process.env.SERVER_PORT, host: process.env.SERVER_HOST, debug: process.env.DEBUG ? { request: process.env.DEBUG, log: process.env.DEBUG } : false, state: { strictHeader: false, // Avoid "invalid cookie name" error }, routes: { validate: { failAction: async (_request, _h, error) => { if (error.isBoom) { throw Boom.badRequest(error.output.payload.message); } throw Boom.badRequest(error.message); }, }, }, }); const kernel = new Kernel(server); // Register logging handlers kernel.on('plugin', pin => console.info('Loaded plugin <%s>', pin.constructor.name), ); kernel.on('feature.register', name => console.info('Registered feature <%s>', name), ); kernel.on('feature.use', (name, target, opts) => { console.info( 'Using feature <%s>', name, 'target=', target, 'options=', opts, ); }); kernel.on('controller', (ctrl, route) => { console.info( 'Loaded ctrl <%s> at %s:%s', ctrl.constructor.name, ctrl.method(kernel), ctrl.path(kernel), 'route=', route, ); }); // Register debugging handlers kernel.on('request', (req, ctrl) => { debug( `Incoming request on "${req.route.fingerprint}" dispatched by <${ctrl.constructor.name}>`, 'payload=', req.payload, ); }); // These might be different, depending on settings // eslint-disable-next-line global-require const plugins = require('../plugins'); // eslint-disable-next-line global-require const controllers = require('../controllers'); // Configure and bootstrap kernel await kernel.plugin(...plugins); await kernel.controller(...controllers); await kernel.bootstrap(); console.log('Server running on %s', server.info.uri); }; // Handle unexpected issues process.on('unhandledRejection', error => { console.log(error); process.exit(1); }); // Start the server init(); <file_sep>/controllers/tag/upsert.js const BaseController = require('./lib/base-ctrl'); class Upsert extends BaseController { method = () => 'POST'; path = () => '/admin/tag'; features = () => ({ auth: true, ws: false, docs: true }); config = ({ Joi }) => { return { description: 'Update or insert a bunch of tags.', validate: this._validationSchema(Joi, /* multiple = */ true), }; }; /** * @inheritdoc */ async handler(kernel, request, _h) { const tags = request.payload; const { transaction: txInit, Sequelize } = kernel.plugins.db; if (!request.user.isAdmin()) { throw kernel.Boom.unauthorized('You must be an admin'); } const Tag = this._tagModel(request); const tagsNames = tags.map(tag => tag.name); const tagDescription = name => tags.filter(tag => tag.name === name)[0].description; // Upsert tags... await txInit.call(kernel.plugins.db, kernel, async transaction => { const foundTags = await Tag.findAll({ where: { name: tagsNames }, transaction, }); const isNewTag = name => foundTags.find(tag => tag.name === name) === undefined; await Promise.all([ // remove missing tags Tag.destroy({ where: { name: { [Sequelize.Op.notIn]: tagsNames } }, transaction, }), // create new tags Tag.bulkCreate( tags.filter(tag => isNewTag(tag.name)), { transaction }, ), // update existing tags ...foundTags.map(tag => { tag.description = tagDescription(tag.name); return tag.save({ transaction }); }), ]); }); return Tag.findAll(); } } module.exports = Upsert; <file_sep>/seeders/20200321111148-add-tags.js 'use strict'; const { MYSQL_NOW } = process.env; module.exports = { up: (queryInterface, _Sequelize) => { return queryInterface.bulkInsert( 'Tags', [ { name: 'copii', description: 'Copii', createdAt: MYSQL_NOW, updatedAt: MYSQL_NOW, }, { name: 'adulti', description: 'Adulti', createdAt: MYSQL_NOW, updatedAt: MYSQL_NOW, }, { name: 'gravide', description: 'Femei gravide', createdAt: MYSQL_NOW, updatedAt: MYSQL_NOW, }, { name: 'forma-usoara', description: 'Forma usoara', createdAt: MYSQL_NOW, updatedAt: MYSQL_NOW, }, { name: 'forma-medie', description: 'Forma medie', createdAt: MYSQL_NOW, updatedAt: MYSQL_NOW, }, { name: 'forma-severa', description: 'Forma severa', createdAt: MYSQL_NOW, updatedAt: MYSQL_NOW, }, ], {}, ); }, down: (queryInterface, Sequelize) => { return queryInterface.bulkDelete( 'Tags', { name: { [Sequelize.Op.in]: [ 'copii', 'adulti', 'gravide', 'forma-usoara', 'forma-medie', 'forma-severa', ], }, }, {}, ); }, }; <file_sep>/plugins/index.js const Core = require('./core'); const Docs = require('./docs'); const Health = require('./health'); const Auth = require('./auth'); const WebSocketServer = require('./wss'); const DB = require('./db'); const Paginate = require('./paginate'); const Mailer = require('./mailer'); module.exports = [ new Core(), new Health(), new Auth(), new WebSocketServer(), new DB(), new Paginate(), new Mailer(), new Docs(), ]; <file_sep>/controllers/hospital/list.js const BaseController = require('./lib/base-ctrl'); class List extends BaseController { method = () => 'GET'; path = () => '/hospital'; features = () => ({ auth: true, ws: false, docs: true }); config = () => ({ description: 'List hospitals' }); /** * @inheritdoc */ async handler(_kernel, request, _h) { const Hospital = this._hospitalModel(request); return Hospital.scope('tags', 'inventory', 'supervisors').findAll(); } } module.exports = List; <file_sep>/plugins/auth/strategies/db.js const Strategy = require('../strategy'); class DBStrategy extends Strategy { /** * @param {object} config * @example { * model: 'User' * } */ constructor(config) { super(); this.config = config; } /** * @inheritdoc */ async authorize(_kernel, request, _h) { const { username, password } = request.payload; const user = await this._model(request).findOne({ where: { username, password }, attributes: ['id', 'password', 'type'], }); return user || false; } /** * @inheritdoc */ async validate(_kernel, decoded, request, _h) { const { id, password } = decoded; const user = await this._model(request).findOne({ where: { id, password }, }); return user || false; } /** * Get model to work * @param {Hapi.Request} request * @returns {Sequelize.Model} */ _model(request) { return request.getModel(this.config.model); } } module.exports = DBStrategy; <file_sep>/plugins/paginate.js const HapiPagination = require('hapi-pagination'); const Joi = require('@hapi/joi'); const Plugin = require('../src/plugin'); /** * @ref https://www.npmjs.com/package/hapi-pagination */ class Paginate extends Plugin { FEATURE = 'paginate'; /** * @inheritdoc */ name() { return 'paginate'; } /** * @inheritdoc * @returns {HapiPagination} */ instance() { return { plugin: HapiPagination, options: { routes: { include: [], exclude: ['*'] }, }, }; } /** * @inheritdoc */ async configure(kernel) { kernel.feature(this.FEATURE, this._featureDecorator.bind(this)); } /** * Docs feature decorator * @param {*} routeObj * @param {*} options * @returns {*} * @todo use options parameter */ async _featureDecorator(routeObj, options) { // "options === false" meaning that endpoint should not be paginated if (options === false) { return routeObj; } routeObj.config = routeObj.config || {}; routeObj.config.plugins = routeObj.config.plugins || {}; routeObj.config.validate = routeObj.config.validate || {}; routeObj.config.validate.options = routeObj.config.validate.options || {}; routeObj.config.plugins.pagination = { enabled: true }; routeObj.config.validate.options.allowUnknown = true; const validation = { paginate: Joi.number() .integer() .default(50) .description('Items per page') .example(50), page: Joi.number() .integer() .default(1) .description('Page') .example(1), }; routeObj.config.validate.query = routeObj.config.validate.query ? routeObj.config.validate.query.append(validation) : validation; const originalHandler = routeObj.handler; routeObj.handler = async (request, h) => { const { docs, total } = await originalHandler(request, h); request.totalCount = total; return docs || []; }; return routeObj; } } module.exports = Paginate; <file_sep>/models/hospital.js const Sequelize = require('sequelize'); const sequelizePaginate = require('sequelize-paginate'); class Hospital extends Sequelize.Model { /** * Check if an user is hospital supervisor * @param {string|User} user */ isSupervisor(user) { const id = typeof user === 'string' ? user : user.id; return ( (this.supervisors || []).filter(supervisor => supervisor.id === id) .length >= 1 ); } } module.exports = sequelize => { Hospital.init( { id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true }, name: { type: Sequelize.STRING, allowNull: false, unique: true }, description: { type: Sequelize.TEXT, allowNull: true }, createdAt: Sequelize.DATE, updatedAt: Sequelize.DATE, }, { sequelize, timestamps: true, }, ); Hospital.associate = models => { const { Tag, Inventory, HospitalInventory, User } = models; Hospital.belongsToMany(Tag, { through: 'HospitalTag', as: 'tags' }); Hospital.belongsToMany(Inventory, { through: HospitalInventory, as: 'inventory', }); Hospital.hasMany(HospitalInventory, { as: 'assignedInventory' }); Hospital.belongsToMany(User, { through: 'HospitalSupervisor', as: 'supervisors', }); Hospital.addScope('supervisors', { include: [ { model: User, as: 'supervisors', attributes: ['id'], }, ], }); Hospital.addScope('tags', { include: [ { model: Tag, as: 'tags', }, ], }); Hospital.addScope('inventory', { include: [ { model: Inventory, as: 'inventory', }, ], }); }; sequelizePaginate.paginate(Hospital); return Hospital; }; <file_sep>/src/kernel.js const Joi = require('@hapi/joi'); const Boom = require('boom'); const EventEmitter = require('./utils/ee'); const Features = require('./features'); const AbstractPlugin = require('./plugin'); const AbstractController = require('./controller'); const WrongImplementationError = require('./error/wrong-impl'); class Kernel extends EventEmitter { plugins = {}; /** * @param {Hapi.server} server */ constructor(server) { super(); this.server = server; this.features = new Features().pipe(this, 'feature'); } /** * Register a feature * @param {string} name * @param {string} handler * @returns {Kernel} */ async feature(name, handler) { this.features.register(name, handler); return this; } /** * Load a plugin * @param {...AbstractPlugin} plugins * @returns {Kernel} */ async plugin(...plugins) { for (const plugin of plugins) { WrongImplementationError.assert(plugin, AbstractPlugin); await plugin.configure(this); const pluginDefinition = plugin.instance(this); if (pluginDefinition) { // it might be internal plugin await this.server.register(pluginDefinition); } await plugin.load(this); this.plugins[plugin.name()] = plugin; this.emit('plugin', plugin); } return this; } /** * Load a controller * @param {...AbstractController} controllers * @returns {Kernel} */ async controller(...controllers) { for (const controller of controllers) { WrongImplementationError.assert(controller, AbstractController); await controller.configure(this); const route = await this._applyRouteFeatures( { method: controller.method(this), path: controller.path(this), handler: this._requestHandler(controller), /* optionals */ config: controller.config(this), vhost: controller.vhost(this), rules: controller.rules(this), }, controller.features(this), ); this.server.route(route); this.emit('controller', controller, route); } return this; } /** * Bootstrap and start API server * @param {*} opts */ async bootstrap(opts = {}) { return this.server.start(opts); } /** * Shortcut to "const Joi = require('@hapi/joi');" * @returns {Joi} */ get Joi() { return Joi; } /** * Shortcut to "const Boom = require('boom');" * @returns {Boom} */ get Boom() { return Boom; } /** * Apply route features * @param {*} route * @param {*} features */ async _applyRouteFeatures(route, features) { if (!features || typeof features !== 'object') { return route; } return this.features.useAll(route, features); } /** * Create wrapped request handler * @param {AbstractController} controller * @returns {function} */ _requestHandler(controller) { const kernel = this; // avoid missing context return async (request, h) => { kernel.emit('request', request, controller); return controller.handler(kernel, request, h); }; } } module.exports = Kernel; <file_sep>/controllers/identity/me.js const BaseController = require('./lib/base-ctrl'); class Me extends BaseController { method = () => 'GET'; path = () => '/identity/me'; features = () => ({ auth: true, ws: false, docs: true }); config = () => ({ description: 'Returns logged in identity' }); /** * @inheritdoc */ async handler(_kernel, request, _h) { return request.user; } } module.exports = Me; <file_sep>/seeders/20200321112137-add-inventory.js 'use strict'; const { MYSQL_NOW } = process.env; module.exports = { up: (queryInterface, _Sequelize) => { return queryInterface.bulkInsert( 'Inventories', [ { name: 'pat', description: '<NAME>', createdAt: MYSQL_NOW, updatedAt: MYSQL_NOW, }, ], {}, ); }, down: (queryInterface, Sequelize) => { return queryInterface.bulkDelete( 'Inventories', { name: { [Sequelize.Op.in]: ['pat'] } }, {}, ); }, }; <file_sep>/models/inventory.js const Sequelize = require('sequelize'); const sequelizePaginate = require('sequelize-paginate'); class Inventory extends Sequelize.Model { // TODO } module.exports = sequelize => { Inventory.init( { id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true }, name: { type: Sequelize.STRING, allowNull: false, unique: true }, description: { type: Sequelize.TEXT, allowNull: true }, createdAt: Sequelize.DATE, updatedAt: Sequelize.DATE, }, { sequelize, timestamps: true, }, ); Inventory.associate = models => { const { Tag, Hospital, HospitalInventory } = models; Inventory.belongsToMany(Tag, { through: 'InventoryTag', as: 'tags' }); Inventory.belongsToMany(Hospital, { through: HospitalInventory, as: 'hospitals', }); Inventory.addScope('tags', { include: [ { model: Tag, as: 'tags', }, ], }); Inventory.addScope('hospitals', { include: [ { model: Hospital, as: 'hospitals', }, ], }); }; sequelizePaginate.paginate(Inventory); return Inventory; }; <file_sep>/plugins/core.js const { default: HapiGracefulPM2 } = require('hapi-graceful-pm2'); const Twig = require('twig'); const HapiCORS = require('hapi-cors'); const HapiVision = require('@hapi/vision'); const path = require('path'); const Plugin = require('../src/plugin'); /** * @ref https://github.com/roylines/hapi-graceful-pm2 */ class Core extends Plugin { /** * @inheritdoc */ name() { return 'core'; } /** * @inheritdoc */ instance() { return [ HapiVision, { plugin: HapiGracefulPM2, options: { timeout: 4000 }, }, { plugin: HapiCORS, options: { origins: ['*'], methods: ['POST, GET, OPTIONS', 'PUT', 'PATCH', 'DELETE'], allowCredentials: 'true', }, }, ]; } /** * @inheritdoc */ async load(kernel) { kernel.server.views({ engines: { twig: { compile: (src, options) => { const template = Twig.twig({ id: options.filename, data: src }); return ctx => template.render(ctx); }, }, }, relativeTo: path.join(__dirname, '..'), path: 'templates', }); } } module.exports = Core; <file_sep>/src/utils/abc.js class AbstractClass { constructor(_class, _required) { if (this.constructor === _class) { throw new Error( `Abstract class ${_class.name} cannot be instantiated without a subclass implementation.`, ); } // This weird trick is to allow defininf class properties using new syntax // @todo remove when fixed process.nextTick(() => { for (const method of _required) { if (typeof this[method] !== 'function') { throw new Error( `Classes extending abstract class "${_class.name}" ` + `must implement "${_class.name}.${method}()"`, ); } } }); } } module.exports = AbstractClass; <file_sep>/src/utils/ee.js const OriginalEventEmitter = require('events'); const WrongImplementationError = require('../error/wrong-impl'); class EventEmitter extends OriginalEventEmitter { _pipes = []; /** * Pipe all events from original emitter with or without a prefix * @param {OriginalEventEmitter} consumer * @param {string} prefix * @returns {EventEmitter} */ pipe(consumer, prefix = null) { WrongImplementationError.assert(consumer, OriginalEventEmitter); this._pipes.push({ consumer, prefix }); return this; } /** * Remove registered pipes * @returns {EventEmitter} */ depipe() { this._pipes = []; return this; } /** * @inheritdoc * @returns {boolean} True if itself or piped * emitters has listeners on propagated event */ emit(eventName, ...args) { return ( [ super.emit(eventName, ...args), this._pipes.map(({ consumer, prefix }) => { return consumer.emit( prefix ? `${prefix}.${eventName}` : eventName, ...args, ); }), ].filter(Boolean).length > 0 ); } } module.exports = EventEmitter; <file_sep>/bin/deploy.sh #!/usr/bin/env bash function _info() { echo "" echo " ===> $1" echo "" } function _fail() { if [ !-z "$1" ]; then echo "$1" fi exit 1 } _info "Validating environment" if [ -z "$DEPLOY_SERVER_DSN" ] || [ -z "$DEPLOY_SERVER_ROOT" ]; then _fail "Missing deploy server configuration" elif [ -z "$(which rsync)" ]; then _fail "Missing rsync utility" fi _info "Building dc-api image" docker build -t dc-api . || _fail _info "Exporting image into dc-api.tar archive" docker save dc-api > dc-api.tar || _fail _info "Sending image and configuration to $DEPLOY_SERVER_DSN" if [ -z "$DEPLOY_SEEDS" ] && [ -z "$DEPLOY_SEEDS_RELOAD" ]; then rsync -av dc-api.tar docker-compose.yml \ "$DEPLOY_SERVER_DSN:$DEPLOY_SERVER_ROOT/" || _fail else rsync -av dc-api.tar docker-compose.yml .docker.env .sequelizerc package.json seeders node_modules bin \ "$DEPLOY_SERVER_DSN:$DEPLOY_SERVER_ROOT/" || _fail fi _info "Deploying image on remote server" _CMD_ADD="echo 'Skip running database seeds...'" if [ ! -z "$DEPLOY_SEEDS" ] || [ ! -z "$DEPLOY_SEEDS_RELOAD" ]; then _SEED_CMD_ADD="echo 'Skip droping old database seeds...'" if [ ! -z "$DEPLOY_SEEDS_RELOAD" ]; then _SEED_CMD_ADD="npm run db:seeds:down" fi _CMD_ADD="$(cat <<-EOF echo "Waiting 5 seconds till services are up.." sleep 5 mv .docker.env .env . /root/.nvm/nvm.sh $_SEED_CMD_ADD npm run db:seeds:up rm -rf .env .sequelizerc package.json seeders node_modules bin EOF )" fi _CMD="$(cat <<-EOF cd '$DEPLOY_SERVER_ROOT' docker load --input dc-api.tar docker-compose up -d $_CMD_ADD rm -rf dc-api.tar docker-compose.yml docker ps EOF )" ssh "$DEPLOY_SERVER_DSN" "$_CMD" || _fail <file_sep>/models/user.js const Sequelize = require('sequelize'); const EncryptedField = require('sequelize-encrypted'); const sequelizePaginate = require('sequelize-paginate'); class User extends Sequelize.Model { /** * User types vector * @returns {Array<string>} */ static get TYPES() { return Object.values(this.TYPE); } /** * Get user types mapping * @returns {object} */ static get TYPE() { return { USER: 'user', SUPERVISOR: 'supervisor', ADMIN: 'admin', }; } /** * Check if this is a default user * @returns {boolean} */ isUser() { return this.type === User.TYPE.USER; } /** * Check if this is an supervisor user * @returns {boolean} */ isSupervisor() { return this.type === User.TYPE.SUPERVISOR; } /** * Check if this is at least an supervisor user * @returns {boolean} */ isAtLeastSupervisor() { return this.isAdmin() || this.isSupervisor(); } /** * Check if this is an admin user * @returns {boolean} */ isAdmin() { return this.type === User.TYPE.ADMIN; } /** * Get object to serialize * @returns {object} */ toJSON() { const data = this.get({ plain: true }); delete data.vault; delete data.password; return data; } } module.exports = sequelize => { const encFields = EncryptedField(Sequelize, process.env.SEC_SEED); User.init( { id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true }, username: { type: Sequelize.STRING, allowNull: false, unique: true }, password: { type: Sequelize.STRING, allowNull: false }, type: { type: Sequelize.ENUM, allowNull: false, values: User.TYPES, defaultValue: User.TYPE.USER, }, vault: encFields.vault('vault'), data: encFields.field('data', { type: Sequelize.JSON, allowNull: true, }), createdAt: Sequelize.DATE, updatedAt: Sequelize.DATE, }, { sequelize, timestamps: true, }, ); User.associate = models => { const { Hospital } = models; User.belongsToMany(Hospital, { through: 'HospitalSupervisor', as: 'hospitals', }); User.addScope('hospitals', { include: [ { model: Hospital, as: 'hospitals', }, ], }); }; sequelizePaginate.paginate(User); return User; }; <file_sep>/plugins/mailer.js const nodemailer = require('nodemailer'); const Plugin = require('../src/plugin'); /** * @ref https://www.npmjs.com/package/nodemailer */ class Mailer extends Plugin { transporter = null; parameters = null; defaultFrom = null; kernel = null; /** * @inheritdoc */ name() { return 'mailer'; } /** * @inheritdoc */ instance() { return null; } /** * @inheritdoc */ async configure(kernel) { this.kernel = kernel; this.parameters = JSON.parse(process.env.MAILER_PARAMS); this.transporter = nodemailer.createTransport(this.parameters); this.defaultFrom = process.env.MAILER_EMAIL_FROM; } /** * Send an email * @param {object} payload {from, to, body} * @returns {object} */ async send({ template, to, parameters = {}, from = null }) { from = from || this.defaultFrom; template = template.toLowerCase(); to = Array.isArray(to) ? to.join(',') : to.toString(); const subject = await this.kernel.server.render( `email/${template}/subject`, parameters, ); const html = await this.kernel.server.render( `email/${template}/html`, parameters, ); const text = await this.kernel.server.render( `email/${template}/text`, parameters, ); const info = await this.transporter.sendMail({ from, to, subject, text, html, }); if (this.isTestSetup) { console.info( '------------\n', `Email base on "${template}" template w/ parameters: ${JSON.stringify( parameters, null, ' ', )}\n`, `Preview URL: ${nodemailer.getTestMessageUrl(info)}`, ); } } /** * Check if it's a test setup * @returns {boolean} */ get isTestSetup() { return (this.parameters.host || '').toLowerCase() === 'smtp.ethereal.email'; } } module.exports = Mailer; <file_sep>/controllers/hospital/index.js const ListController = require('./list'); const WebsocketListController = require('./list-ws'); const CreateController = require('./create'); const PatchController = require('./patch'); const RemoveController = require('./remove'); const UpdateInventoryController = require('./update-inventory'); module.exports = [ new ListController(), new WebsocketListController(), new CreateController(), new RemoveController(), new PatchController(), new UpdateInventoryController(), ]; <file_sep>/controllers/identity/lib/base-ctrl.js const crypto = require('crypto'); const Controller = require('../../../src/controller'); class BaseController extends Controller { /** * Prepare passed raw password * @param {Kernel} kernel * @param {string} password * @returns {string} */ _preparePassword(kernel, password) { // @think on moving it somewhere // This is used on json strategy setup if (kernel.plugins.auth.strategy !== 'db') { return password; } return crypto .createHmac('sha256', process.env.SEC_SEED) .update(password) .digest('hex'); } /** * Get user model * @param {Hapi.Request} request * @returns {User} */ _userModel(request) { return request.getModel('User'); } /** * Get two fa request model * @param {Hapi.Request} request * @returns {TwoFARequest} */ _requestModel(request) { return request.getModel('TwoFARequest'); } /** * Identity validation schema * @param {Joi} * @param {boolean} onlyUsername * @returns {*} */ _validationSchema(Joi, onlyUsername = false) { const username = Joi.string() .email() .required() .example('<EMAIL>'); const password = Joi.string() .required() .example('<PASSWORD>'); const schema = onlyUsername ? { username } : { username, password }; return { payload: Joi.object(schema).label(onlyUsername ? 'PartialUser' : 'User'), }; } } module.exports = BaseController; <file_sep>/controllers/hospital/update-inventory.js const BaseController = require('./lib/base-ctrl'); class UpdateInventory extends BaseController { method = () => 'POST'; path = () => '/hospital/{id}/inventory/{hospitalInventoryId}'; features = () => ({ auth: true, ws: false, docs: true }); config = ({ Joi }) => { return { description: 'Update hospital inventory', validate: { params: Joi.object({ id: Joi.number() .integer() .required() .min(1) .description('Hospital ID') .example(1), hospitalInventoryId: Joi.number() .integer() .required() .min(1) .description('Hospital Inventory ID') .example(1), }).label('HospitalID'), payload: Joi.object({ quantity: Joi.number() .integer() .optional() .min(0) .description('Hospital Inventory Quantity') .example(100), detailed: Joi.object() .optional() .description('Hospital Inventory Detailed Quantity') .unknown(true) .example({ 'critical severity': 50, 'medium severity': 50 }) .label('InventoryDetailed'), total: Joi.number() .integer() .optional() .min(0) .description('Hospital Inventory Total Quantity (admin only)') .example(250), }).label('InventoryUpdate'), }, }; }; /** * @inheritdoc */ async handler(kernel, request, _h) { const { id, hospitalInventoryId } = request.params; const { quantity, total, detailed } = request.payload; if (!request.user.isAtLeastSupervisor()) { throw kernel.Boom.unauthorized('You must be a supervisor or an admin'); } const User = this._userModel(request); const Hospital = this._hospitalModel(request); const HospitalInventory = this._hospitaliInventoryModel(request); const hospital = await Hospital.findOne({ where: { id }, include: [ { model: HospitalInventory, where: { id: hospitalInventoryId }, as: 'assignedInventory', }, { model: User, as: 'supervisors', attributes: ['id'], through: { attributes: [] }, }, ], }); if ( !hospital || !hospital.assignedInventory || hospital.assignedInventory.length <= 0 ) { throw kernel.Boom.notFound('Hospital or Inventory Item does not exist'); } else if ( !request.user.isAdmin() && !hospital.isSupervisor(request.user) ) { throw kernel.Boom.unauthorized('You can update only assigned hospitals'); } else if (!quantity && !total && !detailed) { throw kernel.Boom.badRequest('Nothing to update'); } /** The order of callls below is really important!!! */ try { if (total && request.user.isAdmin()) { hospital.assignedInventory[0].total = total; } if (detailed) { hospital.assignedInventory[0].detailed = detailed; } if (quantity) { hospital.assignedInventory[0].quantity = quantity; } } catch (e) { throw kernel.Boom.badRequest(e.message); } await hospital.assignedInventory[0].save(); return Hospital.scope('tags', 'inventory', 'supervisors').findByPk( hospital.id, ); } } module.exports = UpdateInventory; <file_sep>/controllers/inventory/upsert.js const BaseController = require('./lib/base-ctrl'); class Upsert extends BaseController { method = () => 'POST'; path = () => '/admin/inventory'; features = () => ({ auth: true, ws: false, docs: true }); config = ({ Joi }) => { return { description: 'Update or insert a bunch of inventory items.', validate: this._validationSchema(Joi, /* multiple = */ true), }; }; /** * @inheritdoc */ async handler(kernel, request, _h) { const inventory = request.payload; const { transaction: txInit, Sequelize } = kernel.plugins.db; if (!request.user.isAdmin()) { throw kernel.Boom.unauthorized('You must be an admin'); } const Inventory = this._inventoryModel(request); const inventoryNames = inventory.map(iv => iv.name); const inventoryDescription = name => inventory.filter(iv => iv.name === name)[0].description; // Upsert inventory items... await txInit.call(kernel.plugins.db, kernel, async transaction => { const foundInventory = await Inventory.findAll({ where: { name: inventoryNames }, transaction, }); const isNewInventory = name => foundInventory.find(iv => iv.name === name) === undefined; await Promise.all([ // remove missing inventory items Inventory.destroy({ where: { name: { [Sequelize.Op.notIn]: inventoryNames } }, transaction, }), // create new inventory items Inventory.bulkCreate( inventory.filter(iv => isNewInventory(iv.name)), { transaction }, ), // update existing inventory items ...foundInventory.map(iv => { iv.description = inventoryDescription(iv.name); return iv.save({ transaction }); }), ]); }); return Inventory.findAll(); } } module.exports = Upsert; <file_sep>/controllers/identity/list.js const BaseController = require('./lib/base-ctrl'); class List extends BaseController { method = () => 'GET'; path = () => '/admin/identity'; features = () => ({ auth: true, ws: false, docs: true, paginate: true }); config = () => ({ description: 'List identities' }); /** * @inheritdoc */ async handler(kernel, request, _h) { const { paginate, page } = request.query; if (!request.user.isAdmin()) { throw kernel.Boom.unauthorized('You must be an admin'); } const User = this._userModel(request); return User.scope('hospitals').paginate({ paginate, page }); } } module.exports = List; <file_sep>/controllers/identity/register.js const BaseController = require('./lib/base-ctrl'); class Register extends BaseController { method = () => 'POST'; path = () => '/admin/identity/register'; features = () => ({ auth: true, ws: false, docs: true }); config = kernel => { const { Joi, plugins: { docs: { getBaseUrl }, db: { default: db }, }, } = kernel; const User = db(kernel).getModel('User'); const fullBaseUrl = getBaseUrl(); const { payload } = this._validationSchema(Joi); return { description: 'Register a new identity.', notes: `In order to obtain JWT token use "${fullBaseUrl}/identity/login" endpoint.`, validate: { payload: payload.append({ role: Joi.string() .required() .lowercase() .valid(...User.TYPES) .default(User.TYPE.USER) .example(User.TYPE.USER), }), }, }; }; /** * @inheritdoc */ async handler(kernel, request, _h) { if (!request.user.isAdmin()) { throw kernel.Boom.unauthorized('You must be an admin'); } request.payload.password = this._preparePassword( kernel, request.payload.password, ); const { username, password, role: type } = request.payload; const User = this._userModel(request); const userExists = await User.count({ where: { username } }); if (userExists) { throw kernel.Boom.conflict('Identity Already Exists'); } const user = await User.create({ username, password, type }); kernel.emit('user.register', user); return user; } } module.exports = Register; <file_sep>/controllers/identity/reset.js const cryptoRandomString = require('crypto-random-string'); const BaseController = require('./lib/base-ctrl'); class Reset extends BaseController { method = () => 'POST'; path = () => '/identity/reset'; features = () => ({ auth: false, ws: true, docs: true }); config = ({ Joi }) => { return { description: 'Reset account password.', validate: this._validationSchema(Joi, /* onlyUsername = */ true), }; }; /** * @inheritdoc */ async handler(kernel, request, _h) { const { username } = request.payload; const User = this._userModel(request); const user = await User.findOne({ where: { username } }); if (!user) { throw kernel.Boom.notFound('Identity Does Not Exist'); } const password = <PASSWORD>RandomString({ length: 8 }); await user.update({ password: this._preparePassword(kernel, password) }); const to = user.username; const parameters = { user, password }; const template = 'reset'; await kernel.plugins.mailer.send({ to, template, parameters }); return { message: 'Password Reset Request Received' }; } } module.exports = Reset; <file_sep>/bin/db-config.sh #!/usr/bin/env bash SCRIPT_DIR=$(dirname "$0") PROJECT_ROOT="$SCRIPT_DIR/.." function _info() { echo "" echo " ===> $1" echo "" } function _fail() { if [ ! -z "$1" ]; then echo "$1" fi exit 1 } _info "Accessing working directory" cd "$PROJECT_ROOT" || _fail _info "Loading .env configuration" source .env || _fail _info "Creating database config to .db.json" _CMD="$(cat <<-EOF { "development": { "url": "$DB_DSN", "dialect": "mysql" } } EOF )" touch .db.json || _fail echo "$_CMD" > .db.json || _fail <file_sep>/seeders/20200321095706-add-users.js 'use strict'; const crypto = require('crypto'); function hash(password) { return crypto .createHmac('sha256', process.env.SEC_SEED) .update(password) .digest('hex'); } const USERS = ['admin', 'user', 'supervisor']; // user types/names const { MYSQL_NOW } = process.env; module.exports = { up: (queryInterface, _Sequelize) => { return queryInterface.bulkInsert( 'Users', USERS.map(user => ({ username: <EMAIL>`, password: <PASSWORD>('<PASSWORD>'), type: user, createdAt: MYSQL_NOW, updatedAt: MYSQL_NOW, })), {}, ); }, down: (queryInterface, Sequelize) => { return queryInterface.bulkDelete( 'Users', { username: { [Sequelize.Op.in]: USERS.map(user => <EMAIL>`), }, }, {}, ); }, }; <file_sep>/controllers/inventory/index.js const ListController = require('./list'); const UpsertController = require('./upsert'); module.exports = [new ListController(), new UpsertController()]; <file_sep>/plugins/auth.js const HapiJwt2 = require('hapi-auth-jwt2'); const JWT = require('jsonwebtoken'); const Plugin = require('../src/plugin'); const WrongImplementationError = require('../src/error/wrong-impl'); const AbstractStrategy = require('./auth/strategy'); const authStrategies = require('./auth/strategies'); /** * @ref https://www.npmjs.com/package/hapi-auth-jwt2 */ class Auth extends Plugin { FEATURE = 'auth'; AUTH_KEY = 'jwt'; TOKEN_KEY = 'token'; STRATEGIES = authStrategies; _strategy = null; strategy = null; /** * @inheritdoc */ name() { return 'auth'; } /** * @inheritdoc * @returns {HapiJwt2} */ instance() { return HapiJwt2; } /** * @inheritdoc */ async configure(kernel) { const Strategy = this.STRATEGIES[process.env.AUTH_STRATEGY]; WrongImplementationError.assert(Strategy, AbstractStrategy); const strategyOpts = JSON.parse(process.env.AUTH_PARAMS || null); this.strategy = process.env.AUTH_STRATEGY; this._strategy = new Strategy(strategyOpts); kernel.feature(this.FEATURE, this._featureDecorator.bind(this)); } /** * @inheritdoc */ async load(kernel) { kernel.server.auth.strategy(this.AUTH_KEY, this.AUTH_KEY, { key: process.env.SEC_SEED, // Never Share your secret key validate: async (decoded, request, h) => { try { const user = await this._strategy.validate( kernel, decoded, request, h, ); // case we have some credentials returned if (user && typeof user === 'object') { request.user = user; return { isValid: true, credentials: user }; } return { isValid: !!user }; } catch (e) { throw kernel.Boom.unauthorized('Authorization Service Failure'); } }, }); kernel.server.auth.default(this.AUTH_KEY); } /** * Gain authorization based on request object * @param {*} kernel * @param {*} request * @param {*} h */ async authorize(kernel, request, h) { let user; try { user = await this._strategy.authorize(kernel, request, h); } catch (e) { throw kernel.Boom.unauthorized('Authorization Service Failure'); } if (!user) { throw kernel.Boom.unauthorized('Authorization Declined'); } request.user = user; return { [this.TOKEN_KEY]: this._createToken(user) }; } /** * Create signed JWT token from an object * @param {*} obj * @returns {string} */ _createToken(obj) { // Allow change toJSON strategy of user object if (typeof obj.get === 'function') { obj = obj.get(); } return JWT.sign(JSON.stringify(obj), process.env.SEC_SEED); } /** * Auth feature decorator * @param {*} routeObj * @param {*} options * @returns {*} * @todo use options parameter */ async _featureDecorator(routeObj, options) { routeObj.config = routeObj.config || {}; // "options === false" meaning that endpoint should not be secured routeObj.config.auth = options === false ? false : this.AUTH_KEY; return routeObj; } } module.exports = Auth; <file_sep>/controllers/identity/index.js const MeController = require('./me'); const LoginController = require('./login'); const RegisterController = require('./register'); const ResetController = require('./reset'); const PromoteController = require('./promote'); const RemoveController = require('./remove'); const ListController = require('./list'); module.exports = [ new MeController(), new LoginController(), new ResetController(), new PromoteController(), new RegisterController(), new RemoveController(), new ListController(), ]; <file_sep>/plugins/docs.js const Inert = require('@hapi/inert'); const Vision = require('@hapi/vision'); const HapiSwagger = require('hapi-swagger'); const path = require('path'); const Plugin = require('../src/plugin'); const Pack = require('../package'); /** * @ref https://github.com/rse/hapi-plugin-websocket */ class Docs extends Plugin { FEATURE = 'docs'; PRIVATE_ENDPOINT = 'private'; tokenSchema = null; /** * @inheritdoc */ name() { return 'docs'; } /** * @inheritdoc */ instance() { return [ Inert, Vision, { plugin: HapiSwagger, options: { host: process.env.DOCS_HOST, documentationPath: process.env.DOCS_PATH, schemes: [process.env.DOCS_SCHEME], info: { title: `${Pack.description} Documentation`, version: Pack.version, }, routeTag: this.FEATURE, }, }, ]; } /** * @inheritdoc */ async configure(kernel) { if (kernel.plugins.auth) { this.tokenSchema = kernel.Joi.object({ [kernel.plugins.auth.TOKEN_KEY]: kernel.Joi.string() .required() .description('Your JWT token') .example('your-jwt-token'), }); } kernel.feature(this.FEATURE, this._featureDecorator.bind(this)); } /** * Docs feature decorator * @param {*} routeObj * @param {*} options * @returns {*} * @todo use options parameter */ async _featureDecorator(routeObj, options) { routeObj.config = routeObj.config || {}; // "options === false" meaning that endpoint should not be exposed in docs if (options === false) { routeObj.config.tags = routeObj.config.tags || []; routeObj.config.tags.push(this.PRIVATE_ENDPOINT); } const predefinedTags = ['api']; // Integrate wss plugin if ( routeObj.config && routeObj.config.plugins && routeObj.config.plugins.websocket ) { // @ref https://www.npmjs.com/package/hapi-plugin-websocket if (routeObj.config.plugins.websocket.only) { predefinedTags.shift(); // remove api tag } predefinedTags.push('ws'); } // Integrate auth plugin if (routeObj.config.auth) { if (this.tokenSchema) { routeObj.config.validate = routeObj.config.validate || {}; routeObj.config.validate.query = routeObj.config.validate.query ? routeObj.config.validate.query.append(this.tokenSchema) : this.tokenSchema; routeObj.config.plugins = routeObj.config.plugins || {}; // show lock icon in UI routeObj.config.plugins['hapi-swagger'] = { security: { jwt: {} }, }; } predefinedTags.push('secured'); } routeObj.config.tags = routeObj.config.tags ? [...routeObj.config.tags, ...predefinedTags] : predefinedTags; routeObj.config.tags.push(this.FEATURE); return routeObj; } /** * Get base url of documentation website * @param {boolean} includeProtocol * @returns {boolean} */ getBaseUrl(includeProtocol = true) { const baseUrl = path .join(process.env.DOCS_HOST, process.env.DOCS_PATH) .replace(/[/]+$/, ''); if (!includeProtocol) { return baseUrl; } return `${process.env.DOCS_SCHEME}://${baseUrl}`; } } module.exports = Docs; <file_sep>/models/hospital-inventory.js const Sequelize = require('sequelize'); const sequelizePaginate = require('sequelize-paginate'); class HospitalInventory extends Sequelize.Model { // TODO } module.exports = sequelize => { HospitalInventory.init( { id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true }, quantity: { type: Sequelize.INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, set(value) { value = parseInt(value, 10); if (value > this.getDataValue('total')) { throw new Error('Quantity cannot be more than the total amount'); } const detailed = this.getDataValue('detailed') || {}; let count = 0; for (const key of Object.keys(detailed)) { count += Math.abs(parseInt(detailed[key], 10)); } if (value !== count) { throw new Error( 'Detailed amount is different from detailed amount', ); } this.setDataValue('quantity', value); }, }, total: { type: Sequelize.INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, set(value) { value = parseInt(value, 10); if (value < this.getDataValue('quantity')) { throw new Error('Total amount cannot be less than the quantity'); } this.setDataValue('total', value); }, }, detailed: { type: Sequelize.JSON, allowNull: true, set(value) { if (!value || typeof value !== 'object') { throw new Error('Inventory details not an object'); } let total = 0; const details = { ...value }; for (const key of Object.keys(details)) { details[key] = Math.abs(parseInt(details[key], 10)); total += details[key]; } this.setDataValue('detailed', details); this.setDataValue('quantity', total); }, }, createdAt: Sequelize.DATE, updatedAt: Sequelize.DATE, }, { sequelize, timestamps: true, }, ); sequelizePaginate.paginate(HospitalInventory); return HospitalInventory; }; <file_sep>/controllers/hospital/list-ws.js const crypto = require('crypto'); const BaseController = require('./lib/base-ctrl'); class List extends BaseController { method = () => 'POST'; path = () => '/hospital/live'; features = () => ({ auth: true, ws: { only: true, autoping: 30 * 1000 }, docs: true, }); config = ({ Joi, plugins: { docs: { getBaseUrl }, }, }) => { const baseUrl = getBaseUrl(/* includeProtocol = */ false); return { description: 'List hospital and subscribe to changes.', notes: ` To test connection use "wscat --connect ${baseUrl}/hospital/live". ----------- > To authorize your calls to WebSocket endpoints you must use "?token={token}" query parameter. > To subscribe to changes send an empty frame. > To install wscat run "npm i -g wscat" `, }; }; /** * @inheritdoc */ async handler(_kernel, request, _h) { let lastHash = null; const tick = async (id = null) => { const { peers, ws } = request.websocket(); try { const { hash, data } = await this._tick(request); if (id && (!peers || peers.length <= 0)) { clearInterval(id); return JSON.parse(data); } if (hash !== lastHash) { lastHash = hash; ws.send(data); } } catch (e) { clearInterval(id); throw e; } return null; }; await tick(); return new Promise((resolve, reject) => { const id = setInterval(async () => { try { const data = await tick(id); if (data) { resolve(data); } } catch (e) { reject(e); } }, 30000); }); } /** * @param {Hapi.Request} request * @returns {object} */ async _tick(request) { const Hospital = this._hospitalModel(request); const data = JSON.stringify( await Hospital.scope('tags', 'inventory', 'supervisors').findAll(), ); const hash = crypto .createHash('md5') .update(data) .digest('hex'); return { hash, data }; } } module.exports = List; <file_sep>/README.md DiseaseControl API ======== DiseaseControl is a disease control platform that facilitates end-to-end tracking of disease cases and resolutions keeping all nodes involved, starting from local level and growing up into a county wide level. This piece of software is originally designed to cover the needs of control software for Moldovan healthcare system for fighting against Coronavirus Covid-19. > The project started at [C19.md Initiative](https://c19.md/) [Hackaton](https://c19.md/hackathon) (March 2020). Features: -------- - [x] Milestone I - [x] Authentication and Authorization (RBAC) - [x] Add ability to onboard hospitals and groups them (2 level structure for now) - [x] Add ability to manage hospital “beds” and critical inventory (such as Lung Ventilation Systems, protective stuff, main medicine) - [x] Add ability to see available “beds” (e.g. for an ambulance) depending on the patient state and his needs. - [ ] Milestone II - [ ] Milestone III - [ ] Milestone IV Prerequisites ----------- - [ ] Git - [ ] Docker - [ ] *NodeJS v12.x.x (for non docker usage)* Installation --------- Clone the project: ```bash git clone https://github.com/AlexanderC/DiseaseControl.git cd DiseaseControl ``` > If you do NOT run docker mode you need to install dependencies by yourself by running `npm install` Configure environment: ```bash cp sample.env .env ``` > You might want to edit `.env` to fill in your configuration > For testing purpose you might omit this step. System will use `sample.env` as configuration file, which might be enough so far. Non-Docker Usage -------- Starting production server: ```bash npm start ``` Monitoring production server: ```bash npm run monitor ``` Starting development server: ```bash npm run start:dev ``` Docker Usage ----------- Build image: ```bash cp .sample.env .docker.env # Adjust your configurations... docker build -t dc-api . ``` > Check if the image is available by running `docker images` Run services: ```bash docker-compose up -d ``` > Check if services as up and running by using `docker ps` Your application should have started on `0.0.0.0` at port `8000`. Seed Data ----- Run all database seeds: ```bash npm run db:seeds:up ``` Drop all data seeded: ```bash npm run db:seeds:down ``` Deploy ------ Deploy to a server you have SSH access given: ```bash # Add DEPLOY_SEEDS=1 in case you need to run seeds, mainly on first deploy # Add DEPLOY_SEEDS_RELOAD=1 if you want to re-run seeds (e.g. a new one added) DEPLOY_SERVER_ROOT=/root/api DEPLOY_SERVER_DSN=root@172.16.31.10 ./bin/deploy.sh ``` > The server has to be set up as of section `Prerequisites` (except Git). > NPM and Node needs to be set up using nvm, which is the only one supported for now =( > If your database host is not resolving when `DEPLOY_SEEDS=1` or `DEPLOY_SEEDS_RELOAD=1` option added on deploy- add it to `/etc/hosts` (e.g. `127.0.0.1 database`). Links -------- - [Frontend Repository](https://github.com/AlexanderC/DiseaseControl-SPA) - [Api Docs](http://localhost:8000/) - [Product Vision](https://docs.google.com/document/d/15XOLQsRgfhh7dy5_gKIxMTNreHUQNgU5r3dOybIkKrw/edit) - [Models EER Diagram](artifacts/models.png) TODO ---- - [ ] Move logic from controllers into services - [ ] Implement Milestone II (see [Product Vision](https://docs.google.com/document/d/15XOLQsRgfhh7dy5_gKIxMTNreHUQNgU5r3dOybIkKrw/edit)) - [ ] Implement Milestone III (see [Product Vision](https://docs.google.com/document/d/15XOLQsRgfhh7dy5_gKIxMTNreHUQNgU5r3dOybIkKrw/edit)) - [ ] Implement Milestone IV (see [Product Vision](https://docs.google.com/document/d/15XOLQsRgfhh7dy5_gKIxMTNreHUQNgU5r3dOybIkKrw/edit)) <file_sep>/plugins/wss.js const HapiWebSocket = require('hapi-plugin-websocket'); const Plugin = require('../src/plugin'); /** * @ref https://github.com/rse/hapi-plugin-websocket */ class WebSocketServer extends Plugin { FEATURE = 'ws'; /** * @inheritdoc */ name() { return 'wss'; } /** * @inheritdoc * @returns {HapiWebSocket} */ instance() { return HapiWebSocket; } /** * @inheritdoc */ async configure(kernel) { kernel.feature(this.FEATURE, this._featureDecorator.bind(this)); } /** * WS feature decorator * @param {*} routeObj * @param {*} options * @returns {*} */ async _featureDecorator(routeObj, options) { routeObj.config = routeObj.config || {}; routeObj.config.plugins = routeObj.config.plugins || {}; // "options === false" meaning that endpoint should not be exposed via WS if (options === false) { return routeObj; } routeObj.config.plugins.websocket = options; return routeObj; } } module.exports = WebSocketServer; <file_sep>/plugins/auth/strategies/index.js const JSONStrategy = require('./json'); const DBStrategy = require('./db'); module.exports = { json: JSONStrategy, db: DBStrategy, }; <file_sep>/controllers/identity/promote.js const BaseController = require('./lib/base-ctrl'); class Promote extends BaseController { method = () => 'PUT'; path = () => '/admin/identity/{id}/promote'; features = () => ({ auth: true, ws: false, docs: true }); config = kernel => { const { Joi, plugins: { db: { default: db }, }, } = kernel; const User = db(kernel).getModel('User'); return { description: 'Update user role', notes: `Available roles: ${User.TYPES.join(', ')}`, validate: { params: Joi.object({ id: Joi.number() .integer() .required() .min(1) .description('User ID') .example(1), }).label('UserID'), payload: Joi.object({ role: Joi.string() .required() .lowercase() .valid(...User.TYPES) .example(User.TYPE.USER), }).label('Role'), }, }; }; /** * @inheritdoc */ async handler(kernel, request, _h) { const { id } = request.params; const { role } = request.payload; if (!request.user.isAdmin()) { throw kernel.Boom.unauthorized('You must be an admin'); } const User = this._userModel(request); const user = await User.findByPk(id); if (!user) { throw kernel.Boom.notFound('Identity Does Not Exist'); } user.type = role; return user.save(); } } module.exports = Promote;
150858114cca80888b1803aa94a80931b499981e
[ "JavaScript", "Dockerfile", "Markdown", "Shell" ]
38
Dockerfile
AlexanderC/DiseaseControl
43a7849568471b50bce97c2283769d7320dba68a
d36fb2089e880af06b50bf7d99ddbab23605a52a
refs/heads/main
<file_sep>a=0 b=0 try: a=int(input("enter a number")) except: print("error") b=int(input("enter anthor number")) div=0 div=a/b print(div) <file_sep>l=[1,2,3] t=(1,2,3) d={"name":"ashna","age":23} c={5,7,"ash"} print(d) print(d["name"]) d["name"]="anu" print(d["name"]) s={} a=input("enter name") b=int(input("age")) s["name"]=a s["age"]=b print(s) <file_sep>import pickle l=pickle.load(open("bcd.pickle","rb")) l=[] d={} def stud(): n=input("entr name") a=int(input("enter age")) d={"name":"as","age":"2"} l.append(d) pickle.dump(l,open("bcd.pickle","wb")) def readobject(): l=pickle.load(open("bcd.pickle","rb")) print(l) def menu(): n=0 while(n!=3): print("1.registration") print("2.view") print("3.exit") n=int(input("enter choice")) if(n==1): stud() elif(n==2): readobject() else: print("exit") menu() <file_sep>a=int(input("enter a number")) b=int(input("enter a number")) if (a>b): if(b==0): print("not defined") else: div=a/b print(div) else: if(a==0): print("not defined") else: div=b/a print(div) <file_sep># Enterprise-employee-operations-management
47e33a4fd5fe1a513c5535227e5efa9d36d63ee2
[ "Markdown", "Python" ]
5
Python
Ashna-mansur/Enterprise-employee-operations-management
8a6f03a2875f68141eb41d10c392edf0009dfc9e
0f8eead7c8b0e1583f71fcc78f5f9b7d13ad2c9a
refs/heads/master
<file_sep>""" pip install git+https://github.com/brennerm/python-apt-repo.git@master pip install apt-repo Python2 ImportError: No module named lzma import urllib.error ImportError: No module named error Sources listed at https://github.com/OSGeo/OSGeoLive/blob/master/sources.list.d/ubuntugis.list deb http://ppa.launchpad.net/ubuntugis/ubuntugis-unstable/ubuntu bionic main """ from apt_repo import APTSources, APTRepository def get_package(): url = 'http://archive.ubuntu.com/ubuntu' # url = 'https://launchpad.net/~ubuntugis/+archive/ubuntu/ubuntugis-experimental' components = ['main', 'universe', 'multiverse', 'restricted'] #components = ['main'] sources = APTSources([ APTRepository(url, 'bionic', components), #APTRepository(url, 'bionic-updates', components), #APTRepository(url, 'bionic-backports', components), #APTRepository(url, 'bionic-proposed', components) ]) pkg = "python-mapscript" print([(package.package, package.version) for package in sources.get_packages_by_name(pkg)]) repo = APTRepository(url, 'bionic', components) for pkg in ["python-mapscript"]: print([(package.package, package.version) for package in repo.get_packages_by_name(pkg)]) #package = repo.get_packages_by_name(pkg_name) #print((package.package, package.version)) get_package() print("Done!")<file_sep>MapScript Python Notebook ReadMe ================================ Creating a Virtual Environment with Jupyter and mapscript: .. code-block:: bat SET PYTHON_HOME=C:\Python36 SET PYTHON_HOME=C:\Python27 SET VENV=C:\VirtualEnvs\mapscript-jupyter3 SET VENV=C:\VirtualEnvs\mapscript-jupyter %PYTHON_HOME%\Scripts\virtualenv %VENV% %VENV%\scripts\activate python -m pip install pip -U pip install jupytext python -m pip install jupyter pip install mapscript -U To create a notebook from a Python script jupytext is used - https://github.com/mwouts/jupytext The script is written using the "percent" format - https://github.com/mwouts/jupytext/blob/master/demo/World%20population.pct.py To create the notebook: .. code-block:: bat SET NOTEBOOK_HOME=D:\GitHub\GeoPythonNotebooks\notebooks %VENV%\scripts\activate cd /D %NOTEBOOK_HOME% jupytext --to notebook mapscript-quickstart.py To set up the paths to MapServer and run the notebook: .. code-block:: bat SET MAPSERVER_HOME=C:\Installation\release-1911-x64-gdal-2-3-2-mapserver-7-2-1 SET MAPSERVER_HOME=D:\MapServer\release-1911-x64-gdal-2-3-2-mapserver-7-2-1 SET MAPSERVER_DEMO=D:\GitHub\mapserver-demo SET PATH=%MAPSERVER_HOME%\bin;%PATH% SET PROJ_LIB=%MAPSERVER_HOME%\bin\proj\SHARE cd /D %NOTEBOOK_HOME% REM run the script python mapscript-quickstart.py REM run the notebook jupyter notebook mapscript-quickstart.ipynb Jupyter and Binder ------------------ + https://mybinder.org/ + Repo - https://github.com/geographika/GeoPythonNotebooks + Path to notebook - notebooks/mapscript-quickstart.ipynb Running on OSGeoLive -------------------- .. code-block:: bash wget https://github.com/geographika/GeoPythonNotebooks/archive/master.zip unzip master.zip cd GeoPythonNotebooks-master/jupyter/quickstarts export MAPSERVER_DEMO="/rofs/usr/local/share/mapserver/demos/itasca" python -m jupyter notebook mapscript-quickstart.ipynb .. Can't set export PYTHONPATH="/rofs/usr/lib/python2.7/dist-packages:$PYTHONPATH" /usr/lib/otb/python unset PYTHONPATH printenv $PYTHONPATH /usr/lib/otb/python /rofs/usr/lib/python2.7/dist-packages/_mapscript.x86_64-linux-gnu.so jupyter is set to use python3 cat `which jupyter` #!/usr/bin/python3 /usr/bin/jupyter MapScript on Ubuntu ------------------- https://packages.ubuntu.com/search?suite=default&section=all&arch=any&keywords=mapscript&searchon=names + bionic (18.04LTS) (devel): Python library for MapServer [universe] + 7.0.7-1build2: amd64 arm64 armhf i386 ppc64el s390x + /usr/lib/x86_64-linux-gnu/libmapserver.so.2 + /usr/lib/x86_64-linux-gnu/libmapserver.so.7.0.7 Script Updates -------------- To add: + buffer - needs GEOS support + queryByShape towns near a lake .. #result = mapscript.msIO_getStdoutBufferString() # for string data, but this does not clear the buffer! # any future requests to msIO_getStdoutBufferBytes will get all the previous requests output_file = r"C:\Temp\map_ref.png" ref_image = map.drawReferenceMap() ref_image.save(output_file) result = results.getResult(0) print(result.classindex) # can get class, so therefore can test EXPRESSIONs! Linux Install ------------- .. code-block:: bash sudo apt-get update sudo apt-get install libmapserver2 sudo apt-get install python-mapscript sudo apt-get install python-pip pip install ipython ipython -c "import mapscript" python2 -c "import mapscript" .. ImportError: /usr/lib/libgdal.so.20: undefined symbol: sqlite3_column_table_name .. OSGeoLive repo https://git.osgeo.org/gitea/osgeolive/OSGeoLive12-Notebooks/src/branch/master<file_sep># --- # jupyter: # jupytext: # formats: ipynb,pct.py:percent,lgt.py:light,spx.py:sphinx,md,Rmd # text_representation: # extension: .pct.py # format_name: percent # format_version: '1.1' # jupytext_version: 0.8.0 # kernelspec: # display_name: Python 2 # language: python # name: python2 # language_info: # codemirror_mode: # name: ipython # version: 3 # file_extension: .py # mimetype: text/x-python # name: python # nbconvert_exporter: python # pygments_lexer: ipython3 # version: 3.6.6 # --- # %% [markdown] # # MapScript Quick Start # # Welcome to the Python MapScript quick start guide. # MapScript provides a programming interface to MapServer, and this notebook # provides an overview of its key functionality. # # ## Mapfiles # The simplest way to use MapScript is to work with an existing [Mapfile](https://mapserver.org/mapfile/). # A new ```mapObj``` can be created by passing the path to a Mapfile. We will # be working with the Itasca demo map that is also used in the # [MapServer Demo](http://localhost/mapserver_demos/itasca/) on OSGeoLive. # %% import sys sys.path.append("/rofs/usr/lib/python2.7/dist-packages") # temporary hack for OSGeoLive import os import mapscript from IPython.display import Image demo_fld = os.getenv("MAPSERVER_DEMO") mapfile = os.path.join(demo_fld, "itasca.map") map = mapscript.mapObj(mapfile) # %% [markdown] # Anything found in the Mapfile can be accessed and manipulated using MapScript. # For example we can get the count of all the layers in the Mapfile, and loop # through them printing out each layers name. # # MapScript objects are typically accessed using an index. # %% for idx in range(0, map.numlayers): lyr = map.getLayer(idx) print(lyr.name) # %% [markdown] # ## Drawing Maps # MapScript can be used to create an image file. The draw method # returns an imageObj which can be saved to a filename on disk. # %% import tempfile # before creating images let's set the working directory to the temp folder os.chdir(tempfile.gettempdir()) output_file = "map.png" image = map.draw() image.save(output_file) Image(filename=output_file) # %% [markdown] # The map image above doesn't contain all the layers in the Mapfile. # This can be because they are set to hidden by default using ```LAYER STATUS OFF```. # # To turn on these layers and create a more interesting map, we # can loop through the layers again and set their ```STATUS``` to ```ON```. # We can then use the ```isVisible``` method to check if the layer will # be drawn onto the map. # %% for idx in range(0, map.numlayers): lyr = map.getLayer(idx) lyr.status = mapscript.MS_ON print(lyr.name, lyr.isVisible()) # %% [markdown] # You may notice that the *ctybdpy2* layer is still not visible even though # we set its ```STATUS``` to ```ON```. This is due to the ```REQUIRES``` keyword in its layer # definition that hides the layer if the *drgs* layer is displayed. # The *ctyrdln3* and *ctyrdln3_anno* layers are both hidden because of the ```MAXSCALE 300000``` # layer setting. # Now we can now draw the map again with the newly visible layers. # %% output_file = "map_full.png" image = map.draw() image.save(output_file) Image(filename=output_file) # %% [markdown] # Other types of images can also be created from the ```mapObj```. These # use the same process of creating an ```imageObj``` and saving it to disk. # # For example to create a legend image: # %% output_file = "map_legend.png" legend_img = map.drawLegend() legend_img.save(output_file) Image(filename=output_file) # %% [markdown] # ## Querying Maps # As well as drawing maps using MapScript we can also query the data # referenced by the layers. In this example we will be finding the # layer to query using its name, and then querying the ```NAME``` field to find # the name of an airport. # %% qry_layer = map.getLayerByName('airports') qry_layer.queryByAttributes(qry_layer.map, "NAME", "Bowstring Municipal Airport", mapscript.MS_SINGLE) results = qry_layer.getResults() assert results.numresults == 1 # as we did a single query (using MS_SINGLE) there should be only one result result = results.getResult(0) Image(filename=output_file) # %% [markdown] # Query results are stored as ```resultCacheObj```. These contain a reference to the # result feature - a ```shapeObj```. The ```shapeObj``` can access both the geometry and # attributes of a feature. # # Let's get the ```shapeObj``` from the ```resultCacheObj``` and # loop through the shapes attributes to store them in a list. # %% result_shp = qry_layer.getShape(result) values = [] for idx in range(0, result_shp.numvalues): values.append(result_shp.getValue(idx)) print(values) # %% [markdown] # It would be nice to have also the property names alongside the values. Field names # are stored in the layer in which the ```shapeObj``` belongs, and not in the ```shapeObj``` # itself. We can get a list of fields from the layer, and then use the Python ```zip``` function # to join them with the shape values: # %% fields = [] for idx in range(0, qry_layer.numitems): fields.append(qry_layer.getItem(idx)) print(fields) props = zip(fields, values) # join fields to values print(props) # %% [markdown] # We can also create a map showing the query results: # *Note the imageObj is broken for Python MapScript 7.0, but is fixed in 7.2* # %% # create a new 400 by 400 empty image query_image = mapscript.imageObj(400, 400) # draw the query into the image and save it to file qry_layer.drawQuery(qry_layer.map, query_image) output_file = r"layer_query.png" query_image.save(output_file) Image(filename=output_file) # %% [markdown] # If we want to zoom in on the results we can set the map extent to a buffered area # around the results: # %% bbox = result_shp.bounds print(bbox.minx, bbox.miny, bbox.maxx, bbox.maxy) buffer = 2000 map.getLayerByName('drgs').status = mapscript.MS_OFF # hide the raster layer for this map map.setExtent(bbox.minx - buffer, bbox.miny - buffer, bbox.maxx + buffer, bbox.maxy + buffer) output_file = r"map_query.png" image = map.draw() image.save(output_file) Image(filename=output_file) # %% [markdown] # ## OGC Web Services # # MapScript can also be used to send requests to MapServer OWS capabilities, to # query WMS and WFS services. First we will get the WMS GetCapabilities XML for the map: # %% ows_req = mapscript.OWSRequest() ows_req.type = mapscript.MS_GET_REQUEST ows_req.setParameter("SERVICE", "WMS"); ows_req.setParameter("VERSION", "1.3.0"); ows_req.setParameter("REQUEST", "GetCapabilities"); # %% [markdown] # We use the msIO methods to capture the response the request # that is sent to ```stdout```. # The response is typically an HTTP response with HTTP content headers. # We can strip these out using MapScript # %% mapscript.msIO_installStdoutToBuffer() map.OWSDispatch(ows_req) content_type = mapscript.msIO_stripStdoutBufferContentType() # remove the content type header from the XML mapscript.msIO_stripStdoutBufferContentHeaders() # Strip all Content-* headers result = mapscript.msIO_getStdoutBufferBytes() print(result) # %% [markdown] # We can also retrieve images from a WMS service. # Rather than setting lots of individual parameters we can simply load them from # a string in the same format was would be sent via a web client. # %% # First let's get the extent of the map to use in the request extent = map.extent print(extent) bbox = "BBOX={},{},{},{}".format(extent.minx, extent.miny, extent.maxx, extent.maxy) querystring = "SERVICE=WMS&REQUEST=GetMap&VERSION=1.3.0&LAYERS=lakespy2&CRS=EPSG:26915&FORMAT=image/png&WIDTH=400&HEIGHT=400&{}".format(bbox) ows_req = mapscript.OWSRequest() ows_req.loadParamsFromURL(querystring) success = map.OWSDispatch(ows_req) assert success == mapscript.MS_SUCCESS # clear the HTTP headers or we will have an invalid image headers = mapscript.msIO_getAndStripStdoutBufferMimeHeaders() result = mapscript.msIO_getStdoutBufferBytes() output_file = "wms.png" with open(output_file, "wb") as f: f.write(result) Image(filename=output_file) # %% [markdown] # Finally let's get the SLD for one of the layers in the map: # %% lakes_layer = map.getLayerByName('lakespy2') result = lakes_layer.generateSLD() print(result) # %% [markdown] # Thanks for working through this notebook! For more information on MapScript # please see the [MapScript documentation](https://mapserver.org/mapscript/introduction.html). # Additional Python examples can be found in the [MapServer GitHub repository](https://github.com/mapserver/mapserver/tree/master/mapscript/python/examples)
edce6d895dadd16742260532aa153bff7c64ee35
[ "Python", "reStructuredText" ]
3
Python
geographika/GeoPythonNotebooks
288a0ed21820f4ad8ecfd989c288992122d9c46c
a1143a204b995b344cbf8cda457b99fc4cb3545f
refs/heads/master
<repo_name>jprogrammers/SpringSample<file_sep>/src/main/java/com/jprogrammers/spring/ConfigurationRunner.java package com.jprogrammers.spring; import com.jprogrammers.spring.config.Configuration; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * Created by alireza on 9/19/15. */ public class ConfigurationRunner { public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(Configuration.class); ctx.refresh(); SimpleBean myBean = (SimpleBean) ctx.getBean("myBean"); System.out.println(myBean.getName()); } } <file_sep>/src/main/java/com/jprogrammers/spring/config/Configuration.java package com.jprogrammers.spring.config; import com.jprogrammers.spring.SimpleBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; /** * Created by alireza on 9/19/15. */ @org.springframework.context.annotation.Configuration @PropertySource("classpath:app.properties") public class Configuration { @Autowired Environment env; @Bean public SimpleBean myBean(){ SimpleBean simpleBean = new SimpleBean(); simpleBean.setName(env.getProperty("simplebean.name")); return simpleBean; } }
03c67b156b1555931375c34476d1a40b65e4a18f
[ "Java" ]
2
Java
jprogrammers/SpringSample
ceed4bc53433ca3b02b61ab27782369e064ba0d6
66ccf6beb862a5640e606003ec25c3f4da568a6a
refs/heads/master
<repo_name>Hdonge/Algorithms<file_sep>/Array/word-search_79.js /** * @param {character[][]} board * @param {string} word * @return {boolean} */ var exist = function(board, word) { let rows = board.length; let columns = board[0].length; for(let i = 0; i < rows; i++){ for(let j = 0; j < columns; j++){ if(board[i][j] === word.charAt(0) && searchWordDfs(i, j, 0, board, word, rows, columns)){ return true; } } } return false; }; function searchWordDfs(i, j, countIndex, board, word, rows, columns){ if(countIndex === word.length){ //Break backtracking return true; }else{ //Continue backtracking if(i < 0 || i >= rows || j < 0 || j >= columns || board[i][j] !== word.charAt(countIndex)){ //Boundry conditions and non satisfying condition return false; } let temp = board[i][j]; board[i][j] = ''; // Make visted/used elements blank let found = searchWordDfs(i+1, j, countIndex+1, board, word, rows, columns) || searchWordDfs(i-1, j, countIndex+1, board, word, rows, columns) || searchWordDfs(i, j+1, countIndex+1, board, word, rows, columns) || searchWordDfs(i, j-1, countIndex+1, board, word, rows, columns); board[i][j] = temp; return found; } }<file_sep>/Array/pascals-triangle_118.js /** * @param {number} numRows * @return {number[][]} */ var generate = function(numRows) { let triangle = []; if(numRows == 0){ return triangle; } //first row triangle.push([1]); for(let i = 1; i < numRows; i++){ let row = []; let prev_row = triangle[i - 1]; //Initial 1 row.push(1); //element boundry cells from insertion in this loop. boundry cells will only contain 1. for(let j = 1; j < i; j++){ row.push(prev_row[j-1] + prev_row[j]); } //last 1 row.push(1); triangle.push(row); } return triangle; };<file_sep>/Array/spiral-matrix_54.js /** * @param {number[][]} matrix * @return {number[]} */ //With using direction flag var spiralOrder = function(matrix) { let output = []; if(matrix === null || matrix.length === 0){ return output; } let top = 0; let bottom = matrix.length - 1; let left = 0; let right = matrix[0].length -1; let dir = 0; //dir (direction can be 0,1,2,3) while(left <= right && top <= bottom){ if(dir === 0){ //Print column elements for(let i = left; i <= right; i++){ output.push(matrix[top][i]); } top++; dir = 1; }else if(dir === 1){ //Print row elements for(let i = top; i <= bottom; i++ ){ output.push(matrix[i][right]); } right--; dir = 2; }else if(dir === 2){ //Print column elements for(let i = right; i >= left; i--){ output.push(matrix[bottom][i]); } bottom--; dir = 3; }else if(dir === 3){ //Print row elements for(let i = bottom; i >= top; i--){ output.push(matrix[i][left]); } left++; dir = 0; } } return output; }; //Without using direction flag /*var spiralOrder = function(matrix) { let output = []; if(matrix === null || matrix.length === 0){ return output; } let top = 0; let bottom = matrix.length - 1; let left = 0; let right = matrix[0].length -1; let matrixLength = matrix.length * matrix[0].length; while(output.length < matrixLength){ //Print column elements for(let i = left; i <= right && output.length < matrixLength; i++){ output.push(matrix[top][i]); } top++; //Print row elements for(let i = top; i <= bottom && output.length < matrixLength; i++ ){ output.push(matrix[i][right]); } right--; //Print column elements for(let i = right; i >= left && output.length < matrixLength; i--){ output.push(matrix[bottom][i]); } bottom--; //Print row elements for(let i = bottom; i >= top && output.length < matrixLength; i--){ output.push(matrix[i][left]); } left++; } return output; };*/<file_sep>/Array/move_zeros_283.js /** * @param {number[]} nums * @return {void} Do not return anything, modify nums in-place instead. */ var moveZeroes = function(nums) { let length = nums.length let indexToBeFilled = 0; for(let i = 0; i < length; i++){ if(nums[i]!==0){ //below swap pulls non zero elements to left. //if non zero element is found at zero index then nothing will be swapped until zero is found. swap(nums, i, indexToBeFilled); indexToBeFilled++; } } return nums; }; var swap = function(nums, i, indexToBeFilled){ let temp = nums[indexToBeFilled]; nums[indexToBeFilled] = nums[i]; nums[i] = temp; } //Follow to fill empty spaces(0s) from start so it will push empty spaces(0s) at the end.<file_sep>/README.md # Algorithms Notes for data structures and algorithms Leetcode Solutions <file_sep>/Array/max-area-of-island_695.js /** * @param {number[][]} grid * @return {number} */ var maxAreaOfIsland = function(grid) { if(grid == null || grid.length ==0){ return 0; } let maxAreaOfIsland = 0; for(let i = 0; i < grid.length; i++){ for(let j = 0; j < grid[i].length; j++){ maxAreaOfIsland = Math.max(maxAreaOfIsland, dfs(grid, i, j)); } } return maxAreaOfIsland; }; var dfs = function(grid, i, j){ //If land not found at given indices then return 0 if(i < 0 || i >= grid.length || j < 0 || j >= grid[i].length || grid[i][j] != 1){ return 0; } //Before returning 1 mark all the connected neibours to 2 using dfs so during next iteration those will not get considered. grid[i][j] = 2; let noOfConnectedIsland = 1 + dfs(grid, i-1, j) + dfs(grid, i+1, j) + dfs(grid, i, j-1) + dfs(grid, i, j+1); return noOfConnectedIsland; };<file_sep>/LinkedList/intersection-of-two-linked-lists_169.js /** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} headA * @param {ListNode} headB * @return {ListNode} */ //1. Two pointer approach var getIntersectionNode = function(headA, headB) { if(headA == null || headB == null){ return null; } let a_pointer = headA; let b_pointer = headB; while(a_pointer !==b_pointer){ if(a_pointer == null){za a_pointer = headB; }else{ a_pointer = a_pointer.next; } if(b_pointer == null){ b_pointer = headA; }else{ b_pointer = b_pointer.next; } } return a_pointer; }; //2. Using Hashset /*var getIntersectionNode = function(headA, headB) { let visitedMap = new Map(); while(headA !== null){ visitedMap.set(headA); headA = headA.next; } while(headB !== null){ if(visitedMap.has(headB)){ return headB; }; headB = headB.next; } return null; };*/<file_sep>/Array/two-sum_1.js /** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function(nums, target) { let length = nums.length; let map = new Map(); for(let i= 0; i<length; i++){ //First get the index of the diffrenece of target and new value getting inserted . Then check if the difference is already present let difIndex = map.get(target - nums[i]); if(difIndex !== undefined){ return [difIndex,i]; }else{ map.set(nums[i],i); } } return [-1,-1]; };<file_sep>/Tree/flatten-binary-tree-to-linked-list_114.js /** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {void} Do not return anything, modify root in-place instead. */ var flatten = function(root) { if(root == null){ return; } let stack = []; stack.push(root); while(stack.length != 0){ let current = stack.pop(); if(current.right != null){ stack.push(current.right); } if(current.left != null){ stack.push(current.left); } if(stack.length != 0){ current.right = stack[stack.length -1]; } current.left = null; } }; <file_sep>/Tree/house-robber-iii_337.js /** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number} */ /* basically Math.max(child+grandparents,parents) in layman terms! */ let map = new Map(); var rob = function(root) { if (root == null){ return 0; } if(map.has(root)){ return map.get(root) } let total = 0; if(root.left != null){ total += rob(root.left.left) + rob(root.left.right); } if(root.right != null){ total += rob(root.right.left) + rob(root.right.right) } map.set(root, Math.max(root.val + total, rob(root.left) + rob(root.right))); return map.get(root); }; <file_sep>/Tree/populating-next-right-pointers-in-each-node_116.js /** * // Definition for a Node. * function Node(val, left, right, next) { * this.val = val === undefined ? null : val; * this.left = left === undefined ? null : left; * this.right = right === undefined ? null : right; * this.next = next === undefined ? null : next; * }; */ /** * @param {Node} root * @return {Node} */ var connect = function(root) { if(root == null){ return null; } let q = []; q.push(root); q.push(null); while(q.length != 0){ let current = q.shift(); if(current == null && q.length == 0){//This step says operation is completed which means there is no element from tree present in queue. return root; }else if(current == null){//When iteration reaches to null which means the all the child nodes of current level are inserted into queue and can insert null in queue now. q.push(null); }else{ current.next = q[0]; //Current node point towards next node in queue. if(current.left != null){ q.push(current.left); } if(current.right != null){ q.push(current.right); } } } return root; };<file_sep>/LinkedList/add-two-numbers_2.js /** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ var addTwoNumbers = function(l1, l2) { let v1 = 0, v2 = 0, sum = 0, carry = 0; let sumHead = new ListNode(-1); let ptr = sumHead; while(l1!=null || l2!= null){ v1 = l1 != null ? l1.val : 0; l1 = l1 != null ? l1.next : null; v2 = l2 != null ? l2.val : 0; l2 = l2 != null ? l2.next : null; sum = v1 + v2 + carry; carry = Math.floor(sum/10); sum = Math.floor(sum%10); let temp = new ListNode(sum); ptr.next = temp; ptr = ptr.next; } if(carry != 0){ let temp = new ListNode(carry); ptr.next = temp; } return sumHead.next; };<file_sep>/Array/majority_element_169.js /** * @param {number[]} nums * @return {number} */ //O(n) & O(n) var majorityElement = function(nums) { let length = nums.length; let majorityLength = length/2; let map = new Map(); let majorityElement; for(let i = 0; i< length; i++){ let count = map.get(nums[i]) || 0; count = count + 1; map.set(nums[i], count); } for(let [key, value] of map){ if(value > majorityLength){ majorityElement = key } } return majorityElement; }; //To solve this is O(1) it can be done with sorting but there it will affect the time complexity which will go O(nlogn). //O(nlogn) & O(1) /*var majorityElement = function(nums) { return nums.sort()[Math.floor(nums.length/2)]; }*/<file_sep>/Tree/diameter-of-binary-tree_543.js /** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number} */ let num_of_nodes; var diameterOfBinaryTree = function(root) { num_of_nodes = 1; getDiameter(root) return num_of_nodes - 1; }; var getDiameter = function(node){ if(node == null){ return 0; } let leftDiameter = getDiameter(node.left); let rightDiameter = getDiameter(node.right); num_of_nodes = Math.max(num_of_nodes, leftDiameter + rightDiameter + 1); return Math.max(leftDiameter, rightDiameter) + 1 } //Calculate no. of nodes - 1 = edges.<file_sep>/Array/merge-intervals_56.js /** * @param {number[][]} intervals * @return {number[][]} */ //1. Basic alogrithm /*var merge = function(intervals) { if(intervals === null || intervals.length === 0){ return intervals; } //Sort intervals intervals.sort((a, b) => a[0] - b[0]); //O(nlog(n)) let output = []; let current_interval = intervals[0]; output.push(current_interval); for(let interval = 1; interval < intervals.length; interval++){ let current_begin = current_interval[0]; let current_end = current_interval[1]; let next_begin = intervals[interval][0]; let next_end = intervals[interval][1]; if(next_begin <= current_end){ current_interval[1] = Math.max(current_end, next_end); }else{ current_interval = intervals[interval]; output.push(current_interval); } } return output; };*/ //2. Improved solution. inplace var merge = function(intervals) { if(intervals === null || intervals.length === 0){ return intervals; } //Sort intervals intervals.sort((a, b) => a[0] - b[0]); //O(nlog(n)) for(let interval = 0; interval < intervals.length -1; interval++){ let [current_begin, current_end] = intervals[interval]; let [next_begin, next_end] = intervals[interval + 1]; if(next_begin <= current_end){ intervals[interval][0] = Math.min(current_begin, next_begin); intervals[interval][1] = Math.max(current_end, next_end); //Splice next interval since next interval information got merged into current. intervals.splice(interval+1,1); //To check if current interval is again matching to next to next interval will have to keep pointer to first element in for loop for next loop interval--; } } return intervals; }; <file_sep>/Array/remove-duplicates-from-sorted-array_26.js /** * @param {number[]} nums * @return {number} */ var removeDuplicates = function(nums) { let length = nums.length; let indexToBeFilled = 0; for(let i = 0; i< length; i++){ //below pulls the non equal , unique elements to front of the array if(nums[i] !== nums[indexToBeFilled]){ indexToBeFilled++; swap(nums, i, indexToBeFilled); } } let uniqueCount = indexToBeFilled +1; return uniqueCount; }; var swap = function(nums, i, indexToBeFilled){ let temp = nums[i]; nums[i] = nums[indexToBeFilled]; nums[indexToBeFilled] = temp; }
111448ca661296d1a03f13644be4a31472a27a67
[ "JavaScript", "Markdown" ]
16
JavaScript
Hdonge/Algorithms
a9f1e3e1825ebc6b3252409b74640c4c7dc4db07
bd8bc60a170e0e69f90d75f69275024dae66b9ef
refs/heads/master
<repo_name>Mikhail1988/interview-task<file_sep>/src/main/java/my/infobip/task/data/ShorterStorage.java package my.infobip.task.data; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public interface ShorterStorage { String save(String url, String userName, int redirectType); ShorterRecord find(String shortUrl); Map<String, Integer> findByUser(String user); } <file_sep>/src/main/java/my/infobip/task/rest/controller/AppController.java package my.infobip.task.rest.controller; import my.infobip.task.data.ShorterRecord; import my.infobip.task.data.ShorterStorage; import my.infobip.task.rest.message.CreateAccountRequest; import my.infobip.task.rest.message.CreateAccountResponse; import my.infobip.task.rest.message.RegisterURLRequest; import my.infobip.task.rest.message.RegisterURLResponse; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.provisioning.UserDetailsManager; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; @RestController public class AppController { @Autowired private UserDetailsManager userDetailsManager; @Autowired private ShorterStorage shorterStorage; @RequestMapping(value = "account", method = RequestMethod.POST) ResponseEntity<CreateAccountResponse> craeteAccount(@Valid @RequestBody CreateAccountRequest accountMsg) { if(userDetailsManager.userExists(accountMsg.getAccountId())) { CreateAccountResponse createAccountResponce = new CreateAccountResponse(false, "Name is busy", null); return ResponseEntity.badRequest().body(createAccountResponce); } List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new SimpleGrantedAuthority("USER")); String password = RandomStringUtils.randomAlphanumeric(8); UserDetails user = new User(accountMsg.getAccountId(), password, authorities); userDetailsManager.createUser(user); CreateAccountResponse createAccountResponce = new CreateAccountResponse(true, "Your account is opened", password); return ResponseEntity.status(HttpStatus.CREATED).body(createAccountResponce); } @GetMapping("statistic/{accountId}") ResponseEntity<Map<String, Integer>> statisticsForUser(@PathVariable String accountId) { if(userDetailsManager.userExists(accountId)) { return ResponseEntity.ok(shorterStorage.findByUser(accountId)); } else { return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); } } @RequestMapping(value = "register", method = RequestMethod.POST) ResponseEntity<?> registerURL(HttpServletRequest req, @Valid @RequestBody RegisterURLRequest urlRequest) throws MalformedURLException { String name = SecurityContextHolder.getContext().getAuthentication().getName(); String shortUrl = shorterStorage.save(urlRequest.getUrl(),name, urlRequest.getRedirectType()); URL shortUrl1 = new URL(req.getScheme(), req.getServerName(), req.getServerPort(), "/" + shortUrl); return ResponseEntity.status(HttpStatus.CREATED).body(new RegisterURLResponse(shortUrl1)); } @GetMapping("{shortUrl}") void redirect(@PathVariable String shortUrl, HttpServletResponse response) { ShorterRecord r = shorterStorage.find(shortUrl); if(r == null) { response.setStatus(HttpStatus.NOT_FOUND.value()); } else { r.hit(); response.setStatus(r.getRedirectType()); response.setHeader("Location", r.getUrl()); response.setHeader("Connection", "close"); } } } <file_sep>/src/main/java/my/infobip/task/config/SecurityConfiguration.java package my.infobip.task.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Bean public InMemoryUserDetailsManager userDetailsManager() { InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); return manager; } // @Autowired // public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception { // auth.inMemoryAuthentication().withUser("user2").password("<PASSWORD>").roles("USER"); // } @Override protected void configure(HttpSecurity http) throws Exception { http.userDetailsService(userDetailsManager()) .csrf().disable() .authorizeRequests() .mvcMatchers("/register", "/statistic/{account}").authenticated() .mvcMatchers("/help", "/account").permitAll() .and() .httpBasic(); } }
e86375a17913ab193e03405e34fc1fea6aa36d24
[ "Java" ]
3
Java
Mikhail1988/interview-task
ff39dc52ac823485b6b6f904801ad30e164bfda3
f2c09a213e0fe97c557e83d8f6d12a1da463c96e
refs/heads/master
<repo_name>veditor/veditor<file_sep>/packages/editor/src/plugins/utils/predictions.js /** * * @param {string} tagName * @return {function(Element): boolean} */ export function isElement (tagName) { tagName = tagName.toUpperCase() if (isElement.map[tagName]) { return isElement.map[tagName] } const prediction = element => { return element.tagName === tagName } isElement.map[tagName] = prediction return prediction } isElement.map = {} <file_sep>/packages/editor/src/lib/plugins.js import Vue from 'vue' export class PluginManager { constructor (frame) { this.groups = [] this.hotKeys = {} this.pluginMap = {} this.plugins = [] this.$frame = frame } install (plugin) { if (typeof plugin === 'function') { plugin(this) } else if (typeof plugin === 'object') { if (Array.isArray(plugin)) { this.registerInGroup(null, plugin) } else if (plugin) { this.register(plugin) } } } register (pluginOptions, Constructor = Plugin) { const { groupName, hotKey, key } = pluginOptions const plugin = new Constructor(pluginOptions, this) if (groupName) { const group = this.findGroup(groupName) group.plugins.push(plugin) plugin.group = group } Vue.set(this.pluginMap, key, plugin) this.plugins.push(plugin) if (hotKey) { Vue.set(this.hotKeys, hotKey, key) } } registerInGroup (groupName, arr) { if (groupName) { const group = this.findGroup(groupName) arr.forEach(item => { this.register(Object.assign({ groupName }, item), group.pluginType) }) } else { arr.forEach(item => { this.register(item) }) } } registerGroup (group) { this.groups.push(group) } findGroup (name) { let group if (!(group = this.groups.find(group => group.name === name))) { throw new Error(`No such group ${name}`) } return group } handle (groupName, handlers) { Object.assign(this.findGroup(groupName).handlers, handlers) } triggerPlugin (key, selection, e) { const plugin = this.pluginMap[key] if (!plugin) { return false } plugin.group ? plugin.group.handlers.run(plugin, selection, e) : plugin.handler(selection, e) return true } } export class PluginGroup { name plugins handlers pluginType constructor (name, pluginType = Plugin, handlers = {}) { this.name = name this.handlers = { ...handlers } this.pluginType = pluginType this.plugins = [] } } export class Plugin { key icon iconContent order handler title description state hotKey isActive panelComponent getStyle constructor (options = {}, manager) { Object.assign(this, options) this.$manager = manager } get isPanelOpen () { if (!this.panelComponent || !this.$panelInstance) { return false } return !!this.$panelInstance.$el.parentElement } get editor () { return this.$manager.$frame.$refs.editor } get bar () { return this.$manager.$frame.$refs.bar } togglePanel () { if (!this.panelComponent) return if (this.isPanelOpen) { this.$panelInstance.$el.parentElement.removeChild(this.$panelInstance.$el) this.state.active = false return } const frame = this.$manager.$frame const el = frame.$refs.panel this.state.active = true if (this.$manager.$currentPanelPlugin) this.$manager.$currentPanelPlugin.state.active = false el.childNodes.forEach(node => node.remove()) if (this.$panelInstance) { el.appendChild(this.$panelInstance.$el) } else { const instance = new this.$manager.$frame.constructor({ data () { return { show: false } }, render: (h) => h(this.panelComponent), parent: frame }) instance.$mount() this.$panelInstance = instance el.appendChild(instance.$el) } this.$manager.$currentPanelPlugin = this } } export class FormatPlugin extends Plugin { constructor ({ key, icon, iconContent, command, commandArg, order, description, hotKey }, manager) { super({ key, icon, iconContent, command, order, description, hotKey, isActive () { return document.queryCommandState(command) }, state: { active: document.queryCommandState(command) }, handler (_, selection) { selection.select() document.execCommand(command, false, typeof commandArg === 'function' ? commandArg() : commandArg) this.$manager.$frame.$refs.editor.focus() return { active: document.queryCommandState(command) } } }, manager) } } export class PanelPlugin extends Plugin { constructor ({ key, icon, iconContent, order, description, hotKey, component, initialValue, handleChange, anchor, focus }) { super({ key, icon, iconContent, order, description, hotKey, component, initialValue, handleChange, anchor, focus, isActive: () => false, state: { active: false } }) } } <file_sep>/packages/ui/src/components/List/index.js export { default as List } from './List' export { default as ListDivider } from './ListDivider' export { default as ListItem } from './ListItem' <file_sep>/packages/editor/src/plugins/common/basic-command/index.js import Basic from './basic.json' import Heading from './heading.json' import Indent from './indent.json' import Align from './align.json' import List from './list.json' export default [...Basic, ...Heading, ...Indent, ...Align, ...List] <file_sep>/packages/ui/src/index.js export * from './components/Article' export * from './components/Bar' export * from './components/Form' export * from './components/Icon' export * from './components/List' export * from './components/Menu' export * from './components/Scrollable' <file_sep>/packages/editor/vue.config.js const path = require('path') module.exports = { chainWebpack: config => { config.resolve.alias.set('@veditor/ui', path.resolve(__dirname, '../ui/')) } } <file_sep>/packages/editor/src/plugins/common/invisible/select-all.js export default { key: 'select-all', hotKey: 'mod+a', handler () { document.getSelection().selectAllChildren(this.editor.$el) this.editor.handleSelectionMoved() return false } } <file_sep>/packages/ui/src/components/Menu/index.js export { createPopMenu } from './global' export { default as PopMenu } from './PopMenu' <file_sep>/packages/editor/src/plugins/common/panel-plugin/index.js import Hyperlink from './hyperlink' import FrontColor from './front-color' import BackColor from './back-color' export default [ Hyperlink, FrontColor, BackColor ] <file_sep>/packages/editor/src/plugins/common/panel-plugin/hyperlink.js import HyperLinkPanel from './HyperLinkPanel' export default { key: 'hyperlink', icon: 'insert_link', state: { active: false, peek: false }, focus: true, component: HyperLinkPanel, initialValue ({editor, bar}) { return { insertion: editor.$lastSelection.type === 'Caret', selection: editor.$lastSelection } }, handleChange ({title, href}, {editor, bar}) { if (editor.$lastSelection.select()) { switch (editor.$lastSelection.type) { case 'Range': document.execCommand('createLink', false, href) bar.dismissPop() break case 'Caret': const a = document.createElement('a') a.href = href a.innerText = title editor.$lastSelection.rawRange.insertNode(a) document.getSelection().selectAllChildren(a) document.getSelection().collapseToEnd() bar.dismissPop() break } } } } <file_sep>/packages/ui/src/directive/click-highlight.js import './click-highlight.scss' const MAX_TIMEOUT = 250 const HIGHLIGHT_CLASS = 'v-click-highlight' export default { bind (el) { const trigger = el.__highlightTrigger = () => triggerHighlight(el) el.addEventListener('mousedown', trigger) el.addEventListener('touchstart', trigger) }, unbind (el) { el.removeEventListener('mousedown', el.__highlightTrigger) el.removeEventListener('mouseup', el.__highlightRemover) el.removeEventListener('mouseout', el.__highlightRemover) el.removeEventListener('touchend', el.__highlightRemover) } } export function trigger (el) { if (el instanceof Element) { triggerHighlight(el, false) setTimeout(() => removeHighlight(el), MAX_TIMEOUT) } else { trigger(el.$el) } } function triggerHighlight (el, bindEvents = true) { const remover = el.__highlightRemover = () => removeHighlight(el) el.classList.add(HIGHLIGHT_CLASS) el.__highlightStartTimestamp = Date.now() if (bindEvents) { el.addEventListener('mouseup', remover) el.addEventListener('mouseout', remover) el.addEventListener('touchend', remover) } if (el.__highlightStopTimeout) { clearTimeout(el.__highlightStopTimeout) el.__highlightStopTimeout = undefined } } function removeHighlight (el) { const delta = Date.now() - el.__highlightStartTimestamp if (delta > MAX_TIMEOUT) { el.classList.remove(HIGHLIGHT_CLASS) } else { el.__highlightStopTimeout = setTimeout(() => removeHighlight(el), MAX_TIMEOUT - delta) } } <file_sep>/packages/editor/src/lib/wysiwyg-utils.js import { css, StyleSheet } from 'aphrodite' const selection = document.getSelection() export class CurrentSelection { type caret range /** * * @type {Range} */ rawRange constructor () { this.rawRange = selection.getRangeAt(0) switch (selection.type) { case 'Caret': { this.type = 'Caret' this.caret = { node: selection.baseNode, offset: selection.baseOffset } break } case 'Range': { this.type = 'Range' this.range = { start: { node: selection.anchorNode, offset: selection.anchorOffset }, end: { node: selection.extentNode, offset: selection.extentOffset } } } } } select () { try { switch (this.type) { case 'Caret': { selection.setPosition(this.caret.node, this.caret.offset) } break case 'Range': { const { start, end } = this.range selection.setBaseAndExtent(start.node, start.offset, end.node, end.offset) break } } return true } catch (e) { console.error(e) return false } } /** * @return {CSSStyleDeclaration} */ get style () { if (!this._style) { switch (this.type) { case 'Caret': this._style = getComputedStyle(getNearestElement(this.caret.node)) break case 'Range': this._style = getComputedStyle( getNearestElement(this.range.start.node)) break } } return this._style } get element () { return getNearestElement(this.rawRange.endContainer) } } function getNearestElement (node) { while (node.nodeType !== Node.ELEMENT_NODE) { node = node.parentNode } return node } export function getCurrentSelection () { return new CurrentSelection() } /** * * @param {Selection} selection * @param {String} text */ export function insertOrReplaceText (selection, text) { let positioningNode let positioningOffset switch (selection.type) { case 'Caret': { const node = selection.baseNode const offset = selection.baseOffset const textContent = node.textContent node.textContent = textContent.slice(0, offset) + text + textContent.slice(offset) positioningNode = node positioningOffset = offset + text.length break } case 'Range': { for (let i = 0; i < selection.rangeCount; i++) { const range = selection.getRangeAt(i) range.deleteContents() } let node = selection.baseNode while (node.nodeType === Node.ELEMENT_NODE) { node = node.childNodes.item(0) } node.textContent += text positioningNode = node positioningOffset = node.textContent.length break } } if (positioningNode.nodeType === Node.ELEMENT_NODE) { selection.setPosition(positioningNode.childNodes.item(0), positioningOffset) } else { selection.setPosition(positioningNode, positioningOffset) } } /** * * @param {Selection} selection * @param {Object} styles */ export function insertOrReplaceStyle (selection, styles) { const cssString = StyleSheet.create({ default: styles }) switch (selection.type) { case 'Caret': const node = selection.baseNode const offset = selection.baseOffset const span = document.createElement('span') span.className = css(cssString.default) const fragment = document.createDocumentFragment() fragment.append(node.textContent.slice(0, offset), span, node.textContent.slice(offset)) node.parentNode.replaceChild(fragment, node) span.append('') selection.setPosition(span.nextSibling, 0) } } /** * * @param {Selection} selection * @param {Object} styles */ export function isChildren (selection, styles) { } <file_sep>/packages/editor/src/plugins/common/panel-plugin/back-color.js import ColorPanel from './ColorPanel' export default { key: 'background-color', icon: 'format_color_fill', state: { active: false }, component: ColorPanel, initialValue ({editor, bar}) { return editor.$lastSelection.style.backgroundColor }, handleChange (color, {editor, bar}) { if (editor.$lastSelection.select()) { document.execCommand('hiliteColor', false, color) } } } <file_sep>/packages/ui/src/components/Menu/global.js import Vue from 'vue' import PopMenu from './PopMenu' import VClickOutside from 'v-click-outside' /** * * @param position * @param {function(CreateElement): VNode[]} render * @param props */ export function createPopMenu ( position, render, props = {}, el = document.body) { const pop = (new Vue({ name: 'GlobalPopMenu', data () { return { show: false } }, directives: { 'click-outside': VClickOutside.directive }, render (h) { return <Transition name="pop-out"> { this.show ? <PopMenu position={position} mousetrapTarget={props.mousetrapTarget} vClickOutside={{ handler: () => this.onClickOutside(), middleware: () => !this.__clickingFrame, events: ['click', 'dbclick', 'contextmenu', 'touchstart'] }}> {render(h)} </PopMenu> : '' } </Transition> }, class: 'v-global-pop-menu', methods: { onClickOutside () { dismissPopMenu() } }, mounted () { this.show = true this.__clickingFrame = true setTimeout(() => this.__clickingFrame = false, 0) }, beforeDestroy () { this.show = false } })).$mount() document.body.appendChild(pop.$el) function dismissPopMenu () { if (!pop.show) { return } pop.show = false pop.$nextTick(() => { pop.$destroy() pop.$el.remove() cbs.forEach(cb => cb()) }) } const cbs = [] dismissPopMenu.onDismiss = function onPopMenuDismissed (cb) { cbs.push(cb) return dismissPopMenu } return dismissPopMenu } <file_sep>/README.md [![lerna](https://img.shields.io/badge/maintained%20with-lerna-cc00ff.svg)](https://lernajs.io/) # veditor - VEditor is a editor and viewer for pluggable document. - VEditor uses raw html to store texts. - All plugins should use HTML5 api.
81decf1978bfe5af936b71092b4d7b37b6af0121
[ "JavaScript", "Markdown" ]
15
JavaScript
veditor/veditor
2af696811fad92e4442b7c73ea1b71973ab5c1f9
c0f685eb81922e1372829055f8901800d2e36e31
refs/heads/master
<file_sep>import csv import hw2 from sklearn.svm import * def get_svm_accuracy(train_data, train_labels, validation_data, validation_labels, kernel): linear_svc_instance = SVC(kernel=kernel, gamma=1.2) linear_svc_instance.fit(train_data, train_labels) validation_accuracy = linear_svc_instance.score(validation_data, validation_labels) train_accuracy = linear_svc_instance.score(train_data, train_labels) return [kernel, train_accuracy, validation_accuracy] kernels = ['linear', 'poly', 'rbf'] train_data, train_labels, test_data, test_labels, validation_data, validation_labels = hw2.get_data() for kernel in kernels: print(get_svm_accuracy(train_data, train_labels, validation_data, validation_labels, kernel=kernel))<file_sep>from numpy import * import numpy.random from sklearn.datasets import fetch_mldata import sklearn.preprocessing def get_data(): mnist = fetch_mldata('MNIST original') data = mnist['data'] labels = mnist['target'] neg, pos = 0,8 train_idx = numpy.random.RandomState(0).permutation(where((labels[:60000] == neg) | (labels[:60000] == pos))[0]) test_idx = numpy.random.RandomState(0).permutation(where((labels[60000:] == neg) | (labels[60000:] == pos))[0]) train_data_size = 2000 train_data_unscaled = data[train_idx[:train_data_size], :].astype(float) train_labels = (labels[train_idx[:train_data_size]] == pos)*2-1 #validation_data_unscaled = data[train_idx[6000:], :].astype(float) #validation_labels = (labels[train_idx[6000:]] == pos)*2-1 test_data_size = 2000 test_data_unscaled = data[60000+test_idx[:test_data_size], :].astype(float) test_labels = (labels[60000+test_idx[:test_data_size]] == pos)*2-1 # Preprocessing train_data = sklearn.preprocessing.scale(train_data_unscaled, axis=0, with_std=False) #validation_data = sklearn.preprocessing.scale(validation_data_unscaled, axis=0, with_std=False) test_data = sklearn.preprocessing.scale(test_data_unscaled, axis=0, with_std=False) # noramlize normalize_dataset(train_data) normalize_dataset(test_data) train_positive_data = list() train_negative_data = list() for i in range(len(train_data)): if train_labels[i] == 1: train_positive_data.append(train_data[i]) else: train_negative_data.append(train_data[i]) return numpy.array(train_positive_data), numpy.array(train_negative_data), numpy.array(train_data), train_labels def normalize_dataset(dataset): for i in range(len(dataset)): train_data_norm = numpy.linalg.norm(dataset[i]) dataset[i] /= float(train_data_norm)<file_sep>from k_nn_a import * import csv def k_nn_d(): results = list() n = 100 k = 10 while n < 5100: accuracy = k_nn_executor(k, n) result_entry = (n, accuracy) results.append(result_entry) print(result_entry) n += 100 # write to csv with open("k_nn_d.csv", "wb") as f: writer = csv.writer(f) writer.writerows(results) k_nn_d() <file_sep>from pca import * import hw4 import matplotlib.pyplot as plt # prepare data for testing train_positive_data, train_negative_data, train_data, train_labels = hw4.get_data() mypca = MyPCA() mypca.fit(np.array(train_data)) projections_matrix = mypca.transform(train_data, n_components=2) projections_x = list() projections_y = list() projections_colors = list() for i in range(len(train_data)): projections_x.append(projections_matrix[i][0]) projections_y.append(projections_matrix[i][1]) projections_colors.append(0 if train_labels[i] == 1 else 2000) plt.scatter(projections_x, projections_y, c=projections_colors) #plt.show() plt.savefig("plot/plot.png") print(projections_x)<file_sep>import numpy as np from matplotlib.pyplot import savefig, imshow class MyPCA: def __init__(self): pass def fit(self, X): self.mean = np.mean(X, axis=0) X -= self.mean u, s, v_t = np.linalg.svd(X, full_matrices=False) S = np.diag(s) self.U = u self.V = v_t self.S = S def get_mean(self): return self.mean def get_eigenvectors(self): return self.V def get_eigenvalues(self): return np.diag(self.S) def transform(self, X, n_components): X = X - self.mean X_transformed = np.dot(X, self.get_eigenvectors()[:n_components].T) return X_transformed def reconstruct(self, projection, n_components): X = np.dot(projection, self.get_eigenvectors()[0:n_components]) return X def experiment(dataset, folder_to_save): mypca = MyPCA() mypca.fit(np.array(dataset)) # save mean matrix mean_matrix = mypca.get_mean() imshow(np.reshape(mean_matrix, (28, 28)), interpolation="nearest") savefig(folder_to_save + "/mean_matrix.png") # save eigenvectors eigenvectors = mypca.get_eigenvectors() for i in range(5): imshow(np.reshape(eigenvectors[i], (28, 28)), interpolation="nearest") savefig(folder_to_save + "/eigenvector_" + str(i + 1) + ".png") eigenvalues = mypca.get_eigenvalues() with open(folder_to_save + "/eigenvalues", "w") as f: for i in range(100): f.write(str(eigenvalues[i]) + "\n") <file_sep>from numpy import reshape from matplotlib.pyplot import imshow, savefig import hw2 import sgd eta_zero = 10 ** -1 c = 10 ** -2 def get_best_w(training_set, C, eta_zero, T): sgd_instance = sgd.SGD(training_set) sgd_instance.train(C, eta_zero, T) return sgd_instance.get_w() def experiment(): train_data, train_labels, test_data, test_labels, validation_data, validation_labels = hw2.get_data() return get_best_w(zip(train_data, train_labels), C=c, eta_zero=eta_zero, T=2000) w = experiment() imshow(reshape(w, (28, 28)), interpolation="nearest") savefig("sgd_c.png") <file_sep>import csv import hw2 from sklearn.svm import * C = 10 def get_svm_accuracy(log_c, train_data, train_labels, validation_data, validation_labels): linear_svc_instance = LinearSVC(loss='hinge', fit_intercept=False, C=C ** log_c) linear_svc_instance.fit(train_data, train_labels) validation_accuracy = linear_svc_instance.score(validation_data, validation_labels) train_accuracy = linear_svc_instance.score(train_data, train_labels) return [log_c, train_accuracy, validation_accuracy] train_data, train_labels, test_data, test_labels, validation_data, validation_labels = hw2.get_data() log_c = -10 results = list() while log_c <= 10: results.append(get_svm_accuracy(log_c, train_data, train_labels, validation_data, validation_labels)) log_c += 1 # write to csv with open("svm_a.csv", "wb") as f: writer = csv.writer(f) writer.writerows(results)<file_sep>import csv import numpy import hw2 import sgd eta_zero = 10 ** -1 c_base = 10 def calculate_accuracy(training_set, validation_data, validation_labels, C, eta_zero, T): sgd_instance = sgd.SGD(training_set) sgd_instance.train(C, eta_zero, T) accuracy = 0 for i in range(len(validation_data)): prediction = sgd_instance.predict(validation_data[i]) if prediction == validation_labels[i]: accuracy += 1 return float(accuracy) / float(len(validation_data)) def experiment(C): train_data, train_labels, test_data, test_labels, validation_data, validation_labels = hw2.get_data() results = list() for i in range(10): results.append(calculate_accuracy(zip(train_data, train_labels), validation_data, validation_labels, C=c_base ** c_exponent, eta_zero=eta_zero, T=1000)) return [C, numpy.mean(results)] c_exponent = -10 results = list() while c_exponent <= 10: results.append(experiment(c_exponent)) c_exponent += 1 # write to csv with open("sgd_b.csv", "wb") as f: writer = csv.writer(f) writer.writerows(results) <file_sep>import numpy import operator import random from matplotlib.pyplot import imshow, savefig class LinearKernel(object): def __init__(self, gamma=1.0): self.gamma = gamma def compute(self, x, y): return numpy.dot(x, y) class QuadraticKernel(object): def __init__(self, gamma=1.0): self.gamma = gamma def compute(self, x, y): return numpy.dot(x, y) ** 2 class PolynomialKernel(object): def __init__(self, gamma=1.0): self.gamma = gamma def compute(self, x, y): return numpy.dot(x, y) ** self.gamma class RBFKernel(object): def __init__(self, gamma=1.0): self.gamma = gamma def compute(self, x, y): a = numpy.dot(x, y) ** 2 return numpy.math.e ** (-a / (2 * self.gamma ** 2)) class KernelMultiClassSVM: def __init__(self, training_set, k, kernel=LinearKernel()): # each entry represent w_i self._training_set = training_set # init mu matrix self._m = list() for i in range(k): self._m.append(numpy.zeros(len(training_set))) self._kernel = kernel def train(self, C, eta_zero, T): training_length = len(self._training_set) for t in range(T): eta = eta_zero i = random.randint(0, training_length - 1) training_element = self._training_set[i][0] training_element_label = int(self._training_set[i][1]) best_index = self.get_max_j(training_element, training_element_label) self.update_weights(i, training_element_label, best_index, eta, C) def get_max_j(self, element, element_label): arguments = list() for j in range(len(self._m)): arg = 0 for k in range(len(self._training_set)): arg += self._m[j][k] * self._kernel.compute(self._training_set[k][0], element) arg -= self._m[element_label][k] * self._kernel.compute(self._training_set[k][0], element) arg += 1 if j != element_label else 0 arguments.append(arg) index, value = max(enumerate(arguments), key=operator.itemgetter(1)) return index def predict(self, element): arguments = list() for j in range(len(self._m)): arg = 0 for k in range(len(self._training_set)): arg += self._m[j][k] * self._kernel.compute(self._training_set[k][0], element) arguments.append(arg) index, value = max(enumerate(arguments), key=operator.itemgetter(1)) return index def get_w(self): return self._w def update_weights(self, training_element_index, training_label, actual_index, eta, C): for i in range(len(self._m)): if int(training_label) == actual_index: self._m[i] = (1 - eta) * self._m[i] else: curr_m = self._m self._m[i] = (1 - eta) * curr_m[i] if i == actual_index: self._m[i][training_element_index] = curr_m[i][training_element_index] - eta * C elif i == int(training_label): self._m[i][training_element_index] = curr_m[i][training_element_index] + eta * C <file_sep>import csv import numpy import hw3 import kernel_svm from kernel_svm import QuadraticKernel, RBFKernel def calculate_accuracy(training_set, validation_data, validation_labels, C, eta_zero, T): sgd_instance = kernel_svm.KernelMultiClassSVM(training_set, k=10, kernel=kernel_svm.PolynomialKernel(gamma=6)) sgd_instance.train(C, eta_zero, T) # calculate train accuracy train_accuracy = 0 for i in range(len(training_set)): prediction = sgd_instance.predict(training_set[i][0]) # print("{0}, {1}".format(prediction, int(validation_labels[i]))) if prediction == int(training_set[i][1]): train_accuracy += 1 # calculate test accuracy test_accuracy = 0 for i in range(len(validation_data)): prediction = sgd_instance.predict(validation_data[i]) # print("{0}, {1}".format(prediction, int(validation_labels[i]))) if prediction == int(validation_labels[i]): test_accuracy += 1 return [float(train_accuracy) / float(len(training_set)), float(test_accuracy) / float(len(validation_data))] def experiment(eta, C, T=1000, I=10): train_data, train_labels, test_data, test_labels, validation_data, validation_labels = hw3.get_data() results = list() for i in range(I): results.append( calculate_accuracy(zip(train_data, train_labels), validation_data, validation_labels, C=C, eta_zero=eta, T=T)) train_errors = [results[i][0] for i in range(len(results))] test_errors = [results[i][1] for i in range(len(results))] return [eta, C, T, numpy.mean(train_errors), numpy.mean(test_errors)] def search_eta_log_base(): eta_exponent = -10 results = list() while eta_exponent <= 10: res = experiment(C=1, eta=10 ** eta_exponent, I=1) print(res) results.append(res) eta_exponent += 1 # write to csv with open("logs/m_svm_eta_search_log_base.csv", "wb") as f: writer = csv.writer(f) writer.writerows(results) def search_eta(): eta_exponent = -6 results = list() while eta_exponent <= -4: res = experiment(C=1, eta=10 ** eta_exponent) print(res) results.append(res) eta_exponent += 0.3 # write to csv with open("logs/m_svm_eta_search.csv", "wb") as f: writer = csv.writer(f) writer.writerows(results) def search_C_log_base(eta): c_exponent = -10 results = list() while c_exponent <= 10: res = experiment(C=10 ** c_exponent, eta=eta, I=1) print(res) results.append(res) c_exponent += 1 # write to csv with open("logs/m_svm_c_search_log_base.csv", "wb") as f: writer = csv.writer(f) writer.writerows(results) def search_C(eta): c = 0.001 results = list() while c <= 0.01: res = experiment(C=c, eta=eta) print(res) results.append(res) c += 0.0005 # write to csv with open("logs/m_svm_c_search.csv", "wb") as f: writer = csv.writer(f) writer.writerows(results) def search_T(eta, c): T = 1000 results = list() while T <= 1000000: res = experiment(C=c, eta=eta, T=T, I=1) print(res) results.append(res) T *= 10 # write to csv with open("logs/m_svm_t_search.csv", "wb") as f: writer = csv.writer(f) writer.writerows(results) best_eta = 10 ** -10 c = 0.0001 print(experiment(eta=best_eta, C=c, I=1)) <file_sep>from pca import * import hw4 # prepare data for testing train_positive_data, train_negative_data, train_data, train_labels = hw4.get_data() experiment(train_data, "joint") <file_sep>from numpy import reshape from matplotlib.pyplot import imshow, savefig import hw2 import perceptron train_data, train_labels, test_data, test_labels, validation_data, validation_labels = hw2.get_data() perceptron_instance = perceptron.Perceptron(zip(train_data, train_labels)) perceptron_instance.train() w = perceptron_instance.get_w() image = imshow(reshape(w, (28, 28)), interpolation="nearest") savefig("perceptron_b.png")<file_sep>import csv import numpy as np import hw4 def h1(pixel, threshold): return 1 if float(pixel) <= float(threshold) else -1 def h2(pixel, threshold): return -1 if float(pixel) <= float(threshold) else 1 class H: def __init__(self, hypo_func, index, training_set): self._hypo_func = hypo_func self._training_set = training_set self._index = index self._loss_matrix = np.zeros((255, len(training_set))) self._prediction_matrix = np.zeros((255, len(training_set))) def train(self): for i in range(255): predictions, loss = self.get_prediction(i) self._prediction_matrix[i] = np.array(predictions) self._loss_matrix[i] = np.array(loss) def get_minimal_hypothesis(self, distribution): dist = np.array(distribution) loss_vector = np.dot(self._loss_matrix, dist) min_index = np.argmin(loss_vector) return loss_vector[min_index], self._prediction_matrix[min_index], min_index def get_prediction(self, threshold): predictions = list() loss = list() for i in range(len(self._training_set)): predicted_label = self.predict(self._training_set[i][0], threshold) predictions.append(predicted_label) loss.append(1 if int(predicted_label) != int(self._training_set[i][1]) else 0) return predictions, loss def predict(self, x, threshold): return self._hypo_func(x[self._index], threshold) class Adaboost: def __init__(self, training_set): self._training_set = training_set self._h = list() for i in range(len(training_set[0][0])): self._h.append(H(h1, i, training_set)) for i in range(len(training_set[0][0])): self._h.append(H(h2, i, training_set)) self.d_i = [float(1) / float(len(training_set)) for i in range(len(training_set))] self.prediction = list() for i in range(len(self._h)): self._h[i].train() def train(self, T=50): for i in range(T): print("boosting - iter {0}".format(i)) min_loss = 2 ** 32 min_predictions = None min_index = 0 threshold = 0 for index in range(len(self._h)): min_loss1, min_predictions1, min_threshold1 = self._h[index].get_minimal_hypothesis(self.d_i) if min_loss1 < min_loss: min_loss = min_loss1 min_predictions = min_predictions1 min_index = index threshold = min_threshold1 epsilon = min_loss chosen = min_index alpha = 0.5 * np.math.log(float(1 - epsilon) / float(epsilon)) / np.math.log(np.math.e) z = float(2 * (epsilon * (1 - epsilon)) ** 0.5) self.d_i = [self.d_i[i] * np.math.e ** (-self._training_set[i][1] * alpha * min_predictions[i]) / z for i in range(len(self.d_i))] self.prediction.append((chosen, alpha, threshold)) def predict(self, x, T=50): temp = 0 for i in range(T): prediction = self.prediction[i] temp += prediction[1] * self._h[prediction[0]].predict(x, prediction[2]) temp = float(temp) return 1 if temp >= 0 else -1 def get_error(adaboost, t, data, labels): error = 0 for i in range(len(data)): actual_label = adaboost.predict(data[i], t) if actual_label != labels[i]: error += 1 return float(error) / float(len(data)) def experiment(): train_data, train_labels, test_data, test_labels = hw4.get_data() training_set = [[train_data[i], train_labels[i]] for i in range(len(train_data))] adaboost = Adaboost(training_set) adaboost.train(T=50) print("calculating errors") errors = list() for i in range(50): errors.append( (i, get_error(adaboost, i, train_data, train_labels), get_error(adaboost, i, test_data, test_labels))) print(errors[i]) # write to csv with open("logs/adaboost_a_error.csv", "wb") as f: writer = csv.writer(f) writer.writerows(errors) experiment() <file_sep>import random import numpy class SGD: def __init__(self, training_set): self._w = numpy.zeros(training_set[0][0].size) self._training_set = training_set def train(self, C, eta_zero, T): training_length = len(self._training_set) for t in range(T): eta = eta_zero / (t + 1) i = random.randint(0, training_length - 1) training_element = self._training_set[i][0] training_element_label = self._training_set[i][1] dot_product = numpy.dot(self._w, training_element) if training_element_label * dot_product < 1: # update self._w = (1 - eta) * self._w + eta * C * training_element_label * training_element def predict(self, element): return 1 if numpy.dot(self._w, element) >= 0 else -1 def get_w(self): return self._w <file_sep>from sets import Set y_distribution_intervals = [(0, 0.25), (0.25, 0.5), (0.5, 0.75), (0.75, 1)] y_distribution_points = [0.0, 0.25, 0.5, 0.75, 1.0] def is_interval_included(interval, in_interval): return interval[0] >= in_interval[0] and interval[1] <= in_interval[1] def is_interval_included_in_intervals(interval, in_intervals): for in_interval in in_intervals: if is_interval_included(interval, in_interval): return True return False def get_intervals_agreement_map(intervals, true_intervals): intervals_map = dict() for interval in intervals: if is_interval_included_in_intervals(interval, true_intervals): intervals_map[interval] = 1 else: intervals_map[interval] = 0 return intervals_map def get_all_intersecting_intervals(intervals_list): intervals_points = y_distribution_points for interval in intervals_list: intervals_points.append(interval[0]) intervals_points.append(interval[1]) sorted_intervals_points = sorted(Set(intervals_points)) intervals = list() for i in range(len(sorted_intervals_points) - 1): intervals.append((sorted_intervals_points[i], sorted_intervals_points[i + 1])) return intervals def get_distribution_prob(interval, result): if is_interval_included(interval, (0, 0.25)) or is_interval_included(interval, (0.6, 0.75)): if result == 1: return 0.8 else: return 0.2 else: return 0.1 def get_intervals_error(intervals): intersecting_intervals = get_all_intersecting_intervals(intervals) x = get_intervals_agreement_map(intersecting_intervals, intervals) error = 0 for interval, result in x.iteritems(): # expect error we want that the interval will return different from distribution error += get_distribution_prob(interval, 1 - result) * (interval[1] - interval[0]) return error <file_sep>from pca import * import hw4 # prepare data for testing train_positive_data, train_negative_data, train_data, train_labels = hw4.get_data() experiment(train_negative_data, "negative") <file_sep>from numpy import reshape from matplotlib.pyplot import imshow, savefig from ex2.preceptron import hw2 from ex2.preceptron import perceptron train_data, train_labels, test_data, test_labels, validation_data, validation_labels = hw2.get_data() def get_two_error_images(training_set, test_data, test_labels): perceptron_instance = perceptron.Perceptron(training_set) perceptron_instance.train() error_image_indexes = list() for i in range(len(test_data)): prediction = perceptron_instance.predict(test_data[i]) if prediction != test_labels[i]: error_image_indexes.append(i) return error_image_indexes error_images_indexes = get_two_error_images(zip(train_data, train_labels), test_data, test_labels) error_image_1 = test_data[error_images_indexes[0]] error_image_2 = test_data[error_images_indexes[1]] imshow(reshape(error_image_1, (28, 28)), interpolation="nearest") savefig("error_image_1.png") imshow(reshape(error_image_2, (28, 28)), interpolation="nearest") savefig("error_image_2.png") <file_sep>import csv import numpy import hw3 import m_svm def calculate_accuracy(training_set, validation_data, validation_labels, C, eta_zero, T): sgd_instance = m_svm.MultiClassSVM(training_set, k=10) sgd_instance.train(C, eta_zero, T) sgd_instance.save_images() # calculate train accuracy train_accuracy = 0 for i in range(len(training_set)): prediction = sgd_instance.predict(training_set[i][0]) if prediction == int(training_set[i][1]): train_accuracy += 1 # calculate test accuracy test_accuracy = 0 for i in range(len(validation_data)): prediction = sgd_instance.predict(validation_data[i]) # print("{0}, {1}".format(prediction, int(validation_labels[i]))) if prediction == int(validation_labels[i]): test_accuracy += 1 return [float(train_accuracy) / float(len(training_set)), float(test_accuracy) / float(len(validation_data))] def experiment(eta, C, T=1000, I=10): train_data, train_labels, test_data, test_labels, validation_data, validation_labels = hw3.get_data() results = list() for i in range(I): results.append( calculate_accuracy(zip(train_data, train_labels), validation_data, validation_labels, C=C, eta_zero=eta, T=T)) train_errors = [results[i][0] for i in range(len(results))] test_errors = [results[i][1] for i in range(len(results))] return [eta, C, T, numpy.mean(train_errors), numpy.mean(test_errors)] best_eta = 1.58 * 10**-5 c = 0.0045 print(experiment(eta=best_eta, C=c, T=100000, I=1)) <file_sep>from k_nn_a import * import csv def k_nn_c(): results = list() for k in range(1, 101): accuracy = k_nn_executor(k, 1000) result_entry = (k, accuracy) results.append(result_entry) print(result_entry) # write to csv with open("k_nn_c.csv", "wb") as f: writer = csv.writer(f) writer.writerows(results) k_nn_c() <file_sep>from intervals import * from intervals_points import * from intervals_error import * import csv import operator def get_experiment_results(k, m): empirical_error_avg = 0 true_error_avg = 0 for t in range(100): points = generate_sample_points(m) points.sort(key=operator.itemgetter(0)) xs = [x[0] for x in points] ys = [x[1] for x in points] intervals, besterror = find_best_interval(numpy.array(xs), numpy.array(ys), k) empirical_error = float(besterror) / float(m) true_error = get_intervals_error(intervals) # print("k = {0}, m = {1}, error = {2}, true error = {3}".format(k, m, empirical_error, true_error)) empirical_error_avg += empirical_error true_error_avg += true_error return [k, m, empirical_error_avg / float(100), true_error_avg / float(100)] k = 2 m = 10 results = list() while m < 105: results.append(get_experiment_results(k, m)) m += 5 # write to csv with open("intervals_c.csv", "wb") as f: writer = csv.writer(f) writer.writerows(results) <file_sep>from pca import * import hw4 # prepare data for testing train_positive_data, train_negative_data, train_data, train_labels = hw4.get_data() experiment(train_positive_data, "positive") <file_sep>import csv import numpy import hw2 import sgd eta_base = 10 def calculate_accuracy(training_set, validation_data, validation_labels, C, eta_zero, T): sgd_instance = sgd.SGD(training_set) sgd_instance.train(C, eta_zero, T) accuracy = 0 for i in range(len(validation_data)): prediction = sgd_instance.predict(validation_data[i]) if prediction == validation_labels[i]: accuracy += 1 return float(accuracy) / float(len(validation_data)) def experiment(eta_exponent): train_data, train_labels, test_data, test_labels, validation_data, validation_labels = hw2.get_data() results = list() for i in range(10): results.append(calculate_accuracy(zip(train_data, train_labels), validation_data, validation_labels, C=1, eta_zero=eta_base ** eta_exponent, T=1000)) return [eta_exponent, numpy.mean(results)] eta_exponent = -10 results = list() while eta_exponent <= 10: results.append(experiment(eta_exponent)) eta_exponent += 1 # write to csv with open("sgd_a.csv", "wb") as f: writer = csv.writer(f) writer.writerows(results) <file_sep>from sklearn.svm import * import hw2 C = 10 best_log_c = 0 train_data, train_labels, test_data, test_labels, validation_data, validation_labels = hw2.get_data() linear_svc_instance = LinearSVC(loss='hinge', fit_intercept=False, C=C ** best_log_c) linear_svc_instance.fit(train_data, train_labels) print(linear_svc_instance.score(test_data, test_labels))<file_sep>from numpy import * import numpy.random from sklearn.datasets import fetch_mldata import sklearn.preprocessing def get_data(): mnist = fetch_mldata('MNIST original') data = mnist['data'] labels = mnist['target'] neg, pos = 0,8 train_idx = numpy.random.RandomState(0).permutation(where((labels[:60000] == neg) | (labels[:60000] == pos))[0]) test_idx = numpy.random.RandomState(0).permutation(where((labels[60000:] == neg) | (labels[60000:] == pos))[0]) train_data_size = 2000 train_data_unscaled = data[train_idx[:train_data_size], :].astype(float) train_labels = (labels[train_idx[:train_data_size]] == pos)*2-1 #validation_data_unscaled = data[train_idx[6000:], :].astype(float) #validation_labels = (labels[train_idx[6000:]] == pos)*2-1 test_data_size = 2000 test_data_unscaled = data[60000+test_idx[:test_data_size], :].astype(float) test_labels = (labels[60000+test_idx[:test_data_size]] == pos)*2-1 # Preprocessing train_data = sklearn.preprocessing.scale(train_data_unscaled, axis=0, with_std=False) #validation_data = sklearn.preprocessing.scale(validation_data_unscaled, axis=0, with_std=False) test_data = sklearn.preprocessing.scale(test_data_unscaled, axis=0, with_std=False) return train_data, train_labels, test_data, test_labels <file_sep>from numpy import * import numpy.random from sklearn.datasets import fetch_mldata import sklearn.preprocessing def get_data(): mnist = fetch_mldata('MNIST original') data = mnist['data'] labels = mnist['target'] train_idx = numpy.random.RandomState(0).permutation(range(60000)) train_data_size = 50000 train_data_unscaled = data[train_idx[:train_data_size], :].astype(float) train_labels = labels[train_idx[:train_data_size]] validation_data_unscaled = data[train_idx[train_data_size:60000], :].astype(float) validation_labels = labels[train_idx[train_data_size:60000]] test_data_unscaled = data[60000:, :].astype(float) test_labels = labels[60000:] # Preprocessing train_data = sklearn.preprocessing.scale(train_data_unscaled, axis=0, with_std=False) validation_data = sklearn.preprocessing.scale(validation_data_unscaled, axis=0, with_std=False) test_data = sklearn.preprocessing.scale(test_data_unscaled, axis=0, with_std=False) return train_data, train_labels, test_data, test_labels, validation_data, validation_labels<file_sep>from numpy import * import numpy.random from sklearn.datasets import fetch_mldata import sklearn.preprocessing def get_data(): mnist = fetch_mldata('MNIST original') data = mnist['data'] labels = mnist['target'] neg, pos = 0, 8 train_idx = numpy.random.RandomState(0).permutation(where((labels[:60000] == neg) | (labels[:60000] == pos))[0]) test_idx = numpy.random.RandomState(0).permutation(where((labels[60000:] == neg) | (labels[60000:] == pos))[0]) train_data_unscaled = data[train_idx[:6000], :].astype(float) train_labels = (labels[train_idx[:6000]] == pos) * 2 - 1 validation_data_unscaled = data[train_idx[6000:], :].astype(float) validation_labels = (labels[train_idx[6000:]] == pos) * 2 - 1 test_data_unscaled = data[60000 + test_idx, :].astype(float) test_labels = (labels[60000 + test_idx] == pos) * 2 - 1 # Preprocessing train_data = sklearn.preprocessing.scale(train_data_unscaled, axis=0, with_std=False) validation_data = sklearn.preprocessing.scale(validation_data_unscaled, axis=0, with_std=False) test_data = sklearn.preprocessing.scale(test_data_unscaled, axis=0, with_std=False) # normalize the data normalize_data_set(train_data) normalize_data_set(test_data) normalize_data_set(validation_data) return train_data, train_labels, test_data, test_labels, validation_data, validation_labels def normalize_data_set(data_set): for i in range(len(data_set)): train_element_norm = numpy.linalg.norm(data_set[i]) if train_element_norm != 0: data_set[i] /= float(train_element_norm) <file_sep>import csv import numpy from random import shuffle import hw2 import perceptron train_data, train_labels, test_data, test_labels, validation_data, validation_labels = hw2.get_data() def experiment(n, train_data, train_labels, test_data, test_labels): accuracies = list() train_d = train_data[:n] train_l = train_labels[:n] test_d = test_data test_l = test_labels training_set = zip(train_d, train_l) for i in range(100): shuffle(training_set) accuracies.append(calculate_accuracy(training_set, test_d, test_l)) mean = numpy.mean(accuracies) five_precentiles = numpy.percentile(accuracies, 5) ninety_five_precentiles = numpy.percentile(accuracies, 95) return [n, mean, five_precentiles, ninety_five_precentiles] def calculate_accuracy(training_set, test_data, test_labels): perceptron_instance = perceptron.Perceptron(training_set) perceptron_instance.train() accuracy = 0 for i in range(len(test_data)): prediction = perceptron_instance.predict(test_data[i]) if prediction == test_labels[i]: accuracy += 1 return float(accuracy) / float(len(test_data)) experiment_n = [5, 10, 50, 100, 500, 1000, 5000] results = list() for n in experiment_n: results.append(experiment(n, train_data, train_labels, test_data, test_labels)) # write to csv with open("perceptron_a.csv", "wb") as f: writer = csv.writer(f) writer.writerows(results)<file_sep>from k_nn_a import * def k_nn_b(): print(k_nn_executor(10, 1000)) k_nn_b() <file_sep>import numpy class Perceptron: def __init__(self, training_set): self._w = numpy.zeros(training_set[0][0].size) self._training_set = training_set def train(self): for i in range(len(self._training_set)): train_element = self._training_set[i][0] train_element_label = self._training_set[i][1] dot_product = numpy.dot(self._w, train_element) self._update_weights(train_element, train_element_label, dot_product) def predict(self, element): return 1 if numpy.dot(self._w, element) >= 0 else -1 def get_w(self): return self._w def _update_weights(self, element, element_label, dot_product): if element_label == 1 and dot_product < 0: self._w += element elif element_label == -1 and dot_product >= 0: self._w -= element<file_sep>from intervals import * from intervals_error import * from intervals_points import * import csv import operator def get_experiment_results(k, m, points): points.sort(key=operator.itemgetter(0)) xs = [x[0] for x in points] ys = [x[1] for x in points] intervals, besterror = find_best_interval(numpy.array(xs), numpy.array(ys), k) empirical_error = float(besterror) / float(m) true_error = get_intervals_error(intervals) return [empirical_error, true_error] m = 50 results = dict() for k in range(1, 21): results[k] = [0, 0] for t in range(100): points = generate_sample_points(m) for k in range(1, 21): empirical_error, true_error = get_experiment_results(k, m, points) print([k, empirical_error, true_error]) results[k][0] += empirical_error results[k][1] += true_error results_list = list() for k, errors in results.iteritems(): results_list.append([k, errors[0] / float(100), errors[1] / float(100)]) # write to csv with open("intervals_e.csv", "wb") as f: writer = csv.writer(f) writer.writerows(results_list) <file_sep>from ex2.preceptron import hw2 from ex2.preceptron import perceptron train_data, train_labels, test_data, test_labels, validation_data, validation_labels = hw2.get_data() def calculate_accuracy(training_set, test_data, test_labels): perceptron_instance = perceptron.Perceptron(training_set) perceptron_instance.train() accuracy = 0 for i in range(len(test_data)): prediction = perceptron_instance.predict(test_data[i]) if prediction == test_labels[i]: accuracy += 1 return float(accuracy) / float(len(test_data)) print(calculate_accuracy(zip(train_data, train_labels), test_data, test_labels)) <file_sep>from numpy import reshape from matplotlib.pyplot import imshow, savefig from sklearn.svm import * import hw2 C = 10 best_log_c = 0 train_data, train_labels, test_data, test_labels, validation_data, validation_labels = hw2.get_data() linear_svc_instance = LinearSVC(loss='hinge', fit_intercept=False, C=C ** best_log_c) linear_svc_instance.fit(train_data, train_labels) w = linear_svc_instance.coef_ imshow(reshape(w, (28, 28)), interpolation="nearest") savefig("best_c_w.png")<file_sep>import csv import numpy import hw2 import sgd eta_zero = 10 ** -1 c = 10 ** -2 def calculate_accuracy(training_set, validation_data, validation_labels, C, eta_zero, T): sgd_instance = sgd.SGD(training_set) sgd_instance.train(C, eta_zero, T) accuracy = 0 for i in range(len(validation_data)): prediction = sgd_instance.predict(validation_data[i]) if prediction == validation_labels[i]: accuracy += 1 return float(accuracy) / float(len(validation_data)) def experiment(): train_data, train_labels, test_data, test_labels, validation_data, validation_labels = hw2.get_data() return calculate_accuracy(zip(train_data, train_labels), validation_data, validation_labels, C=c, eta_zero=eta_zero, T=1000) print(experiment())<file_sep>import numpy import random from intervals import * def generate_sample_point(): x = random.uniform(0, 1) if (0 <= x <= 0.25) or (0.5 <= x <= 0.75): y = numpy.random.choice([0, 1], size=1, p=[0.2, 0.8])[0] elif (0.25 <= x <= 0.5) or (0.75 <= x <= 1): y = numpy.random.choice([0, 1], size=1, p=[0.9, 0.1])[0] return [x, y] def generate_sample_points(m): points = list() for i in range(m): points.append(generate_sample_point()) return points <file_sep>from intervals import * from intervals_points import * import operator import csv def get_experiment_results(k, m, points): print(points) points.sort(key=operator.itemgetter(0)) xs = [x[0] for x in points] ys = [x[1] for x in points] intervals, besterror = find_best_interval(numpy.array(xs), numpy.array(ys), k) empirical_error = float(besterror) / float(m) return [k, m, empirical_error] m = 50 results = list() points = generate_sample_points(m) for k in range(1, 21): results.append(get_experiment_results(k, m, points)) # write to csv with open("intervals_d.csv", "wb") as f: writer = csv.writer(f) writer.writerows(results) <file_sep>from pca import * import hw4 # prepare data for testing train_positive_data, train_negative_data, train_data, train_labels = hw4.get_data() def reconstruct_image(image, mypca, cnt): components = [10, 30, 50] for n_components in components: projection = mypca.transform(image, n_components=n_components) reconstruced_image = mypca.reconstruct(projection, n_components=n_components) # save original image imshow(np.reshape(image, (28, 28)), interpolation="nearest") savefig("reconstruction/original_" + str(cnt) + "_image_" + str(n_components) + ".png") imshow(np.reshape(reconstruced_image, (28, 28)), interpolation="nearest") savefig("reconstruction/reconstructed_" + str(cnt) + "_image_" + str(n_components) + ".png") mypca = MyPCA() mypca.fit(np.array(train_data)) for i in range(4): reconstruct_image(train_data[i], mypca, i + 1) <file_sep>import csv import operator from intervals_points import * def find_best(): points = generate_sample_points(100) # write to csv with open("points.csv", "wb") as f: writer = csv.writer(f) writer.writerows(points) points.sort(key=operator.itemgetter(0)) xs = [x[0] for x in points] ys = [x[1] for x in points] intervals, besterror = find_best_interval(numpy.array(xs), numpy.array(ys), 2) print("intervals: {0}".format(intervals)) print("intervals error: {0}".format(besterror)) find_best() <file_sep>import numpy import operator import random from matplotlib.pyplot import imshow, savefig class MultiClassSVM: def __init__(self, training_set, k): # each entry represent w_i self._w = [numpy.zeros(training_set[0][0].size) for i in range(k)] self._training_set = training_set def train(self, C, eta_zero, T): training_length = len(self._training_set) for t in range(T): eta = eta_zero i = random.randint(0, training_length - 1) training_element = self._training_set[i][0] training_element_label = self._training_set[i][1] best_index = self.get_max_j(training_element, training_element_label) self.update_weights(training_element, training_element_label, best_index, eta, C) def get_max_j(self, element, element_label): dot_products = [numpy.dot(self._w[j], element) - numpy.dot(self._w[int(element_label)], element) + 1 if j != element_label else 0 for j in range(len(self._w))] index, value = max(enumerate(dot_products), key=operator.itemgetter(1)) return index def predict(self, element): dot_products = [numpy.dot(self._w[i], element) for i in range(len(self._w))] index, value = max(enumerate(dot_products), key=operator.itemgetter(1)) return index def get_gradient(self, element, actual_j, element_label): gradient = list() for j in range(len(self._w)): if j == element_label: gradient.append(-1 * element) elif j == actual_j: gradient.append(element) else: gradient.append(numpy.zeros(len(element))) return gradient def get_w(self): return self._w def update_weights(self, training_element, training_label, actual_index, eta, C): gradient = self.get_gradient(training_element, actual_index, training_label) for i in range(len(self._w)): if int(training_label) == actual_index: self._w[i] = self._w[i] - eta*self._w[i] else: self._w[i] = self._w[i] - eta*(self._w[i] + C*gradient[i]) def save_images(self): w = self._w cnt = 0 for w_i in w: imshow(numpy.reshape(w_i, (28, 28)), interpolation="nearest") savefig("images/best_w" + str(cnt) + ".png") cnt += 1<file_sep>import numpy import operator from collections import defaultdict import numpy.random from sklearn.datasets import fetch_mldata from k_nn_a import * class MnistData: def __init__(self): mnist = fetch_mldata('MNIST original') data = mnist['data'] labels = mnist['target'] idx = numpy.random.RandomState(0).choice(70000, 11000) n_train_data = 10000 self._train_data = data[idx[:n_train_data], :].astype(float) # normalize the data for i in range(len(self._train_data)): train_data_norm = numpy.linalg.norm(self._train_data[i]) self._train_data[i] /= float(train_data_norm) self._train_data_labels = labels[idx[:n_train_data]] self._test_data = data[idx[n_train_data:], :].astype(float) # normalize the test data for i in range(len(self._test_data)): test_data_norm = numpy.linalg.norm(self._test_data[i]) self._test_data[i] /= float(test_data_norm) self._test_data_labels = labels[idx[n_train_data:]] def get_train_data(self): return self._train_data def get_train_data_labels(self): return self._train_data_labels def get_test_data(self): return self._test_data def get_test_data_labels(self): return self._test_data_labels def get_euclidean_distance(first_image, second_image): return numpy.linalg.norm(first_image - second_image) def get_majority_label(labels): labels_dict = defaultdict(int) for label in labels: labels_dict[label] += 1 majority_count = max(labels_dict.values()) for label, count in labels_dict.items(): if majority_count == count: return label def get_nearest_neighbors(training_images, training_labels, query_image, k): # calculate all distances label_to_distance_map = [(training_labels[i], get_euclidean_distance(query_image, training_images[i])) for i in range(len(training_images))] # sort all distances label_to_distance_map.sort(key=operator.itemgetter(1)) # extract k nearest neighbors indexes return [label_to_distance_map[i][0] for i in range(k)] def get_image_label(training_images, training_labels, query_image, k): # run k-nearest neighbors on the training_images with the query_image k_nearest_labels = get_nearest_neighbors(training_images, training_labels, query_image, k) # calculate the most common label among the neighbors and return it return get_majority_label(k_nearest_labels) def k_nn_executor(k, n_train_data): mnist_data = MnistData() accurate_labels = list() test_dataset_length = len(mnist_data.get_test_data()) for i in range(test_dataset_length): label = get_image_label(mnist_data.get_train_data()[:n_train_data], mnist_data.get_train_data_labels()[:n_train_data], mnist_data.get_test_data()[i], k) accurate_labels.append(label == mnist_data.get_test_data_labels()[i]) return float(sum(accurate_labels)) / float(test_dataset_length)
35b8eff04b26ba6e70cf179a7fdb9acc24200ae8
[ "Python" ]
39
Python
akafri/machine_learning
142ecdd57b31991b766218c5bf219cc2284c1bd9
534d3bfdff8fa685ea7b8fc2155df45eaae2731d
refs/heads/master
<file_sep>import { buildCustomElementConstructor } from 'lwc'; import Header from 'sb/header'; import Services from 'sb/services'; customElements.define('sb-header', buildCustomElementConstructor(Header)); customElements.define('sb-services', buildCustomElementConstructor(Services)); <file_sep>import { LightningElement } from 'lwc'; export default class Header extends LightningElement { toggleMenu() { const nav = this.template.querySelector('nav'); nav.classList.toggle('open'); } navigateToServices() { } }
0de34f37842d4792b498117e6222fe607e6f7cd1
[ "JavaScript" ]
2
JavaScript
ebordeau/sbm-www
6084aee6858deb7b831aae3457c4413f1385a6dc
b39c18f230a66dc340cfd18e082cd8c7201840d6
refs/heads/master
<file_sep># shellcheck shell=bash field description "Modern, cross-platform, distributed IRC client based on the Qt framework." field homepage https://quassel-irc.org field license "GPL-2.0|GPL-3.0" field version "0.0.0" field architecture.\"32bit\".url "_" field architecture.\"32bit\".hash "_" field architecture.\"64bit\".url "_" field architecture.\"64bit\".hash "_" field 'autoupdate.architecture."32bit".url' "https://quassel-irc.org/pub/quassel-x86-setup-\$version.7z" field 'autoupdate.architecture."64bit".url' "https://quassel-irc.org/pub/quassel-x64-setup-\$version.7z" field checkver.github https://github.com/quassel/quassel bin quassel.exe quassel.exe "-c \$dir\\config" bin quasselclient.exe quasselclient.exe "-c \$dir\\config" bin quasselcore.exe quasselcore.exe "-c \$dir\\config" shortcut quassel.exe "Quassel" "-c \$dir\\config" shortcut quasselclient.exe "Quassel Client" "-c \$dir\\config" shortcut quasselcore.exe "Quassel Core" "-c \$dir\\config" field persist config <file_sep># shellcheck shell=bash # FIXME - Shellcheck is actually broken on this script! ### # version=$(find_latest_version) # download_base_url="https://downloads.mixxx.org/mixxx-$version" field homepage https://mixxx.org field description "Mixxx is Free DJ software that gives you everything you need to perform live mixes." field version "0.0.0" bin "Mixxx\\mixxx.exe" "mixxx" "--settingsPath \"\$persist_dir\\appdata\"" shortcut "Mixxx\\mixxx.exe" "Mixxx" "--settingsPath \"\$persist_dir\\appdata\"" field persist appdata field license "GPL-2.0+" field dependencies[0] wixtoolset field dependencies[1] vcredist2015 field architecture.\"32bit\".url "" field architecture.\"32bit\".hash "" field architecture.\"64bit\".url "" field architecture.\"64bit\".hash "" field checkver.url "https://mixxx.org/download/" field checkver.re '\bhttps://downloads.mixxx.org/mixxx-([\d.]+)\b' field autoupdate.hash.url "https://downloads.mixxx.org/mixxx-\$version/mixxx-\$version.sha256sum" field 'autoupdate.architecture."32bit".url' "https://downloads.mixxx.org/mixxx-\$version/mixxx-\$version-win32.exe#!/_setup.exe" field 'autoupdate.architecture."64bit".url' "https://downloads.mixxx.org/mixxx-\$version/mixxx-\$version-win64.exe#!/_setup.exe" #autofill_download #field 'architecture."32bit".hash' "$(find_sha256sum "mixxx-$version-win32.exe")" #field 'architecture."64bit".hash' "$(find_sha256sum "mixxx-$version-win64.exe")" extra_file mixxx.mst pre_install <<-EOF dark -nologo -sw -sct -sdet -sui -x "\$dir\\\\\_1" "\$dir\\\\_setup.exe" NUL | Out-Null rm "\$dir\\\\_setup.exe" $(ps_install_extra_file mixxx.mst "\$dir\\\\_transform.mst") run 'msiexec' @('/a', "\`"\$((get-item "\$dir\\\\_1\\\\AttachedContainer\\\\*.msi").FullName)\`"", '/qn', "TARGETDIR=\`"\$dir\`"", "TRANSFORMS=\`"\$dir\\\\_transform.mst\`"") rm "\$dir\\\\*.*" rm -Recurse "\$dir\\\\_1" EOF <file_sep># Icedream's Scoop Bucket This repository contains the source files to generate Scoop-compatible packages for the following software: - Mixxx ([`mixxx`](packages/mixxx) and [`mixxx-nightly`](packages/mixxx-nightly)) - PuTTY ([`putty-snapshot`](packages/putty-snapshot)) - Mumble ([`mumble`](packages/mumble) and [`mumble-snapshot`](packages/mumble-snapshot)) - Quassel ([`quassel`](packages/quassel)) ## Adding this bucket You can add this bucket to your Scoop installation with this command: scoop bucket add icedream https://github.com/icedream/scoop-bucket.git ## Building the bucket In PowerShell on a Windows where WSL is available: & bin/regenerate.ps1 The package files will be placed in a new folder `bucket`. <file_sep># shellcheck shell=bash ### extend mumble remove_field architecture remove_field url remove_field hash field architecture.\"32bit\".url "_" field architecture.\"32bit\".hash "_" field architecture.\"64bit\".url "_" field architecture.\"64bit\".hash "_" field shortcuts[0][1] "Mumble (Snapshot)" field description "Open-source voice-over-IP communication client. (Snapshot version)" remove_field 'checkver' field checkver.url "https://wiki.mumble.info/wiki/Main_Page" # field checkver.re 'mumble-(?<version>[\d\.]+)~(?<short>\d+)~g(?<commit>[\dA-Fa-f]+)~snapshot\.msi' field checkver.re '<td style="background-color: #c7e4ff">\s*<a .*href="https://(?<base>.+)/(?<filename>mumble\-(?<version>[\d\.]+)(?<delim>~|\-)(?<short>[a-z\d]+)(~g(?<commit>[\dA-Fa-f]+)~snapshot)?)\.msi"' field checkver.replace '$4.$6' remove_field 'autoupdate' field 'autoupdate.architecture."32bit".url' "https://dl.mumble.info/\$matchFilename.msi#!/mumble.bin" field 'autoupdate.architecture."64bit".url' "https://dl.mumble.info/\$matchFilename.winx64.msi#!/mumble.bin" <file_sep># shellcheck shell=bash field description "Open-source voice-over-IP communication client." field homepage https://mumble.info field license GPL field version "0.0.0" field url "_" field hash "_" field checkver.url https://wiki.mumble.info/wiki/Main_Page field checkver.re '<td style="background-color: #ccffc7">\s*<a .*href="https://(?<base>.+/.+)/mumble-(?<version>.+)\.msi"' field 'autoupdate.url' 'https://$matchBase/mumble-$version.msi' bin Mumble\\mumble.exe shortcut Mumble\\mumble.exe Mumble field persist[0][0] Mumble\\mumble.ini field persist[0][1] appdata\\mumble.ini field persist[1][0] Mumble\\mumble.sqlite field persist[1][1] appdata\\mumble.sqlite field persist[2][0] Mumble\\Console.txt field persist[2][1] appdata\\Console.txt field persist[3][0] Mumble\\Overlay field persist[3][1] appdata\\Overlay field persist[4][0] Mumble\\Plugins field persist[4][1] appdata\\Plugins field persist[5][0] Mumble\\Snapshots field persist[5][1] appdata\\Snapshots field persist[6][0] Mumble\\Themes field persist[6][1] appdata\\Themes extra_file mumble.mst pre_install <<-EOF $(ps_install_extra_file mumble.mst "\$cachedir\\\\___\$app_transform.mst") mv -Force "\$dir\\\\mumble.bin" "\$cachedir\\\\___\$app_mumble.msi" run 'msiexec' @('/a', "\`"\$((get-item "\$cachedir\\\\___\$app_mumble.msi").FullName)\`"", '/qn', "TARGETDIR=\`"\$dir\`"", "TRANSFORMS=\`"\$cachedir\\\\___\$app_transform.mst\`"") rm -Force "\$cachedir\\\\___\$app_*" rm -Force "\$dir\\\\*.msi" if (!(Test-Path "\$dir\\\\Mumble\\\\Console.txt")) { New-Item -ItemType File "\$dir\\\\Mumble\\\\Console.txt" } if (!(Test-Path "\$dir\\\\Mumble\\\\mumble.ini")) { New-Item -ItemType File "\$dir\\\\Mumble\\\\mumble.ini" } if (!(Test-Path "\$dir\\\\Mumble\\\\mumble.sqlite")) { New-Item -ItemType File "\$dir\\\\Mumble\\\\mumble.sqlite" } EOF <file_sep>#!/bin/bash -e package="$1" package_dir="packages/$package" package_json_path="bucket/$package.json" package_json="{}" # if [ -f "$package_json_path" ] # then # package_json="$(cat "$package_json_path")" # fi mkdir -p bucket json_value() { if [ "$1" = '[' ] then shift 1 echo -n '[' delimiter="" while [ "$1" != ']' ] do echo -n "$delimiter" delimiter="," json_value "$@" shift 1 done echo -n ']' else echo "$(jq --raw-input . <<< "$1")" shift 1 fi } extend() { package_json="$( package="$1" package_dir="packages/$package" package_json_path="/dev/null" # shellcheck source=/dev/null source "$package_dir/package.sh" echo -n "$package_json" )" } remove_field() { name="$1" package_json="$(jq "del(.${name})" <<< "$package_json")" } field() { field_name="$1" shift 1 field_value="$(json_value "$@")" package_json=$(jq ".${field_name}=${field_value}" <<< "$package_json") } field_array() { lines=() while read line do lines+=("$line") done field "$1" [ "${lines[@]}" ] } alias script=field_array pre_install() { field_array pre_install } post_install() { field_array post_install } # Embeds the given extra file (path relative to package source directory) as # a base64-encoded string in the resulting manifest. extra_file() { name="$1" file="${2:-$1}" field "_extra.\"$name\"" "$(base64 -w 0 "${package_dir}/${file}")" } # Generates a PowerShell snippet to copy write extra manifest contents to a file. ps_install_extra_file() { src="$1" dest="${2:-\$dir\\$src}" cat <<EOF [IO.File]::WriteAllBytes("${dest}", [Convert]::FromBase64String(\$manifest._extra."${src}")) EOF } find_sha256sum() { wanted_filename="$1" while read hash filename do if [ "$wanted_filename" = "" ] ||\ [ "$wanted_filename" = "$filename" ] then echo -n "$hash" break fi done } autofill_download() { echo "ERROR: autofill_download is not implemented yet." >&2 false } bin() { name="$1" path="$2" args="$3" index="$(jq '.bin|length' <<< "$package_json")" if [ -z "$path" ] then field "bin[$index]" "$name" else field "bin[$index][0]" "$name" field "bin[$index][1]" "$path" if [ -n "$args" ] then field "bin[$index][2]" "$args" fi fi } shortcut() { name="$1" path="$2" args="$3" index="$(jq '.shortcuts|length' <<< "$package_json")" if [ -z "$path" ] then field "shortcuts[$index]" "$name" else field "shortcuts[$index][0]" "$name" field "shortcuts[$index][1]" "$path" if [ -n "$args" ] then field "shortcuts[$index][2]" "$args" fi fi } # shellcheck source=/dev/null . "$package_dir/package.sh" cat >"$package_json_path" <<<"$package_json" <file_sep># shellcheck shell=bash ### extend mixxx field checkver.url "https://downloads.mixxx.org/builds/master/release/" field checkver.re '\bmixxx\-([\w.\-]+\-git\d+)\-release-x86\.exe\b' remove_field 'autoupdate.hash' field 'autoupdate.architecture."32bit".url' "https://downloads.mixxx.org/builds/master/release/mixxx-\$version-release-x86.exe#!/_setup.exe" field 'autoupdate.architecture."64bit".url' "https://downloads.mixxx.org/builds/master/release/mixxx-\$version-release-x64.exe#!/_setup.exe" <file_sep>The Mixxx installer is packed into an WiX Burn-based EXE installer, as such dark.exe from the WiX toolset is needed to retrieve the actual MSI installer. The MSI installer itself ships with the debug symbols for Mixxx which are about 190 MB in size. The file mixxx.mst in this folder contains a Windows Installer Transform to allow unpacking of all MSI files without the debug symbol file. Of course, alternatively, one can just unpack the file and delete it afterwards but that would theoretically require the user to keep at least 190 MB of free space available for things the installer will just delete after installation. <file_sep>#!/bin/bash -e for package_script in packages/*/package.sh do package="$(basename "$(dirname "$package_script")")" echo "Generating package: $package" bin/generate_bucket_package.sh "$package" done <file_sep># shellcheck shell=bash field description "SSH client for Windows (Snapshot version)" field homepage "https://www.chiark.greenend.org.uk/~sgtatham/putty/" field license MIT field version "0.0.0" field autoupdate.architecture.\"64bit\".url https://tartarus.org/~simon/putty-snapshots/w64/putty.zip field autoupdate.architecture.\"32bit\".url https://tartarus.org/~simon/putty-snapshots/w64/putty.zip field checkver.url https://tartarus.org/~simon/putty-snapshots/w64/ field checkver.re 'putty-64bit-([\d\-]+)-installer\.msi' field architecture.\"32bit\".url "" field architecture.\"32bit\".hash "" field architecture.\"64bit\".url "" field architecture.\"64bit\".hash "" bin putty.exe bin puttygen.exe bin pscp.exe bin pageant.exe bin psftp.exe bin plink.exe shortcut putty.exe PuTTY shortcut pageant.exe Pageant shortcut psftp.exe PSFTP shortcut puttygen.exe PuTTYgen
8d908ea61e63546d24fcb41e5ff7fed1a30fba26
[ "Markdown", "Shell" ]
10
Shell
icedream/scoop-bucket
e9edc82ebc9f83266024cc155739813c949a67f6
8d790aaca9a31aa101b7d054de31ea5dc5c52278
refs/heads/master
<repo_name>ling0322/troubadour<file_sep>/QQClient.py # -*- coding: utf-8 -*- ''' Created on Jun 18, 2011 @author: ling0322 ''' import tornado.web import tornado.auth from DB_sqlite3 import DB import urllib from tornado import httpclient import logging import tornado.escape import base64 import time import uuid import binascii import datetime class QQMixin(tornado.auth.OAuthMixin, tornado.web.RequestHandler): _OAUTH_REQUEST_TOKEN_URL = "https://open.t.qq.com/cgi-bin/request_token" _OAUTH_ACCESS_TOKEN_URL = "https://open.t.qq.com/cgi-bin/access_token" _OAUTH_AUTHORIZE_URL = "https://open.t.qq.com/cgi-bin/authorize" _OAUTH_AUTHENTICATE_URL = "https://open.t.qq.com/cgi-bin/authorize" _OAUTH_NO_CALLBACKS = False def authenticate_redirect(self): """Just like authorize_redirect(), but auto-redirects if authorized. This is generally the right interface to use if you are using Twitter for single-sign on. """ http = tornado.httpclient.AsyncHTTPClient() http.fetch(self._oauth_request_token_url(callback_uri = '/qq_api/access_token'), self.async_callback( self._on_request_token, self._OAUTH_AUTHENTICATE_URL, None)) def _on_twitter_request(self, callback, response): if response.error: logging.warning("Error response %s fetching %s", response.error, response.request.url) callback(None) return callback(tornado.escape.json_decode(response.body)) def _oauth_request_parameters(self, url, access_token, parameters={}, method="GET"): """Returns the OAuth parameters as a dict for the given request. parameters should include all POST arguments and query string arguments that will be sent with the request. """ consumer_token = self._oauth_consumer_token() base_args = dict( oauth_consumer_key=consumer_token["key"], oauth_token=access_token["key"], oauth_signature_method="HMAC-SHA1", oauth_timestamp=str(int(time.time())), oauth_nonce=binascii.b2a_hex(uuid.uuid4().bytes), oauth_version="1.0", ) args = {} args.update(base_args) args.update(parameters) signature = tornado.auth._oauth_signature(consumer_token, method, url, args, access_token) base_args["oauth_signature"] = signature return base_args def qq_request(self, path, callback, access_token=None, post_args=None, **args): url = 'http://open.t.qq.com/api' + path # self._OAUTH_VERSION = '1.0' if access_token: all_args = {} all_args.update(args) all_args.update(post_args or {}) consumer_token = self._oauth_consumer_token() method = "POST" if post_args is not None else "GET" oauth = self._oauth_request_parameters( url, access_token, all_args, method=method) args.update(oauth) if args: url += "?" + urllib.urlencode(args) callback = self.async_callback(self._on_twitter_request, callback) http = httpclient.AsyncHTTPClient() if post_args is not None: http.fetch(url, method="POST", body=urllib.urlencode(post_args), callback=callback) else: http.fetch(url, callback=callback) def _oauth_consumer_token(self): self.require_setting("qq_consumer_key", "Sina OAuth") self.require_setting("qq_consumer_secret", "Sina OAuth") return dict( key=self.settings["qq_consumer_key"], secret=self.settings["qq_consumer_secret"]) def _oauth_get_user(self, access_token, callback): callback = self.async_callback(self._parse_user_response, callback) self.qq_request( "/user/other_info", access_token = access_token, name = access_token['name'], format = 'json', callback=callback) def _parse_user_response(self, callback, user): if user: user["username"] = user['data']["name"] callback(user) @tornado.web.asynchronous def get(self): if self.get_argument('oauth_token', None): self.get_authenticated_user(self.async_callback(self._on_auth)) return self.authenticate_redirect() class QQSignInHandler(QQMixin, tornado.web.RequestHandler): def _on_auth(self, user): user_access_token = self.get_cookie('access_token') access_token = {} access_token = user['access_token'] access_token['screen_name'] = user['username'] json_at = tornado.escape.json_encode(access_token) db = DB() db.update_api_access_token('qq', user_access_token, json_at) self.clear_cookie('at') self.redirect('/') pass @tornado.web.asynchronous def get(self): if self.get_argument('oauth_token', None): self.get_authenticated_user(self.async_callback(self._on_auth)) return self.authenticate_redirect() pass class QQClient(QQMixin, tornado.web.RequestHandler): ''' A Twitter Client for Madoka frontend supported request: POST update GET tl mention show (得到某个特定id的Tweet usertl (User Timeline remove ''' def _on_twitter_request(self, callback, response): # 这个也是TwitterMixin里面的东西,重写方法来拦截错误 if response.error: raise tornado.web.HTTPError(403) return # 如果callback为None表示不需要回调函数,就直接调用self.finish就可以了ww if callback != None: callback(tornado.escape.json_decode(response.body)) else: self.finish() def _dumpTweet(self, tweet): ''' 整理Tweet的内容将Twitter API返回的Tweet的格式转换成本地使用的格式 ''' t = {} t['text'] = tweet['text'] t['name'] = tweet['name'] t['screen_name'] = tweet['nick'] t['created_at'] = datetime.datetime.utcfromtimestamp(tweet['timestamp']).strftime("%a %b %d %X +0000 %Y") t['id'] = str(tweet['id']) if 'source' in tweet and tweet['source']: t['in_reply_to_status_id'] = str(tweet['source']['id']) else: t['in_reply_to_status_id'] = None if tweet['head'] == "": t['profile_image_url'] = 'http://mat1.gtimg.com/www/mb/images/head_50.jpg' else: t['profile_image_url'] = tweet['head'] + '/50' t['from'] = 'QQ' return t def _on_fetch(self, tweets, single_tweet = False): # 重载_on_twitter_request方法以后错误被拦截了,以下代码就不需要了 # if tweets == None: # raise tornado.httpclient.HTTPError(403) if single_tweet == False: dump = [self._dumpTweet(tweet) for tweet in tweets['data']['info']] else: dump = self._dumpTweet(tweets) self.write(tornado.escape.json_encode(dump)) self.finish() def _on_related_results(self, res): # 处理/related_results/show/:id.json API返回结果 # 如果有相关结果list就有1个元素 反之则没有 in_reply_to = [] replies = [] if res['data']['source']: in_reply_to.append(self._dumpTweet(res['data']['source'])) dump = dict( in_reply_to = in_reply_to, replies = replies, ) self.write(tornado.escape.json_encode(dump)) self.finish() def _dump_user_info(self, user_info): ui = {} ui['id'] = user_info['id'] ui['name'] = user_info['name'] ui['screen_name'] = user_info['screen_name'] ui['location'] = user_info['location'] ui['description'] = user_info['description'] ui['profile_image_url'] = user_info['profile_image_url'] ui['followers_count'] = user_info['followers_count'] ui['friends_count'] = user_info['friends_count'] ui['created_at'] = user_info['created_at'].replace('+0000', 'UTC') ui['favourites_count'] = user_info['favourites_count'] ui['following'] = user_info['following'] ui['statuses_count'] = user_info['statuses_count'] return ui def _on_user_info(self, user_info): self.write(tornado.escape.json_encode(self._dump_user_info(user_info))) self.finish() @tornado.web.asynchronous def get(self, request): db = DB() try: access_token = tornado.escape.json_decode( db.get_api_access_token('qq', self.get_argument('access_token')) ) except: raise tornado.web.HTTPError(403) secret = access_token['secret'] key = access_token['key'] if request == 'home_timeline': # get home timeline kwargs = {} if self.get_argument('since_id', None): kwargs['since_id'] = self.get_argument('since_id', None) if self.get_argument('page', None): kwargs['page'] = self.get_argument('page', None) self.qq_request( path = "/statuses/home_timeline", access_token = {u'secret': secret, u'key': key}, callback = self._on_fetch, reqnum = 50, **kwargs ) elif request == 'mentions': # 得到mention一个用户的Tweet self.qq_request( path = "/statuses/mentions", page = self.get_argument('page', 1), access_token = {u'secret': secret, u'key': key}, callback = self._on_fetch, count = 50, ) elif request == 'show': #得到某个特定id的Tweet self.qq_request( path = "/t/show/" + str(self.get_argument('id')), access_token = {u'secret': secret, u'key': key}, callback = self.async_callback(self._on_fetch, single_tweet = True), ) elif request == 'related_results': #得到某个特定id的Tweet相关的结果 self.qq_request( path = "/t/show", access_token = {u'secret': secret, u'key': key}, callback = self._on_related_results, format = 'json', id = self.get_argument('id'), ) elif request == 'user_info': # 得到某个用户的信息 self.qq_request( path = "/users/show", access_token = {u'secret': secret, u'key': key}, callback = self._on_user_info, screen_name = self.get_argument('screen_name') ) elif request == 'remove': # 删除某个Tweet def on_fetch(tweet): pass self.qq_request( path = "/statuses/destroy/" + str(self.get_argument('id')), access_token = {u'secret': secret, u'key': key}, post_args = {}, callback = None, ) elif request == 'user_timeline': # 得到某用户的Timeline self.qq_request( path = "/statuses/user_timeline", access_token = {u'secret': secret, u'key': key}, page = self.get_argument('page', 1), screen_name = self.get_argument('screen_name'), callback = self._on_fetch, ) elif request == 'signout': db = DB() if False == db.remove_api_access_token('qq', self.get_argument('access_token')): raise tornado.web.HTTPError(403) self.finish() elif request == 'test': self.write('喵~') self.finish() else: raise tornado.httpclient.HTTPError(403, 'Invaild Request Path ~') @tornado.web.asynchronous def post(self, request): db = DB() try: access_token = tornado.escape.json_decode( db.get_api_access_token('qq', self.get_argument('access_token')) ) except: raise tornado.web.HTTPError(403) secret = access_token['secret'] key = access_token['key'] if request == 'update': # tweet status = tornado.escape.url_unescape(self.get_argument('status').encode('utf-8')) def on_fetch(tweets): self.write('Done ~') self.finish() # 将多于140个字符的部分截去 if len(status) > 140: text = status[:136] + '...' else: text = status # 如果有in_reply_to参数则带上这个参数ww in_reply_to_param = {} if self.get_argument('in_reply_to', None): in_reply_to_param['in_reply_to_status_id'] = self.get_argument('in_reply_to', None) self.qq_request( path = "/t/add", post_args={"content": text}, access_token = {u'secret': secret, u'key': key}, clientip = '172.16.17.32', # 这里需要伪造一个用户IP callback = on_fetch, format = 'json', ) <file_sep>/Main.py # -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web import os.path import TwitterClient import SinaClient import QQClient from tornado.options import define, options from DB_sqlite3 import DB define("port", default=3232, help="run on the given port", type=int) class Application(tornado.web.Application): def __init__(self): handlers = [ (r"/", MainHandler), (r"/api/(.*)", ApiHandler), (r"/sina_api/access_token", SinaClient.SinaSignInHanhler), (r"/sina_api/(.*)", SinaClient.SinaClient), (r"/twitter_api/access_token", TwitterClient.TwitterSignInHandler), (r"/twitter_api/(.*)", TwitterClient.TwitterClient), (r"/qq_api/access_token", QQClient.QQSignInHandler), (r"/qq_api/(.*)", QQClient.QQClient), (r"/signin", LoginHandler), (r"/signup", SignUpHandler), (r"/logout", LogoutHandler), ] settings = dict( login_url = "/signin", sina_consumer_key = "3436920788", sina_consumer_secret = "1591823d9615cc4687776a575b73c75a", twitter_consumer_key = "cFDUg6a9DU08rPQTukw2w", twitter_consumer_secret = "<KEY>", qq_consumer_key = "3a24ef97429a4b3db68e67ad491d0f32", qq_consumer_secret = "d1822d2e15e7e0ed389ab96100044cf2", cookie_secret="<KEY> template_path = os.path.join(os.path.dirname(__file__), "templates"), static_path = os.path.join(os.path.dirname(__file__), "static"), ) tornado.web.Application.__init__(self, handlers, **settings) class TroubadourBaseHandler(tornado.web.RequestHandler): def get_current_user(self): return self.get_cookie("access_token", None) class MainHandler(TroubadourBaseHandler): @tornado.web.authenticated def get(self): self.render("homura.html") class SignUpHandler(TroubadourBaseHandler): def get(self): status = self.get_argument('status', None) self.render("signup.html", status = status) def post(self): db = DB() if True == db.create_user(self.get_argument('username'), self.get_argument('md5passwd')): self.redirect('/signin') else: self.redirect('signup?status=failed') class LoginHandler(TroubadourBaseHandler): def get(self): status = self.get_argument('status', None) self.render('signin.html', status = status) def post(self): username = self.get_argument('username') md5passwd = self.get_argument('md5passwd') db = DB() if db.verify_user(username, md5passwd) == True: self.set_cookie( 'access_token', db.create_access_token(username), expires_days = 30 ) self.redirect('/') else: self.redirect('/signin?status=failed') class ApiHandler(tornado.web.RequestHandler): ''' 本地的API调用 ''' def get(self, request): if request == "vaildation": access_token = self.get_argument('access_token') db = DB() if False == db.verify_access_token(access_token): raise tornado.web.HTTPError(403) elif request == "access_state": access_token = self.get_argument('access_token') db = DB() self.write(tornado.escape.json_encode(db.access_state(access_token))) class LogoutHandler(tornado.web.RequestHandler): def get(self): self.clear_all_cookies() self.redirect('/') def main(): tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(Application()) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start() if __name__ == "__main__": main() <file_sep>/DB_sqlite3.py # -*- coding: utf-8 -*- ''' Created on Jul 1, 2011 @author: ling0322 数据库接口模型, 定义了Troubadour的一些基本的数据库接口 ''' import sqlite3 import Singleton import re import uuid import base64 class DB(Singleton.Singleton): ''' 数据接口, 这是使用单件模式, 通过get_instance()函数得到这个类的实例 ''' def __init__(self): self.conn = sqlite3.connect('dbsqlite3') self.cursor = self.conn.cursor() def _is_strange_word(self, word): if len(re.findall('[^A-Za-z0-9_]', word)) == 0: return False else: return True def verify_user(self, username, md5passwd): # 首先检查用户名和密码是否合法, 防止sql注入 if self._is_strange_word(username) == True: return False if self._is_strange_word(md5passwd) == True: return False self.cursor.execute("select * from user where name = '{0}' and md5passwd = '{1}'".format(username, md5passwd)) if len(self.cursor.fetchall()) > 0: return True else: return False def access_state(self, access_token): ''' 得到一个access_token能够访问的微博状态 ''' self.cursor.execute("""select twitter_access_token, sina_access_token, qq_access_token from user where access_token = '{0}' """.format(access_token)) result = self.cursor.fetchall() try: twitter = result[0][0] sina = result[0][1] qq = result[0][2] except: return False twitter_state = False sina_state = False qq_state = False if twitter: twitter_state = True if sina: sina_state = True if qq: qq_state = True state = dict( twitter = twitter_state, sina = sina_state, qq = qq_state, ) return state def verify_access_token(self, access_token): ''' 验证一个access_token是否有效 ''' self.cursor.execute("select * from user where access_token = '{0}'".format(access_token)) if len(self.cursor.fetchall()) > 0: return True else: return False def create_user(self, username, md5passwd): ''' 创建用户, 创建返回True, 否则返回False ''' # 首先检查用户名和密码是否合法, 防止sql注入 if self._is_strange_word(username) == True: return False if self._is_strange_word(md5passwd) == True: return False self.cursor.execute("insert into user(name, md5passwd) values('{0}', '{1}')".format(username, md5passwd)) self.conn.commit() self.cursor.execute("select * from user where name = '{0}' and md5passwd = '{1}'".format(username, md5passwd)) if len(self.cursor.fetchall()) > 0: return True else: return False def create_access_token(self, username): # 首先检查用户名和密码是否合法, 防止sql注入 if self._is_strange_word(username) == True: return False # 首先要检查一下用户是否存在 self.cursor.execute("select * from user where name = '{0}'".format(username)) if len(self.cursor.fetchall()) == 0: return False access_token = str(uuid.uuid1()) self.cursor.execute("update user set access_token = '{0}' where name = '{1}'".format(access_token, username)) self.conn.commit() return access_token def remove_api_access_token(self, api, access_token): self.cursor.execute("select * from user where access_token = '{0}'".format(access_token)) if len(self.cursor.fetchall()) == 0: return False self.cursor.execute("update user set {0}_access_token = NULL where access_token = '{1}'".format(api, access_token)) self.conn.commit() return True def get_api_access_token(self, api, access_token): self.cursor.execute("select {1}_access_token from user where access_token = '{0}'".format(access_token, api)) result = self.cursor.fetchall() if len(result) == 1: return base64.decodestring(result[0][0]) else: return False def update_api_access_token(self, api, access_token, api_access_token): # 首先要检查一下用户是否存在 self.cursor.execute("select * from user where access_token = '{0}'".format(access_token)) if len(self.cursor.fetchall()) == 0: return False base64_token = base64.encodestring(api_access_token) self.cursor.execute("update user set {2}_access_token = '{0}' where access_token = '{1}'".format(base64_token, access_token, api)) self.conn.commit() return True <file_sep>/static/homura.js var api_url = 'http://127.0.0.1:3322/api' $(function() { init(); }); function hide_message_bar() { $("#message-bar").fadeOut("normal"); } function hide_signin_box() { $("#signin-main").slideUp("normal"); } function hide_confirm_box() { $("#confirm-main").slideUp("normal"); } function show_message_bar(text) { $("#message").text(text); $("#message").css('display', 'inline-block') $("#message-bar").fadeIn("normal"); } function rt(user, post) { $("#textarea").val(' RT @' + user + ': ' + $("#" + post).text()); $("#textarea")[0].focus(); var obj = document.getElementById("textarea"); obj.selectionStart = 0; obj.selectionEnd = 0; } function async_callback(func, args) { function callback() { return func(args); } return callback; } function init() { verify_access_token(); } function init_UI(next) { // // 初始化界面, 将一些原本隐藏的东西显示出来 // $("#page-container").show(); access_state(); } function API_call(url, param, success_func, error_func, retry_times) { // // 用GET的方式调用API函数, 带有重试 // $.ajax({ url: url + '?' + $.param(param), type: 'GET', success: function(body) { success_func(body); }, error: function() { // // 当retry_times不为0的时候出错就重试 // if (retry_times == 0) error_func(); else API_call(url, param, success_func, error_func, retry_times - 1); } }); } function API_post(kwargs) { // // 用POST的方式调用API函数, 带有重试 // $.ajax({ url: kwargs['url'] + '?' + $.param(kwargs['params']), type: 'POST', data: $.param(kwargs['post_params']), timeout: 30000, success: kwargs['success_func'], error: function() { // // 当retry_times不为0的时候出错就重试 // if (kwargs['retry_times'] == 0) kwargs['error_func'](); else API_post({ url: kwargs['url'], params: kwargs['params'], post_params: kwargs['post_params'], success_func: kwargs['success_func'], error_func: kwargs['error_func'], retry_times: kwargs['retry_times'] - 1 }); } }); } function api_signout(api) { hide_confirm_box(); show_message_bar('Signing out ...'); var access_token = $.cookie('access_token') if (access_token == null) return false; var param = { access_token: access_token, }; API_call( '/' + api + '_api/signout', param, function(body) { hide_message_bar(); access_state(); }, function() { show_message_bar("Oops! " + api + " signout failed!"); }, 3 ); return false; } function twitter_signin() { hide_signin_box(); show_message_bar('Signing in Twitter ...'); var access_token = $.cookie('access_token') if (access_token == null) return false; var param = { access_token: access_token, user: $('#user').val(), passwd: $('#<PASSWORD>').val(), }; API_call( '/twitter_api/access_token', param, function(body) { // // 登录成功就刷新状态 // hide_message_bar(); access_state(); }, function() { show_message_bar("Oops! twitter signin failed!"); }, 3 ); return false; } function show_signin_box(args) { $('#signin-name').html(args['api']); if (args['direct_signin'] == true) { $('#direct-signin').show(); $('#goto-signin').hide(); } else { $('#direct-signin').hide(); $('#goto-signin').show(); } $("#signin-main").slideDown("normal"); $('#signin_form').unbind(); $('#signin_form').submit(args['callback']); } function show_confirm_box(args) { $('#confirm-text').html(args['text']); $("#confirm-main").slideDown("normal"); $('#confirm-ok').unbind(); $('#confirm-ok').click(args['callback']); } function goto_sina_signin_page() { window.location.href='sina_api/access_token'; return false; } var access_api = {}; function access_state(next) { // // 验证cookies里面的access_token是否有效 // var access_token = $.cookie('access_token') if (access_token == null) return false; var param = { access_token: access_token }; API_call( '/api/access_state', param, function(body) { state = JSON.parse(body); access_api = state; // // 先把所有的定时器移除掉 // $('body').stopTime('get_timeline_twitter'); $('body').stopTime('get_timeline_sina'); $('#twitter-icon').unbind(); if (state['twitter'] == true) { $('#twitter-icon').attr('src', 'static/twitter-on.gif'); get_timeline('twitter', true); $('body').everyTime('60s', 'get_timeline_twitter', async_callback(get_timeline, 'twitter')); $('#twitter-icon').bind('click', async_callback(show_confirm_box, { text: 'Are you sure to sign out twitter?', callback: async_callback(api_signout, 'twitter'), })); } else { $('body').stopTime('get_timeline_twitter'); $('#twitter-icon').attr('src', 'static/twitter-off.gif'); $('#twitter-icon').bind('click', async_callback(show_signin_box, { api: 'Twitter', direct_signin: true, callback: twitter_signin })); } $('#sina-icon').unbind(); if (state['sina'] == true) { $('#sina-icon').attr('src', 'static/sina-on.gif'); get_timeline('sina', true); $('body').everyTime('60s', 'get_timeline_sina', async_callback(get_timeline, 'sina')); $('#sina-icon').bind('click', async_callback(show_confirm_box, { text: 'Are you sure to sign out sina weibo?', callback: async_callback(api_signout, 'sina'), })); } else { $('body').stopTime('get_timeline_sina'); $('#sina-icon').attr('src', 'static/sina-off.gif'); $('#sina-icon').bind('click', async_callback(show_signin_box, { api: 'Sina', direct_signin: false, callback: goto_sina_signin_page })); } $('#qq-icon').unbind(); if (state['qq'] == true) { $('#qq-icon').attr('src', 'static/qq-on.png'); get_timeline('qq', true); $('body').everyTime('60s', 'get_timeline_qq', async_callback(get_timeline, 'qq')); $('#qq-icon').bind('click', async_callback(show_confirm_box, { text: 'Are you sure to sign out Tencent weibo?', callback: async_callback(api_signout, 'qq'), })); } else { $('body').stopTime('get_timeline_qq'); $('#qq-icon').attr('src', 'static/qq-off.png'); $('#qq-icon').bind('click', async_callback(show_signin_box, { api: 'QQ', direct_signin: false, callback: function () { window.location.href='qq_api/access_token'; return false; }, })); } }, function() { show_message_bar("Oops! get access state failed!"); }, 3 ); } function verify_access_token(next) { // // 验证cookies里面的access_token是否有效 // var access_token = $.cookie('access_token') if (access_token == null) return false; var param = { access_token: access_token }; API_call( '/api/vaildation', param, init_UI, function() { window.location.href = "/signin"; }, 3 ); } function solve(pid) { $.ajax({ url: 'request.php?req=solve&pid=' + pid, type: 'GET', timeout: 5000, success: function(json) { update(); }, error: function(err) { show_message_bar("Oops! remove timeline failed!"); } }); } function json2obj(json) { eval("o = " + json); return o; } function get_list() { if (content == 'Timeline') { return timeline_list; } else if (content == 'Mentions') { return mentions_list; } } function get_current_sid() { if (content == 'Timeline') { return current_status_id; } else { return current_mentions_id; } } var content = 'Timeline'; var timeline_list = { twitter: [], sina: [], qq: [], }; var current_status_id = { twitter: 0, sina: 0, qq: 0, }; var mentions_list = { twitter: [], sina: [], qq: [], }; var current_mentions_id = { twitter: 0, sina: 0, qq: 0, }; function content_switch(con) { $('#page-name').text(con); content = con; $("#new-message").hide(); refresh_timeline(); access_state(); } function related_results(from, id) { $("#d" + id.toString()).html('<img src="static/loading.gif" />'); if (from == 'Sina') { api_url = '/sina_api/related_results'; } else if (from == 'Twitter') { api_url = '/twitter_api/related_results'; } else if (from == 'QQ') { api_url = '/qq_api/related_results'; } var access_token = $.cookie('access_token') var params = { access_token: access_token, id: id }; API_call( api_url, params, function(json) { $("#d" + id.toString()).html(''); related = JSON.parse(json); thtml = ''; if (related['in_reply_to'].length > 0) { thtml += '<div>---- in reply to &darr; ----</div>' list = related['in_reply_to']; for (i in list) { thtml += '<div>@'+ list[i]['screen_name'] +'<a href="#" class="note-action" onclick="rt(\'' + list[i]['screen_name'] + '\', \'p' + list[i]['id'] +'\')">RT</a></div>'; thtml += '<div id="p' + list[i]['id'] + '">'+ list[i]['text'] +'</div>'; thtml += '<div class="status-foot">'+ time_format(list[i]["created_at"]) +'</div>'; } } if (related['replies'].length > 0) { thtml += '<div>---- replies &darr; ----</div>' list = related['replies']; for (i in list) { thtml += '<div>@'+ list[i]['screen_name'] +'<a href="#" class="note-action" onclick="rt(\'' + list[i]['screen_name'] + '\', \'p' + list[i]['id'] +'\')">RT</a></div>'; thtml += '<div id="p' + list[i]['id'] + '">'+ list[i]['text'] +'</div>'; thtml += '<div class="status-foot">'+ time_format(list[i]["created_at"]) +'</div>'; } } $("#d" + id.toString()).html(thtml); }, function() { show_message_bar("Oops! Get related result failed!"); $("#d" + id.toString()).html('');$("#d" + id.toString()).html(''); }, 3 ); } // // // // // function refresh_timeline() { var thtml = ''; var list = []; var timeline_list = get_list(); for (api in timeline_list) { list = list.concat(timeline_list[api]); } list.sort(function (a, b) {return b['timestamp'] - a['timestamp']}); for (i in list) { thtml += '<div class="note">'; thtml += ' <div class="profile-image"><img src="' + list[i]['profile_image_url'] + '" /></div>'; thtml += ' <div class="status">' thtml += ' <div>'; thtml += ' <span>@' + list[i]['screen_name'] + '</span>'; thtml += ' <a href="javascript: void(0)" class="note-action" onclick="rt(\'' + list[i]['screen_name'] + '\', \'p' + list[i]['id'] +'\')">RT</a>'; if (list[i]['in_reply_to_status_id']) thtml += ' <a href="javascript: void(0)" class="note-action" onclick="related_results(\'' + list[i]['from'] + '\', \'' + list[i]['id'] + '\')">Related</a>'; thtml += ' </div>'; thtml += ' <div class="note-content"><span id="p' + list[i]['id'] + '">' + list[i]["text"] + '</span></div>'; thtml += ' <div>' thtml += ' <span class="status-foot">' + time_format(list[i]["created_at"]) + '</span>' thtml += ' <span class="status-foot">From</span>' thtml += ' <span class="status-foot">' + list[i]['from'] + '</span>' thtml += ' </div>'; thtml += ' <div id="d' + list[i]['id'] + '">'; thtml += ' </div>'; thtml += ' </div>'; thtml += ' <div><hr /></div>'; thtml += '</div>'; } $("#notes").html(thtml); $("#new-message-number").text(''); $("#new-message").fadeOut('normal'); } var get_timeline_lock = { sina: { Timeline: false, Mentions: false }, twitter: { Timeline: false, Mentions: false }, qq: { Timeline: false, Mentions: false }, } function strint_isgrt(a, b) { // // 这个是两个字符串型数字比较的函数 默认假设a和b都是非零数字开头的字符串 // 且不包含其他非阿拉伯数字字符 // if (a.length > b.length) { return true; } else if (a.length < b.length) { return false; } else { return a > b; } } function get_timeline(api_name, refresh_tl) { var sid = get_current_sid(); var tl = get_list(); var access_token = $.cookie('access_token') var param = { access_token: access_token }; var con = content; // // 如果有一个api请求进来的时候正好有一个同样的api的请求正在被执行则 // 放弃执行这个API请求 // if (get_timeline_lock[api_name][con] == true) return ; get_timeline_lock[api_name][con] = true; if (sid[api_name] != 0) param['since_id'] = sid[api_name]; if (con == 'Timeline') { request = 'home_timeline'; } else if (con == 'Mentions') { request = 'mentions'; } API_call( '/' + api_name + '_api/' + request, param, function(json) { res = JSON.parse(json); tweet_list = []; // // 返回长度为0则表示没有新状态, 退出即可 // if (res.length == 0) { get_timeline_lock[api_name][con] = false; return ; } var c = 0; for (i = 0; i < res.length && strint_isgrt(res[i]['id'], sid[api_name]); ++i) { res[i]['timestamp'] = Date.parse(res[i]['created_at']); tweet_list.push(res[i]); c++; } tl[api_name] = tweet_list.concat(tl[api_name]); sid[api_name] = tl[api_name][0]['id']; // // 显示新的消息数目 // if (c != 0 && !refresh_tl) { if ($('#new-message-number').text() == '') { $('#new-message').slideDown('normal'); $('#new-message-number').text(c.toString()); } else { $('#new-message-number').text((parseInt($('#new-message-number').text()) + c).toString()); } } get_timeline_lock[api_name][con] = false; if (refresh_tl) { refresh_timeline(); } }, function() { // show_message_bar("Oops! update timeline failed!"); get_timeline_lock[api_name][con] = false; }, 3 ); } function new_note() { var access_token = $.cookie('access_token') $('#loading-icon').fadeIn('normal'); if (access_token == null) return false; var params = { access_token: access_token }; var post_params = { status: $("#textarea").val() }; n = 0; for (i in access_api) { if (access_api[i] == false) continue; n++; API_post({ url: '/' + i + '_api/update', params: params, post_params: post_params, success_func: async_callback(function (api_n) { n--; if (n == 0) { $("#textarea").val(''); $('#loading-icon').fadeOut('normal'); } get_timeline(api_n, true); }, i), error_func: function () { show_message_bar("Oops! update status failed!"); $('#loading-icon').fadeOut('normal'); }, retry_times: 3 }); } } month = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']; function time_format(time) { // // 将time转换成字符串 // now = new Date(); t = new Date(time) delta = Math.floor((now.getTime() - t.getTime()) / 1000) if (t.getFullYear() != now.getFullYear()) // 如果年份不一样,则把年份显示出来 return month[t.getMonth()] + ' ' + t.getDate().toString() + ' ' + t.getFullYear().toString(); if (delta > 24 * 60 * 60) { // 如果时间间隔大于1天则把日期显示出来 return month[t.getMonth()] + ' ' + t.getDate().toString(); } else { ret = ''; if (Math.floor(delta / 3600) > 0) { ret = ret + Math.floor((delta / 3600)).toString() + 'hr'; delta = delta % 3600; } else if (Math.floor(delta / 60) > 0) { ret = ret + Math.floor((delta / 60)).toString() + 'min'; delta = delta % 60; } else { ret = ret + delta.toString() + 's'; } ret += ' ago'; return ret; } } <file_sep>/SinaClient.py # -*- coding: utf-8 -*- ''' Created on Jun 18, 2011 @author: ling0322 ''' import tornado.web import tornado.auth from DB_sqlite3 import DB import urllib from tornado import httpclient import logging import tornado.escape import base64 class SinaMixin(tornado.auth.OAuthMixin, tornado.web.RequestHandler): _OAUTH_REQUEST_TOKEN_URL = "http://api.t.sina.com.cn/oauth/request_token" _OAUTH_ACCESS_TOKEN_URL = "http://api.t.sina.com.cn/oauth/access_token" _OAUTH_AUTHORIZE_URL = "http://api.t.sina.com.cn/oauth/authorize" _OAUTH_AUTHENTICATE_URL = "http://api.t.sina.com.cn/oauth/authorize" _OAUTH_NO_CALLBACKS = False def authenticate_redirect(self): """Just like authorize_redirect(), but auto-redirects if authorized. This is generally the right interface to use if you are using Twitter for single-sign on. """ http = tornado.httpclient.AsyncHTTPClient() http.fetch(self._oauth_request_token_url(callback_uri = '/sina_api/access_token'), self.async_callback( self._on_request_token, self._OAUTH_AUTHENTICATE_URL, None)) def _on_twitter_request(self, callback, response): if response.error: logging.warning("Error response %s fetching %s", response.error, response.request.url) callback(None) return callback(tornado.escape.json_decode(response.body)) def sina_request(self, path, callback, access_token=None, post_args=None, **args): url = "http://api.t.sina.com.cn" + path + ".json" if access_token: all_args = {} all_args.update(args) all_args.update(post_args or {}) consumer_token = self._oauth_consumer_token() method = "POST" if post_args is not None else "GET" oauth = self._oauth_request_parameters( url, access_token, all_args, method=method) args.update(oauth) if args: url += "?" + urllib.urlencode(args) callback = self.async_callback(self._on_twitter_request, callback) http = httpclient.AsyncHTTPClient() if post_args is not None: http.fetch(url, method="POST", body=urllib.urlencode(post_args), callback=callback) else: http.fetch(url, callback=callback) def _oauth_consumer_token(self): self.require_setting("sina_consumer_key", "Sina OAuth") self.require_setting("sina_consumer_secret", "Sina OAuth") return dict( key=self.settings["sina_consumer_key"], secret=self.settings["sina_consumer_secret"]) def _oauth_get_user(self, access_token, callback): callback = self.async_callback(self._parse_user_response, callback) self.sina_request( "/users/show/" + access_token["user_id"], access_token=access_token, callback=callback) def _parse_user_response(self, callback, user): if user: user["username"] = user["name"] callback(user) @tornado.web.asynchronous def get(self): if self.get_argument('oauth_token', None): self.get_authenticated_user(self.async_callback(self._on_auth)) return self.authenticate_redirect() class SinaSignInHanhler(SinaMixin, tornado.web.RequestHandler): def _on_auth(self, user): user_access_token = self.get_cookie('access_token') access_token = {} access_token = user['access_token'] access_token['screen_name'] = user['name'] json_at = tornado.escape.json_encode(access_token) db = DB() db.update_api_access_token('sina', user_access_token, json_at) self.clear_cookie('at') self.redirect('/') pass @tornado.web.asynchronous def get(self): if self.get_argument('oauth_token', None): self.get_authenticated_user(self.async_callback(self._on_auth)) return self.authenticate_redirect() pass class SinaClient(SinaMixin, tornado.web.RequestHandler): ''' A Twitter Client for Madoka frontend supported request: POST update GET tl mention show (得到某个特定id的Tweet usertl (User Timeline remove ''' def _on_twitter_request(self, callback, response): # 这个也是TwitterMixin里面的东西,重写方法来拦截错误 if response.error: raise tornado.web.HTTPError(403) return # 如果callback为None表示不需要回调函数,就直接调用self.finish就可以了ww if callback != None: callback(tornado.escape.json_decode(response.body)) else: self.finish() def _dumpTweet(self, tweet): ''' 整理Tweet的内容将Twitter API返回的Tweet的格式转换成本地使用的格式 ''' t = {} t['text'] = tweet['text'] t['name'] = tweet['user']['name'] t['screen_name'] = tweet['user']['screen_name'] t['created_at'] = tweet['created_at'] t['id'] = str(tweet['id']) if 'retweeted_status' in tweet: t['in_reply_to_status_id'] = str(tweet['retweeted_status']['id']) else: t['in_reply_to_status_id'] = None t['profile_image_url'] = tweet['user']['profile_image_url'] t['from'] = 'Sina' return t def _on_fetch(self, tweets, single_tweet = False): # 重载_on_twitter_request方法以后错误被拦截了,以下代码就不需要了 # if tweets == None: # raise tornado.httpclient.HTTPError(403) if single_tweet == False: dump = [self._dumpTweet(tweet) for tweet in tweets] else: dump = self._dumpTweet(tweets) self.write(tornado.escape.json_encode(dump)) self.finish() def _on_related_results(self, res): # 处理/related_results/show/:id.json API返回结果 # 如果有相关结果list就有1个元素 反之则没有 in_reply_to = [] replies = [] if 'retweeted_status' in res: in_reply_to.append(self._dumpTweet(res['retweeted_status'])) dump = dict( in_reply_to = in_reply_to, replies = replies, ) self.write(tornado.escape.json_encode(dump)) self.finish() def _dump_user_info(self, user_info): ui = {} ui['id'] = user_info['id'] ui['name'] = user_info['name'] ui['screen_name'] = user_info['screen_name'] ui['location'] = user_info['location'] ui['description'] = user_info['description'] ui['profile_image_url'] = user_info['profile_image_url'] ui['followers_count'] = user_info['followers_count'] ui['friends_count'] = user_info['friends_count'] ui['created_at'] = user_info['created_at'].replace('+0000', 'UTC') ui['favourites_count'] = user_info['favourites_count'] ui['following'] = user_info['following'] ui['statuses_count'] = user_info['statuses_count'] return ui def _on_user_info(self, user_info): self.write(tornado.escape.json_encode(self._dump_user_info(user_info))) self.finish() @tornado.web.asynchronous def get(self, request): db = DB() try: access_token = tornado.escape.json_decode( db.get_api_access_token('sina', self.get_argument('access_token')) ) except: raise tornado.web.HTTPError(403) secret = access_token['secret'] key = access_token['key'] if request == 'home_timeline': # get home timeline kwargs = {} if self.get_argument('since_id', None): kwargs['since_id'] = self.get_argument('since_id', None) if self.get_argument('page', None): kwargs['page'] = self.get_argument('page', None) self.sina_request( path = "/statuses/home_timeline", access_token = {u'secret': secret, u'key': key}, callback = self._on_fetch, count = 50, **kwargs ) elif request == 'mentions': # 得到mention一个用户的Tweet self.sina_request( path = "/statuses/mentions", page = self.get_argument('page', 1), access_token = {u'secret': secret, u'key': key}, callback = self._on_fetch, count = 50, ) elif request == 'show': #得到某个特定id的Tweet self.sina_request( path = "/statuses/show/" + str(self.get_argument('id')), access_token = {u'secret': secret, u'key': key}, callback = self.async_callback(self._on_fetch, single_tweet = True), ) elif request == 'related_results': #得到某个特定id的Tweet相关的结果 self.sina_request( path = "/statuses/show/" + str(self.get_argument('id')), access_token = {u'secret': secret, u'key': key}, callback = self._on_related_results, ) elif request == 'user_info': # 得到某个用户的信息 self.twitter_request( path = "/users/show", access_token = {u'secret': secret, u'key': key}, callback = self._on_user_info, screen_name = self.get_argument('screen_name') ) elif request == 'remove': # 删除某个Tweet def on_fetch(tweet): pass self.twitter_request( path = "/statuses/destroy/" + str(self.get_argument('id')), access_token = {u'secret': secret, u'key': key}, post_args = {}, callback = None, ) elif request == 'user_timeline': # 得到某用户的Timeline self.sina_request( path = "/statuses/user_timeline", access_token = {u'secret': secret, u'key': key}, page = self.get_argument('page', 1), screen_name = self.get_argument('screen_name'), callback = self._on_fetch, ) elif request == 'signout': self.sina_request( path = "/account/end_session", access_token = {u'secret': secret, u'key': key}, callback = None, ) db = DB() if False == db.remove_api_access_token('sina', self.get_argument('access_token')): raise tornado.web.HTTPError(403) self.finish() elif request == 'test': self.write('喵~') self.finish() else: raise tornado.httpclient.HTTPError(403, 'Invaild Request Path ~') @tornado.web.asynchronous def post(self, request): db = DB() try: access_token = tornado.escape.json_decode( db.get_api_access_token('sina', self.get_argument('access_token')) ) except: raise tornado.web.HTTPError(403) secret = access_token['secret'] key = access_token['key'] if request == 'update': # tweet status = tornado.escape.url_unescape(self.get_argument('status').encode('utf-8')) def on_fetch(tweets): self.write('Done ~') self.finish() # 将多于140个字符的部分截去 if len(status) > 140: text = status[:136] + '...' else: text = status # 如果有in_reply_to参数则带上这个参数ww in_reply_to_param = {} if self.get_argument('in_reply_to', None): in_reply_to_param['in_reply_to_status_id'] = self.get_argument('in_reply_to', None) self.sina_request( path = "/statuses/update", post_args={"status": text}, access_token = {u'secret': secret, u'key': key}, callback = on_fetch, **in_reply_to_param )
c81369db65bb3c5c2985a1ddc37d115bf6be6848
[ "JavaScript", "Python" ]
5
Python
ling0322/troubadour
6b1f858d3ed296e6a99428cda66118a036764404
3728dc11521c225c19b7a730279ef0cf2ae4049f
refs/heads/main
<repo_name>santhosharani/student-info<file_sep>/delete.php <?php session_start(); $roll1=$_SESSION['roll']; $con=mysqli_connect("localhost","root","","student_registration"); $row="DELETE FROM student WHERE Roll_number='".$roll1."'"; $re=mysqli_query($con,$row); echo "<script>alert('Account deleted successfully,');location.href='signup.html'</script>"; ?><file_sep>/login.php <?php session_start(); if (isset($_POST['login'])) { $roll_no=$_POST['roll']; $password=$_POST['pwd']; if(!empty($roll_no) || !empty($password)){ $con=mysqli_connect("localhost","root","","student_registration"); $select="SELECT * FROM student WHERE Roll_number='$roll_no' AND Password='$<PASSWORD>'"; $res=mysqli_query($con,$select); $row=mysqli_num_rows($res); if($row==1){ echo "<script>location.href='home.php'</script>"; $_SESSION['roll']=$roll_no; } else{ echo "<script>alert('Please enter valid details');location.href='login.html'</script>"; } } } ?><file_sep>/newsdelete.php <?php session_start(); $roll1=$_SESSION['roll']; $con=mysqli_connect("localhost","root","","student_registration"); if (@$_GET['delete_id']!=""){ $did=$_GET['delete_id']; $sql="DELETE FROM news Where ID='$did' and Rollno='$roll1'"; $result=mysqli_query($con,$sql); if($result){ echo"<script>alert('record deleted');location.href='profile.php'</script>"; } } ?><file_sep>/news.php <?php $con=mysqli_connect("localhost","root","","student_registration"); $row="SELECT * FROM news order by Time DESC"; $re=mysqli_query($con,$row); ?> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <link rel="stylesheet" href="navbar.css"> </head> <body style="background-image:url('index.jpg') ;"> <nav class="navbar-fixed-top"> <input type="checkbox" id="check"> <label style="width: 0px;" for="check" class="checkbtn"> <i class="glyphicon glyphicon-th-list"></i> </label> <label class="logo"><a href="#" style="text-decoration: none;color: #d8b566"> Student Info</a></label> <ul> <li><a href="home.php">HOME</a></li> <li ><a class="active" href="#">News</a></li> <li ><a href="profile.php">Profile</a></li> <li><a href="update.php">Update</a></li> <li><a href="logout.php">Logout</a></li> </ul> </nav> <div class="row" style="margin-top:100px;"> <div class="col-md-3"> </div> <div class="col-md-6"> <?php while($row1=mysqli_fetch_array($re)) { ?> <form style="margin-top:50px;border-radius: 10px;background-color: rgba(0,0,0,.15);box-shadow: 0 0 10px rgba(255,255,255,.3);padding: 30px;"> <h3 style="margin-top:20px;"><?php echo $row1['Name']?></h3> <h4 style="margin-top:20px;font-weight: bold;"><?php echo $row1['Heading']?></h4> <p style="margin-top:10px;border-radius: 10px;background-color: rgba(0,0,0,.1);box-shadow: 0 0 10px rgba(255,255,255,.3);padding: 10px;"> <?php echo $row1['Description']?> </p> <h5 style="text-align: right;"><?php echo $row1['Time']?></h5> </form> <?php } ?> </div> <div class="col-md-3"> </div> </div> </body> </html><file_sep>/config.php <?php $host=get_env("MARIADB_SERVICE_HOST"); $user=get_env("db-user"); $pass=get_env("db-password"); $con=mysqli_connect($host,$user,$pass,"student_registration"); ?>
241afb169b900e1dbaff512b0bd61b044bff9908
[ "PHP" ]
5
PHP
santhosharani/student-info
7939b5d22c0adc7e615f06cd4b64106cb8715d25
33828358415e9ec10f9c0f8cc6663f87af80789e
refs/heads/master
<file_sep>Collection of go tutorials found over the internet <file_sep>Taken from https://www.toptal.com/go/go-programming-a-step-by-step-introductory-tutorial <file_sep>package funding type Fund struct { // private because lowercase balance int } // Function returning a pointer to a Fund struct func NewFund(initialBalance int) *Fund { return &Fund{ balance: initialBalance, } } // Method with a receiver returning the balance as int func (f *Fund) Balance() int { return f.balance } func (f *Fund) Withdraw(amount int) { f.balance -= amount }
c9a5cab054966fe405aafe15f4df03c07b5715f4
[ "Markdown", "Go" ]
3
Markdown
lilorox/go-tutorials
7d6b7b5d07872cc5f839e0951a2082fcc3e577d3
29e741a8db3df87dacd77424ed28da03e6bf3a6f
refs/heads/master
<repo_name>fay3r/Unforgotted_Debts_client<file_sep>/app/src/main/java/com/example/udclient/HttpSevice.java package com.example.udclient; import com.example.udclient.classes.LoginDto; import com.example.udclient.classes.MeetingDetailsDto; import com.example.udclient.classes.MeetingListDto; import com.example.udclient.classes.PaymentDto; import com.example.udclient.classes.PaymentGetDto; import com.example.udclient.classes.PaymentListDto; import com.example.udclient.classes.ProductListDto; import com.example.udclient.classes.RegisterDto; import java.util.List; import java.util.Map; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Path; import retrofit2.http.Query; public interface HttpSevice { @POST ("ud-server/login") Call<Map<String,String>> login(@Body LoginDto loginDto); @POST("ud-server/register") Call<Void> register(@Body RegisterDto registerDto); @POST("ud-server/create_meeting") Call<String> createMeeting(@Query("name") String name , @Query("password") String password); @POST("ud-server/join_meeting") Call<Void> joinMeeting(@Query("name") String name , @Query("password") String password); @GET("ud-server/meeting_details_code") Call<MeetingDetailsDto> getMeetingDetails(@Query("code") String code); @GET("ud-server/person_meetings") Call<MeetingListDto> getPersonsMeetingList(@Query("id_person") String idPerson); @GET("ud-server/products") Call<ProductListDto> getMeetingsProducts(@Query("id_meeting") String id_meeting); @POST("ud-server/delete_product") Call<Void> deleteProduct(@Query("id_product") String id_product); @POST("ud-server/add_person") Call<Void> addPerson(@Query("id_meeting") String id_meeting,@Query("nick") String nick); @POST("ud-server/product") Call<Void> addProduct(@Query("name") String name,@Query("price") String price,@Query("id_person") String id_person,@Query("id_meeting") String id_meeting); @GET("ud-server/payments_meeting/{id_meeting}") Call<PaymentListDto> getMeetingsPayments(@Path("id_meeting") String id_meeting); @POST("ud-server/payment") Call<Void> insertPayment(@Body PaymentDto paymentDto); @GET("ud-server/payments_sum_meeting/{id_meeting}") Call<Double> getMeetingsPayment(@Path("id_meeting") String id_meeting); @GET("ud-server/payments_sum_person/{id_person}") Call<Double> getSumPersonPayments(@Path("id_person") String id_person); @GET("ud-server/payments_person/{id_person}") Call<PaymentListDto> getPersonPayments(@Path("id_person") String id_person); } <file_sep>/settings.gradle include ':app' rootProject.name = "UDClient"<file_sep>/README.md # Unforgotted_Debts_client server for the application https://bitbucket.org/unforgottendebt/ud_client/src/develop/
8858aa57548b33e34892c704c96bd97589cbc623
[ "Markdown", "Java", "Gradle" ]
3
Java
fay3r/Unforgotted_Debts_client
90169eca0b2c4cfbf497d01bd0fa0c9dc6bafe65
a022406de9d3c1bc7a1b7cf086a724a508f34042
refs/heads/master
<file_sep>''' 1.先将滑块验证的图片给下载下来 ''' import selenium import time from selenium import webdriver import lxml from lxml import html from PIL import Image from io import StringIO from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By import random import re from selenium.webdriver.common.action_chains import ActionChains import requests from urllib.request import urlretrieve import cv2 import numpy as np def get_captcha(): wait = WebDriverWait(driver, 30) element = wait.until( EC.presence_of_element_located((By.CLASS_NAME, "gt_box"))) time.sleep(random.uniform(3.0, 5.0)) captcha_el = driver.find_element_by_xpath("//div[@class=\"gt_box\"]") location = captcha_el.location size = captcha_el.size left = int(location['x']) top = int(location['y']) right = int(location['x'] + size['width']) bottom = int(location['y'] + size['height']) # print(left,top,right,bottom) file1 = "test1.png" screenshot = driver.save_screenshot(file1) im = Image.open(file1) captcha = im.crop((left, top, right, bottom)) captcha.save(file1) def get_merge_image(filename,locationlist): im = Image.open(filename) new_im = Image.new("RGB",(260,116)) list_upper = [] list_down = [] for location in locationlist: if(location['y'] == 0): list_down.append(im.crop((abs(location['x']),0,abs(location['x'])+10,58))) if location['y'] == -58: list_upper.append(im.crop((abs(location['x']),58,abs(location['x'])+10,116))) x_offset = 0 for im in list_upper: new_im.paste(im,(x_offset,0)) x_offset += im.size[0] x_offset = 0 for im in list_down: new_im.paste(im, (x_offset, 58)) x_offset += im.size[0] new_im.save(filename) return new_im def pixel_equal(img1,img2,x,y): pix1 = img1.load()[x,y] pix2 = img2.load()[x,y] threshold = 50 if (abs(pix1[0] - pix2[0] < threshold) and abs(pix1[1] - pix2[1] < threshold) and abs( pix1[2] - pix2[2] < threshold)): return True else: return False def get_gap(): '''基于调试的代码''' img1 = Image.open("full.png") img2 = Image.open("cut.png") left = 43 print(img1.size[0],img1.size[1]) for i in range(left,img1.size[0]): for j in range(img1.size[1]): if not pixel_equal(img1,img2,i,j): print("不相同") left = i return left return left '''基于opencv的代码''' '''target = cv2.imread("cut.png",0) template = cv2.imread("full.png",0) w,h = target.shape[::-1] temp = "temp.jpg" targ = "targ.jpg" cv2.imwrite(temp,template) cv2.imwrite(targ,target) target = cv2.imread(targ) target = cv2.cvtColor(target,cv2.COLOR_BGR2GRAY) target = abs(255-target) cv2.imwrite(targ,target) target = cv2.imread(targ) template = cv2.imread(temp) result = cv2.matchTemplate(target,template,cv2.TM_CCOEFF_NORMED) x,y = np.unravel_index(result.argmax(),result.shape) print("x方向的偏移", int(y * 0.4 + 18), 'x:', x, 'y:', y) cv2.rectangle(template, (y, x), (y + w, x + h), (7, 249, 151), 2) cv2.imshow('Show', template) cv2.waitKey(0) cv2.destroyAllWindows() return int(y * 0.4 + 18)''' def get_track(distance): print(distance) track = [] current = 0 mid = distance*4/5 t = 0.2 v = 0 while current < distance: if current < mid: a = 20 else: a = -3 v0 = v v = v0 + a*t move = v0*t + 1/2*a*t*t current += move track.append(round(move)) return track def set_track(distance): result = [(0, 0), (6, 0), (14, 0), (18, 0), (20, 0), (22, 0), (24, 0), (25, 0), (26, 0), (27, 0), (29, 0), (31, 0), (32, 0), (34, 0), (35, 0), (38, 0), (38, 0), (40, 0), (42, 0), (44, 0), (45, 0), (47, 0), (49, 0), (51, 0), (53, 0), (54, 0), (55, 0), (58, 0), (58, 0), (60, -1), (60, -1), (62, -1), (63, -2), (64, -2), (65, -2), (66, -2), (67, -2), (69, -2), (69, -2), (71, -2), (72, -2), (73, -2), (75, -4), (78, -4), (78, -4), (80, -4), (82, -4), (84, -4), (85, -4), (86, -4), (87, -4), (89, -4), (91, -4), (92, -4), (93, -4), (94, -4), (95, -4), (98, -4), (98, -4), (100, -4), (100, -4), (102, -4), (104, -4), (105, -3), (107, -3), (109, -3), (111, -3), (112, -3), (113, -3), (114, -3), (115, -3), (116, -3), (118, -3), (120, -3), (120, -3), (122, -3), (123, -3), (124, -3), (126, -3), (127, -3), (129, -3), (131, -2), (133, -2), (134, -2), (135, -2), (138, -2), (138, -1), (138, -1), (140, -1), (140, -1), (142, -1), (143, -1), (144, -1), (145, -1), (146, -1), (147, -1), (149, -1), (151, -1), (151, 0), (152, 0), (153, 0), (155, 0), (158, 0), (160, 0), (160, 0), (162, 0), (163, 0), (164, 0), (166, 0), (167, 0), (169, 0), (169, 0), (171, 0), (173, 0), (174, 0), (175, 0), (176, 0), (178, 0), (180, 0), (180, 0), (184, 1), (189, 1), (198, 1), (202, 1), (205, 1), (206, 1), (209, 3), (211, 3), (213, 3), (215, 3), (218, 3), (220, 3), (220, 3), (222, 3), (223, 3), (225, 3), (226, 3), (227, 3), (229, 3), (231, 3), (232, 3), (233, 3), (234, 3), (235, 3), (236, 3), (238, 3), (240, 3), (240, 3), (242, 3), (243, 3), (244, 3), (245, 3), (246, 3), (247, 3), (249, 3), (249, 3), (253, 3), (255, 3), (256, 3), (258, 3), (260, 3), (262, 3), (263, 3), (265, 3), (266, 3), (267, 3), (269, 3), (269, 3), (271, 3), (272, 3), (273, 3), (274, 1), (275, 1), (276, 1), (278, 0), (280, 0), (282, -2), (283, -2), (284, -2), (285, -2), (286, -2), (289, -2), (289, -2), (291, -2), (293, -2), (295, -2), (296, -2), (298, -2), (298, -2), (300, -2), (302, -2), (303, -2), (305, -2), (306, -2), (309, -2), (309, -2), (311, -2), (312, -2), (313, -2), (314, -2), (315, -2), (316, -2), (318, -2), (320, -2), (322, -2), (322, -1), (325, 0), (326, 0), (327, 0), (329, 0), (329, 0), (332, 0), (333, 1), (334, 3), (335, 3), (343, 3), (344, 3), (347, 3), (349, 3), (349, 5), (351, 5), (353, 5), (354, 5), (355, 5), (358, 5), (358, 7), (360, 7), (360, 7), (362, 7), (363, 7), (364, 7), (369, 7), (371, 7), (373, 7), (374, 7), (375, 7), (376, 7), (378, 7)] track = [] for location in result: print(location) if location[0] > distance-2 and location[0] < distance+2: return track elif location[0] > distance+4: return [] track.append(location) return track def move_to_gap(driver,slider,track): ActionChains(driver).click_and_hold(slider).perform() '''while track: x = random.choice(track) ActionChains(driver).move_by_offset(xoffset=x,yoffset=0).perform() track.remove(x) time.sleep(0.2)''' for index in range(0,len(track)): time.sleep(0.1) if index > 0 and index < len(track): print(track[index][0]-track[index-1][0]) ActionChains(driver).move_by_offset(xoffset=track[index][0]-track[index-1][0], yoffset=track[index][1]).perform() ActionChains(driver).release(slider).perform() driver = selenium.webdriver.Chrome() url = ("http://gsxt.hljaic.gov.cn/index.jspx") driver.get(url) time.sleep(2) input = driver.find_element_by_xpath("//input[@class=\"searchInput\"]") search = driver.find_element_by_xpath("//div[@id=\"click\"]") input.send_keys(u"师范大学") search.click() wait = WebDriverWait(driver, 30) element = wait.until( EC.presence_of_element_located((By.CLASS_NAME, "gt_box"))) time.sleep(random.uniform(3.0, 5.0)) captacha = lxml.html.fromstring(driver.page_source) fullbglist = captacha.xpath("//div[@class=\"gt_cut_fullbg_slice\"]/@style") cutbglist = captacha.xpath("//div[@class=\"gt_cut_bg_slice\"]/@style") fullurllist =[] for fullbg in fullbglist: fullurllist.append(re.findall('url\(\"(.*?)\"\);',fullbg)[0].replace('webp', 'jpg')) cuturllist = [] for cutbg in cutbglist: cuturllist.append(re.findall('url\(\"(.*?)\"\);',cutbg)[0].replace('webp', 'jpg')) full_location_list = [] for fullbg in fullbglist: location = {} location['x'] = eval(re.findall('background-position: (.*?)px (.*?)px',fullbg)[0][0]) location['y'] = eval(re.findall('background-position: (.*?)px (.*?)px',fullbg)[0][1]) full_location_list.append(location) print(full_location_list) cut_location_list=[] for cutbg in cutbglist: location={} location['x'] = eval(re.findall('background-position: (.*?)px (.*?)px',cutbg)[0][0]) location['y'] = eval(re.findall('background-position: (.*?)px (.*?)px',cutbg)[0][1]) cut_location_list.append(location) print(fullurllist) urlretrieve(fullurllist[0],"full.png") urlretrieve(cuturllist[0],"cut.png") get_merge_image("full.png",full_location_list) get_merge_image("cut.png",cut_location_list) gap = get_gap() print(gap) #track = get_track(gap-9) track = set_track(gap-5) print(track) slider = driver.find_element_by_xpath("//div[@class=\"gt_slider_knob gt_show\"]") move_to_gap(driver,slider,track) <file_sep># slideCpatcha 破解滑块验证码
189564e6ac725380aeb661a933d3d0359d5413db
[ "Markdown", "Python" ]
2
Python
bluewold/slideCpatcha
95f9337bcd19c83e39d09e13aefa1793738f9c90
01fd2dbf4f8e855c79fd45c38ef58829f584991a
refs/heads/master
<repo_name>Lukasz-Kowalik/AuthenticationWithJWT<file_sep>/BackEnd/Repositories/IMongoRepository.cs using BackEnd.Helpers; using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; namespace BackEnd.Generics { public interface IMongoRepository<T> where T : IDocument { IEnumerable<T> GetAll(); T GetById(string id); Task<T> GetByIdAsync(string id); T Get(Expression<Func<T, bool>> expression); Task<T> GetAsync(Expression<Func<T, bool>> expression); void Insert(T obj); void Update(T obj); void DeleteOne(Expression<Func<T, bool>> filterExpression); } }<file_sep>/BackEnd/Controllers/UserController.cs using BackEnd.DTOs.Response; using BackEnd.Entities; using BackEnd.Enums; using BackEnd.Models; using BackEnd.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using MongoDB.Bson; using System.Collections.Generic; namespace BackEnd.Controllers { [ApiController] [Route("api/[controller]")] public class UserController : Controller { private readonly IUserService _userService; public UserController(IUserService userService) { _userService = userService; } [HttpGet] public ActionResult<IEnumerable<UserResponse>> Get() { var users = _userService.Get(); return Ok(users); } [Authorize(Policy = nameof(Policies.Default))] [HttpGet("{id}", Name = "GetUser")] [ProducesResponseType(200)] [ProducesResponseType(400)] [ProducesResponseType(401)] public ActionResult<UserResponse> Get(string id) { var user = _userService.Get(id); if (user is not null) { return Ok(user); } return NotFound(); } [HttpDelete("{id}")] [Authorize(Policy = nameof(Policies.Default))] [ProducesResponseType(200)] [ProducesResponseType(401)] public IActionResult Delete(string id) { var result = _userService.Delete(id); return Ok(result); } [HttpPost] public ActionResult<ObjectId> Create(UserRequest userRequest) { var user = new User { Name = userRequest.Name, Email = userRequest.Email, Surname = userRequest.Surname, Password = <PASSWORD>, Token = new Token() }; var result = _userService.Create(user); return Ok(result); } [HttpPut("{id}")] [Authorize(Policy = nameof(Policies.Default))] [ProducesResponseType(200)] [ProducesResponseType(401)] public IActionResult Update(string id, UserRequest request) { var result = _userService.Update(id, request); return Ok(result); } } }<file_sep>/BackEnd/Services/IUserService.cs using BackEnd.DTOs.Response; using BackEnd.Entities; using BackEnd.Models; using System.Collections.Generic; namespace BackEnd.Services { public interface IUserService { UserResponse Get(string id); bool Create(User user); bool Update(string id, UserRequest user); bool Delete(string id); IEnumerable<UserResponse> Get(); } }<file_sep>/BackEnd/Services/UserService.cs using BackEnd.DTOs.Response; using BackEnd.Entities; using BackEnd.Generics; using BackEnd.Models; using MongoDB.Bson; using System.Collections.Generic; using System.Linq; namespace BackEnd.Services { public class UserService : IUserService { private readonly IMongoRepository<User> _userRepository; public UserService(IMongoRepository<User> userRepository) { _userRepository = userRepository; } public bool Create(User user) { try { _userRepository.Insert(user); return true; } catch (System.Exception) { return false; } } public bool Delete(string id) { try { _userRepository.DeleteOne(x => x.Id == new ObjectId(id)); return true; } catch (System.Exception) { return false; } } public UserResponse Get(string id) { var user = _userRepository.GetById(id); return new UserResponse { Id = user.Id.ToString(), Email = user.Email, Name = user.Name, Surname = user.Surname }; } public bool Update(string id, UserRequest request) { var user = _userRepository.GetById(id); user.Email = request.Email; user.Name = request.Name; user.Surname = request.Surname; user.Password = request.Password; try { _userRepository.Update(user); return true; } catch (System.Exception) { return false; } } public IEnumerable<UserResponse> Get() { var users = _userRepository.GetAll(); return users.Select(x => new UserResponse { Id = x.Id.ToString(), Email = x.Email, Name = x.Name, Surname = x.Surname }); } } }<file_sep>/BackEnd/Models/ITokenSettings.cs using System; namespace BackEnd.Entities { public interface ITokenSettings { string Secret { get; init; } TimeSpan ExpireTimeLimit { get; init; } } }<file_sep>/BackEnd/DTOs/Response/TokenDto.cs namespace BackEnd.DTOs.Response { public record TokenDto { public string Token { get; set; } public string RefreshToken { get; set; } } }<file_sep>/BackEnd/Controllers/AuthController.cs using BackEnd.Managers; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace BackEnd.Controllers { [ApiController] [Route("api/[controller]")] public class AuthController : Controller { private readonly IJwtManager _manager; public AuthController(IJwtManager manager) { _manager = manager; } [HttpPost(template: "SignIn")] public async Task<IActionResult> SignInAsync(string email, string password) { var response = await _manager.SignInAsync(email, password); return Ok(response); } [HttpPost("Refresh")] public IActionResult Refresh(string token, string refreshToken) { var response = _manager.RefreshToken(token, refreshToken); return Ok(response); } } }<file_sep>/BackEnd/Managers/JwtManager.cs using BackEnd.Entities; using BackEnd.Generics; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using System; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Security.Cryptography; using System.Threading.Tasks; namespace BackEnd.Managers { public class JwtManager : IJwtManager { private readonly byte[] _secret; private readonly TimeSpan _expireTimes; private readonly TokenValidationParameters _tokenValidationParameters; private readonly IMongoRepository<User> _userRepository; public JwtManager(ITokenSettings settings, IOptionsMonitor<JwtBearerOptions> jwtOptions, IMongoRepository<User> userRepository) { _secret = Convert.FromBase64String(settings.Secret); _expireTimes = settings.ExpireTimeLimit; _tokenValidationParameters = jwtOptions.Get(JwtBearerDefaults.AuthenticationScheme).TokenValidationParameters; _userRepository = userRepository; } private Token GenerateToken(User user) { var tokenHandler = new JwtSecurityTokenHandler(); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Name, user.Name), new Claim(ClaimTypes.Surname,user.Surname), new Claim(ClaimTypes.Email,user.Email) } ), Expires = DateTime.UtcNow.Add(_expireTimes), SigningCredentials = new SigningCredentials( new SymmetricSecurityKey(_secret), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); user.Token ??= new Token(); user.Token.CreationDate = DateTime.UtcNow; user.Token.ExpiryDate = DateTime.UtcNow.Add(_expireTimes); user.Token.JwtToken = tokenHandler.WriteToken(token); return user.Token; } public Token RefreshToken(string token, string refreshToken) { var principal = GetPrincipalFromToken(token); if (principal is null) { throw new Exception("Empty principal"); } var user = _userRepository.GetById(principal.Claims.Single(x => x.Type == ClaimTypes.NameIdentifier).Value); if (user.Token.RefreshToken != refreshToken) { throw new SecurityTokenException("Invalid refresh token"); } GenerateToken(user); GenerateRefreshToken(user); return user.Token; } private ClaimsPrincipal GetPrincipalFromToken(string token) { var tokenHandler = new JwtSecurityTokenHandler(); var principal = tokenHandler.ValidateToken(token, _tokenValidationParameters, out var securityToken); if (IsJwtWithValidSecurityArgorithm(securityToken)) throw new SecurityTokenException("Invalid token"); return principal; } private bool IsJwtWithValidSecurityArgorithm(SecurityToken securityToken) { return (securityToken is JwtSecurityToken jwtSecurityToken) && jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256Signature, StringComparison.InvariantCultureIgnoreCase); } public User GenerateRefreshToken(User user) { var randomNumber = new byte[32]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(randomNumber); user.Token.RefreshToken = Convert.ToBase64String(randomNumber); user.Token.CreationDate = DateTime.UtcNow; user.Token.ExpiryDate = DateTime.UtcNow.AddDays(7); _userRepository.Update(user); return user; } } public async Task<Token> SignInAsync(string email, string password) { var user = await _userRepository.GetAsync(x => x.Email.Equals(email) && x.Password.Equals(<PASSWORD>)); if (user is null) return null; user.Token = GenerateToken(user); _userRepository.Update(user); return user.Token; } } }<file_sep>/BackEnd/Startup.cs using BackEnd.Entities; using BackEnd.Enums; using BackEnd.Generics; using BackEnd.Managers; using BackEnd.Models; using BackEnd.Services; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; using System; namespace BackEnd { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddOptions(); services.Configure<DatabaseSettings>( Configuration.GetSection(nameof(DatabaseSettings))); services.AddSingleton<IDatabaseSettings>(sp => sp.GetRequiredService<IOptions<DatabaseSettings>>().Value); services.Configure<TokenSettings>( Configuration.GetSection(nameof(TokenSettings))); services.AddSingleton<ITokenSettings>(ts => ts.GetRequiredService<IOptions<TokenSettings>>().Value); services.AddScoped(typeof(IMongoRepository<>), typeof(MongoRepository<>)); services.AddScoped<IUserService, UserService>(); services.AddScoped<IJwtManager, JwtManager>(); JwtBearerOptions options(JwtBearerOptions jwtBearerOptions, string audience) { jwtBearerOptions.RequireHttpsMetadata = false; jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = false, ValidateIssuer = false, RequireExpirationTime = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Convert.FromBase64String(Configuration["TokenSettings:Secret"])) }; return jwtBearerOptions; } services.AddAuthentication(x => { x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(jwtBearerOptions => options(jwtBearerOptions, "access")); services.AddAuthorization(options => { options.AddPolicy(nameof(Policies.Default), policy => { policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme); policy.RequireAuthenticatedUser(); }); }); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "BackEnd", Version = "v1" }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { In = ParameterLocation.Header, Description = "Please insert JWT with Bearer into field", Name = "Authorization", Type = SecuritySchemeType.ApiKey }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, new string[] { } } }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BackEnd v1")); } app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }<file_sep>/BackEnd/Helpers/Document.cs using MongoDB.Bson; namespace BackEnd.Helpers { public abstract class Document { public ObjectId Id { get; set; } } }<file_sep>/BackEnd/Managers/IJwtManager.cs using BackEnd.Entities; using System.Threading.Tasks; namespace BackEnd.Managers { public interface IJwtManager { Task<Token> SignInAsync(string email, string password); Token RefreshToken(string token, string refreshToken); } }<file_sep>/BackEnd/Repositories/MongoRepository.cs using BackEnd.Attributes; using BackEnd.Helpers; using BackEnd.Models; using MongoDB.Bson; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace BackEnd.Generics { public class MongoRepository<T> : IMongoRepository<T> where T : IDocument { private readonly IMongoCollection<T> _collection; public MongoRepository(IDatabaseSettings settings) { var _client = new MongoClient(settings.ConnectionString); var db = _client.GetDatabase(settings.DatabaseName); _collection = db.GetCollection<T>(GetCollectionName(typeof(T))); } private string GetCollectionName(Type documentType) { return ((BsonCollectionAttribute)documentType.GetCustomAttributes( typeof(BsonCollectionAttribute), true) .FirstOrDefault())?.CollectionName; } public virtual void DeleteOne(Expression<Func<T, bool>> filterExpression) { _collection.FindOneAndDelete(filterExpression); } public virtual IEnumerable<T> GetAll() { return _collection.Find(_ => true).ToEnumerable(); } public virtual T GetById(string id) { return _collection.Find(x => x.Id == new ObjectId(id)).FirstOrDefault(); } public virtual T Get(Expression<Func<T, bool>> expression) { return _collection.Find(expression).FirstOrDefault(); } public virtual Task<T> GetAsync(Expression<Func<T, bool>> expression) { return Task.Run(() => _collection.Find(expression).FirstOrDefault()); } public virtual Task<T> GetByIdAsync(string id) { return Task.Run(() => { var objectId = new ObjectId(id); var filter = Builders<T>.Filter.Eq(doc => doc.Id, objectId); return _collection.Find(filter).SingleOrDefaultAsync(); }); } public virtual void Insert(T obj) { _collection.InsertOne(obj); } public virtual void Update(T obj) { var filter = Builders<T>.Filter.Eq(x => x.Id, obj.Id); _collection.FindOneAndReplace<T>(filter, obj); } } }<file_sep>/BackEnd/Models/DatabaseSettings.cs namespace BackEnd.Models { public class DatabaseSettings : IDatabaseSettings { public string UsersCollectionName { get; init; } public string TokensCollectionName { get; init; } public string ConnectionString { get; init; } public string DatabaseName { get; init; } public string UserName { get; init; } public string Password { get; init; } } }<file_sep>/BackEnd/Models/IDatabaseSettings.cs namespace BackEnd.Models { public interface IDatabaseSettings { string UsersCollectionName { get; init; } string TokensCollectionName { get; init; } string ConnectionString { get; init; } string DatabaseName { get; init; } string UserName { get; init; } string Password { get; init; } } }<file_sep>/BackEnd/Helpers/IDocument.cs using MongoDB.Bson; namespace BackEnd.Helpers { public interface IDocument { //[BsonId] //[BsonRepresentation(BsonType.String)] public ObjectId Id { get; set; } } }<file_sep>/BackEnd/Models/TokenSettings.cs using System; namespace BackEnd.Entities { public class TokenSettings : ITokenSettings { public string Secret { get; init; } public TimeSpan ExpireTimeLimit { get; init; } } }<file_sep>/BackEnd/Enums/Policies.cs namespace BackEnd.Enums { public enum Policies { Default } }<file_sep>/BackEnd/Entities/User.cs using BackEnd.Attributes; using BackEnd.Helpers; using MongoDB.Bson; namespace BackEnd.Entities { [BsonCollection("Users")] public class User : IDocument { public ObjectId Id { get; set; } public string Name { get; set; } public string Surname { get; set; } public string Email { get; set; } public string Password { get; set; } public Token Token { get; set; } } }<file_sep>/BackEnd/Entities/Token.cs using BackEnd.Attributes; using System; namespace BackEnd.Entities { [BsonCollection("Tokens")] public class Token { public string JwtToken { get; set; } public string RefreshToken { get; set; } public DateTime CreationDate { get; set; } public DateTime ExpiryDate { get; set; } public bool IsUsed { get; set; } public bool Invalidated { get; set; } } }<file_sep>/README.md How to run: ========== Database: --------- Run docker-compose from main path run: <code>docker-compose up</code> MongoDb is on lokalhost with port 27017 MongoExpress is on http://localhost:8081/ You can login with: <code> Login: admin Password: <PASSWORD> </code> App: --------- In the main path run: <code>dotnet run --project .\BackEnd\BackEnd.csproj</code> Swagger is aveliable on: http://localhost:5000/swagger/index.html
ef3ef8a0200d8630a4e6c77fe6d227458d2e6c25
[ "Markdown", "C#" ]
20
C#
Lukasz-Kowalik/AuthenticationWithJWT
857cf412b4be8a1c7b0a8af09df143cc1d93d0d7
738aaef7df87b40ace07cd48cf023bde194d3c91
refs/heads/master
<file_sep># Ctlos keyring gpg-key pkgname=ctlos-keyring pkgver=stable pkgrel=2 pkgdesc='ctlos PGP keyring' arch=('x86_64') url='https://github.com/ctlos/ctlos-keyring' license=('GPL') install="${pkgname}.install" source=('Makefile' 'ctlos.gpg' 'ctlos-revoked' 'ctlos-trusted') sha256sums=('SKIP' 'SKIP' 'SKIP' 'SKIP') package() { cd "${srcdir}" make PREFIX=/usr DESTDIR=${pkgdir} install } <file_sep># ctlos keyring ```bash gpg --export-ownertrust > ctlos-trusted ```
c786899229b93225c79fc89b434e18691360cfb9
[ "Markdown", "Shell" ]
2
Shell
ctlos/ctlos-keyring
fd41f36c19c30903a950942b2ca9589db5d8b0c1
dbf81c037be90c42adf2ced0804baaab516f9a58
refs/heads/master
<repo_name>heintzyuan/Face-Detection<file_sep>/DetectShush.py import numpy as np import cv2 import os from os import listdir from os.path import isfile, join import sys def detectShush(frame, location, ROI, cascade): mouths = cascade.detectMultiScale(ROI, 1.05, 14, 0, (2, 2)) for (mx, my, mw, mh) in mouths: mx += location[0] my += location[1] cv2.rectangle(frame, (mx, my), (mx + mw, my + mh), (0, 0, 255), 2) return len(mouths) def detect(frame, faceCascade, mouthsCascade): gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # possible frame pre-processing: rows, cols = gray_frame.shape total = 0 for i in range(0, rows): for j in range(0, cols): total += gray_frame[i, j] avg = total / (rows * cols) dummy_frame = frame if avg > 190 or avg < 65: img_yuv = cv2.cvtColor(frame, cv2.COLOR_BGR2YUV) img_yuv[:, :, 0] = cv2.equalizeHist(img_yuv[:, :, 0]) dummy_frame = cv2.cvtColor(img_yuv, cv2.COLOR_YUV2BGR) blur_frame = cv2.GaussianBlur(dummy_frame, (5, 5), 0) faces = faceCascade.detectMultiScale( blur_frame, 1.061, 13, 0 | cv2.CASCADE_SCALE_IMAGE, (30, 30)) detected = 0 for (x, y, w, h) in faces: # ROI for mouth x1 = x h2 = int(h*2/3) y1 = y + h2 mouthROI = dummy_frame[y1:y+h, x1:x1+w] if detectShush(frame, (x1, y1), mouthROI, mouthsCascade) == 0: detected += 1 cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) else: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) if len(faces) == 0: result = detectShush(frame, (0, 0), frame, mouthsCascade) if result == 0: detected += 1 cv2.rectangle(frame, (0, 0), (cols, rows), (255, 0, 0), 2) else: cv2.rectangle(frame, (0, 0), (cols, rows), (0, 255, 0), 2) return detected def run_on_folder(cascade1, cascade2, folder): if (folder[-1] != "/"): folder = folder + "/" files = [join(folder, f) for f in listdir(folder) if isfile(join(folder, f))] windowName = None totalCnt = 0 for f in files: img = cv2.imread(f) if type(img) is np.ndarray: lCnt = detect(img, cascade1, cascade2) totalCnt += lCnt if windowName != None: cv2.destroyWindow(windowName) windowName = f cv2.namedWindow(windowName, cv2.WINDOW_AUTOSIZE) cv2.imshow(windowName, img) cv2.waitKey(0) return totalCnt def runonVideo(face_cascade, eyes_cascade): videocapture = cv2.VideoCapture(0) if not videocapture.isOpened(): print("Can't open default video camera!") exit() windowName = "Live Video" showframe = True while (showframe): ret, frame = videocapture.read() if not ret: print("Can't capture frame") break detect(frame, face_cascade, eyes_cascade) cv2.imshow(windowName, frame) if cv2.waitKey(30) >= 0: showframe = False videocapture.release() cv2.destroyAllWindows() if __name__ == "__main__": # check command line arguments: nothing or a folderpath if len(sys.argv) != 1 and len(sys.argv) != 2: print(sys.argv[0] + ": got " + len(sys.argv) - 1 + "arguments. Expecting 0 or 1:[image-folder]") exit() # load pretrained cascades face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') mouth_cascade = cv2.CascadeClassifier('Mouth.xml') if (len(sys.argv) == 2): # one argument folderName = sys.argv[1] detections = run_on_folder(face_cascade, mouth_cascade, folderName) print("Total of ", detections, "detections") else: # no arguments runonVideo(face_cascade, mouth_cascade)<file_sep>/DetectWink.py import numpy as np import cv2 import os from os import listdir from os.path import isfile, join import sys def detectWink(frame, location, ROI, cascade): sharpness = cv2.Laplacian(ROI, cv2.CV_64F).var() if sharpness < 20: kernel = np.array([[1, 1, 1], [1, -7, 1], [1, 1, 1]]) ROI = cv2.filter2D(ROI, -1, kernel) scaleFactor = 1.1 minNeighbors = 15 eyes = cascade.detectMultiScale(ROI, scaleFactor, minNeighbors, 0 | cv2.CASCADE_SCALE_IMAGE, (2, 2)) #decrease scaleFactor if no eyes detected while scaleFactor > 1.001 and len(eyes) == 0: scaleFactor = (scaleFactor - 1) / 2 + 1 minNeighbors += 10 eyes = cascade.detectMultiScale(ROI, scaleFactor, minNeighbors, 0 | cv2.CASCADE_SCALE_IMAGE, (2, 2)) for e in eyes: e[0] += location[0] e[1] += location[1] x, y, w, h = e[0], e[1], e[2], e[3] cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2) return len(eyes) # number of eyes is one def detect(frame, faceCascade, eyesCascade): gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # possible frame pre-processing: rows, cols = gray_frame.shape total = 0 for i in range(0, rows): for j in range(0, cols): total += gray_frame[i, j] avg = total / (rows * cols) dummy_frame = frame if avg > 190 or avg < 65: img_yuv = cv2.cvtColor(frame, cv2.COLOR_BGR2YUV) img_yuv[:, :, 0] = cv2.equalizeHist(img_yuv[:, :, 0]) dummy_frame = cv2.cvtColor(img_yuv, cv2.COLOR_YUV2BGR) # blur_frame = cv2.medianBlur(frame, 5) blur_frame = cv2.GaussianBlur(dummy_frame, (3, 3), 0) scaleFactor = 1.131 # range is from 1 to .. minNeighbors = 15 # range is from 0 to .. flag = 0 | cv2.CASCADE_SCALE_IMAGE # either 0 or 0|cv2.CASCADE_SCALE_IMAGE minSize = (30, 30) # range is from (0,0) to .. faces = faceCascade.detectMultiScale( blur_frame, scaleFactor, minNeighbors, flag, minSize) detected = 0 if len(faces) == 0: result = detectWink(frame, (0, 0), frame, eyesCascade) if result == 1: detected += 1 cv2.rectangle(frame, (0, 0), (cols, rows), (255, 0, 0), 2) if result == 2: cv2.rectangle(frame, (0, 0), (cols, rows), (0, 255, 0), 2) for f in faces: x, y, w, h = f[0], f[1], f[2], f[3] h1 = int(y + h / 1.5) faceROI = dummy_frame[y:h1, x:x + w] if detectWink(frame, (x, y), faceROI, eyesCascade) == 1: detected += 1 cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) else: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) return detected def run_on_folder(cascade1, cascade2, folder): if (folder[-1] != "/"): folder = folder + "/" files = [join(folder, f) for f in listdir(folder) if isfile(join(folder, f))] windowName = None totalCount = 0 for f in files: img = cv2.imread(f, 1) if type(img) is np.ndarray: lCnt = detect(img, cascade1, cascade2) totalCount += lCnt if windowName != None: cv2.destroyWindow(windowName) windowName = f cv2.namedWindow(windowName, cv2.WINDOW_AUTOSIZE) cv2.imshow(windowName, img) cv2.waitKey(0) return totalCount def runonVideo(face_cascade, eyes_cascade): videocapture = cv2.VideoCapture(0) if not videocapture.isOpened(): print("Can't open default video camera!") exit() windowName = "Live Video" showlive = True while (showlive): ret, frame = videocapture.read() if not ret: print("Can't capture frame") exit() detect(frame, face_cascade, eyes_cascade) cv2.imshow(windowName, frame) if cv2.waitKey(30) >= 0: showlive = False # outside the while loop videocapture.release() cv2.destroyAllWindows() if __name__ == "__main__": # check command line arguments: nothing or a folderpath if len(sys.argv) != 1 and len(sys.argv) != 2: print(sys.argv[0] + ": got " + len(sys.argv) - 1 + "arguments. Expecting 0 or 1:[image-folder]") exit() # load pretrained cascades face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml') if (len(sys.argv) == 2): # one argument folderName = sys.argv[1] detections = run_on_folder(face_cascade, eye_cascade, folderName) print("Total of ", detections, "detections") else: # no arguments runonVideo(face_cascade, eye_cascade)
2fb77496f6eb46a7b25d5567117f86c8dcfc1607
[ "Python" ]
2
Python
heintzyuan/Face-Detection
06b86ed2f58f11515e2ecf9a524b6b909f868149
ffe63cc16fa659c40f24795cfeea9553831fa27b
refs/heads/main
<repo_name>Ralph250/SUPHERO-BUILDER<file_sep>/main.js var canvas = new fabric.Canvas("myCanvas"); var block_width = 30; var block_height = 30; var player_x = 0; var player_y = 0; var player_object = "" ; var block_image = ""; function player_update(){ fabric.Image.fromURL("player.png", function(Img){ player_object = Img; player_object.scaleToWidth(150); player_object.scaleToHeight(140); player_object.set( { top:player_y, left:player_x } ); canvas.add(player_object); }); } function newImage(get_image){ fabric.Image.fromURL(get_image, function(Img){ block_image = Img; block_image.scaleToWidth(block_width); block_image.scaleToHeight(block_height); block_image.set({ top:player_y, left:player_x }); canvas.add(block_image); }); } window.addEventListener("keydown", mykeydown); function mykeydown(e){ var keyPressed = e.keyCode; console.log(keyPressed); if (e.shiftKey == true && keyPressed == "80"){ console.log("shift and P pressed together"); block_height = block_height + 10; block_width = block_width + 10; document.getElementById("current_width").innerHTML = (block_width); document.getElementById("current_height").innerHTML = (block_height); } if (e.shiftKey == true && keyPressed == "77"){ console.log("shift and M pressed together"); block_height = block_height - 10; block_width = block_width - 10; document.getElementById("current_width").innerHTML = (block_width); document.getElementById("current_height").innerHTML = (block_height); } if (keyPressed == "70"){ console.log("f") newImage("ironman_face.png"); } if (keyPressed == "66"){ console.log("b") newImage("hulkd_body.png"); } if (keyPressed == "76"){ console.log("l") newImage("spiderman_legs.png"); } if (keyPressed == "82"){ console.log("r") newImage("thor_right_hand.png"); } if (keyPressed == "72"){ console.log("h") newImage("thor_left_hand.png"); } ////////////////////////////////////////////////////////////////////////// if (keyPressed == "37"){ console.log("left") left(); } if (keyPressed == "38"){ console.log("up") up(); } if (keyPressed == "39"){ console.log("right") right(); } if (keyPressed == "40"){ console.log("down") down(); } } //////START OF THE MOVING FUNCTIONS////// function up(){ if (player_y>=0){ player_y=player_y - block_height; console.log("block height = " + block_height); console.log("when UP arrow is pressed, X = " + player_x + "Y = " + player_y); canvas.remove(player_object); player_update(); } } function down(){ if (player_y<=440){ player_y=player_y + block_height; console.log("block height = " + block_height); console.log("when DOWN arrow is pressed, X = " + player_x + "Y = " + player_y); canvas.remove(player_object); player_update(); } } function left(){ if (player_x>=0){ player_x=player_x - block_height; console.log("block height = " + block_height); console.log("when LEFT arrow is pressed, X = " + player_x + "Y = " + player_y); canvas.remove(player_object); player_update(); } } function right(){ if (player_x<=850){ player_x=player_x + block_height; console.log("block height = " + block_height); console.log("when RIGHT arrow is pressed, X = " + player_x + "Y = " + player_y); canvas.remove(player_object); player_update(); } }
1b27b81b3d52f89c6f6e0611a3ea5e8717542a7c
[ "JavaScript" ]
1
JavaScript
Ralph250/SUPHERO-BUILDER
4778fb2323b5322535b8a1e0d3dd497dbff3b6d9
5d6d80270a3dd858c6c201785ac6ea9fa4626982
refs/heads/master
<file_sep>var $TABLE = $('#table'); var $BTN = $('#export-btn'); var $EXPORT = $('#export'); $('.table-add').click(function () { var $clone = $TABLE.find('tr.hide').clone(true).removeClass('hide table-line'); $TABLE.find('table').append($clone); }); $('.table-remove').click(function () { $(this).parents('tr').detach(); }); $('.table-up').click(function () { var $row = $(this).parents('tr'); if ($row.index() === 1) return; // Don't go above the header $row.prev().before($row.get(0)); }); $('.table-down').click(function () { var $row = $(this).parents('tr'); $row.next().after($row.get(0)); }); // A few jQuery helpers for exporting only jQuery.fn.pop = [].pop; jQuery.fn.shift = [].shift; $BTN.click(function () { var $rows = $TABLE.find('tr:not(:hidden)'); var headers = []; var data = []; // Get the headers (add special header logic here) $($rows.shift()).find('th:not(:empty)').each(function () { headers.push($(this).text().toLowerCase()); }); // Turn all existing rows into a loopable array $rows.each(function () { var $td = $(this).find('td'); var h = {}; // Use the headers from earlier to name our hash keys headers.forEach(function (header, i) { h[header] = $td.eq(i).text(); }); data.push(h); }); // Output the result // $EXPORT.text(JSON.stringify(data)); }); var xport = { _fallbacktoCSV: true, toXLS: function(tableId, filename) { this._filename = (typeof filename == 'undefined') ? tableId : filename; //var ieVersion = this._getMsieVersion(); //Fallback to CSV for IE & Edge if ((this._getMsieVersion() || this._isFirefox()) && this._fallbacktoCSV) { return this.toCSV(tableId); } else if (this._getMsieVersion() || this._isFirefox()) { alert("Not supported browser"); } //Other Browser can download xls var htmltable = document.getElementById(tableId); var html = htmltable.outerHTML; this._downloadAnchor("data:application/vnd.ms-excel" + encodeURIComponent(html), 'xls'); }, toCSV: function(tableId, filename) { this._filename = (typeof filename === 'undefined') ? tableId : filename; // Generate our CSV string from out HTML Table var csv = this._tableToCSV(document.getElementById(tableId)); // Create a CSV Blob var blob = new Blob([csv], { type: "text/csv" }); // Determine which approach to take for the download if (navigator.msSaveOrOpenBlob) { // Works for Internet Explorer and Microsoft Edge navigator.msSaveOrOpenBlob(blob, this._filename + ".csv"); } else { this._downloadAnchor(URL.createObjectURL(blob), 'csv'); } }, _getMsieVersion: function() { var ua = window.navigator.userAgent; var msie = ua.indexOf("MSIE "); if (msie > 0) { // IE 10 or older => return version number return parseInt(ua.substring(msie + 5, ua.indexOf(".", msie)), 10); } var trident = ua.indexOf("Trident/"); if (trident > 0) { // IE 11 => return version number var rv = ua.indexOf("rv:"); return parseInt(ua.substring(rv + 3, ua.indexOf(".", rv)), 10); } var edge = ua.indexOf("Edge/"); if (edge > 0) { // Edge (IE 12+) => return version number return parseInt(ua.substring(edge + 5, ua.indexOf(".", edge)), 10); } // other browser return false; }, _isFirefox: function(){ if (navigator.userAgent.indexOf("Firefox") > 0) { return 1; } return 0; }, _downloadAnchor: function(content, ext) { var anchor = document.createElement("a"); anchor.style = "display:none !important"; anchor.id = "downloadanchor"; document.body.appendChild(anchor); // If the [download] attribute is supported, try to use it if ("download" in anchor) { anchor.download = this._filename + "." + ext; } anchor.href = content; anchor.click(); anchor.remove(); }, _tableToCSV: function(table) { // We'll be co-opting `slice` to create arrays var slice = Array.prototype.slice; return slice .call(table.rows) .map(function(row) { return slice .call(row.cells) .map(function(cell) { return '"t"'.replace("t", cell.textContent); }) .join(","); }) .join("\r\n"); } };
f101400cd2a0aa1a4b0d5be12942a6e00d8eadd3
[ "JavaScript" ]
1
JavaScript
rizwanhaque1994/apilocks-site
c082416a073dcb10207c8bdf014a411f0bd8c529
a42a12bff91469ce90a6a1376537292c9311ab4b
refs/heads/master
<repo_name>esrfree/Ironhack-lab-javascript-greatest-movies<file_sep>/starter_code/src/movies.js /* eslint no-restricted-globals: 'off' */ /************** TOOLS ****************/ // Utility function to sorted an array function ordered ( val1, val2 ) { return typeof val1 == 'number' && typeof val2 == 'number' ? val1 - val2 : val1.localeCompare(val2); } // Utility function to format time function timeFormat( acc, cur ) { if ( cur.includes('min')) cur = parseInt( cur ) else if ( cur.includes('h')) { cur = parseInt( cur ) * 60 } return acc + cur; } /************************************/ // Iteration 1: Ordering by year - Order by year, ascending (in growing order) function orderByYear( moviesArr) { let orderedArray = [...moviesArr]; orderedArray.sort( (elm1, elm2) => { if ( elm1.year - elm2.year == 0 ) return ordered (elm1.title, elm2.title) return ordered( elm1.year, elm2.year); }); return orderedArray; } // Iteration 2: <NAME>. The best? - How many drama movies did STEVEN SPIELBERG direct function howManyMovies( arr ) { return arr.filter( elm => elm.genre.includes('Drama') && elm.director.toUpperCase() === "STEVEN SPIELBERG").length; } // Iteration 3: Alphabetic Order - Order by title and print the first 20 titles function orderAlphabetically( moviesArr ) { let orderedArray = [...moviesArr]; let onlyFirst20Titles = orderedArray .sort( ( elm1, elm2 ) => ordered( elm1.title, elm2.title)) .map( elm => elm.title) .filter( (elm, idx) => idx < 20 ); return onlyFirst20Titles; } // Iteration 4: All rates average - Get the average of all rates with 2 decimals function ratesAverage( moviesArr ) { if ( moviesArr.length == 0 ) return 0; // Sum of all movies' rate let ratesSum = moviesArr.reduce( function(acc, cur) { if ( !cur.rate ) cur.rate = 0; return acc + cur.rate; }, 0); // Average let avg = Math.round( (ratesSum / moviesArr.length) * 100) / 100 ; return avg; } // Iteration 5: Drama movies - Get the average of Drama Movies function dramaMoviesRate( moviesArr ) { let dramaMovies = moviesArr.filter( el => el.genre.includes("Drama")); return ratesAverage(dramaMovies); } // Iteration 6: Time Format - Turn duration of the movies from hours to minutes function turnHoursToMinutes( moviesArr ) { // creating a shadow copy of an array of objects let localArr = moviesArr.map( obj => { const newObj = {...obj}; return newObj; }) // changing the movies' duration format let moviesArrFormatted = localArr .map( elm => { elm.duration = elm.duration .split(' ') .reduce( timeFormat, 0) return elm; }); return moviesArrFormatted; } // BONUS Iteration: Best yearly rate average - Best yearly rate average function bestYearAvg( moviesArr ) { if ( moviesArr.length == 0 ) return null; let arrYearAvgRate = []; // finding unique values of years let uniqueYears = moviesArr .map( el => el.year ) .filter( (el, idx, arr) => arr.indexOf(el) == idx); // calculating average rate per year for ( let i = 0; i < uniqueYears.length; i++ ) { let moviesPerYear = []; let avg = 0; for ( let j = 0; j < moviesArr.length; j++) { if ( uniqueYears[i] === moviesArr[j].year ) { moviesPerYear.push( moviesArr[j] ) } } avg = ratesAverage( moviesPerYear ); arrYearAvgRate.push( { year: uniqueYears[i], avg }) } // sorting the array by rate average value arrYearAvgRate.sort( ( elm1, elm2 ) => ordered( elm1.avg, elm2.avg )) return `The best year was ${arrYearAvgRate[arrYearAvgRate.length - 1].year} with an average rate of ${arrYearAvgRate[arrYearAvgRate.length - 1].avg}`; }
9a9e01355cea99ad974d91ab3b5952b68e282602
[ "JavaScript" ]
1
JavaScript
esrfree/Ironhack-lab-javascript-greatest-movies
bac348c388b919df46e99aa0da113999145c4281
78a448af6a6b7ebae1ba857d80ec7513822ac265
refs/heads/master
<repo_name>meadhikari/Link-Extractor<file_sep>/hello.py from flask import render_template from flask import Flask,request import mechanize br = mechanize.Browser() app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') @app.route('/links/', methods=('GET', 'POST')) def link(): url = request.args.get("url",'') try: br.open(url) except: return "There was a error processing the url is the url correct." links = [] extension = request.args.get("extension","") for l in br.links(): if l.url.endswith(extension): links.append(l.url) return render_template('links.html',links=links) #return "Hello World" if __name__ == "__main__": app.run()
d344181619ef8766dc46f68a7ccafb738af99145
[ "Python" ]
1
Python
meadhikari/Link-Extractor
857fd402e7eee1eed35f579f42c9bfbcb53aaabe
c94f5c52edf4a33c1f22072128ddf0e583c92ec1
refs/heads/master
<file_sep>// // AppDelegate.swift // Assignment2 // // Created by skistams on 1/24/17. // Copyright © 2017 skistams. All rights reserved. // // I give right to the instuctor and the University with the right to build and evaluate the software package for the purpose of determining my grade and program assessment // Purpose: It contains all the life cycle methods and the logs related to it // Ser423 Mobile Applications // see http://pooh.poly.asu.edu/Mobile // @author <NAME> <EMAIL> // Software Engineering, CIDSE, ASU Poly // @version January 24, 2017 import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } //On click of Home Button the applicationWillResignActive function is called func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. NSLog("Application : %@", "applicationWillResignActive") } //On click of Home Button the applicationDidEnterBackground function is called func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. NSLog("Application : %@", "applicationDidEnterBackgroud") } //When the user reclicks the application second time, then the applicationWillEnterForeground function is called func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. NSLog("Application : %@", "applicationWillEnterForeground") } //The applicationDidBecomeActive function is called whenever the application launches func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. NSLog("Application : %@", "applicationDidBecomeActive") } //When the application is terminated when on foreground, the applicationWillTerminate function is called func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. NSLog("Application : %@", "applicationWillTerminate") } } <file_sep>// // ViewController.swift // Assignment2 // // Created by skistams on 1/24/17. // Copyright © 2017 skistams. All rights reserved. // I give right to the instuctor and the University with the right to build and evaluate the software package for the purpose of determining my grade and program assessment // It contains all the life cycle methods and the logs related to it // Ser423 Mobile Applications // see http://pooh.poly.asu.edu/Mobile // @author <NAME> <EMAIL> // Software Engineering, CIDSE, ASU Poly // @version January 24, 2017 import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //When the application launches or when the ViewController screen is about to appear, the viewWillApppear function is called override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NSLog("In ViewController, viewWillAppear") } //when the ViewController screen appears,the viewDidAppear function is called override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) NSLog("In ViewController, viewDidAppear") } //On click of a button,when the application is transferring to the SecondViewController, viewWillDisappear function is called override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NSLog("In ViewController, viewWillDisappear") } //Once the application is transferred from ViewController screen, the viewDidDisappear function is called override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NSLog("In ViewController, viewDidDisappear") } } <file_sep>// // SecondViewController.swift // Assignment2 // // Created by skistams on 1/24/17. // Copyright © 2017 skistams. All rights reserved. // I give right to the instuctor and the University with the right to build and evaluate the software package for the purpose of determining my grade and program assessment // It contains all the life cycle methods and the logs related to it // Ser423 Mobile Applications // see http://pooh.poly.asu.edu/Mobile // @author <NAME> <EMAIL> // Software Engineering, CIDSE, ASU Poly // @version January 24, 2017 import UIKit class SecondViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //when the SecondViewController screen is opened on click of a button in the ViewController, the viewWillAppear function is called override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NSLog("In SecondViewController, viewWillAppear") } //when the SecondViewController is opened on click of a button in the ViewController, the viewWillAppear function is called override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) NSLog("In SecondViewController, viewDidAppear") } //On click of a button in SecondViewController when the application is transferring to the ViewController, viewWillDisappear function is called override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NSLog("In SecondViewController, viewWillDisappear") } //Once the application is transferred from SecondViewController screen, the viewDidDisappear function is called override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NSLog("In SecondViewController, viewDidDisappear") } //When the "Move to Second View" button on the SecondViewController screen is clicked, the buttonFuntion is called @IBAction func buttonFunction(_ sender: Any) { NSLog("In Second View Controller popClicked") self.dismiss(animated: false, completion: nil) } }
7a0461f81afa5b0917f7434d14dcb7884e4337e6
[ "Swift" ]
3
Swift
susmithak16/Assignment2
78c9b1d55580f938baa02b1479328950108b204a
c5a565f5d9ea2dc7cc3be67e493d6e77aed15362
refs/heads/master
<file_sep>import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class VoteLogistic { public static void main(String[] args) throws FileNotFoundException { List<Example> examples = new ArrayList<>(); examples = readFile(args[0]); //examples int nsteps = Integer.parseInt(args[1]); //steps double alpha = Double.parseDouble(args[2]); // LogisticClassifier l_classifier = new LogisticClassifier(examples.get(0).inputs.length); if (alpha > 0) { l_classifier.train(examples, nsteps, alpha); } else { l_classifier.train(examples, 100000, new LearningRateSchedule() { public double alpha(int t) { return 1000.0/(1000.0+t); } }); } } public static List<Example> readFile(String filename) throws FileNotFoundException { Scanner file_in = new Scanner(new File(filename)); List<Example> examples = new ArrayList<>(); while(file_in.hasNext()) { String line = file_in.nextLine(); String[] new_line = line.split(","); // for (String i : new_line) { // System.out.println(i); // } Example e = new Example(17); //initializing Example for input from text e.inputs[0] = 1; e.inputs[1] = Integer.parseInt(new_line[0]); e.inputs[2] = Integer.parseInt(new_line[1]); e.inputs[3] = Integer.parseInt(new_line[2]); e.inputs[4] = Integer.parseInt(new_line[3]); e.inputs[5] = Integer.parseInt(new_line[4]); e.inputs[6] = Integer.parseInt(new_line[5]); e.inputs[7] = Integer.parseInt(new_line[6]); e.inputs[8] = Integer.parseInt(new_line[7]); e.inputs[9] = Integer.parseInt(new_line[8]); e.inputs[10] = Integer.parseInt(new_line[9]); e.inputs[11] = Integer.parseInt(new_line[10]); e.inputs[12] = Integer.parseInt(new_line[11]); e.inputs[13] = Integer.parseInt(new_line[12]); e.inputs[14] = Integer.parseInt(new_line[13]); e.inputs[15] = Integer.parseInt(new_line[14]); e.inputs[16] = Integer.parseInt(new_line[15]); e.output = Integer.parseInt(new_line[16]); examples.add(e); } return examples; //returning examples in the text file } } <file_sep>import java.util.List; public class LogisticClassifier extends LinearClassifier { public LogisticClassifier(double[] weights) { super(weights); } public LogisticClassifier(int ninputs) { super(ninputs); } /** * A LogisticClassifier uses the logistic update rule * (AIMA Eq. 18.8): w_i \leftarrow w_i+\alpha(y-h_w(x)) \times h_w(x)(1-h_w(x)) \times x_i */ public void update(double[] x, double y, double alpha) { // This must be implemented by you for(int i=0; i<this.weights.length; i++) { double h = threshold(VectorOps.dot(this.weights, x)); this.weights[i] = this.weights[i] + alpha*(y - h) * x[i] * h * (1-h); } } /** * A LogisticClassifier uses a 0/1 sigmoid threshold at z=0. */ public double threshold(double z) { // This must be implemented by you //Page 726 return 1/(1 + Math.exp(-z)); } @Override protected void trainingReport(List<Example> examples, int stepnum, int nsteps) { super.trainingReport(examples, stepnum, nsteps); System.out.println(stepnum + "\t" + (1 - squaredErrorPerSample(examples))); } } <file_sep>import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class EarthLogistic { public static void main(String[] args) throws FileNotFoundException { List<Example> examples = new ArrayList<>(); examples = readFile(args[0]); //examples int nsteps = Integer.parseInt(args[1]); //steps double alpha = Double.parseDouble(args[2]); // LogisticClassifier l_classifier = new LogisticClassifier(examples.get(0).inputs.length); if (alpha > 0) { l_classifier.train(examples, nsteps, alpha); } else { l_classifier.train(examples, 100000, new LearningRateSchedule() { public double alpha(int t) { return 1000.0/(1000.0+t); } }); } } public static List<Example> readFile(String filename) throws FileNotFoundException { Scanner file_in = new Scanner(new File(filename)); List<Example> examples = new ArrayList<>(); while(file_in.hasNext()) { String line = file_in.nextLine(); String[] new_line = line.split(","); // for (String i : new_line) { // System.out.println(i); // } Example e = new Example(3); //initializing Example for input from text e.inputs[0] = 1; e.inputs[1] = Double.parseDouble(new_line[0]); e.inputs[2] = Double.parseDouble(new_line[1]); e.output = Integer.parseInt(new_line[2]); examples.add(e); } return examples; //returning examples in the text file } }
e5dc983b684c888f7f74bc12b79f48badc74e00f
[ "Java" ]
3
Java
waynexu1998/LC
34c4252664ddf312eb8ad0688da6804c77602c05
91bbb76ea8994eba41e7c78a286e61e87ddc4110
refs/heads/master
<repo_name>ekcasey/bosh-bootloader<file_sep>/commands/version_test.go package commands_test import ( "bytes" "fmt" "runtime" "github.com/cloudfoundry/bosh-bootloader/commands" "github.com/cloudfoundry/bosh-bootloader/storage" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Version", func() { var ( version commands.Version stdout *bytes.Buffer ) Context("when no version number was passed in", func() { BeforeEach(func() { stdout = bytes.NewBuffer([]byte{}) version = commands.NewVersion("", stdout) }) Describe("Execute", func() { It("prints out dev as the version", func() { err := version.Execute([]string{}, storage.State{}) Expect(err).NotTo(HaveOccurred()) Expect(stdout.String()).To(Equal(fmt.Sprintf("bbl dev (%s/%s)\n", runtime.GOOS, runtime.GOARCH))) }) }) }) Context("when a version number was passed in", func() { BeforeEach(func() { stdout = bytes.NewBuffer([]byte{}) version = commands.NewVersion("1.2.3", stdout) }) Describe("Execute", func() { It("prints out the passed in version information", func() { err := version.Execute([]string{}, storage.State{}) Expect(err).NotTo(HaveOccurred()) Expect(stdout.String()).To(Equal(fmt.Sprintf("bbl 1.2.3 (%s/%s)\n", runtime.GOOS, runtime.GOARCH))) }) }) }) }) <file_sep>/aws/cloudformation/templates/load_balancer_template_builder_test.go package templates_test import ( "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("LoadBalancerTemplateBuilder", func() { var builder templates.LoadBalancerTemplateBuilder BeforeEach(func() { builder = templates.NewLoadBalancerTemplateBuilder() }) Describe("CFRouterLoadBalancer", func() { It("returns a template containing the cf load balancer", func() { cfRouterLoadBalancerTemplate := builder.CFRouterLoadBalancer(2, "some-certificate-arn") Expect(cfRouterLoadBalancerTemplate.Outputs).To(HaveLen(2)) Expect(cfRouterLoadBalancerTemplate.Outputs).To(HaveKeyWithValue("CFRouterLoadBalancer", templates.Output{ Value: templates.Ref{"CFRouterLoadBalancer"}, })) Expect(cfRouterLoadBalancerTemplate.Outputs).To(HaveKeyWithValue("CFRouterLoadBalancerURL", templates.Output{ Value: templates.FnGetAtt{ []string{ "CFRouterLoadBalancer", "DNSName", }, }, })) Expect(cfRouterLoadBalancerTemplate.Resources).To(HaveLen(1)) Expect(cfRouterLoadBalancerTemplate.Resources).To(HaveKeyWithValue("CFRouterLoadBalancer", templates.Resource{ Type: "AWS::ElasticLoadBalancing::LoadBalancer", DependsOn: "VPCGatewayAttachment", Properties: templates.ElasticLoadBalancingLoadBalancer{ CrossZone: true, Subnets: []interface{}{templates.Ref{"LoadBalancerSubnet1"}, templates.Ref{"LoadBalancerSubnet2"}}, SecurityGroups: []interface{}{templates.Ref{"CFRouterSecurityGroup"}}, HealthCheck: templates.HealthCheck{ HealthyThreshold: "5", Interval: "12", Target: "tcp:80", Timeout: "2", UnhealthyThreshold: "2", }, Listeners: []templates.Listener{ { Protocol: "http", LoadBalancerPort: "80", InstanceProtocol: "http", InstancePort: "80", }, { Protocol: "https", LoadBalancerPort: "443", InstanceProtocol: "http", InstancePort: "80", SSLCertificateID: "some-certificate-arn", }, { Protocol: "ssl", LoadBalancerPort: "4443", InstanceProtocol: "tcp", InstancePort: "80", SSLCertificateID: "some-certificate-arn", }, }, }, })) }) }) Describe("CFSSHProxyLoadBalancer", func() { It("returns a template containing the cf ssh proxy load balancer", func() { cfSSHProxyLoadBalancerTemplate := builder.CFSSHProxyLoadBalancer(2) Expect(cfSSHProxyLoadBalancerTemplate.Outputs).To(HaveLen(2)) Expect(cfSSHProxyLoadBalancerTemplate.Outputs).To(HaveKeyWithValue("CFSSHProxyLoadBalancer", templates.Output{ Value: templates.Ref{"CFSSHProxyLoadBalancer"}, })) Expect(cfSSHProxyLoadBalancerTemplate.Outputs).To(HaveKeyWithValue("CFSSHProxyLoadBalancerURL", templates.Output{ Value: templates.FnGetAtt{ []string{ "CFSSHProxyLoadBalancer", "DNSName", }, }, })) Expect(cfSSHProxyLoadBalancerTemplate.Resources).To(HaveLen(1)) Expect(cfSSHProxyLoadBalancerTemplate.Resources).To(HaveKeyWithValue("CFSSHProxyLoadBalancer", templates.Resource{ Type: "AWS::ElasticLoadBalancing::LoadBalancer", DependsOn: "VPCGatewayAttachment", Properties: templates.ElasticLoadBalancingLoadBalancer{ CrossZone: true, Subnets: []interface{}{templates.Ref{"LoadBalancerSubnet1"}, templates.Ref{"LoadBalancerSubnet2"}}, SecurityGroups: []interface{}{templates.Ref{"CFSSHProxySecurityGroup"}}, HealthCheck: templates.HealthCheck{ HealthyThreshold: "5", Interval: "6", Target: "tcp:2222", Timeout: "2", UnhealthyThreshold: "2", }, Listeners: []templates.Listener{ { Protocol: "tcp", LoadBalancerPort: "2222", InstanceProtocol: "tcp", InstancePort: "2222", }, }, }, })) }) }) Describe("ConcourseLoadBalancer", func() { It("returns a template containing the concourse load balancer", func() { concourseLoadBalancer := builder.ConcourseLoadBalancer(2, "some-certificate-arn") Expect(concourseLoadBalancer.Outputs).To(HaveLen(2)) Expect(concourseLoadBalancer.Outputs).To(HaveKeyWithValue("ConcourseLoadBalancer", templates.Output{ Value: templates.Ref{"ConcourseLoadBalancer"}, })) Expect(concourseLoadBalancer.Outputs).To(HaveKeyWithValue("ConcourseLoadBalancerURL", templates.Output{ Value: templates.FnGetAtt{ []string{ "ConcourseLoadBalancer", "DNSName", }, }, })) Expect(concourseLoadBalancer.Resources).To(HaveLen(1)) Expect(concourseLoadBalancer.Resources).To(HaveKeyWithValue("ConcourseLoadBalancer", templates.Resource{ Type: "AWS::ElasticLoadBalancing::LoadBalancer", DependsOn: "VPCGatewayAttachment", Properties: templates.ElasticLoadBalancingLoadBalancer{ Subnets: []interface{}{templates.Ref{"LoadBalancerSubnet1"}, templates.Ref{"LoadBalancerSubnet2"}}, SecurityGroups: []interface{}{templates.Ref{"ConcourseSecurityGroup"}}, HealthCheck: templates.HealthCheck{ HealthyThreshold: "2", Interval: "30", Target: "tcp:8080", Timeout: "5", UnhealthyThreshold: "10", }, Listeners: []templates.Listener{ { Protocol: "tcp", LoadBalancerPort: "80", InstanceProtocol: "tcp", InstancePort: "8080", }, { Protocol: "tcp", LoadBalancerPort: "2222", InstanceProtocol: "tcp", InstancePort: "2222", }, { Protocol: "ssl", LoadBalancerPort: "443", InstanceProtocol: "tcp", InstancePort: "8080", SSLCertificateID: "some-certificate-arn", }, }, }, })) }) }) }) <file_sep>/bosh/networks_generator_test.go package bosh_test import ( "github.com/cloudfoundry/bosh-bootloader/bosh" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("NetworksGenerator", func() { Describe("Generate", func() { It("returns a slice of networks for cloud config", func() { generator := bosh.NewNetworksGenerator([]bosh.SubnetInput{ bosh.SubnetInput{ AZ: "us-east-1a", CIDR: "10.0.16.0/20", Subnet: "some-subnet-1", SecurityGroups: []string{"some-security-group-1"}, }, bosh.SubnetInput{ AZ: "us-east-1b", CIDR: "10.0.32.0/20", Subnet: "some-subnet-2", SecurityGroups: []string{"some-security-group-2"}, }, bosh.SubnetInput{ AZ: "us-east-1c", CIDR: "10.0.48.0/20", Subnet: "some-subnet-3", SecurityGroups: []string{"some-security-group-3"}, }, }, map[string]string{ "us-east-1a": "z1", "us-east-1b": "z2", "us-east-1c": "z3", }) networks, err := generator.Generate() Expect(err).NotTo(HaveOccurred()) Expect(networks).To(ConsistOf( bosh.Network{ Name: "private", Type: "manual", Subnets: []bosh.NetworkSubnet{ { AZ: "z1", Gateway: "10.0.16.1", Range: "10.0.16.0/20", Reserved: []string{ "10.0.16.2-10.0.16.3", "10.0.31.255", }, Static: []string{ "10.0.31.190-10.0.31.254", }, CloudProperties: bosh.SubnetCloudProperties{ Subnet: "some-subnet-1", SecurityGroups: []string{ "some-security-group-1", }, }, }, { AZ: "z2", Gateway: "10.0.32.1", Range: "10.0.32.0/20", Reserved: []string{ "10.0.32.2-10.0.32.3", "10.0.47.255", }, Static: []string{ "10.0.47.190-10.0.47.254", }, CloudProperties: bosh.SubnetCloudProperties{ Subnet: "some-subnet-2", SecurityGroups: []string{ "some-security-group-2", }, }, }, { AZ: "z3", Gateway: "10.0.48.1", Range: "10.0.48.0/20", Reserved: []string{ "10.0.48.2-10.0.48.3", "10.0.63.255", }, Static: []string{ "10.0.63.190-10.0.63.254", }, CloudProperties: bosh.SubnetCloudProperties{ Subnet: "some-subnet-3", SecurityGroups: []string{ "some-security-group-3", }, }, }, }, }, )) }) Context("failure cases", func() { It("returns an error when CIDR block cannot be parsed", func() { generator := bosh.NewNetworksGenerator([]bosh.SubnetInput{ bosh.SubnetInput{ AZ: "us-east-1a", CIDR: "not-a-cidr-block", Subnet: "some-subnet-1", SecurityGroups: []string{"some-security-group-1"}, }, }, map[string]string{ "us-east-1a": "z1", }) _, err := generator.Generate() Expect(err).To(MatchError(ContainSubstring("cannot parse CIDR block"))) }) It("returns an error when CIDR block is too small to contain the required reserved ips", func() { generator := bosh.NewNetworksGenerator([]bosh.SubnetInput{ bosh.SubnetInput{ AZ: "us-east-1a", CIDR: "10.0.16.0/32", Subnet: "some-subnet-1", SecurityGroups: []string{"some-security-group-1"}, }, }, map[string]string{ "us-east-1a": "z1", }) _, err := generator.Generate() Expect(err).To(MatchError(ContainSubstring("not enough IPs allocated in CIDR block for subnet"))) }) }) }) }) <file_sep>/fakes/cloud_config_generator.go package fakes import "github.com/cloudfoundry/bosh-bootloader/bosh" type CloudConfigGenerator struct { GenerateCall struct { Receives struct { CloudConfigInput bosh.CloudConfigInput } Returns struct { CloudConfig bosh.CloudConfig Error error } CallCount int } } func (c *CloudConfigGenerator) Generate(cloudConfigInput bosh.CloudConfigInput) (bosh.CloudConfig, error) { c.GenerateCall.CallCount++ c.GenerateCall.Receives.CloudConfigInput = cloudConfigInput return c.GenerateCall.Returns.CloudConfig, c.GenerateCall.Returns.Error } <file_sep>/aws/cloudformation/templates/template_builder_test.go package templates_test import ( "encoding/json" "io/ioutil" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" "github.com/cloudfoundry/bosh-bootloader/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/extensions/table" . "github.com/onsi/gomega" ) var _ = Describe("TemplateBuilder", func() { var ( builder templates.TemplateBuilder logger *fakes.Logger ) BeforeEach(func() { logger = &fakes.Logger{} builder = templates.NewTemplateBuilder(logger) }) Describe("Build", func() { Context("concourse elb template", func() { It("builds a cloudformation template", func() { template := builder.Build("keypair-name", 5, "concourse", "", "", "") Expect(template.AWSTemplateFormatVersion).To(Equal("2010-09-09")) Expect(template.Description).To(Equal("Infrastructure for a BOSH deployment with a Concourse ELB.")) Expect(template.Parameters).To(HaveKey("SSHKeyPairName")) Expect(template.Resources).To(HaveKey("BOSHUser")) Expect(template.Resources).To(HaveKey("NATInstance")) Expect(template.Resources).To(HaveKey("VPC")) Expect(template.Resources).To(HaveKey("BOSHSubnet")) Expect(template.Resources).To(HaveKey("InternalSubnet1")) Expect(template.Resources).To(HaveKey("InternalSubnet2")) Expect(template.Resources).To(HaveKey("InternalSubnet3")) Expect(template.Resources).To(HaveKey("InternalSubnet4")) Expect(template.Resources).To(HaveKey("InternalSubnet5")) Expect(template.Resources).To(HaveKey("InternalSecurityGroup")) Expect(template.Resources).To(HaveKey("BOSHSecurityGroup")) Expect(template.Resources).To(HaveKey("BOSHEIP")) Expect(template.Resources).To(HaveKey("LoadBalancerSubnet1")) Expect(template.Resources).To(HaveKey("LoadBalancerSubnet2")) Expect(template.Resources).To(HaveKey("LoadBalancerSubnet3")) Expect(template.Resources).To(HaveKey("LoadBalancerSubnet4")) Expect(template.Resources).To(HaveKey("LoadBalancerSubnet5")) Expect(template.Resources).To(HaveKey("ConcourseSecurityGroup")) Expect(template.Resources).To(HaveKey("ConcourseInternalSecurityGroup")) Expect(template.Resources).To(HaveKey("ConcourseLoadBalancer")) }) }) Context("cf elb template", func() { It("builds a cloudformation template", func() { template := builder.Build("keypair-name", 5, "cf", "", "", "") Expect(template.AWSTemplateFormatVersion).To(Equal("2010-09-09")) Expect(template.Description).To(Equal("Infrastructure for a BOSH deployment with a CloudFoundry ELB.")) Expect(template.Parameters).To(HaveKey("SSHKeyPairName")) Expect(template.Resources).To(HaveKey("BOSHUser")) Expect(template.Resources).To(HaveKey("NATInstance")) Expect(template.Resources).To(HaveKey("VPC")) Expect(template.Resources).To(HaveKey("BOSHSubnet")) Expect(template.Resources).To(HaveKey("InternalSubnet1")) Expect(template.Resources).To(HaveKey("InternalSubnet2")) Expect(template.Resources).To(HaveKey("InternalSubnet3")) Expect(template.Resources).To(HaveKey("InternalSubnet4")) Expect(template.Resources).To(HaveKey("InternalSubnet5")) Expect(template.Resources).To(HaveKey("InternalSecurityGroup")) Expect(template.Resources).To(HaveKey("BOSHSecurityGroup")) Expect(template.Resources).To(HaveKey("BOSHEIP")) Expect(template.Resources).To(HaveKey("LoadBalancerSubnet1")) Expect(template.Resources).To(HaveKey("LoadBalancerSubnet2")) Expect(template.Resources).To(HaveKey("LoadBalancerSubnet3")) Expect(template.Resources).To(HaveKey("LoadBalancerSubnet4")) Expect(template.Resources).To(HaveKey("LoadBalancerSubnet5")) Expect(template.Resources).To(HaveKey("CFRouterSecurityGroup")) Expect(template.Resources).To(HaveKey("CFRouterInternalSecurityGroup")) Expect(template.Resources).To(HaveKey("CFRouterLoadBalancer")) Expect(template.Resources).To(HaveKey("CFSSHProxySecurityGroup")) Expect(template.Resources).To(HaveKey("CFSSHProxyInternalSecurityGroup")) Expect(template.Resources).To(HaveKey("CFSSHProxyLoadBalancer")) }) }) Context("no elb template", func() { It("builds a cloudformation template", func() { template := builder.Build("keypair-name", 5, "", "", "", "") Expect(template.AWSTemplateFormatVersion).To(Equal("2010-09-09")) Expect(template.Description).To(Equal("Infrastructure for a BOSH deployment.")) Expect(template.Parameters).To(HaveKey("SSHKeyPairName")) Expect(template.Resources).To(HaveKey("BOSHUser")) Expect(template.Resources).To(HaveKey("NATInstance")) Expect(template.Resources).To(HaveKey("VPC")) Expect(template.Resources).To(HaveKey("BOSHSubnet")) Expect(template.Resources).To(HaveKey("InternalSubnet1")) Expect(template.Resources).To(HaveKey("InternalSubnet2")) Expect(template.Resources).To(HaveKey("InternalSubnet3")) Expect(template.Resources).To(HaveKey("InternalSubnet4")) Expect(template.Resources).To(HaveKey("InternalSubnet5")) Expect(template.Resources).To(HaveKey("InternalSecurityGroup")) Expect(template.Resources).To(HaveKey("BOSHSecurityGroup")) Expect(template.Resources).To(HaveKey("BOSHEIP")) Expect(template.Resources).NotTo(HaveKey("LoadBalancerSubnet1")) Expect(template.Resources).NotTo(HaveKey("LoadBalancerSubnet2")) Expect(template.Resources).NotTo(HaveKey("LoadBalancerSubnet3")) Expect(template.Resources).NotTo(HaveKey("LoadBalancerSubnet4")) Expect(template.Resources).NotTo(HaveKey("LoadBalancerSubnet5")) Expect(template.Resources).NotTo(HaveKey("ConcourseSecurityGroup")) Expect(template.Resources).NotTo(HaveKey("ConcourseLoadBalancer")) Expect(template.Resources).NotTo(HaveKey("CFRouterSecurityGroup")) Expect(template.Resources).NotTo(HaveKey("CFRouterLoadBalancer")) Expect(template.Resources).NotTo(HaveKey("CFSSHProxySecurityGroup")) Expect(template.Resources).NotTo(HaveKey("CFSSHProxyLoadBalancer")) }) }) It("logs that the cloudformation template is being generated", func() { builder.Build("keypair-name", 0, "", "", "", "") Expect(logger.StepCall.Receives.Message).To(Equal("generating cloudformation template")) }) }) Describe("template marshaling", func() { DescribeTable("marshals template to JSON", func(lbType string, fixture string) { template := builder.Build("keypair-name", 4, lbType, "some-certificate-arn", "bosh-iam-user-some-env-id", "bbl-env-id") buf, err := ioutil.ReadFile("fixtures/" + fixture) Expect(err).NotTo(HaveOccurred()) output, err := json.Marshal(template) Expect(err).NotTo(HaveOccurred()) Expect(output).To(MatchJSON(string(buf))) }, Entry("without load balancer", "", "cloudformation_without_elb.json"), Entry("with cf load balancer", "cf", "cloudformation_with_cf_elb.json"), Entry("with concourse load balancer", "concourse", "cloudformation_with_concourse_elb.json"), ) }) }) <file_sep>/fakes/bosh_init_runner.go package fakes import "github.com/cloudfoundry/bosh-bootloader/boshinit" type BOSHInitCommandRunner struct { ExecuteCall struct { Receives struct { Manifest []byte PrivateKey string State boshinit.State } Returns struct { State boshinit.State Error error } } } func (r *BOSHInitCommandRunner) Execute(manifest []byte, privateKey string, state boshinit.State) (boshinit.State, error) { r.ExecuteCall.Receives.Manifest = manifest r.ExecuteCall.Receives.PrivateKey = privateKey r.ExecuteCall.Receives.State = state return r.ExecuteCall.Returns.State, r.ExecuteCall.Returns.Error } <file_sep>/aws/cloudformation/templates/vpc_template_builder_test.go package templates_test import ( "fmt" "math/rand" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("VPCTemplateBuilder", func() { var builder templates.VPCTemplateBuilder BeforeEach(func() { builder = templates.NewVPCTemplateBuilder() }) Describe("VPC", func() { It("returns a template with the VPC-related parameters", func() { vpc := builder.VPC("") Expect(vpc.Parameters).To(HaveLen(1)) Expect(vpc.Parameters).To(HaveKeyWithValue("VPCCIDR", templates.Parameter{ Description: "CIDR block for the VPC.", Type: "String", Default: "10.0.0.0/16", })) }) It("returns a template with the VPC-related resources", func() { envID := fmt.Sprintf("some-env-id-%v", rand.Int()) vpc := builder.VPC(envID) Expect(vpc.Resources).To(HaveLen(3)) Expect(vpc.Resources).To(HaveKeyWithValue("VPC", templates.Resource{ Type: "AWS::EC2::VPC", Properties: templates.VPC{ CidrBlock: templates.Ref{"VPCCIDR"}, Tags: []templates.Tag{ { Value: fmt.Sprintf("vpc-%s", envID), Key: "Name", }, }, }, })) Expect(vpc.Resources).To(HaveKeyWithValue("VPCGatewayInternetGateway", templates.Resource{ Type: "AWS::EC2::InternetGateway", })) Expect(vpc.Resources).To(HaveKeyWithValue("VPCGatewayAttachment", templates.Resource{ Type: "AWS::EC2::VPCGatewayAttachment", Properties: templates.VPCGatewayAttachment{ VpcId: templates.Ref{"VPC"}, InternetGatewayId: templates.Ref{"VPCGatewayInternetGateway"}, }, })) }) It("returns a template with the VPC-related outputs", func() { vpc := builder.VPC("") Expect(vpc.Outputs).To(HaveKeyWithValue("VPCID", templates.Output{ Value: templates.Ref{Ref: "VPC"}, })) }) }) }) <file_sep>/bosh/cloud_config.go package bosh type CloudConfig struct { AZs []AZ `yaml:"azs,omitempty"` VMTypes []VMType `yaml:"vm_types,omitempty"` DiskTypes []DiskType `yaml:"disk_types,omitempty"` Compilation *Compilation `yaml:"compilation,omitempty"` Networks []Network `yaml:"networks,omitempty"` VMExtensions []VMExtension `yaml:"vm_extensions,omitempty"` } <file_sep>/aws/config_test.go package aws_test import ( goaws "github.com/aws/aws-sdk-go/aws" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/cloudfoundry/bosh-bootloader/aws" ) var _ = Describe("Config", func() { Describe("ClientConfig", func() { It("returns an AWS config which is consumable by AWS client functions", func() { config := aws.Config{ AccessKeyID: "some-access-key-id", SecretAccessKey: " some-secret-access-key", Region: "some-region", EndpointOverride: "some-endpoint-override", } awsConfig := &goaws.Config{ Credentials: credentials.NewStaticCredentials(config.AccessKeyID, config.SecretAccessKey, ""), Region: goaws.String(config.Region), Endpoint: goaws.String(config.EndpointOverride), } Expect(config.ClientConfig()).To(Equal(awsConfig)) }) }) }) <file_sep>/commands/global_flags.go package commands type GlobalFlags struct { EndpointOverride string AWSAccessKeyID string AWSSecretAccessKey string AWSRegion string StateDir string } <file_sep>/fakes/bosh_client.go package fakes import "github.com/cloudfoundry/bosh-bootloader/bosh" type BOSHClient struct { UpdateCloudConfigCall struct { CallCount int Receives struct { Yaml []byte } Returns struct { Error error } } InfoCall struct { CallCount int Returns struct { Info bosh.Info Error error } } } func (c *BOSHClient) UpdateCloudConfig(yaml []byte) error { c.UpdateCloudConfigCall.CallCount++ c.UpdateCloudConfigCall.Receives.Yaml = yaml return c.UpdateCloudConfigCall.Returns.Error } func (c *BOSHClient) Info() (bosh.Info, error) { c.InfoCall.CallCount++ return c.InfoCall.Returns.Info, c.InfoCall.Returns.Error } <file_sep>/helpers/uuid_generator_test.go package helpers_test import ( "crypto/rand" "errors" "github.com/cloudfoundry/bosh-bootloader/fakes" "github.com/cloudfoundry/bosh-bootloader/helpers" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("UUIDGenerator", func() { Describe("Generate", func() { It("generates random UUID values", func() { generator := helpers.NewUUIDGenerator(rand.Reader) uuid, err := generator.Generate() Expect(err).NotTo(HaveOccurred()) Expect(uuid).To(MatchRegexp(`\w{8}-\w{4}-\w{4}-\w{4}-\w{12}`)) var uuids []string for i := 0; i < 10; i++ { uuid, err := generator.Generate() Expect(err).NotTo(HaveOccurred()) uuids = append(uuids, uuid) } Expect(HasUniqueValues(uuids)).To(BeTrue()) }) Context("failure cases", func() { It("returns an error when the reader fails", func() { reader := &fakes.Reader{} generator := helpers.NewUUIDGenerator(reader) reader.ReadCall.Returns.Error = errors.New("reader failed") _, err := generator.Generate() Expect(err).To(MatchError("reader failed")) }) }) }) }) func HasUniqueValues(values []string) bool { valueMap := make(map[string]struct{}) for _, value := range values { valueMap[value] = struct{}{} } return len(valueMap) == len(values) } <file_sep>/aws/ec2/client.go package ec2 import ( "github.com/cloudfoundry/bosh-bootloader/aws" "github.com/aws/aws-sdk-go/aws/session" awsec2 "github.com/aws/aws-sdk-go/service/ec2" ) type Client interface { ImportKeyPair(*awsec2.ImportKeyPairInput) (*awsec2.ImportKeyPairOutput, error) DescribeKeyPairs(*awsec2.DescribeKeyPairsInput) (*awsec2.DescribeKeyPairsOutput, error) CreateKeyPair(*awsec2.CreateKeyPairInput) (*awsec2.CreateKeyPairOutput, error) DescribeAvailabilityZones(*awsec2.DescribeAvailabilityZonesInput) (*awsec2.DescribeAvailabilityZonesOutput, error) DeleteKeyPair(*awsec2.DeleteKeyPairInput) (*awsec2.DeleteKeyPairOutput, error) DescribeInstances(*awsec2.DescribeInstancesInput) (*awsec2.DescribeInstancesOutput, error) } func NewClient(config aws.Config) Client { return awsec2.New(session.New(config.ClientConfig())) } <file_sep>/fakes/ssl_keypair_generator.go package fakes import "github.com/cloudfoundry/bosh-bootloader/ssl" type SSLKeyPairGenerator struct { GenerateCall struct { CallCount int Returns struct { KeyPair ssl.KeyPair Error error } Receives struct { CACommonName string CertCommonName string } } } func (c *SSLKeyPairGenerator) Generate(caCommonName, certCommonName string) (ssl.KeyPair, error) { c.GenerateCall.CallCount++ c.GenerateCall.Receives.CACommonName = caCommonName c.GenerateCall.Receives.CertCommonName = certCommonName return c.GenerateCall.Returns.KeyPair, c.GenerateCall.Returns.Error } <file_sep>/commands/state_query.go package commands import ( "fmt" "github.com/cloudfoundry/bosh-bootloader/storage" ) const ( EnvIDCommand = "env-id" SSHKeyCommand = "ssh-key" DirectorUsernameCommand = "director-username" DirectorPasswordCommand = "<PASSWORD>" DirectorAddressCommand = "director-address" DirectorCACertCommand = "director-ca-cert" BOSHCACertCommand = "bosh-ca-cert" EnvIDPropertyName = "environment id" SSHKeyPropertyName = "ssh key" DirectorUsernamePropertyName = "director username" DirectorPasswordPropertyName = "<PASSWORD>" DirectorAddressPropertyName = "director address" DirectorCACertPropertyName = "director ca cert" BOSHCACertPropertyName = "bosh ca cert" ) type StateQuery struct { logger logger stateValidator stateValidator propertyName string getProperty getPropertyFunc } type getPropertyFunc func(storage.State) string func NewStateQuery(logger logger, stateValidator stateValidator, propertyName string, getProperty getPropertyFunc) StateQuery { return StateQuery{ logger: logger, stateValidator: stateValidator, propertyName: propertyName, getProperty: getProperty, } } func (s StateQuery) Execute(subcommandFlags []string, state storage.State) error { err := s.stateValidator.Validate() if err != nil { return err } propertyValue := s.getProperty(state) if propertyValue == "" { return fmt.Errorf("Could not retrieve %s, please make sure you are targeting the proper state dir.", s.propertyName) } s.logger.Println(propertyValue) return nil } <file_sep>/fakes/bosh_client_provider.go package fakes import ( "github.com/cloudfoundry/bosh-bootloader/bosh" ) type BOSHClientProvider struct { ClientCall struct { Receives struct { DirectorAddress string DirectorUsername string DirectorPassword string } Returns struct { Client bosh.Client } } } func (b *BOSHClientProvider) Client(directorAddress, directorUsername, directorPassword string) bosh.Client { b.ClientCall.Receives.DirectorAddress = directorAddress b.ClientCall.Receives.DirectorUsername = directorUsername b.ClientCall.Receives.DirectorPassword = <PASSWORD> return b.ClientCall.Returns.Client } <file_sep>/aws/cloudformation/templates/bosh_eip_template_builder_test.go package templates_test import ( "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("BOSHEIPTemplateBuilder", func() { var builder templates.BOSHEIPTemplateBuilder BeforeEach(func() { builder = templates.NewBOSHEIPTemplateBuilder() }) Describe("BOSHEIP", func() { It("returns a template containing the bosh elastic ip", func() { eip := builder.BOSHEIP() Expect(eip.Resources).To(HaveLen(1)) Expect(eip.Resources).To(HaveKeyWithValue("BOSHEIP", templates.Resource{ DependsOn: "VPCGatewayAttachment", Type: "AWS::EC2::EIP", Properties: templates.EIP{ Domain: "vpc", }, })) Expect(eip.Outputs).To(HaveLen(2)) Expect(eip.Outputs).To(HaveKeyWithValue("BOSHEIP", templates.Output{ Value: templates.Ref{"BOSHEIP"}, })) Expect(eip.Outputs).To(HaveKeyWithValue("BOSHURL", templates.Output{ Value: templates.FnJoin{ Delimeter: "", Values: []interface{}{"https://", templates.Ref{"BOSHEIP"}, ":25555"}, }, })) }) }) }) <file_sep>/fakes/keypair_validator.go package fakes type KeyPairValidator struct { ValidateCall struct { CallCount int Receives struct { PEMData []byte } Returns struct { Error error } } } func (v *KeyPairValidator) Validate(pemData []byte) error { v.ValidateCall.CallCount++ v.ValidateCall.Receives.PEMData = pemData return v.ValidateCall.Returns.Error } <file_sep>/storage/keypair.go package storage import "reflect" type KeyPair struct { Name string `json:"name"` PrivateKey string `json:"privateKey"` PublicKey string `json:"publicKey"` } func (k KeyPair) IsEmpty() bool { return reflect.DeepEqual(k, KeyPair{}) } <file_sep>/aws/cloudformation/templates/template_builder.go package templates type logger interface { Step(message string, a ...interface{}) Dot() } type TemplateBuilder struct { logger logger } func NewTemplateBuilder(logger logger) TemplateBuilder { return TemplateBuilder{ logger: logger, } } func (t TemplateBuilder) Build(keyPairName string, numberOfAvailabilityZones int, lbType, lbCertificateARN string, iamUserName string, envID string) Template { t.logger.Step("generating cloudformation template") boshIAMTemplateBuilder := NewBOSHIAMTemplateBuilder() natTemplateBuilder := NewNATTemplateBuilder() vpcTemplateBuilder := NewVPCTemplateBuilder() internalSubnetsTemplateBuilder := NewInternalSubnetsTemplateBuilder() boshSubnetTemplateBuilder := NewBOSHSubnetTemplateBuilder() boshEIPTemplateBuilder := NewBOSHEIPTemplateBuilder() securityGroupTemplateBuilder := NewSecurityGroupTemplateBuilder() sshKeyPairTemplateBuilder := NewSSHKeyPairTemplateBuilder() loadBalancerSubnetsTemplateBuilder := NewLoadBalancerSubnetsTemplateBuilder() loadBalancerTemplateBuilder := NewLoadBalancerTemplateBuilder() template := Template{ AWSTemplateFormatVersion: "2010-09-09", Description: "Infrastructure for a BOSH deployment.", }.Merge( internalSubnetsTemplateBuilder.InternalSubnets(numberOfAvailabilityZones), sshKeyPairTemplateBuilder.SSHKeyPairName(keyPairName), boshIAMTemplateBuilder.BOSHIAMUser(iamUserName), natTemplateBuilder.NAT(), vpcTemplateBuilder.VPC(envID), boshSubnetTemplateBuilder.BOSHSubnet(), securityGroupTemplateBuilder.InternalSecurityGroup(), securityGroupTemplateBuilder.BOSHSecurityGroup(), boshEIPTemplateBuilder.BOSHEIP(), ) if lbType == "concourse" { template.Description = "Infrastructure for a BOSH deployment with a Concourse ELB." lbTemplate := loadBalancerTemplateBuilder.ConcourseLoadBalancer(numberOfAvailabilityZones, lbCertificateARN) template.Merge( loadBalancerSubnetsTemplateBuilder.LoadBalancerSubnets(numberOfAvailabilityZones), lbTemplate, securityGroupTemplateBuilder.LBSecurityGroup("ConcourseSecurityGroup", "Concourse", "ConcourseLoadBalancer", lbTemplate), securityGroupTemplateBuilder.LBInternalSecurityGroup("ConcourseInternalSecurityGroup", "ConcourseSecurityGroup", "ConcourseInternal", "ConcourseLoadBalancer", lbTemplate), ) } if lbType == "cf" { template.Description = "Infrastructure for a BOSH deployment with a CloudFoundry ELB." routerLBTemplate := loadBalancerTemplateBuilder.CFRouterLoadBalancer(numberOfAvailabilityZones, lbCertificateARN) sshLBTemplate := loadBalancerTemplateBuilder.CFSSHProxyLoadBalancer(numberOfAvailabilityZones) template.Merge( loadBalancerSubnetsTemplateBuilder.LoadBalancerSubnets(numberOfAvailabilityZones), routerLBTemplate, securityGroupTemplateBuilder.LBSecurityGroup("CFRouterSecurityGroup", "Router", "CFRouterLoadBalancer", routerLBTemplate), securityGroupTemplateBuilder.LBInternalSecurityGroup("CFRouterInternalSecurityGroup", "CFRouterSecurityGroup", "CFRouterInternal", "CFRouterLoadBalancer", routerLBTemplate), sshLBTemplate, securityGroupTemplateBuilder.LBSecurityGroup("CFSSHProxySecurityGroup", "CFSSHProxy", "CFSSHProxyLoadBalancer", sshLBTemplate), securityGroupTemplateBuilder.LBInternalSecurityGroup("CFSSHProxyInternalSecurityGroup", "CFSSHProxySecurityGroup", "CFSSHProxyInternal", "CFSSHProxyLoadBalancer", sshLBTemplate), ) } return template } <file_sep>/boshinit/manifests/job_properties_manifest_builder.go package manifests import "fmt" type JobPropertiesManifestBuilder struct { natsUsername string postgresUsername string registryUsername string blobstoreDirectorUsername string blobstoreAgentUsername string hmUsername string natsPassword string postgresPassword string registryPassword string blobstoreDirectorPassword string blobstoreAgentPassword string hmPassword string } func NewJobPropertiesManifestBuilder(natsUsername, postgresUsername, registryUsername, blobstoreDirectorUsername, blobstoreAgentUsername, hmUsername, natsPassword, postgresPassword, registryPassword, blobstoreDirectorPassword, blobstoreAgentPassword, hmPassword string) JobPropertiesManifestBuilder { return JobPropertiesManifestBuilder{ natsUsername: natsUsername, postgresUsername: postgresUsername, registryUsername: registryUsername, blobstoreDirectorUsername: blobstoreDirectorUsername, blobstoreAgentUsername: blobstoreAgentUsername, hmUsername: hmUsername, natsPassword: <PASSWORD>, postgresPassword: <PASSWORD>, registryPassword: <PASSWORD>, blobstoreDirectorPassword: blob<PASSWORD>Director<PASSWORD>, blobstoreAgentPassword: <PASSWORD>, hmPassword: <PASSWORD>, } } func (j JobPropertiesManifestBuilder) NATS() NATSJobProperties { return NATSJobProperties{ Address: "127.0.0.1", User: j.natsUsername, Password: j.<PASSWORD>, } } func (j JobPropertiesManifestBuilder) Postgres() PostgresProperties { return PostgresProperties{ User: j.postgresUsername, Password: <PASSWORD>, } } func (j JobPropertiesManifestBuilder) Registry() RegistryJobProperties { postgres := j.Postgres() return RegistryJobProperties{ Host: "10.0.0.6", Address: "10.0.0.6", Username: j.registryUsername, Password: <PASSWORD>, DB: RegistryPostgresProperties{ User: postgres.User, Password: <PASSWORD>, Database: "bosh", }, HTTP: HTTPProperties{ User: j.registryUsername, Password: <PASSWORD>, }, } } func (j JobPropertiesManifestBuilder) Blobstore() BlobstoreJobProperties { return BlobstoreJobProperties{ Address: "10.0.0.6", Director: Credentials{ User: j.blobstoreDirectorUsername, Password: <PASSWORD>, }, Agent: Credentials{ User: j.blobstoreAgentUsername, Password: <PASSWORD>, }, } } func (j JobPropertiesManifestBuilder) Director(manifestProperties ManifestProperties) DirectorJobProperties { return DirectorJobProperties{ Address: "127.0.0.1", Name: manifestProperties.DirectorName, CPIJob: "aws_cpi", EnablePostDeploy: true, Workers: 11, EnableDedicatedStatusWorker: true, DB: j.Postgres(), UserManagement: UserManagementProperties{ Local: LocalProperties{ Users: []UserProperties{ { Name: manifestProperties.DirectorUsername, Password: <PASSWORD>, }, { Name: j.hmUsername, Password: <PASSWORD>, }, }, }, }, SSL: SSLProperties{ Cert: string(manifestProperties.SSLKeyPair.Certificate), Key: string(manifestProperties.SSLKeyPair.PrivateKey), }, DefaultSSHOptions: DefaultSSHOptions{ GatewayHost: manifestProperties.ElasticIP, }, } } func (j JobPropertiesManifestBuilder) HM() HMJobProperties { return HMJobProperties{ DirectorAccount: Credentials{ User: j.hmUsername, Password: <PASSWORD>, }, ResurrectorEnabled: true, } } func (j JobPropertiesManifestBuilder) Agent() AgentProperties { return AgentProperties{ MBus: fmt.Sprintf("nats://%s:%s@10.0.0.6:4222", j.natsUsername, j.natsPassword), } } <file_sep>/bbl/destroy_test.go package main_test import ( "bufio" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "time" "github.com/cloudfoundry/bosh-bootloader/bbl/awsbackend" "github.com/cloudfoundry/bosh-bootloader/boshinit" "github.com/cloudfoundry/bosh-bootloader/storage" "github.com/cloudfoundry/bosh-bootloader/testhelpers" "github.com/onsi/gomega/gexec" "github.com/rosenhouse/awsfaker" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("destroy", func() { Context("when the state file does not exist", func() { It("exits with status 0 if --skip-if-missing flag is provided", func() { tempDirectory, err := ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) args := []string{ "--state-dir", tempDirectory, "destroy", "--skip-if-missing", } cmd := exec.Command(pathToBBL, args...) session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session, 10*time.Second).Should(gexec.Exit(0)) Expect(session.Out.Contents()).To(ContainSubstring("state file not found, and —skip-if-missing flag provided, exiting")) }) It("exits with status 1 and outputs helpful error message", func() { tempDirectory, err := ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) args := []string{ "--state-dir", tempDirectory, "destroy", } cmd := exec.Command(pathToBBL, args...) session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session, 10*time.Second).Should(gexec.Exit(1)) Expect(session.Err.Contents()).To(ContainSubstring(fmt.Sprintf("bbl-state.json not found in %q, ensure you're running this command in the proper state directory or create a new environment with bbl up", tempDirectory))) }) }) Context("asks for confirmation before it starts destroying things", func() { var ( cmd *exec.Cmd stdin io.WriteCloser stdout io.ReadCloser fakeAWS *awsbackend.Backend fakeAWSServer *httptest.Server fakeBOSH *fakeBOSHDirector fakeBOSHServer *httptest.Server tempDirectory string ) BeforeEach(func() { fakeBOSH = &fakeBOSHDirector{} fakeBOSHServer = httptest.NewServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) { fakeBOSH.ServeHTTP(responseWriter, request) })) fakeAWS = awsbackend.New(fakeBOSHServer.URL) fakeAWS.Stacks.Set(awsbackend.Stack{ Name: "some-stack-name", }) fakeAWS.KeyPairs.Set(awsbackend.KeyPair{ Name: "some-keypair-name", }) fakeAWS.Instances.Set([]awsbackend.Instance{ {Name: "bosh/0", VPCID: "some-vpc-id"}, {Name: "NAT", VPCID: "some-vpc-id"}, }) fakeAWSServer = httptest.NewServer(awsfaker.New(fakeAWS)) var err error tempDirectory, err = ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) buf, err := json.Marshal(storage.State{ AWS: storage.AWS{ AccessKeyID: "some-access-key", SecretAccessKey: "some-access-secret", Region: "some-region", }, KeyPair: storage.KeyPair{ Name: "some-keypair-name", PrivateKey: testhelpers.BBL_KEY, }, Stack: storage.Stack{ Name: "some-stack-name", }, BOSH: storage.BOSH{ DirectorName: "some-bosh-director-name", }, }) Expect(err).NotTo(HaveOccurred()) err = ioutil.WriteFile(filepath.Join(tempDirectory, storage.StateFileName), buf, os.ModePerm) Expect(err).NotTo(HaveOccurred()) args := []string{ fmt.Sprintf("--endpoint-override=%s", fakeAWSServer.URL), "--state-dir", tempDirectory, "destroy", } cmd = exec.Command(pathToBBL, args...) stdin, err = cmd.StdinPipe() Expect(err).NotTo(HaveOccurred()) stdout, err = cmd.StdoutPipe() Expect(err).NotTo(HaveOccurred()) err = cmd.Start() Expect(err).NotTo(HaveOccurred()) Eventually(func() (string, error) { bytes, err := bufio.NewReader(stdout).ReadBytes(':') if err != nil { return "", err } return string(bytes), nil }, "10s", "10s").Should(ContainSubstring("Are you sure you want to delete infrastructure for")) }) It("continues with the destruction if you agree", func() { _, err := stdin.Write([]byte("yes\n")) Expect(err).NotTo(HaveOccurred()) Eventually(func() (string, error) { bytes, err := bufio.NewReader(stdout).ReadBytes('\n') if err != nil { return "", err } return string(bytes), nil }, "10s", "10s").Should(ContainSubstring("step: destroying bosh director")) Eventually(cmd.Wait).Should(Succeed()) }) It("does not destroy your infrastructure if you do not agree", func() { _, err := stdin.Write([]byte("no\n")) Expect(err).NotTo(HaveOccurred()) Eventually(func() (string, error) { bytes, err := bufio.NewReader(stdout).ReadBytes('\n') if err != nil { return "", err } return string(bytes), nil }, "10s", "10s").Should(ContainSubstring("step: exiting")) Eventually(cmd.Wait).Should(Succeed()) }) }) Context("when the bosh director, cloudformation stack, certificate, and ec2 keypair exists", func() { var ( fakeAWS *awsbackend.Backend fakeAWSServer *httptest.Server fakeBOSH *fakeBOSHDirector fakeBOSHServer *httptest.Server tempDirectory string ) BeforeEach(func() { fakeBOSH = &fakeBOSHDirector{} fakeBOSHServer = httptest.NewServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) { fakeBOSH.ServeHTTP(responseWriter, request) })) fakeAWS = awsbackend.New(fakeBOSHServer.URL) fakeAWS.Stacks.Set(awsbackend.Stack{ Name: "some-stack-name", }) fakeAWS.Certificates.Set(awsbackend.Certificate{ Name: "some-certificate-name", }) fakeAWS.KeyPairs.Set(awsbackend.KeyPair{ Name: "some-keypair-name", }) fakeAWS.Instances.Set([]awsbackend.Instance{ {Name: "NAT"}, {Name: "bosh/0"}, }) fakeAWSServer = httptest.NewServer(awsfaker.New(fakeAWS)) var err error tempDirectory, err = ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) buf, err := json.Marshal(storage.State{ AWS: storage.AWS{ AccessKeyID: "some-access-key", SecretAccessKey: "some-access-secret", Region: "some-region", }, Stack: storage.Stack{ Name: "some-stack-name", CertificateName: "some-certificate-name", }, BOSH: storage.BOSH{ State: boshinit.State{ "key": "value", }, }, }) Expect(err).NotTo(HaveOccurred()) ioutil.WriteFile(filepath.Join(tempDirectory, storage.StateFileName), buf, os.ModePerm) }) It("invokes bosh-init delete", func() { session := destroy(fakeAWSServer.URL, tempDirectory, 0) Expect(session.Out.Contents()).To(ContainSubstring("step: destroying bosh director")) Expect(session.Out.Contents()).To(ContainSubstring("bosh-init was called with [bosh-init delete bosh.yml]")) Expect(session.Out.Contents()).To(ContainSubstring(`bosh-state.json: {"key":"value"}`)) }) It("deletes the stack", func() { session := destroy(fakeAWSServer.URL, tempDirectory, 0) Expect(session.Out.Contents()).To(ContainSubstring("step: deleting cloudformation stack")) Expect(session.Out.Contents()).To(ContainSubstring("step: finished deleting cloudformation stack")) _, ok := fakeAWS.Stacks.Get("some-stack-name") Expect(ok).To(BeFalse()) }) It("deletes the certificate", func() { session := destroy(fakeAWSServer.URL, tempDirectory, 0) Expect(session.Out.Contents()).To(ContainSubstring("step: deleting certificate")) Expect(session.Out.Contents()).To(ContainSubstring("step: finished deleting cloudformation stack")) _, ok := fakeAWS.Stacks.Get("some-stack-name") Expect(ok).To(BeFalse()) }) It("deletes the keypair", func() { session := destroy(fakeAWSServer.URL, tempDirectory, 0) Expect(session.Out.Contents()).To(ContainSubstring("step: deleting keypair")) Expect(session.Out.Contents()).To(ContainSubstring("step: finished deleting cloudformation stack")) _, ok := fakeAWS.Stacks.Get("some-stack-name") Expect(ok).To(BeFalse()) }) It("deletes the bbl state", func() { destroy(fakeAWSServer.URL, tempDirectory, 0) _, err := os.Stat(filepath.Join(tempDirectory, storage.StateFileName)) Expect(os.IsNotExist(err)).To(BeTrue()) }) Context("reentrance", func() { Context("when destroy fails to delete the stack", func() { It("removes bosh properties from the state", func() { fakeAWS.Stacks.SetDeleteStackReturnError(&awsfaker.ErrorResponse{ HTTPStatusCode: http.StatusBadRequest, AWSErrorCode: "InvalidRequest", AWSErrorMessage: "failed to delete stack", }) session := destroy(fakeAWSServer.URL, tempDirectory, 1) Expect(session.Out.Contents()).To(ContainSubstring("step: destroying bosh director")) Expect(session.Out.Contents()).To(ContainSubstring("bosh-init was called with [bosh-init delete bosh.yml]")) Expect(session.Out.Contents()).To(ContainSubstring(`bosh-state.json: {"key":"value"}`)) Expect(session.Out.Contents()).To(ContainSubstring("step: deleting cloudformation stack")) Expect(session.Out.Contents()).NotTo(ContainSubstring("step: finished deleting cloudformation stack")) state := readStateJson(tempDirectory) Expect(state.BOSH).To(Equal(storage.BOSH{})) }) }) Context("when no bosh director exists", func() { BeforeEach(func() { fakeAWS.Stacks.SetDeleteStackReturnError(&awsfaker.ErrorResponse{ HTTPStatusCode: http.StatusBadRequest, AWSErrorCode: "InvalidRequest", AWSErrorMessage: "failed to delete stack", }) destroy(fakeAWSServer.URL, tempDirectory, 1) fakeAWS.Stacks.SetDeleteStackReturnError(nil) }) It("skips deleting bosh director", func() { session := destroy(fakeAWSServer.URL, tempDirectory, 0) Expect(session.Out.Contents()).To(ContainSubstring("no BOSH director, skipping...")) Expect(session.Out.Contents()).To(ContainSubstring("step: finished deleting cloudformation stack")) Expect(session.Out.Contents()).NotTo(ContainSubstring("step: destroying bosh director")) }) }) Context("when destroy fails to delete the keypair", func() { It("removes the stack from the state", func() { fakeAWS.KeyPairs.SetDeleteKeyPairReturnError(&awsfaker.ErrorResponse{ HTTPStatusCode: http.StatusBadRequest, AWSErrorCode: "InvalidRequest", AWSErrorMessage: "failed to delete keypair", }) session := destroy(fakeAWSServer.URL, tempDirectory, 1) Expect(session.Out.Contents()).To(ContainSubstring("step: deleting cloudformation stack")) Expect(session.Out.Contents()).To(ContainSubstring("step: finished deleting cloudformation stack")) Expect(session.Out.Contents()).To(ContainSubstring("step: deleting keypair")) state := readStateJson(tempDirectory) Expect(state.Stack.Name).To(Equal("")) Expect(state.Stack.LBType).To(Equal("")) }) It("removes the certificate from the state", func() { fakeAWS.KeyPairs.SetDeleteKeyPairReturnError(&awsfaker.ErrorResponse{ HTTPStatusCode: http.StatusBadRequest, AWSErrorCode: "InvalidRequest", AWSErrorMessage: "failed to delete keypair", }) session := destroy(fakeAWSServer.URL, tempDirectory, 1) Expect(session.Out.Contents()).To(ContainSubstring("step: deleting certificate")) state := readStateJson(tempDirectory) Expect(state.Stack.CertificateName).To(Equal("")) }) }) Context("when no stack exists", func() { BeforeEach(func() { fakeAWS.KeyPairs.SetDeleteKeyPairReturnError(&awsfaker.ErrorResponse{ HTTPStatusCode: http.StatusBadRequest, AWSErrorCode: "InvalidRequest", AWSErrorMessage: "failed to delete keypair", }) destroy(fakeAWSServer.URL, tempDirectory, 1) fakeAWS.KeyPairs.SetDeleteKeyPairReturnError(nil) }) It("skips deleting aws stack", func() { session := destroy(fakeAWSServer.URL, tempDirectory, 0) Expect(session.Out.Contents()).To(ContainSubstring("no AWS stack, skipping...")) }) }) }) }) }) func destroy(serverURL string, tempDirectory string, exitCode int) *gexec.Session { args := []string{ fmt.Sprintf("--endpoint-override=%s", serverURL), "--state-dir", tempDirectory, "destroy", } cmd := exec.Command(pathToBBL, args...) stdin, err := cmd.StdinPipe() Expect(err).NotTo(HaveOccurred()) session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) _, err = stdin.Write([]byte("yes\n")) Expect(err).NotTo(HaveOccurred()) Eventually(session, 10*time.Second).Should(gexec.Exit(exitCode)) return session } <file_sep>/bbl/director_username_test.go package main_test import ( "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "github.com/cloudfoundry/bosh-bootloader/storage" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/onsi/gomega/gexec" ) var _ = Describe("director-username", func() { var ( tempDirectory string ) BeforeEach(func() { var err error tempDirectory, err = ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) }) It("returns the director username from the given state file", func() { state := []byte(`{ "bosh": { "directorUsername": "some-director-user" } }`) err := ioutil.WriteFile(filepath.Join(tempDirectory, storage.StateFileName), state, os.ModePerm) Expect(err).NotTo(HaveOccurred()) args := []string{ "--state-dir", tempDirectory, "director-username", } session, err := gexec.Start(exec.Command(pathToBBL, args...), GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session).Should(gexec.Exit(0)) Expect(session.Out.Contents()).To(ContainSubstring("some-director-user")) }) Context("failure cases", func() { It("returns a non zero exit code when the bbl-state.json does not exist", func() { tempDirectory, err := ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) args := []string{ "--state-dir", tempDirectory, "director-username", } session, err := gexec.Start(exec.Command(pathToBBL, args...), GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session).Should(gexec.Exit(1)) expectedErrorMessage := fmt.Sprintf("bbl-state.json not found in %q, ensure you're running this command in the proper state directory or create a new environment with bbl up", tempDirectory) Expect(session.Err.Contents()).To(ContainSubstring(expectedErrorMessage)) }) It("returns a non zero exit code when the username does not exist", func() { state := []byte(`{}`) err := ioutil.WriteFile(filepath.Join(tempDirectory, storage.StateFileName), state, os.ModePerm) Expect(err).NotTo(HaveOccurred()) args := []string{ "--state-dir", tempDirectory, "director-username", } session, err := gexec.Start(exec.Command(pathToBBL, args...), GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session).Should(gexec.Exit(1)) Expect(session.Err.Contents()).To(ContainSubstring("Could not retrieve director username")) }) }) }) <file_sep>/fakes/cloud_config_manager.go package fakes import "github.com/cloudfoundry/bosh-bootloader/bosh" type CloudConfigManager struct { UpdateCall struct { Receives struct { CloudConfigInput bosh.CloudConfigInput BOSHClient bosh.Client } Returns struct { Error error } } } func (c *CloudConfigManager) Update(cloudConfigInput bosh.CloudConfigInput, boshClient bosh.Client) error { c.UpdateCall.Receives.CloudConfigInput = cloudConfigInput c.UpdateCall.Receives.BOSHClient = boshClient return c.UpdateCall.Returns.Error } <file_sep>/aws/cloudformation/templates/internal_subnet_template_builder_test.go package templates_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" ) var _ = Describe("InternalSubnetTemplateBuilder", func() { var builder templates.InternalSubnetTemplateBuilder BeforeEach(func() { builder = templates.NewInternalSubnetTemplateBuilder() }) Describe("InternalSubnet", func() { It("returns a template with parameters for the internal subnet", func() { subnet := builder.InternalSubnet(0, "1", "10.0.16.0/20") Expect(subnet.Parameters).To(HaveLen(1)) Expect(subnet.Parameters).To(HaveKeyWithValue("InternalSubnet1CIDR", templates.Parameter{ Description: "CIDR block for InternalSubnet1.", Type: "String", Default: "10.0.16.0/20", })) }) It("returns a template with resources for the internal subnet", func() { subnet := builder.InternalSubnet(0, "1", "10.0.16.0/20") Expect(subnet.Resources).To(HaveLen(4)) Expect(subnet.Resources).To(HaveKeyWithValue("InternalSubnet1", templates.Resource{ Type: "AWS::EC2::Subnet", Properties: templates.Subnet{ AvailabilityZone: map[string]interface{}{ "Fn::Select": []interface{}{ "0", map[string]templates.Ref{ "Fn::GetAZs": templates.Ref{"AWS::Region"}, }, }, }, CidrBlock: templates.Ref{"InternalSubnet1CIDR"}, VpcId: templates.Ref{"VPC"}, Tags: []templates.Tag{ { Key: "Name", Value: "Internal1", }, }, }, })) Expect(subnet.Resources).To(HaveKeyWithValue("InternalRouteTable", templates.Resource{ Type: "AWS::EC2::RouteTable", Properties: templates.RouteTable{ VpcId: templates.Ref{"VPC"}, }, })) Expect(subnet.Resources).To(HaveKeyWithValue("InternalRoute", templates.Resource{ Type: "AWS::EC2::Route", DependsOn: "NATInstance", Properties: templates.Route{ DestinationCidrBlock: "0.0.0.0/0", RouteTableId: templates.Ref{"InternalRouteTable"}, InstanceId: templates.Ref{"NATInstance"}, }, })) Expect(subnet.Resources).To(HaveKeyWithValue("InternalSubnet1RouteTableAssociation", templates.Resource{ Type: "AWS::EC2::SubnetRouteTableAssociation", Properties: templates.SubnetRouteTableAssociation{ RouteTableId: templates.Ref{"InternalRouteTable"}, SubnetId: templates.Ref{"InternalSubnet1"}, }, })) }) It("returns a template with outputs for the internal subnet", func() { subnet := builder.InternalSubnet(0, "1", "10.0.16.0/20") Expect(subnet.Outputs).To(HaveLen(3)) Expect(subnet.Outputs).To(HaveKeyWithValue("InternalSubnet1CIDR", templates.Output{ Value: templates.Ref{"InternalSubnet1CIDR"}, })) Expect(subnet.Outputs).To(HaveKeyWithValue("InternalSubnet1AZ", templates.Output{ Value: templates.FnGetAtt{ []string{ "InternalSubnet1", "AvailabilityZone", }, }, })) Expect(subnet.Outputs).To(HaveKeyWithValue("InternalSubnet1Name", templates.Output{ Value: templates.Ref{"InternalSubnet1"}, })) }) }) }) <file_sep>/aws/cloudformation/client_test.go package cloudformation_test import ( "github.com/aws/aws-sdk-go/aws/credentials" "github.com/cloudfoundry/bosh-bootloader/aws" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation" goaws "github.com/aws/aws-sdk-go/aws" awscloudformation "github.com/aws/aws-sdk-go/service/cloudformation" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Client", func() { Describe("NewClient", func() { It("returns a Client with the provided configuration", func() { client := cloudformation.NewClient(aws.Config{ AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", Region: "some-region", EndpointOverride: "some-endpoint-override", }) _, ok := client.(cloudformation.Client) Expect(ok).To(BeTrue()) cloudformationClient, ok := client.(*awscloudformation.CloudFormation) Expect(ok).To(BeTrue()) Expect(cloudformationClient.Config.Credentials).To(Equal(credentials.NewStaticCredentials("some-access-key-id", "some-secret-access-key", ""))) Expect(cloudformationClient.Config.Region).To(Equal(goaws.String("some-region"))) Expect(cloudformationClient.Config.Endpoint).To(Equal(goaws.String("some-endpoint-override"))) }) }) }) <file_sep>/boshinit/manifests/disk_pools_manifest_builder_test.go package manifests_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/cloudfoundry/bosh-bootloader/boshinit/manifests" ) var _ = Describe("DiskPoolsManifestBuilder", func() { var diskPoolsManifestBuilder manifests.DiskPoolsManifestBuilder BeforeEach(func() { diskPoolsManifestBuilder = manifests.NewDiskPoolsManifestBuilder() }) Describe("Build", func() { It("returns all disk pools for manifest", func() { diskPools := diskPoolsManifestBuilder.Build() Expect(diskPools).To(HaveLen(1)) Expect(diskPools).To(ConsistOf([]manifests.DiskPool{ { Name: "disks", DiskSize: 80 * 1024, CloudProperties: manifests.DiskPoolsCloudProperties{ Type: "gp2", Encrypted: true, }, }, })) }) }) }) <file_sep>/bbl/up_test.go package main_test import ( "crypto/x509" "encoding/json" "encoding/pem" "fmt" "io/ioutil" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "strings" "sync" "time" yaml "gopkg.in/yaml.v2" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" "github.com/cloudfoundry/bosh-bootloader/bbl/awsbackend" "github.com/cloudfoundry/bosh-bootloader/bbl/constants" "github.com/cloudfoundry/bosh-bootloader/storage" "github.com/cloudfoundry/bosh-bootloader/testhelpers" "github.com/onsi/gomega/gexec" "github.com/rosenhouse/awsfaker" . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/extensions/table" . "github.com/onsi/gomega" . "github.com/pivotal-cf-experimental/gomegamatchers" ) type fakeBOSHDirector struct { mutex sync.Mutex cloudConfig []byte cloudConfigFail bool } func (b *fakeBOSHDirector) SetCloudConfig(cloudConfig []byte) { b.mutex.Lock() defer b.mutex.Unlock() b.cloudConfig = cloudConfig } func (b *fakeBOSHDirector) GetCloudConfig() []byte { b.mutex.Lock() defer b.mutex.Unlock() return b.cloudConfig } func (b *fakeBOSHDirector) SetCloudConfigEndpointFail(fail bool) { b.mutex.Lock() defer b.mutex.Unlock() b.cloudConfigFail = fail } func (b *fakeBOSHDirector) GetCloudConfigEndpointFail() bool { b.mutex.Lock() defer b.mutex.Unlock() return b.cloudConfigFail } func (b *fakeBOSHDirector) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { switch request.URL.Path { case "/info": responseWriter.Write([]byte(`{ "name": "some-bosh-director", "uuid": "some-uuid", "version": "some-version" }`)) return case "/cloud_configs": if b.GetCloudConfigEndpointFail() { responseWriter.WriteHeader(0) return } buf, err := ioutil.ReadAll(request.Body) if err != nil { panic(err) } b.SetCloudConfig(buf) responseWriter.WriteHeader(http.StatusCreated) return default: responseWriter.WriteHeader(http.StatusNotFound) return } } var _ = Describe("bbl", func() { var ( fakeAWS *awsbackend.Backend fakeAWSServer *httptest.Server fakeBOSHServer *httptest.Server fakeBOSH *fakeBOSHDirector tempDirectory string lbCertPath string lbChainPath string lbKeyPath string ) BeforeEach(func() { fakeBOSH = &fakeBOSHDirector{} fakeBOSHServer = httptest.NewServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) { fakeBOSH.ServeHTTP(responseWriter, request) })) fakeAWS = awsbackend.New(fakeBOSHServer.URL) fakeAWSServer = httptest.NewServer(awsfaker.New(fakeAWS)) var err error tempDirectory, err = ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) lbCertPath, err = testhelpers.WriteContentsToTempFile(testhelpers.BBL_CERT) Expect(err).NotTo(HaveOccurred()) lbChainPath, err = testhelpers.WriteContentsToTempFile(testhelpers.BBL_CHAIN) Expect(err).NotTo(HaveOccurred()) lbKeyPath, err = testhelpers.WriteContentsToTempFile(testhelpers.BBL_KEY) Expect(err).NotTo(HaveOccurred()) }) Describe("up", func() { Context("when AWS creds are provided through environment variables", func() { It("honors the environment variables and bbl's up", func() { os.Setenv("BBL_AWS_ACCESS_KEY_ID", "some-access-key") os.Setenv("BBL_AWS_SECRET_ACCESS_KEY", "some-access-secret") os.Setenv("BBL_AWS_REGION", "some-region") args := []string{ fmt.Sprintf("--endpoint-override=%s", fakeAWSServer.URL), "--state-dir", tempDirectory, "up", } cmd := exec.Command(pathToBBL, args...) session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session, 10*time.Second).Should(gexec.Exit(0)) state := readStateJson(tempDirectory) Expect(state.AWS).To(Equal(storage.AWS{ AccessKeyID: "some-access-key", SecretAccessKey: "some-access-secret", Region: "some-region", })) }) }) Context("when bosh/cpi/stemcell is provided via constants", func() { It("creates a bosh with provided versions", func() { up(fakeAWSServer.URL, tempDirectory, 0) state := readStateJson(tempDirectory) var boshManifest struct { Releases []struct { Name string URL string SHA1 string } ResourcePools []struct { Stemcell struct { URL string SHA1 string } } `yaml:"resource_pools"` } err := yaml.Unmarshal([]byte(state.BOSH.Manifest), &boshManifest) Expect(err).NotTo(HaveOccurred()) boshRelease := boshManifest.Releases[0] boshAWSCPIRelease := boshManifest.Releases[1] stemcell := boshManifest.ResourcePools[0].Stemcell Expect(boshRelease.URL).To(Equal(constants.BOSHURL)) Expect(boshRelease.SHA1).To(Equal(constants.BOSHSHA1)) Expect(boshAWSCPIRelease.URL).To(Equal(constants.BOSHAWSCPIURL)) Expect(boshAWSCPIRelease.SHA1).To(Equal(constants.BOSHAWSCPISHA1)) Expect(stemcell.URL).To(Equal(constants.StemcellURL)) Expect(stemcell.SHA1).To(Equal(constants.StemcellSHA1)) }) }) Context("when the cloudformation stack does not exist", func() { var stack awsbackend.Stack It("creates a stack and a keypair", func() { up(fakeAWSServer.URL, tempDirectory, 0) state := readStateJson(tempDirectory) var ok bool stack, ok = fakeAWS.Stacks.Get(state.Stack.Name) Expect(ok).To(BeTrue()) Expect(state.Stack.Name).To(MatchRegexp(`stack-bbl-env-([a-z]+-{1}){1,2}\d{4}-\d{2}-\d{2}T\d{2}-\d{2}Z`)) keyPairs := fakeAWS.KeyPairs.All() Expect(keyPairs).To(HaveLen(1)) Expect(keyPairs[0].Name).To(MatchRegexp(`keypair-bbl-env-([a-z]+-{1}){1,2}\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z`)) }) It("creates an IAM user", func() { up(fakeAWSServer.URL, tempDirectory, 0) state := readStateJson(tempDirectory) var ok bool stack, ok = fakeAWS.Stacks.Get(state.Stack.Name) Expect(ok).To(BeTrue()) var template struct { Resources struct { BOSHUser struct { Properties templates.IAMUser Type string } } } err := json.Unmarshal([]byte(stack.Template), &template) Expect(err).NotTo(HaveOccurred()) Expect(template.Resources.BOSHUser.Properties.Policies).To(HaveLen(1)) Expect(template.Resources.BOSHUser.Properties.UserName).To(MatchRegexp(`bosh-iam-user-bbl-env-([a-z]+-{1}){1,2}\d{4}-\d{2}-\d{2}T\d{2}-\d{2}Z`)) }) It("does not change the iam user name when state exists", func() { fakeAWS.Stacks.Set(awsbackend.Stack{ Name: "some-stack-name", }) fakeAWS.KeyPairs.Set(awsbackend.KeyPair{ Name: "some-keypair-name", }) writeStateJson(storage.State{ AWS: storage.AWS{ AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", Region: "some-region", }, KeyPair: storage.KeyPair{ Name: "some-keypair-name", }, Stack: storage.Stack{ Name: "some-stack-name", }, BOSH: storage.BOSH{ DirectorAddress: fakeBOSHServer.URL, }, }, tempDirectory) up(fakeAWSServer.URL, tempDirectory, 0) state := readStateJson(tempDirectory) var ok bool stack, ok = fakeAWS.Stacks.Get(state.Stack.Name) Expect(ok).To(BeTrue()) var template struct { Resources struct { BOSHUser struct { Properties templates.IAMUser Type string } } } err := json.Unmarshal([]byte(stack.Template), &template) Expect(err).NotTo(HaveOccurred()) Expect(template.Resources.BOSHUser.Properties.Policies).To(HaveLen(1)) Expect(template.Resources.BOSHUser.Properties.UserName).To(BeEmpty()) }) It("logs the steps and bosh-init manifest", func() { session := up(fakeAWSServer.URL, tempDirectory, 0) stdout := session.Out.Contents() Expect(stdout).To(ContainSubstring("step: creating keypair")) Expect(stdout).To(ContainSubstring("step: generating cloudformation template")) Expect(stdout).To(ContainSubstring("step: creating cloudformation stack")) Expect(stdout).To(ContainSubstring("step: finished applying cloudformation template")) Expect(stdout).To(ContainSubstring("step: generating bosh-init manifest")) Expect(stdout).To(ContainSubstring("step: deploying bosh director")) }) It("invokes bosh-init", func() { session := up(fakeAWSServer.URL, tempDirectory, 0) Expect(session.Out.Contents()).To(ContainSubstring("bosh-init was called with [bosh-init deploy bosh.yml]")) Expect(session.Out.Contents()).To(ContainSubstring("bosh-state.json: {}")) }) It("names the bosh director with env id", func() { session := up(fakeAWSServer.URL, tempDirectory, 0) Expect(session.Out.Contents()).To(ContainSubstring("bosh director name: bosh-bbl-")) }) It("does not change the bosh director name when state exists", func() { fakeAWS.Stacks.Set(awsbackend.Stack{ Name: "some-stack-name", }) fakeAWS.KeyPairs.Set(awsbackend.KeyPair{ Name: "some-keypair-name", }) writeStateJson(storage.State{ AWS: storage.AWS{ AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", Region: "some-region", }, KeyPair: storage.KeyPair{ Name: "some-keypair-name", }, Stack: storage.Stack{ Name: "some-stack-name", }, BOSH: storage.BOSH{ DirectorAddress: fakeBOSHServer.URL, }, }, tempDirectory) session := up(fakeAWSServer.URL, tempDirectory, 0) Expect(session.Out.Contents()).To(ContainSubstring("bosh director name: my-bosh")) }) It("signs bosh-init cert and key with the generated CA cert", func() { up(fakeAWSServer.URL, tempDirectory, 0) state := readStateJson(tempDirectory) caCert := state.BOSH.DirectorSSLCA cert := state.BOSH.DirectorSSLCertificate rawCACertBlock, rest := pem.Decode([]byte(caCert)) Expect(rest).To(HaveLen(0)) rawCertBlock, rest := pem.Decode([]byte(cert)) Expect(rest).To(HaveLen(0)) rawCACert, err := x509.ParseCertificate(rawCACertBlock.Bytes) Expect(err).NotTo(HaveOccurred()) rawCert, err := x509.ParseCertificate(rawCertBlock.Bytes) Expect(err).NotTo(HaveOccurred()) err = rawCert.CheckSignatureFrom(rawCACert) Expect(err).NotTo(HaveOccurred()) }) It("can invoke bosh-init idempotently", func() { session := up(fakeAWSServer.URL, tempDirectory, 0) Expect(session.Out.Contents()).To(ContainSubstring("bosh-init was called with [bosh-init deploy bosh.yml]")) Expect(session.Out.Contents()).To(ContainSubstring("bosh-state.json: {}")) session = up(fakeAWSServer.URL, tempDirectory, 0) Expect(session.Out.Contents()).To(ContainSubstring("bosh-init was called with [bosh-init deploy bosh.yml]")) Expect(session.Out.Contents()).To(ContainSubstring(`bosh-state.json: {"key":"value","md5checksum":`)) Expect(session.Out.Contents()).To(ContainSubstring("No new changes, skipping deployment...")) }) It("fast fails if the bosh state exists", func() { writeStateJson(storage.State{BOSH: storage.BOSH{DirectorAddress: "some-director-address"}}, tempDirectory) session := up(fakeAWSServer.URL, tempDirectory, 1) Expect(session.Err.Contents()).To(ContainSubstring("Found BOSH data in state directory")) }) }) Context("when the keypair and cloudformation stack already exist", func() { BeforeEach(func() { fakeAWS.Stacks.Set(awsbackend.Stack{ Name: "some-stack-name", }) fakeAWS.KeyPairs.Set(awsbackend.KeyPair{ Name: "some-keypair-name", }) }) It("updates the stack with the cloudformation template", func() { buf, err := json.Marshal(storage.State{ KeyPair: storage.KeyPair{ Name: "some-keypair-name", PrivateKey: testhelpers.BBL_KEY, }, Stack: storage.Stack{ Name: "some-stack-name", }, EnvID: "bbl-env-lake-timestamp", }) Expect(err).NotTo(HaveOccurred()) ioutil.WriteFile(filepath.Join(tempDirectory, storage.StateFileName), buf, os.ModePerm) session := up(fakeAWSServer.URL, tempDirectory, 0) template, err := ioutil.ReadFile("fixtures/cloudformation-no-elb.json") Expect(err).NotTo(HaveOccurred()) stack, ok := fakeAWS.Stacks.Get("some-stack-name") Expect(ok).To(BeTrue()) Expect(stack.Name).To(Equal("some-stack-name")) Expect(stack.WasUpdated).To(Equal(true)) Expect(stack.Template).To(MatchJSON(string(template))) stdout := session.Out.Contents() Expect(stdout).To(ContainSubstring("step: using existing keypair")) Expect(stdout).To(ContainSubstring("step: generating cloudformation template")) Expect(stdout).To(ContainSubstring("step: updating cloudformation stack")) Expect(stdout).To(ContainSubstring("step: finished applying cloudformation template")) }) }) Context("when a load balancer is attached", func() { It("attaches certificate to the load balancer", func() { up(fakeAWSServer.URL, tempDirectory, 0) createLBs(fakeAWSServer.URL, tempDirectory, lbCertPath, lbKeyPath, lbChainPath, "concourse", 0, false) state := readStateJson(tempDirectory) stack, ok := fakeAWS.Stacks.Get(state.Stack.Name) Expect(ok).To(BeTrue()) type listener struct { SSLCertificateId string } var template struct { Resources struct { ConcourseLoadBalancer struct { Properties struct { Listeners []listener } } } } err := json.Unmarshal([]byte(stack.Template), &template) Expect(err).NotTo(HaveOccurred()) Expect(template.Resources.ConcourseLoadBalancer.Properties.Listeners).To(ContainElement(listener{ SSLCertificateId: "some-certificate-arn", })) }) }) DescribeTable("cloud config", func(lbType, fixtureLocation string) { contents, err := ioutil.ReadFile(fixtureLocation) Expect(err).NotTo(HaveOccurred()) session := up(fakeAWSServer.URL, tempDirectory, 0) if lbType != "" { createLBs(fakeAWSServer.URL, tempDirectory, lbCertPath, lbKeyPath, lbChainPath, lbType, 0, false) } stdout := session.Out.Contents() Expect(stdout).To(ContainSubstring("step: generating cloud config")) Expect(stdout).To(ContainSubstring("step: applying cloud config")) Expect(fakeBOSH.GetCloudConfig()).To(MatchYAML(string(contents))) By("executing idempotently", func() { args := []string{ fmt.Sprintf("--endpoint-override=%s", fakeAWSServer.URL), "--state-dir", tempDirectory, "up", } executeCommand(args, 0) Expect(fakeBOSH.GetCloudConfig()).To(MatchYAML(string(contents))) }) }, Entry("generates a cloud config with no lb type", "", "fixtures/cloud-config-no-elb.yml"), Entry("generates a cloud config with cf lb type", "cf", "fixtures/cloud-config-cf-elb.yml"), Entry("generates a cloud config with concourse lb type", "concourse", "fixtures/cloud-config-concourse-elb.yml"), ) Describe("reentrant", func() { Context("when the keypair fails to create", func() { It("saves the keypair name to the state", func() { fakeAWS.KeyPairs.SetCreateKeyPairReturnError(&awsfaker.ErrorResponse{ HTTPStatusCode: http.StatusBadRequest, AWSErrorCode: "InvalidRequest", AWSErrorMessage: "failed to create keypair", }) session := up(fakeAWSServer.URL, tempDirectory, 1) stdout := session.Out.Contents() stderr := session.Err.Contents() Expect(stdout).To(MatchRegexp(`step: checking if keypair "keypair-bbl-env-([a-z]+-{1}){1,2}\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z" exists`)) Expect(stdout).To(ContainSubstring("step: creating keypair")) Expect(stderr).To(ContainSubstring("failed to create keypair")) state := readStateJson(tempDirectory) Expect(state.KeyPair.Name).To(MatchRegexp(`keypair-bbl-env-([a-z]+-{1}){1,2}\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z`)) }) }) Context("when the stack fails to create", func() { It("saves the stack name to the state", func() { fakeAWS.Stacks.SetCreateStackReturnError(&awsfaker.ErrorResponse{ HTTPStatusCode: http.StatusBadRequest, AWSErrorCode: "InvalidRequest", AWSErrorMessage: "failed to create stack", }) session := up(fakeAWSServer.URL, tempDirectory, 1) stdout := session.Out.Contents() stderr := session.Err.Contents() Expect(stdout).To(MatchRegexp(`step: checking if cloudformation stack "stack-bbl-env-([a-z]+-{1}){1,2}\d{4}-\d{2}-\d{2}T\d{2}-\d{2}Z" exists`)) Expect(stdout).To(ContainSubstring("step: creating cloudformation stack")) Expect(stderr).To(ContainSubstring("failed to create stack")) state := readStateJson(tempDirectory) Expect(state.Stack.Name).To(MatchRegexp(`stack-bbl-env-([a-z]+-{1}){1,2}\d{4}-\d{2}-\d{2}T\d{2}-\d{2}Z`)) }) It("saves the private key to the state", func() { fakeAWS.Stacks.SetCreateStackReturnError(&awsfaker.ErrorResponse{ HTTPStatusCode: http.StatusBadRequest, AWSErrorCode: "InvalidRequest", AWSErrorMessage: "failed to create stack", }) up(fakeAWSServer.URL, tempDirectory, 1) state := readStateJson(tempDirectory) Expect(state.KeyPair.PrivateKey).To(ContainSubstring(testhelpers.PRIVATE_KEY)) }) It("does not create a new key pair on second call", func() { fakeAWS.Stacks.SetCreateStackReturnError(&awsfaker.ErrorResponse{ HTTPStatusCode: http.StatusBadRequest, AWSErrorCode: "InvalidRequest", AWSErrorMessage: "failed to create stack", }) up(fakeAWSServer.URL, tempDirectory, 1) fakeAWS.Stacks.SetCreateStackReturnError(nil) up(fakeAWSServer.URL, tempDirectory, 0) Expect(fakeAWS.CreateKeyPairCallCount).To(Equal(int64(1))) }) }) Context("when bosh init fails to create", func() { It("does not re-provision stack", func() { originalPath := os.Getenv("PATH") By("rebuilding bosh-init with fail fast flag", func() { pathToFakeBOSHInit, err := gexec.Build("github.com/cloudfoundry/bosh-bootloader/bbl/fakeboshinit", "-ldflags", "-X main.FailFast=true") Expect(err).NotTo(HaveOccurred()) pathToBOSHInit = filepath.Join(filepath.Dir(pathToFakeBOSHInit), "bosh-init") err = os.Rename(pathToFakeBOSHInit, pathToBOSHInit) Expect(err).NotTo(HaveOccurred()) os.Setenv("PATH", strings.Join([]string{filepath.Dir(pathToBOSHInit), os.Getenv("PATH")}, ":")) }) By("running up twice and checking if it created one stack", func() { up(fakeAWSServer.URL, tempDirectory, 1) os.Setenv("PATH", originalPath) up(fakeAWSServer.URL, tempDirectory, 0) Expect(fakeAWS.CreateStackCallCount).To(Equal(int64(1))) }) }) }) Context("when bosh cloud config fails to update", func() { It("saves the bosh properties to the state", func() { fakeBOSH.SetCloudConfigEndpointFail(true) up(fakeAWSServer.URL, tempDirectory, 1) state := readStateJson(tempDirectory) Expect(state.BOSH.DirectorName).To(MatchRegexp(`bosh-bbl-env-([a-z]+-{1}){1,2}\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z`)) originalBOSHState := state.BOSH fakeBOSH.SetCloudConfigEndpointFail(false) up(fakeAWSServer.URL, tempDirectory, 0) state = readStateJson(tempDirectory) Expect(state.BOSH).To(Equal(originalBOSHState)) }) }) }) }) }) func up(serverURL string, tempDirectory string, exitCode int) *gexec.Session { args := []string{ fmt.Sprintf("--endpoint-override=%s", serverURL), "--state-dir", tempDirectory, "up", "--aws-access-key-id", "some-access-key", "--aws-secret-access-key", "some-access-secret", "--aws-region", "some-region", } return executeCommand(args, exitCode) } func createLB(serverURL string, tempDirectory string, lbType string, certPath string, keyPath string, exitCode int) *gexec.Session { args := []string{ fmt.Sprintf("--endpoint-override=%s", serverURL), "--state-dir", tempDirectory, "create-lbs", "--type", lbType, "--cert", certPath, "--key", keyPath, } return executeCommand(args, exitCode) } <file_sep>/fakes/keypair_synchronizer.go package fakes import "github.com/cloudfoundry/bosh-bootloader/aws/ec2" type KeyPairSynchronizer struct { SyncCall struct { Receives struct { KeyPair ec2.KeyPair } Returns struct { KeyPair ec2.KeyPair Error error } } } func (s *KeyPairSynchronizer) Sync(keyPair ec2.KeyPair) (ec2.KeyPair, error) { s.SyncCall.Receives.KeyPair = keyPair return s.SyncCall.Returns.KeyPair, s.SyncCall.Returns.Error } <file_sep>/helpers/string_generator.go package helpers import ( "crypto/rand" "fmt" "io" "math/big" ) type StringGenerator struct { Reader io.Reader } func NewStringGenerator(reader io.Reader) StringGenerator { return StringGenerator{ Reader: reader, } } func (s StringGenerator) Generate(prefix string, length int) (string, error) { var alphaNumericRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") randomString := make([]rune, length) for i := range randomString { charIndex, err := rand.Int(s.Reader, big.NewInt(int64(len(alphaNumericRunes)))) if err != nil { return "", err } randomString[i] = alphaNumericRunes[charIndex.Int64()] } return fmt.Sprintf("%s%s", prefix, string(randomString)), nil } <file_sep>/application/command_finder.go package application import "strings" type CommandFinderResult struct { GlobalFlags []string Command string OtherArgs []string } type CommandFinder interface { FindCommand([]string) CommandFinderResult } type commandFinder struct { } func NewCommandFinder() CommandFinder { return commandFinder{} } func (finder commandFinder) FindCommand(input []string) CommandFinderResult { commandFinderResult := CommandFinderResult{} previousCommand := "" commandIndex := 0 commandFound := false for index, word := range input { if !strings.HasPrefix(word, "-") { if previousCommand != "--state-dir" && previousCommand != "-state-dir" { commandIndex = index commandFound = true break } } previousCommand = word } if commandFound { commandFinderResult.GlobalFlags = input[:commandIndex] commandFinderResult.Command = input[commandIndex] commandFinderResult.OtherArgs = input[commandIndex+1:] } else { commandFinderResult.GlobalFlags = input } return commandFinderResult } <file_sep>/bosh/vm_extensions_generator.go package bosh type VMExtensionsGenerators struct { loadBalancerExtensions []LoadBalancerExtension } type VMExtension struct { Name string `yaml:"name"` CloudProperties VMExtensionCloudProperties `yaml:"cloud_properties"` } type VMExtensionCloudProperties struct { ELBS []string `yaml:"elbs,omitempty"` SecurityGroups []string `yaml:"security_groups,omitempty"` EphemeralDisk *VMExtensionEphemeralDisk `yaml:"ephemeral_disk,omitempty"` } type VMExtensionEphemeralDisk struct { Size int `yaml:"size"` Type string `yaml:"type"` } type LoadBalancerExtension struct { Name string ELBName string SecurityGroups []string } func NewVMExtensionsGenerator(loadBalancerExtensions []LoadBalancerExtension) VMExtensionsGenerators { return VMExtensionsGenerators{ loadBalancerExtensions: loadBalancerExtensions, } } func (g VMExtensionsGenerators) Generate() []VMExtension { vmExtensions := []VMExtension{ { Name: "5GB_ephemeral_disk", CloudProperties: VMExtensionCloudProperties{ EphemeralDisk: &VMExtensionEphemeralDisk{ Size: 5120, Type: "gp2", }, }, }, { Name: "10GB_ephemeral_disk", CloudProperties: VMExtensionCloudProperties{ EphemeralDisk: &VMExtensionEphemeralDisk{ Size: 10240, Type: "gp2", }, }, }, { Name: "50GB_ephemeral_disk", CloudProperties: VMExtensionCloudProperties{ EphemeralDisk: &VMExtensionEphemeralDisk{ Size: 51200, Type: "gp2", }, }, }, { Name: "100GB_ephemeral_disk", CloudProperties: VMExtensionCloudProperties{ EphemeralDisk: &VMExtensionEphemeralDisk{ Size: 102400, Type: "gp2", }, }, }, { Name: "500GB_ephemeral_disk", CloudProperties: VMExtensionCloudProperties{ EphemeralDisk: &VMExtensionEphemeralDisk{ Size: 512000, Type: "gp2", }, }, }, { Name: "1TB_ephemeral_disk", CloudProperties: VMExtensionCloudProperties{ EphemeralDisk: &VMExtensionEphemeralDisk{ Size: 1048576, Type: "gp2", }, }, }, } for _, v := range g.loadBalancerExtensions { vmExtensions = append(vmExtensions, VMExtension{ Name: v.Name, CloudProperties: VMExtensionCloudProperties{ ELBS: []string{v.ELBName}, SecurityGroups: v.SecurityGroups, }, }) } return vmExtensions } <file_sep>/aws/cloudformation/stack.go package cloudformation type Stack struct { Name string Status string Outputs map[string]string } <file_sep>/bbl/awsbackend/backend.go package awsbackend import ( "encoding/json" "fmt" "net/http" "reflect" "sync/atomic" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/cloudformation" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/elb" "github.com/aws/aws-sdk-go/service/iam" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" "github.com/cloudfoundry/bosh-bootloader/testhelpers" "github.com/rosenhouse/awsfaker" ) type Backend struct { KeyPairs *KeyPairs Stacks *Stacks LoadBalancers *LoadBalancers Instances *Instances Certificates *Certificates boshDirectorURL string CreateKeyPairCallCount int64 CreateStackCallCount int64 } func New(boshDirectorURL string) *Backend { return &Backend{ KeyPairs: NewKeyPairs(), Stacks: NewStacks(), Instances: NewInstances(), boshDirectorURL: boshDirectorURL, LoadBalancers: NewLoadBalancers(), Certificates: NewCertificates(), } } func (b *Backend) CreateKeyPair(input *ec2.CreateKeyPairInput) (*ec2.CreateKeyPairOutput, error) { keyPair := KeyPair{ Name: *input.KeyName, } atomic.AddInt64(&b.CreateKeyPairCallCount, 1) b.KeyPairs.Set(keyPair) if err := b.KeyPairs.CreateKeyPairReturnError(); err != nil { return nil, err } return &ec2.CreateKeyPairOutput{ KeyName: aws.String(keyPair.Name), KeyMaterial: aws.String(testhelpers.PRIVATE_KEY), }, nil } func (b *Backend) DeleteKeyPair(input *ec2.DeleteKeyPairInput) (*ec2.DeleteKeyPairOutput, error) { if err := b.KeyPairs.DeleteKeyPairReturnError(); err != nil { return nil, err } b.KeyPairs.Delete(*input.KeyName) return &ec2.DeleteKeyPairOutput{}, nil } func (b *Backend) DescribeKeyPairs(input *ec2.DescribeKeyPairsInput) (*ec2.DescribeKeyPairsOutput, error) { var keyPairs []KeyPair for _, name := range input.KeyNames { keyPair, ok := b.KeyPairs.Get(*name) if !ok { return nil, &awsfaker.ErrorResponse{ HTTPStatusCode: http.StatusBadRequest, AWSErrorCode: "InvalidKeyPair.NotFound", AWSErrorMessage: fmt.Sprintf("The key pair '%s' does not exist", name), } } keyPairs = append(keyPairs, keyPair) } var keyPairInfos []*ec2.KeyPairInfo for _, keyPair := range keyPairs { keyPairInfos = append(keyPairInfos, &ec2.KeyPairInfo{ KeyName: aws.String(keyPair.Name), KeyFingerprint: aws.String("some-fingerprint"), }) } return &ec2.DescribeKeyPairsOutput{ KeyPairs: keyPairInfos, }, nil } func (b *Backend) DescribeInstances(input *ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error) { reservations := []*ec2.Reservation{} for _, instance := range b.Instances.Get() { if aws.StringValue(input.Filters[0].Name) == "vpc-id" && aws.StringValue(input.Filters[0].Values[0]) == instance.VPCID { reservations = append(reservations, &ec2.Reservation{ Instances: []*ec2.Instance{ { Tags: []*ec2.Tag{{ Key: aws.String("Name"), Value: aws.String(instance.Name), }}, }, }, }) } } return &ec2.DescribeInstancesOutput{ Reservations: reservations, }, nil } func (b *Backend) CreateStack(input *cloudformation.CreateStackInput) (*cloudformation.CreateStackOutput, error) { stack := Stack{ Name: *input.StackName, Template: *input.TemplateBody, } atomic.AddInt64(&b.CreateStackCallCount, 1) b.Stacks.Set(stack) if err := b.Stacks.CreateStackReturnError(); err != nil { return nil, err } return &cloudformation.CreateStackOutput{}, nil } func (b *Backend) UpdateStack(input *cloudformation.UpdateStackInput) (*cloudformation.UpdateStackOutput, error) { name := *input.StackName stack, ok := b.Stacks.Get(name) if !ok { return nil, &awsfaker.ErrorResponse{ HTTPStatusCode: http.StatusBadRequest, AWSErrorCode: "ValidationError", AWSErrorMessage: fmt.Sprintf("Stack [%s] does not exist", name), } } stack.WasUpdated = true stack.Template = *input.TemplateBody b.Stacks.Set(stack) return &cloudformation.UpdateStackOutput{}, nil } func (b *Backend) DeleteStack(input *cloudformation.DeleteStackInput) (*cloudformation.DeleteStackOutput, error) { if err := b.Stacks.DeleteStackReturnError(); err != nil { return nil, err } name := *input.StackName b.Stacks.Delete(name) return &cloudformation.DeleteStackOutput{}, nil } func (b *Backend) DescribeAvailabilityZones(input *ec2.DescribeAvailabilityZonesInput) (*ec2.DescribeAvailabilityZonesOutput, error) { validInput := &ec2.DescribeAvailabilityZonesInput{ Filters: []*ec2.Filter{{ Name: aws.String("region-name"), Values: []*string{aws.String("some-region")}, }}, } if !reflect.DeepEqual(input, validInput) { return nil, nil } return &ec2.DescribeAvailabilityZonesOutput{ AvailabilityZones: []*ec2.AvailabilityZone{ {ZoneName: aws.String("us-east-1a")}, {ZoneName: aws.String("us-east-1b")}, {ZoneName: aws.String("us-east-1c")}, }, }, nil } func (b *Backend) DescribeLoadBalancers(input *elb.DescribeLoadBalancersInput) (*elb.DescribeLoadBalancersOutput, error) { var loadBalancer LoadBalancer if len(input.LoadBalancerNames) > 0 { loadBalancer, _ = b.LoadBalancers.Get(aws.StringValue(input.LoadBalancerNames[0])) } output := &elb.DescribeLoadBalancersOutput{ LoadBalancerDescriptions: []*elb.LoadBalancerDescription{ { Instances: []*elb.Instance{}, }, }, } for _, name := range loadBalancer.Instances { instance := &elb.Instance{ InstanceId: aws.String(name), } output.LoadBalancerDescriptions[0].Instances = append(output.LoadBalancerDescriptions[0].Instances, instance) } return output, nil } func (b *Backend) DescribeStacks(input *cloudformation.DescribeStacksInput) (*cloudformation.DescribeStacksOutput, error) { name := *input.StackName stack, ok := b.Stacks.Get(name) if !ok { return nil, &awsfaker.ErrorResponse{ HTTPStatusCode: http.StatusBadRequest, AWSErrorCode: "ValidationError", AWSErrorMessage: fmt.Sprintf("Stack with id %s does not exist", name), } } stackOutput := &cloudformation.DescribeStacksOutput{ Stacks: []*cloudformation.Stack{ { StackName: aws.String(stack.Name), StackStatus: aws.String("CREATE_COMPLETE"), Outputs: []*cloudformation.Output{ { OutputKey: aws.String("BOSHEIP"), OutputValue: aws.String("127.0.0.1"), }, { OutputKey: aws.String("BOSHURL"), OutputValue: aws.String(b.boshDirectorURL), }, { OutputKey: aws.String("InternalSubnet1CIDR"), OutputValue: aws.String("10.0.16.0/20"), }, { OutputKey: aws.String("InternalSubnet2CIDR"), OutputValue: aws.String("10.0.32.0/20"), }, { OutputKey: aws.String("InternalSubnet3CIDR"), OutputValue: aws.String("10.0.48.0/20"), }, { OutputKey: aws.String("InternalSubnet1AZ"), OutputValue: aws.String("us-east-1a"), }, { OutputKey: aws.String("InternalSubnet2AZ"), OutputValue: aws.String("us-east-1b"), }, { OutputKey: aws.String("InternalSubnet3AZ"), OutputValue: aws.String("us-east-1c"), }, { OutputKey: aws.String("InternalSubnet1Name"), OutputValue: aws.String("some-subnet-1"), }, { OutputKey: aws.String("InternalSubnet2Name"), OutputValue: aws.String("some-subnet-2"), }, { OutputKey: aws.String("InternalSubnet3Name"), OutputValue: aws.String("some-subnet-3"), }, { OutputKey: aws.String("InternalSecurityGroup"), OutputValue: aws.String("some-internal-security-group"), }, { OutputKey: aws.String("VPCID"), OutputValue: aws.String("some-vpc-id"), }, }, }, }, } if stack.Template != "" { var template templates.Template err := json.Unmarshal([]byte(stack.Template), &template) if err != nil { return nil, err } if _, ok := template.Resources["ConcourseLoadBalancer"]; ok { stackOutput.Stacks[0].Outputs = append(stackOutput.Stacks[0].Outputs, &cloudformation.Output{ OutputKey: aws.String("ConcourseLoadBalancer"), OutputValue: aws.String("some-concourse-lb"), }) stackOutput.Stacks[0].Outputs = append(stackOutput.Stacks[0].Outputs, &cloudformation.Output{ OutputKey: aws.String("ConcourseInternalSecurityGroup"), OutputValue: aws.String("some-concourse-internal-security-group"), }) } if _, ok := template.Resources["CFRouterLoadBalancer"]; ok { stackOutput.Stacks[0].Outputs = append(stackOutput.Stacks[0].Outputs, &cloudformation.Output{ OutputKey: aws.String("CFRouterLoadBalancer"), OutputValue: aws.String("some-cf-router-lb"), }) stackOutput.Stacks[0].Outputs = append(stackOutput.Stacks[0].Outputs, &cloudformation.Output{ OutputKey: aws.String("CFRouterLoadBalancerURL"), OutputValue: aws.String("some-cf-router-lb-url"), }) stackOutput.Stacks[0].Outputs = append(stackOutput.Stacks[0].Outputs, &cloudformation.Output{ OutputKey: aws.String("CFSSHProxyLoadBalancer"), OutputValue: aws.String("some-cf-ssh-proxy-lb"), }) stackOutput.Stacks[0].Outputs = append(stackOutput.Stacks[0].Outputs, &cloudformation.Output{ OutputKey: aws.String("CFSSHProxyLoadBalancerURL"), OutputValue: aws.String("some-cf-ssh-proxy-lb-url"), }) stackOutput.Stacks[0].Outputs = append(stackOutput.Stacks[0].Outputs, &cloudformation.Output{ OutputKey: aws.String("CFRouterInternalSecurityGroup"), OutputValue: aws.String("some-cf-router-internal-security-group"), }) stackOutput.Stacks[0].Outputs = append(stackOutput.Stacks[0].Outputs, &cloudformation.Output{ OutputKey: aws.String("CFSSHProxyInternalSecurityGroup"), OutputValue: aws.String("some-cf-ssh-proxy-internal-security-group"), }) } } return stackOutput, nil } func (b *Backend) DescribeStackResource(input *cloudformation.DescribeStackResourceInput) (*cloudformation.DescribeStackResourceOutput, error) { return &cloudformation.DescribeStackResourceOutput{ StackResourceDetail: &cloudformation.StackResourceDetail{ ResourceType: aws.String("AWS::IAM::User"), StackName: aws.String("some-stack-name"), PhysicalResourceId: aws.String("some-stack-name-BOSHUser-random"), LogicalResourceId: aws.String("BOSHUser"), }, }, nil } func (b *Backend) GetServerCertificate(input *iam.GetServerCertificateInput) (*iam.GetServerCertificateOutput, error) { certificateName := aws.StringValue(input.ServerCertificateName) if certificate, ok := b.Certificates.Get(certificateName); ok { return &iam.GetServerCertificateOutput{ ServerCertificate: &iam.ServerCertificate{ CertificateBody: aws.String(certificate.CertificateBody), ServerCertificateMetadata: &iam.ServerCertificateMetadata{ Path: aws.String("some-certificate-path"), Arn: aws.String("some-certificate-arn"), ServerCertificateId: aws.String("some-server-certificate-id"), ServerCertificateName: input.ServerCertificateName, }, }, }, nil } return nil, &awsfaker.ErrorResponse{ HTTPStatusCode: http.StatusNotFound, AWSErrorCode: "NoSuchEntity", AWSErrorMessage: fmt.Sprintf("The Server Certificate with name %s cannot be found.", certificateName), } } func (b *Backend) UploadServerCertificate(input *iam.UploadServerCertificateInput) (*iam.UploadServerCertificateOutput, error) { certificateName := aws.StringValue(input.ServerCertificateName) if _, ok := b.Certificates.Get(certificateName); !ok { b.Certificates.Set(Certificate{ Name: certificateName, CertificateBody: aws.StringValue(input.CertificateBody), PrivateKey: aws.StringValue(input.PrivateKey), Chain: aws.StringValue(input.CertificateChain), }) return nil, nil } return nil, &awsfaker.ErrorResponse{ HTTPStatusCode: http.StatusConflict, AWSErrorCode: "EntityAlreadyExists", AWSErrorMessage: fmt.Sprintf("The Server Certificate with name %s already exists.", certificateName), } } func (b *Backend) DeleteServerCertificate(input *iam.DeleteServerCertificateInput) (*iam.DeleteServerCertificateOutput, error) { certificateName := aws.StringValue(input.ServerCertificateName) if _, ok := b.Certificates.Get(certificateName); ok { b.Certificates.Delete(certificateName) return &iam.DeleteServerCertificateOutput{}, nil } return nil, &awsfaker.ErrorResponse{ HTTPStatusCode: http.StatusNotFound, AWSErrorCode: "NoSuchEntity", AWSErrorMessage: fmt.Sprintf("The Server Certificate with name %s cannot be found.", certificateName), } } <file_sep>/aws/ec2/keypair.go package ec2 type KeyPair struct { Name string PrivateKey string PublicKey string } <file_sep>/bosh/cloud_config_generator.go package bosh type CloudConfigInput struct { AZs []string Subnets []SubnetInput LBs []LoadBalancerExtension } type SubnetInput struct { AZ string Subnet string CIDR string SecurityGroups []string } type CloudConfigGenerator struct { input CloudConfigInput cloudConfig CloudConfig } func NewCloudConfigGenerator() CloudConfigGenerator { return CloudConfigGenerator{} } func (c CloudConfigGenerator) Generate(input CloudConfigInput) (CloudConfig, error) { c.input = input c.generateAZs() c.generateVMTypes() c.generateDiskTypes() c.generateCompilation() err := c.generateNetworks() if err != nil { return CloudConfig{}, err } c.generateVMExtensions() return c.cloudConfig, nil } func (c *CloudConfigGenerator) generateVMExtensions() { c.cloudConfig.VMExtensions = NewVMExtensionsGenerator(c.input.LBs).Generate() } func (c *CloudConfigGenerator) generateAZs() { azsGenerator := NewAZsGenerator(c.input.AZs...) c.cloudConfig.AZs = azsGenerator.Generate() } func (c *CloudConfigGenerator) generateVMTypes() { vmTypesGenerator := NewVMTypesGenerator() c.cloudConfig.VMTypes = vmTypesGenerator.Generate() } func (c *CloudConfigGenerator) generateDiskTypes() { diskTypesGenerator := NewDiskTypesGenerator() c.cloudConfig.DiskTypes = diskTypesGenerator.Generate() } func (c *CloudConfigGenerator) generateCompilation() { compilationGenerator := NewCompilationGenerator() c.cloudConfig.Compilation = compilationGenerator.Generate() } func (c *CloudConfigGenerator) generateNetworks() error { azAssociations := map[string]string{} for _, az := range c.cloudConfig.AZs { azAssociations[az.CloudProperties.AvailabilityZone] = az.Name } networksGenerator := NewNetworksGenerator(c.input.Subnets, azAssociations) var err error c.cloudConfig.Networks, err = networksGenerator.Generate() if err != nil { return err } return nil } <file_sep>/integration-test/bbl/lbs_test.go package integration_test import ( "fmt" "strings" "github.com/cloudfoundry/bosh-bootloader/integration-test" "github.com/cloudfoundry/bosh-bootloader/integration-test/actors" "github.com/cloudfoundry/bosh-bootloader/testhelpers" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("load balancer tests", func() { var ( bbl actors.BBL aws actors.AWS bosh actors.BOSH boshcli actors.BOSHCLI state integration.State ) BeforeEach(func() { var err error configuration, err := integration.LoadConfig() Expect(err).NotTo(HaveOccurred()) bbl = actors.NewBBL(configuration.StateFileDir, pathToBBL, configuration) aws = actors.NewAWS(configuration) bosh = actors.NewBOSH() boshcli = actors.NewBOSHCLI() state = integration.NewState(configuration.StateFileDir) }) It("creates, updates and deletes an LB with the specified cert and key", func() { bbl.Up() stackName := state.StackName() directorAddress := bbl.DirectorAddress() caCertPath := bbl.SaveDirectorCA() Expect(aws.StackExists(stackName)).To(BeTrue()) Expect(aws.LoadBalancers(stackName)).To(BeEmpty()) exists, err := boshcli.DirectorExists(directorAddress, caCertPath) Expect(err).NotTo(HaveOccurred()) Expect(exists).To(BeTrue()) natInstanceID := aws.GetPhysicalID(stackName, "NATInstance") Expect(natInstanceID).NotTo(BeEmpty()) tags := aws.GetEC2InstanceTags(natInstanceID) Expect(tags["bbl-env-id"]).To(MatchRegexp(`bbl-env-([a-z]+-{1}){1,2}\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z`)) certPath, err := testhelpers.WriteContentsToTempFile(testhelpers.BBL_CERT) Expect(err).NotTo(HaveOccurred()) chainPath, err := testhelpers.WriteContentsToTempFile(testhelpers.BBL_CHAIN) Expect(err).NotTo(HaveOccurred()) keyPath, err := testhelpers.WriteContentsToTempFile(testhelpers.BBL_KEY) Expect(err).NotTo(HaveOccurred()) otherCertPath, err := testhelpers.WriteContentsToTempFile(testhelpers.OTHER_BBL_CERT) Expect(err).NotTo(HaveOccurred()) otherKeyPath, err := testhelpers.WriteContentsToTempFile(testhelpers.OTHER_BBL_KEY) Expect(err).NotTo(HaveOccurred()) bbl.CreateLB("concourse", certPath, keyPath, chainPath) Expect(aws.LoadBalancers(stackName)).To(HaveKey("ConcourseLoadBalancer")) Expect(strings.TrimSpace(aws.DescribeCertificate(state.CertificateName()).Body)).To(Equal(strings.TrimSpace(testhelpers.BBL_CERT))) bbl.UpdateLB(otherCertPath, otherKeyPath) Expect(aws.LoadBalancers(stackName)).To(HaveKey("ConcourseLoadBalancer")) certificateName := state.CertificateName() Expect(strings.TrimSpace(aws.DescribeCertificate(certificateName).Body)).To(Equal(strings.TrimSpace(string(testhelpers.OTHER_BBL_CERT)))) session := bbl.LBs() stdout := session.Out.Contents() Expect(stdout).To(ContainSubstring(fmt.Sprintf("Concourse LB: %s", aws.LoadBalancers(stackName)["ConcourseLoadBalancer"]))) bbl.DeleteLB() Expect(aws.LoadBalancers(stackName)).NotTo(HaveKey("ConcourseLoadBalancer")) Expect(strings.TrimSpace(aws.DescribeCertificate(certificateName).Body)).To(BeEmpty()) bbl.Destroy() exists, _ = boshcli.DirectorExists(directorAddress, caCertPath) Expect(exists).To(BeFalse()) Expect(aws.StackExists(stackName)).To(BeFalse()) }) }) <file_sep>/fakes/client_provider.go package fakes import ( "github.com/cloudfoundry/bosh-bootloader/aws" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation" "github.com/cloudfoundry/bosh-bootloader/aws/ec2" "github.com/cloudfoundry/bosh-bootloader/aws/iam" ) type ClientProvider struct { SetConfigCall struct { CallCount int Receives struct { Config aws.Config } } GetEC2ClientCall struct { CallCount int Returns struct { EC2Client ec2.Client } } GetCloudFormationClientCall struct { CallCount int Returns struct { CloudFormationClient cloudformation.Client } } GetIAMClientCall struct { CallCount int Returns struct { IAMClient iam.Client } } } func (c *ClientProvider) SetConfig(config aws.Config) { c.SetConfigCall.CallCount++ c.SetConfigCall.Receives.Config = config } func (c *ClientProvider) GetEC2Client() ec2.Client { c.GetEC2ClientCall.CallCount++ return c.GetEC2ClientCall.Returns.EC2Client } func (c *ClientProvider) GetCloudFormationClient() cloudformation.Client { c.GetCloudFormationClientCall.CallCount++ return c.GetCloudFormationClientCall.Returns.CloudFormationClient } func (c *ClientProvider) GetIAMClient() iam.Client { c.GetIAMClientCall.CallCount++ return c.GetIAMClientCall.Returns.IAMClient } <file_sep>/aws/cloudformation/infrastructure_manager_test.go package cloudformation_test import ( "errors" "time" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" "github.com/cloudfoundry/bosh-bootloader/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("InfrastructureManager", func() { var ( builder *fakes.TemplateBuilder stackManager *fakes.StackManager infrastructureManager cloudformation.InfrastructureManager ) BeforeEach(func() { builder = &fakes.TemplateBuilder{} builder.BuildCall.Returns.Template = templates.Template{ AWSTemplateFormatVersion: "some-template-version", Description: "some-description", } stackManager = &fakes.StackManager{} infrastructureManager = cloudformation.NewInfrastructureManager(builder, stackManager) }) Describe("Create", func() { BeforeEach(func() { stackManager.DescribeCall.Returns.Stack = cloudformation.Stack{Name: "some-stack-name"} }) It("creates the underlying infrastructure and returns the stack", func() { describeCallCount := 0 stackManager.DescribeCall.Stub = func(stackName string) (cloudformation.Stack, error) { defer func() { describeCallCount++ }() if describeCallCount == 0 { return cloudformation.Stack{}, cloudformation.StackNotFound } return cloudformation.Stack{Name: "some-stack-name"}, nil } stack, err := infrastructureManager.Create("some-key-pair-name", 2, "some-stack-name", "some-lb-type", "some-lb-certificate-arn", "some-env-id-time:stamp") Expect(err).NotTo(HaveOccurred()) Expect(stack).To(Equal(cloudformation.Stack{Name: "some-stack-name"})) Expect(builder.BuildCall.Receives.KeyPairName).To(Equal("some-key-pair-name")) Expect(builder.BuildCall.Receives.NumberOfAZs).To(Equal(2)) Expect(builder.BuildCall.Receives.LBType).To(Equal("some-lb-type")) Expect(builder.BuildCall.Receives.LBCertificateARN).To(Equal("some-lb-certificate-arn")) Expect(builder.BuildCall.Receives.IAMUserName).To(Equal("bosh-iam-user-some-env-id-time-stamp")) Expect(builder.BuildCall.Receives.EnvID).To(Equal("some-env-id-time:stamp")) Expect(stackManager.CreateOrUpdateCall.Receives.StackName).To(Equal("some-stack-name")) Expect(stackManager.CreateOrUpdateCall.Receives.Template).To(Equal(templates.Template{ AWSTemplateFormatVersion: "some-template-version", Description: "some-description", })) Expect(stackManager.CreateOrUpdateCall.Receives.Tags).To(Equal(cloudformation.Tags{ { Key: "bbl-env-id", Value: "some-env-id-time:stamp", }, })) Expect(stackManager.WaitForCompletionCall.Receives.StackName).To(Equal("some-stack-name")) Expect(stackManager.WaitForCompletionCall.Receives.SleepInterval).To(Equal(15 * time.Second)) Expect(stackManager.WaitForCompletionCall.Receives.Action).To(Equal("applying cloudformation template")) Expect(stackManager.DescribeCall.Receives.StackName).To(Equal("some-stack-name")) }) It("honors the iam user name from an existing stack", func() { stackManager.GetPhysicalIDForResourceCall.Returns.PhysicalResourceID = "some-bosh-user-id" _, err := infrastructureManager.Create("some-key-pair-name", 2, "some-stack-name", "some-lb-type", "some-lb-certificate-arn", "some-env-id-time:stamp") Expect(err).NotTo(HaveOccurred()) Expect(stackManager.GetPhysicalIDForResourceCall.Receives.StackName).To(Equal("some-stack-name")) Expect(stackManager.GetPhysicalIDForResourceCall.Receives.LogicalResourceID).To(Equal("BOSHUser")) Expect(builder.BuildCall.Receives.IAMUserName).To(Equal("some-bosh-user-id")) }) Context("failure cases", func() { It("returns an error when stack can't be created or updated", func() { stackManager.CreateOrUpdateCall.Returns.Error = errors.New("stack create or update failed") _, err := infrastructureManager.Create("some-key-pair-name", 0, "some-stack-name", "", "", "") Expect(err).To(MatchError("stack create or update failed")) }) It("returns an error when waiting for stack completion fails", func() { stackManager.WaitForCompletionCall.Returns.Error = errors.New("stack wait for completion failed") _, err := infrastructureManager.Create("some-key-pair-name", 0, "some-stack-name", "", "", "") Expect(err).To(MatchError("stack wait for completion failed")) }) It("returns an error when getting physical id for resource fails", func() { stackManager.GetPhysicalIDForResourceCall.Returns.Error = errors.New("get physical id for resource failed") _, err := infrastructureManager.Create("some-key-pair-name", 2, "some-stack-name", "some-lb-type", "some-lb-certificate-arn", "some-env-id-time:stamp") Expect(err).To(MatchError("get physical id for resource failed")) }) Context("when checking if the stack exists", func() { It("returns an error when describing the stack fails", func() { stackManager.DescribeCall.Returns.Error = errors.New("stack describe failed") _, err := infrastructureManager.Create("some-key-pair-name", 0, "some-stack-name", "", "", "") Expect(err).To(MatchError("stack describe failed")) }) }) Context("when getting the stack details", func() { It("returns an error when describing the stack fails", func() { describeCallCount := 0 stackManager.DescribeCall.Stub = func(stackName string) (cloudformation.Stack, error) { defer func() { describeCallCount++ }() if describeCallCount == 0 { return cloudformation.Stack{Name: "some-stack-name"}, nil } return cloudformation.Stack{}, errors.New("stack describe failed") } _, err := infrastructureManager.Create("some-key-pair-name", 0, "some-stack-name", "", "", "") Expect(err).To(MatchError("stack describe failed")) }) }) }) }) Describe("Update", func() { BeforeEach(func() { stackManager.DescribeCall.Returns.Stack = cloudformation.Stack{Name: "some-stack-name"} }) It("updates the stack and returns the stack", func() { stackManager.GetPhysicalIDForResourceCall.Returns.PhysicalResourceID = "some-bosh-user-id" stack, err := infrastructureManager.Update("some-key-pair-name", 2, "some-stack-name", "some-lb-type", "some-lb-certificate-arn", "some-env-id-time:stamp") Expect(err).NotTo(HaveOccurred()) Expect(stackManager.GetPhysicalIDForResourceCall.Receives.StackName).To(Equal("some-stack-name")) Expect(stackManager.GetPhysicalIDForResourceCall.Receives.LogicalResourceID).To(Equal("BOSHUser")) Expect(stack).To(Equal(cloudformation.Stack{Name: "some-stack-name"})) Expect(builder.BuildCall.Receives.KeyPairName).To(Equal("some-key-pair-name")) Expect(builder.BuildCall.Receives.NumberOfAZs).To(Equal(2)) Expect(builder.BuildCall.Receives.LBType).To(Equal("some-lb-type")) Expect(builder.BuildCall.Receives.LBCertificateARN).To(Equal("some-lb-certificate-arn")) Expect(builder.BuildCall.Receives.IAMUserName).To(Equal("some-bosh-user-id")) Expect(builder.BuildCall.Receives.EnvID).To(Equal("some-env-id-time:stamp")) Expect(stackManager.UpdateCall.Receives.StackName).To(Equal("some-stack-name")) Expect(stackManager.UpdateCall.Receives.Template).To(Equal(templates.Template{ AWSTemplateFormatVersion: "some-template-version", Description: "some-description", })) Expect(stackManager.UpdateCall.Receives.Tags).To(Equal(cloudformation.Tags{ { Key: "bbl-env-id", Value: "some-env-id-time:stamp", }, })) Expect(stackManager.WaitForCompletionCall.Receives.StackName).To(Equal("some-stack-name")) Expect(stackManager.WaitForCompletionCall.Receives.SleepInterval).To(Equal(15 * time.Second)) Expect(stackManager.WaitForCompletionCall.Receives.Action).To(Equal("applying cloudformation template")) Expect(stackManager.DescribeCall.Receives.StackName).To(Equal("some-stack-name")) }) Context("failure cases", func() { It("returns an error when it cannot get physical id for BOSHUser", func() { stackManager.GetPhysicalIDForResourceCall.Returns.Error = errors.New("failed to get physical id for resource") _, err := infrastructureManager.Update("some-key-pair-name", 2, "some-stack-name", "some-lb-type", "some-lb-certificate-arn", "some-env-id-time:stamp") Expect(err).To(MatchError("failed to get physical id for resource")) }) It("returns an error when the update stack call fails", func() { stackManager.UpdateCall.Returns.Error = errors.New("stack update call failed") _, err := infrastructureManager.Update("some-key-pair-name", 2, "some-stack-name", "some-lb-type", "some-lb-certificate-arn", "some-env-id-time:stamp") Expect(err).To(MatchError("stack update call failed")) }) It("returns an error when the wait for completion call fails", func() { stackManager.WaitForCompletionCall.Returns.Error = errors.New("failed to wait for completion") _, err := infrastructureManager.Update("some-key-pair-name", 2, "some-stack-name", "some-lb-type", "some-lb-certificate-arn", "some-env-id-time:stamp") Expect(err).To(MatchError("failed to wait for completion")) }) }) }) Describe("Exists", func() { It("returns true when the stack exists", func() { stackManager.DescribeCall.Returns.Stack = cloudformation.Stack{} exists, err := infrastructureManager.Exists("some-stack-name") Expect(err).NotTo(HaveOccurred()) Expect(exists).To(BeTrue()) }) It("returns false when the stack does not exist", func() { stackManager.DescribeCall.Returns.Error = cloudformation.StackNotFound exists, err := infrastructureManager.Exists("some-stack-name") Expect(err).NotTo(HaveOccurred()) Expect(exists).To(BeFalse()) }) Describe("failure cases", func() { It("returns an error when the stack manager returns a different error", func() { stackManager.DescribeCall.Returns.Error = errors.New("some other error") _, err := infrastructureManager.Exists("some-stack-name") Expect(err).To(MatchError("some other error")) }) }) }) Describe("Delete", func() { It("deletes the underlying infrastructure", func() { err := infrastructureManager.Delete("some-stack-name") Expect(err).NotTo(HaveOccurred()) Expect(stackManager.DeleteCall.Receives.StackName).To(Equal("some-stack-name")) Expect(stackManager.WaitForCompletionCall.Receives.StackName).To(Equal("some-stack-name")) Expect(stackManager.WaitForCompletionCall.Receives.SleepInterval).To(Equal(15 * time.Second)) Expect(stackManager.WaitForCompletionCall.Receives.Action).To(Equal("deleting cloudformation stack")) }) Context("when the stack goes away after being deleted", func() { It("returns without an error", func() { stackManager.WaitForCompletionCall.Returns.Error = cloudformation.StackNotFound err := infrastructureManager.Delete("some-stack-name") Expect(err).NotTo(HaveOccurred()) }) }) Context("failure cases", func() { Context("when the stack fails to delete", func() { It("returns an error", func() { stackManager.DeleteCall.Returns.Error = errors.New("failed to delete stack") err := infrastructureManager.Delete("some-stack-name") Expect(err).To(MatchError("failed to delete stack")) }) }) Context("when the waiting for completion fails", func() { It("returns an error", func() { stackManager.WaitForCompletionCall.Returns.Error = errors.New("wait for completion failed") err := infrastructureManager.Delete("some-stack-name") Expect(err).To(MatchError("wait for completion failed")) }) }) }) }) Describe("Describe", func() { It("returns a stack with a given name", func() { expectedStack := cloudformation.Stack{ Name: "some-stack-name", Status: "some-status", Outputs: map[string]string{ "some-output": "some-value", "some-other-output": "some-other-value", }, } stackManager.DescribeCall.Returns.Stack = expectedStack stack, err := infrastructureManager.Describe("some-stack-name") Expect(err).NotTo(HaveOccurred()) Expect(stack).To(Equal(expectedStack)) Expect(stackManager.DescribeCall.Receives.StackName).To(Equal("some-stack-name")) }) }) }) <file_sep>/fakes/certstrap_pkix.go package fakes import ( "net" certstrappkix "github.com/square/certstrap/pkix" ) type CertstrapPKIX struct { CreateCertificateAuthorityCall struct { CallCount int Receives struct { Key *certstrappkix.Key OrganizationalUnit string Years int Organization string Country string Province string Locality string CommonName string } Returns struct { Certificate *certstrappkix.Certificate Error error } } CreateCertificateSigningRequestCall struct { CallCount int Receives struct { Key *certstrappkix.Key OrganizationalUnit string Years int Organization string Country string Province string Locality string CommonName string IpList []net.IP DomainList []string } Returns struct { CertificateSigningRequest *certstrappkix.CertificateSigningRequest Error error } } CreateCertificateHostCall struct { CallCount int Receives struct { CrtAuth *certstrappkix.Certificate KeyAuth *certstrappkix.Key Csr *certstrappkix.CertificateSigningRequest Years int } Returns struct { Certificate *certstrappkix.Certificate Error error } } } func (c *CertstrapPKIX) CreateCertificateAuthority(key *certstrappkix.Key, organizationalUnit string, years int, organization string, country string, province string, locality string, commonName string) (*certstrappkix.Certificate, error) { c.CreateCertificateAuthorityCall.CallCount++ c.CreateCertificateAuthorityCall.Receives.Key = key c.CreateCertificateAuthorityCall.Receives.OrganizationalUnit = organizationalUnit c.CreateCertificateAuthorityCall.Receives.Years = years c.CreateCertificateAuthorityCall.Receives.Organization = organization c.CreateCertificateAuthorityCall.Receives.Country = country c.CreateCertificateAuthorityCall.Receives.Province = province c.CreateCertificateAuthorityCall.Receives.Locality = locality c.CreateCertificateAuthorityCall.Receives.CommonName = commonName return c.CreateCertificateAuthorityCall.Returns.Certificate, c.CreateCertificateAuthorityCall.Returns.Error } func (c *CertstrapPKIX) CreateCertificateSigningRequest(key *certstrappkix.Key, organizationalUnit string, ipList []net.IP, domainList []string, organization string, country string, province string, locality string, commonName string) (*certstrappkix.CertificateSigningRequest, error) { c.CreateCertificateSigningRequestCall.CallCount++ c.CreateCertificateSigningRequestCall.Receives.Key = key c.CreateCertificateSigningRequestCall.Receives.OrganizationalUnit = organizationalUnit c.CreateCertificateSigningRequestCall.Receives.Organization = organization c.CreateCertificateSigningRequestCall.Receives.Country = country c.CreateCertificateSigningRequestCall.Receives.Province = province c.CreateCertificateSigningRequestCall.Receives.Locality = locality c.CreateCertificateSigningRequestCall.Receives.CommonName = commonName c.CreateCertificateSigningRequestCall.Receives.DomainList = domainList c.CreateCertificateSigningRequestCall.Receives.IpList = ipList return c.CreateCertificateSigningRequestCall.Returns.CertificateSigningRequest, c.CreateCertificateSigningRequestCall.Returns.Error } func (c *CertstrapPKIX) CreateCertificateHost(crtAuth *certstrappkix.Certificate, keyAuth *certstrappkix.Key, csr *certstrappkix.CertificateSigningRequest, years int) (*certstrappkix.Certificate, error) { c.CreateCertificateHostCall.CallCount++ c.CreateCertificateHostCall.Receives.CrtAuth = crtAuth c.CreateCertificateHostCall.Receives.KeyAuth = keyAuth c.CreateCertificateHostCall.Receives.Csr = csr c.CreateCertificateHostCall.Receives.Years = years return c.CreateCertificateHostCall.Returns.Certificate, c.CreateCertificateHostCall.Returns.Error } <file_sep>/ssl/init_test.go package ssl_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "testing" ) func TestSSL(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "ssl") } const ( caPrivateKeyPEM = `-----<KEY>` privateKeyPEM = `-----<KEY>Xv<KEY> -----END RSA PRIVATE KEY-----` caPEM = `-----<KEY> -----END CERTIFICATE-----` csrPEM = `-----BEGIN CERTIFICATE REQUEST----- <KEY>PQD/044b3PrQ8Rpx<KEY> -----END CERTIFICATE REQUEST-----` certificatePEM = `-----<KEY> -----END CERTIFICATE-----` ) <file_sep>/boshinit/manifests/shared_properties_manifest_builder_test.go package manifests_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/cloudfoundry/bosh-bootloader/boshinit/manifests" ) var _ = Describe("SharedPropertiesManifestBuilder", func() { var sharedPropertiesManifestBuilder *manifests.SharedPropertiesManifestBuilder BeforeEach(func() { sharedPropertiesManifestBuilder = manifests.NewSharedPropertiesManifestBuilder() }) Describe("AWS", func() { It("returns job properties for AWS", func() { aws := sharedPropertiesManifestBuilder.AWS(manifests.ManifestProperties{ ElasticIP: "some-elastic-ip", AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", DefaultKeyName: "some-key-name", Region: "some-region", SecurityGroup: "some-security-group", }) Expect(aws).To(Equal(manifests.AWSProperties{ AccessKeyId: "some-access-key-id", SecretAccessKey: "some-secret-access-key", DefaultKeyName: "some-key-name", DefaultSecurityGroups: []string{"some-security-group"}, Region: "some-region", })) }) }) }) <file_sep>/fakes/bosh_init_manifest_builder.go package fakes import "github.com/cloudfoundry/bosh-bootloader/boshinit/manifests" type BOSHInitManifestBuilder struct { BuildCall struct { Receives struct { Properties manifests.ManifestProperties } Returns struct { Manifest manifests.Manifest Properties manifests.ManifestProperties Error error } } } func (b *BOSHInitManifestBuilder) Build(properties manifests.ManifestProperties) (manifests.Manifest, manifests.ManifestProperties, error) { b.BuildCall.Receives.Properties = properties return b.BuildCall.Returns.Manifest, b.BuildCall.Returns.Properties, b.BuildCall.Returns.Error } <file_sep>/boshinit/manifests/job_properties_manifest_builder_test.go package manifests_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/cloudfoundry/bosh-bootloader/boshinit/manifests" "github.com/cloudfoundry/bosh-bootloader/ssl" ) var _ = Describe("JobPropertiesManifestBuilder", func() { var ( jobPropertiesManifestBuilder manifests.JobPropertiesManifestBuilder natsUsername string postgresUsername string registryUsername string blobstoreDirectorUsername string blobstoreAgentUsername string hmUsername string natsPassword string postgresPassword string registryPassword string blobstoreDirectorPassword string blobstoreAgentPassword string hmPassword string ) BeforeEach(func() { natsUsername = "random-nats-username" postgresUsername = "random-postgres-username" registryUsername = "random-registry-username" blobstoreDirectorUsername = "random-blobstore-director-username" blobstoreAgentUsername = "random-blobstore-agent-username" hmUsername = "random-hm-username" natsPassword = "<PASSWORD>" postgresPassword = "<PASSWORD>" registryPassword = "<PASSWORD>" blobstoreDirectorPassword = "<PASSWORD>" blobstoreAgentPassword = "<PASSWORD>" hmPassword = "<PASSWORD>" jobPropertiesManifestBuilder = manifests.NewJobPropertiesManifestBuilder( natsUsername, postgresUsername, registryUsername, blobstoreDirectorUsername, blobstoreAgentUsername, hmUsername, natsPassword, postgresPassword, registryPassword, blobstoreDirectorPassword, blobstoreAgentPassword, hmPassword, ) }) Describe("NATS", func() { It("returns job properties for NATS", func() { nats := jobPropertiesManifestBuilder.NATS() Expect(nats).To(Equal( manifests.NATSJobProperties{ Address: "127.0.0.1", User: natsUsername, Password: <PASSWORD>, })) }) }) Describe("Postgres", func() { It("returns job properties for Postgres", func() { postgres := jobPropertiesManifestBuilder.Postgres() Expect(postgres).To(Equal(manifests.PostgresProperties{ User: postgresUsername, Password: <PASSWORD>, })) }) }) Describe("Registry", func() { It("returns job properties for Registry", func() { registry := jobPropertiesManifestBuilder.Registry() Expect(registry).To(Equal(manifests.RegistryJobProperties{ Address: "10.0.0.6", Host: "10.0.0.6", Username: registryUsername, Password: <PASSWORD>, DB: manifests.RegistryPostgresProperties{ User: postgresUsername, Password: <PASSWORD>, Database: "bosh", }, HTTP: manifests.HTTPProperties{ User: registryUsername, Password: <PASSWORD>, }, })) }) }) Describe("Blobstore", func() { It("returns job properties for Blobstore", func() { blobstore := jobPropertiesManifestBuilder.Blobstore() Expect(blobstore).To(Equal(manifests.BlobstoreJobProperties{ Address: "10.0.0.6", Director: manifests.Credentials{ User: blobstoreDirectorUsername, Password: <PASSWORD>, }, Agent: manifests.Credentials{ User: blobstoreAgentUsername, Password: <PASSWORD>, }, })) }) }) Describe("Director", func() { It("returns job properties for Director", func() { director := jobPropertiesManifestBuilder.Director(manifests.ManifestProperties{ DirectorName: "my-bosh", DirectorUsername: "bosh-username", DirectorPassword: "<PASSWORD>", SSLKeyPair: ssl.KeyPair{ Certificate: []byte("some-ssl-cert"), PrivateKey: []byte("some-ssl-key"), }, }) Expect(director).To(Equal(manifests.DirectorJobProperties{ Address: "127.0.0.1", Name: "my-bosh", CPIJob: "aws_cpi", Workers: 11, EnableDedicatedStatusWorker: true, EnablePostDeploy: true, DB: manifests.PostgresProperties{ User: postgresUsername, Password: <PASSWORD>, }, UserManagement: manifests.UserManagementProperties{ Local: manifests.LocalProperties{ Users: []manifests.UserProperties{ { Name: "bosh-username", Password: "<PASSWORD>", }, { Name: hmUsername, Password: <PASSWORD>, }, }, }, }, SSL: manifests.SSLProperties{ Cert: "some-ssl-cert", Key: "some-ssl-key", }, })) }) }) Describe("HM", func() { It("returns job properties for HM", func() { hm := jobPropertiesManifestBuilder.HM() Expect(hm).To(Equal(manifests.HMJobProperties{ DirectorAccount: manifests.Credentials{ User: hmUsername, Password: <PASSWORD>, }, ResurrectorEnabled: true, })) }) }) Describe("Agent", func() { It("returns job properties for Agent", func() { agent := jobPropertiesManifestBuilder.Agent() Expect(agent).To(Equal(manifests.AgentProperties{ MBus: "nats://random-nats-username:random-nats-password@10.0.0.6:4222", })) }) }) }) <file_sep>/boshinit/command_builder_test.go package boshinit_test import ( "bytes" "os/exec" "github.com/cloudfoundry/bosh-bootloader/boshinit" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("CommandBuilder", func() { Describe("DeployCommand", func() { It("builds a command with the correct values", func() { stdout := bytes.NewBuffer([]byte{}) stderr := bytes.NewBuffer([]byte{}) builder := boshinit.NewCommandBuilder("/tmp/bosh-init", "/tmp/some-dir", stdout, stderr) cmd := builder.DeployCommand() Expect(cmd).To(Equal(&exec.Cmd{ Path: "/tmp/bosh-init", Args: []string{ "bosh-init", "deploy", "bosh.yml", }, Dir: "/tmp/some-dir", Stdout: stdout, Stderr: stderr, })) }) }) Describe("DeleteCommand", func() { It("builds a command with the correct values", func() { stdout := bytes.NewBuffer([]byte{}) stderr := bytes.NewBuffer([]byte{}) builder := boshinit.NewCommandBuilder("/tmp/bosh-init", "/tmp/some-dir", stdout, stderr) cmd := builder.DeleteCommand() Expect(cmd).To(Equal(&exec.Cmd{ Path: "/tmp/bosh-init", Args: []string{ "bosh-init", "delete", "bosh.yml", }, Dir: "/tmp/some-dir", Stdout: stdout, Stderr: stderr, })) }) }) }) <file_sep>/aws/iam/client_test.go package iam_test import ( "github.com/aws/aws-sdk-go/aws/credentials" "github.com/cloudfoundry/bosh-bootloader/aws" "github.com/cloudfoundry/bosh-bootloader/aws/iam" goaws "github.com/aws/aws-sdk-go/aws" awsiam "github.com/aws/aws-sdk-go/service/iam" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Client", func() { Describe("NewClient", func() { It("returns a Client with the provided configuration", func() { client := iam.NewClient(aws.Config{ AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", Region: "some-region", EndpointOverride: "some-endpoint-override", }) _, ok := client.(iam.Client) Expect(ok).To(BeTrue()) iamClient, ok := client.(*awsiam.IAM) Expect(ok).To(BeTrue()) Expect(iamClient.Config.Credentials).To(Equal(credentials.NewStaticCredentials("some-access-key-id", "some-secret-access-key", ""))) Expect(iamClient.Config.Region).To(Equal(goaws.String("some-region"))) Expect(iamClient.Config.Endpoint).To(Equal(goaws.String("some-endpoint-override"))) }) }) }) <file_sep>/bosh/cloud_config_generator_test.go package bosh_test import ( "io/ioutil" "gopkg.in/yaml.v2" "github.com/cloudfoundry/bosh-bootloader/bosh" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/pivotal-cf-experimental/gomegamatchers" ) var _ = Describe("CloudConfigGenerator", func() { Describe("Generate", func() { var ( cloudConfigGenerator bosh.CloudConfigGenerator ) BeforeEach(func() { cloudConfigGenerator = bosh.NewCloudConfigGenerator() }) It("returns a generated cloud config that matches our example fixture", func() { cloudConfig, err := cloudConfigGenerator.Generate(bosh.CloudConfigInput{ AZs: []string{"us-east-1a", "us-east-1b", "us-east-1c"}, Subnets: []bosh.SubnetInput{ { AZ: "us-east-1a", Subnet: "some-subnet-1", CIDR: "10.0.16.0/20", SecurityGroups: []string{ "some-security-group-1", }, }, { AZ: "us-east-1b", Subnet: "some-subnet-2", CIDR: "10.0.32.0/20", SecurityGroups: []string{ "some-security-group-2", }, }, { AZ: "us-east-1c", Subnet: "some-subnet-3", CIDR: "10.0.48.0/20", SecurityGroups: []string{ "some-security-group-3", }, }, }, }) Expect(err).NotTo(HaveOccurred()) buf, err := ioutil.ReadFile("fixtures/cloud_config_without_load_balancers.yml") Expect(err).NotTo(HaveOccurred()) output, err := yaml.Marshal(cloudConfig) Expect(err).NotTo(HaveOccurred()) Expect(output).To(MatchYAML(string(buf))) }) Context("vm extensions", func() { It("generates a cloud config with load balancer vm extensions", func() { cloudConfig, err := cloudConfigGenerator.Generate(bosh.CloudConfigInput{ LBs: []bosh.LoadBalancerExtension{ { Name: "first-lb", ELBName: "some-lb-1", }, { Name: "second-lb", ELBName: "some-lb-2", SecurityGroups: []string{ "some-security-group", "some-other-security-group", }, }, }, AZs: []string{"us-east-1a", "us-east-1b", "us-east-1c"}, Subnets: []bosh.SubnetInput{ { AZ: "us-east-1a", Subnet: "some-subnet-1", CIDR: "10.0.16.0/20", SecurityGroups: []string{ "some-security-group-1", }, }, { AZ: "us-east-1b", Subnet: "some-subnet-2", CIDR: "10.0.32.0/20", SecurityGroups: []string{ "some-security-group-2", }, }, { AZ: "us-east-1c", Subnet: "some-subnet-3", CIDR: "10.0.48.0/20", SecurityGroups: []string{ "some-security-group-3", }, }, }, }) Expect(err).NotTo(HaveOccurred()) buf, err := ioutil.ReadFile("fixtures/cloud_config_with_load_balancers.yml") Expect(err).NotTo(HaveOccurred()) output, err := yaml.Marshal(cloudConfig) Expect(err).NotTo(HaveOccurred()) Expect(output).To(MatchYAML(string(buf))) }) }) Context("failure cases", func() { It("returns an error when it fails to generate networks for manifest", func() { _, err := cloudConfigGenerator.Generate(bosh.CloudConfigInput{ AZs: []string{"us-east-1a"}, Subnets: []bosh.SubnetInput{ { AZ: "us-east-1a", Subnet: "some-subnet-1", CIDR: "some-bad-cidr-block", SecurityGroups: []string{ "some-security-group-1", }, }, }, }) Expect(err).To(MatchError(ContainSubstring("cannot parse CIDR block"))) }) }) }) }) <file_sep>/application/exports_test.go package application import ( "os" "github.com/cloudfoundry/bosh-bootloader/storage" ) func SetGetwd(f func() (string, error)) { getwd = f } func ResetGetwd() { getwd = os.Getwd } func SetGetState(f func(string) (storage.State, error)) { getState = f } func ResetGetState() { getState = storage.GetState } <file_sep>/fakes/aws_credential_validator.go package fakes type AWSCredentialValidator struct { ValidateCall struct { CallCount int Returns struct { Error error } Receives struct { AccessKeyID string SecretAccessKey string Region string } } } func (a *AWSCredentialValidator) Validate() error { a.ValidateCall.CallCount++ return a.ValidateCall.Returns.Error } <file_sep>/bbl/flags_test.go package main_test import ( "os/exec" "strings" "github.com/onsi/gomega/gbytes" "github.com/onsi/gomega/gexec" . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/extensions/table" . "github.com/onsi/gomega" ) var _ = Describe("flags test", func() { Context("GlobalFlags", func() { DescribeTable("exits with non-zero status code when state-dir is specified twice", func(arguments string) { args := strings.Split(arguments, " ") cmd := exec.Command(pathToBBL, args...) session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session).Should(gexec.Exit(1)) Eventually(session.Err).Should(gbytes.Say("Invalid usage: cannot specify global 'state-dir' flag more than once.")) }, Entry("two --state-dir flags with space/equal sign", "--state-dir /some/fake/dir --state-dir=/some/other/fake/dir up"), Entry("two -state-dir flags with space/equal sign", "-state-dir /some/fake/dir -state-dir=/some/other/fake/dir up"), ) }) Context("Up", func() { Context("failure cases", func() { It("exits with non-zero status when invalid flags are passed", func() { args := []string{ "up", "--aws-access-key-id", "some-aws-access-key-id", "--aws-secret-access-key", "aws-secret-access-key", "--aws-region", "aws-region", "--some-invalid-flag", "some-value", } cmd := exec.Command(pathToBBL, args...) session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session).Should(gexec.Exit(1)) Eventually(session.Err).Should(gbytes.Say("flag provided but not defined: -some-invalid-flag")) }) It("fails when unknown global flags are passed", func() { args := []string{ "-some-global-flag", "up", "--aws-access-key-id", "some-aws-access-key-id", "--aws-secret-access-key", "aws-secret-access-key", "--aws-region", "aws-region", } cmd := exec.Command(pathToBBL, args...) session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session).Should(gexec.Exit(1)) Eventually(session.Err).Should(gbytes.Say("flag provided but not defined: -some-global-flag")) }) It("fails when unknown commands are passed", func() { args := []string{ "-h", "badcmd", "--aws-access-key-id", "some-aws-access-key-id", "--aws-secret-access-key", "aws-secret-access-key", "--aws-region", "aws-region", } cmd := exec.Command(pathToBBL, args...) session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session).Should(gexec.Exit(1)) Eventually(session.Err).Should(gbytes.Say("Unrecognized command 'badcmd'")) }) }) }) Context("Delete-lbs", func() { It("exits with non-zero status when aws creds are passed to it", func() { args := []string{ "delete-lbs", "--aws-access-key-id", "some-aws-access-key-id", "--aws-secret-access-key", "aws-secret-access-key", "--aws-region", "aws-region", } cmd := exec.Command(pathToBBL, args...) session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session).Should(gexec.Exit(1)) Eventually(session.Err).Should(gbytes.Say("flag provided but not defined: -aws-access-key-id")) }) }) }) <file_sep>/aws/ec2/client_test.go package ec2_test import ( "github.com/aws/aws-sdk-go/aws/credentials" "github.com/cloudfoundry/bosh-bootloader/aws" "github.com/cloudfoundry/bosh-bootloader/aws/ec2" goaws "github.com/aws/aws-sdk-go/aws" awsec2 "github.com/aws/aws-sdk-go/service/ec2" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Client", func() { Describe("NewClient", func() { It("returns a Client with the provided configuration", func() { client := ec2.NewClient(aws.Config{ AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", Region: "some-region", EndpointOverride: "some-endpoint-override", }) _, ok := client.(ec2.Client) Expect(ok).To(BeTrue()) ec2Client, ok := client.(*awsec2.EC2) Expect(ok).To(BeTrue()) Expect(ec2Client.Config.Credentials).To(Equal(credentials.NewStaticCredentials("some-access-key-id", "some-secret-access-key", ""))) Expect(ec2Client.Config.Region).To(Equal(goaws.String("some-region"))) Expect(ec2Client.Config.Endpoint).To(Equal(goaws.String("some-endpoint-override"))) }) }) }) <file_sep>/application/command_line_parser.go package application import ( "errors" "fmt" "os" "strings" "github.com/cloudfoundry/bosh-bootloader/flags" ) var getwd func() (string, error) = os.Getwd type CommandLineConfiguration struct { Command string SubcommandFlags []string EndpointOverride string StateDir string help bool version bool } type CommandLineParser struct { usage func() commandSet CommandSet } func NewCommandLineParser(usage func(), commandSet CommandSet) CommandLineParser { return CommandLineParser{ usage: usage, commandSet: commandSet, } } func (p CommandLineParser) Parse(arguments []string) (CommandLineConfiguration, error) { var err error commandLineConfiguration := CommandLineConfiguration{} var commandNotFoundError error commandWasBlank := false commandFinderResult := NewCommandFinder().FindCommand(arguments) _, ok := p.commandSet[commandFinderResult.Command] if !ok { if commandFinderResult.Command == "" { commandWasBlank = true } else { commandNotFoundError = fmt.Errorf("Unrecognized command '%s'", commandFinderResult.Command) } } commandLineConfiguration.SubcommandFlags = commandFinderResult.OtherArgs commandLineConfiguration, _, err = p.parseGlobalFlags(commandLineConfiguration, commandFinderResult.GlobalFlags) if err != nil && commandNotFoundError == nil { p.usage() return CommandLineConfiguration{}, err } commandLineConfiguration.Command = commandFinderResult.Command if commandLineConfiguration.help || commandWasBlank { commandLineConfiguration.Command = "help" if !commandWasBlank { commandLineConfiguration.SubcommandFlags = append([]string{commandFinderResult.Command}, commandLineConfiguration.SubcommandFlags...) } } if commandNotFoundError != nil { p.usage() return CommandLineConfiguration{}, commandNotFoundError } commandLineConfiguration, err = p.setDefaultStateDirectory(commandLineConfiguration) if err != nil { return CommandLineConfiguration{}, err } return commandLineConfiguration, nil } func (c CommandLineParser) parseGlobalFlags(commandLineConfiguration CommandLineConfiguration, arguments []string) (CommandLineConfiguration, []string, error) { if err := c.validateGlobalFlags(arguments); err != nil { return commandLineConfiguration, []string{}, err } globalFlags := flags.New("global") globalFlags.String(&commandLineConfiguration.EndpointOverride, "endpoint-override", "") globalFlags.String(&commandLineConfiguration.StateDir, "state-dir", "") globalFlags.Bool(&commandLineConfiguration.help, "h", "help", false) globalFlags.Bool(&commandLineConfiguration.version, "v", "version", false) err := globalFlags.Parse(arguments) if err != nil { return CommandLineConfiguration{}, []string{}, err } return commandLineConfiguration, globalFlags.Args(), nil } func (c CommandLineParser) validateGlobalFlags(arguments []string) error { hasStateDir := false for _, argument := range arguments { name := strings.Split(argument, "=")[0] if name == "--state-dir" || name == "-state-dir" { if hasStateDir { return errors.New("Invalid usage: cannot specify global 'state-dir' flag more than once.") } hasStateDir = true } } return nil } func (c CommandLineParser) parseCommandAndSubcommandFlags(commandLineConfiguration CommandLineConfiguration, remainingArguments []string) (CommandLineConfiguration, error) { if len(remainingArguments) == 0 { c.usage() return CommandLineConfiguration{}, errors.New("unknown command: [EMPTY]") } commandLineConfiguration.Command = remainingArguments[0] commandLineConfiguration.SubcommandFlags = remainingArguments[1:] return commandLineConfiguration, nil } func (CommandLineParser) setDefaultStateDirectory(commandLineConfiguration CommandLineConfiguration) (CommandLineConfiguration, error) { if commandLineConfiguration.StateDir == "" { wd, err := getwd() if err != nil { return CommandLineConfiguration{}, err } commandLineConfiguration.StateDir = wd } return commandLineConfiguration, nil } <file_sep>/boshinit/manifests/jobs_manifest_builder_test.go package manifests_test import ( "errors" "fmt" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/cloudfoundry/bosh-bootloader/boshinit/manifests" "github.com/cloudfoundry/bosh-bootloader/fakes" ) var _ = Describe("JobsManifestBuilder", func() { var ( jobsManifestBuilder manifests.JobsManifestBuilder stringGenerator *fakes.StringGenerator ) BeforeEach(func() { stringGenerator = &fakes.StringGenerator{} jobsManifestBuilder = manifests.NewJobsManifestBuilder(stringGenerator) }) Describe("Build", func() { BeforeEach(func() { stringGenerator.GenerateCall.Stub = func(prefix string, length int) (string, error) { if length != 15 { return "", errors.New("wrong length passed to string generator") } return fmt.Sprintf("%s%s", prefix, "some-random-string"), nil } }) It("returns all jobs for manifest", func() { jobs, _, err := jobsManifestBuilder.Build(manifests.ManifestProperties{ DirectorName: "some-director-name", ElasticIP: "some-elastic-ip", AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", DefaultKeyName: "some-key-name", Region: "some-region", }) Expect(err).NotTo(HaveOccurred()) job := jobs[0] Expect(jobs).To(HaveLen(1)) Expect(job.Name).To(Equal("bosh")) Expect(job.Instances).To(Equal(1)) Expect(job.ResourcePool).To(Equal("vms")) Expect(job.PersistentDiskPool).To(Equal("disks")) Expect(job.Templates).To(ConsistOf([]manifests.Template{ {Name: "nats", Release: "bosh"}, {Name: "postgres", Release: "bosh"}, {Name: "blobstore", Release: "bosh"}, {Name: "director", Release: "bosh"}, {Name: "health_monitor", Release: "bosh"}, {Name: "registry", Release: "bosh"}, {Name: "aws_cpi", Release: "bosh-aws-cpi"}, })) Expect(job.Networks).To(ConsistOf([]manifests.JobNetwork{ { Name: "private", StaticIPs: []string{"10.0.0.6"}, Default: []string{"dns", "gateway"}, }, { Name: "public", StaticIPs: []string{"some-elastic-ip"}, }, })) Expect(job.Properties.NATS.User).To(Equal("nats-user-some-random-string")) Expect(job.Properties.Postgres.User).To(Equal("postgres-user-some-random-string")) Expect(job.Properties.Registry.Username).To(Equal("registry-user-some-random-string")) Expect(job.Properties.Director.Name).To(Equal("some-director-name")) Expect(job.Properties.HM.ResurrectorEnabled).To(Equal(true)) Expect(job.Properties.AWS.AccessKeyId).To(Equal("some-access-key-id")) Expect(job.Properties.AWS.SecretAccessKey).To(Equal("some-secret-access-key")) Expect(job.Properties.AWS.Region).To(Equal("some-region")) Expect(job.Properties.AWS.DefaultKeyName).To(Equal("some-key-name")) Expect(job.Properties.Agent.MBus).To(Equal("nats://nats-user-some-random-string:nats-some-random-string@10.0.0.6:4222")) }) It("returns manifest properties with new credentials", func() { _, manifestProperties, err := jobsManifestBuilder.Build(manifests.ManifestProperties{ ElasticIP: "some-elastic-ip", AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", DefaultKeyName: "some-key-name", Region: "some-region", }) Expect(err).NotTo(HaveOccurred()) Expect(manifestProperties.Credentials.NatsUsername).To(Equal("nats-user-some-random-string")) Expect(manifestProperties.Credentials.PostgresUsername).To(Equal("postgres-user-some-random-string")) Expect(manifestProperties.Credentials.RegistryUsername).To(Equal("registry-user-some-random-string")) Expect(manifestProperties.Credentials.BlobstoreDirectorUsername).To(Equal("blobstore-director-user-some-random-string")) Expect(manifestProperties.Credentials.BlobstoreAgentUsername).To(Equal("blobstore-agent-user-some-random-string")) Expect(manifestProperties.Credentials.HMUsername).To(Equal("hm-user-some-random-string")) Expect(manifestProperties.Credentials.NatsPassword).To(Equal("nats-some-random-string")) Expect(manifestProperties.Credentials.PostgresPassword).To(Equal("postgres-some-random-string")) Expect(manifestProperties.Credentials.RegistryPassword).To(Equal("registry-some-random-string")) Expect(manifestProperties.Credentials.BlobstoreDirectorPassword).To(Equal("blobstore-director-some-random-string")) Expect(manifestProperties.Credentials.BlobstoreAgentPassword).To(Equal("blobstore-agent-some-random-string")) Expect(manifestProperties.Credentials.HMPassword).To(Equal("hm-some-random-string")) }) It("returns manifest and manifest properties with existing credentials", func() { jobs, manifestProperties, err := jobsManifestBuilder.Build(manifests.ManifestProperties{ ElasticIP: "some-elastic-ip", AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", DefaultKeyName: "some-key-name", Region: "some-region", Credentials: manifests.InternalCredentials{ NatsUsername: "some-persisted-nats-username", PostgresUsername: "some-persisted-postgres-username", RegistryUsername: "some-persisted-registry-username", BlobstoreDirectorUsername: "some-persisted-blobstore-director-username", BlobstoreAgentUsername: "some-persisted-blobstore-agent-username", HMUsername: "some-persisted-hm-username", NatsPassword: "<PASSWORD>", PostgresPassword: "<PASSWORD>", RegistryPassword: "<PASSWORD>", BlobstoreDirectorPassword: "<PASSWORD>store-director-<PASSWORD>", BlobstoreAgentPassword: "<PASSWORD>", HMPassword: "<PASSWORD>", }, }) Expect(err).NotTo(HaveOccurred()) Expect(jobs).To(HaveLen(1)) job := jobs[0] Expect(job.Properties.NATS.User).To(Equal("some-persisted-nats-username")) Expect(job.Properties.Postgres.User).To(Equal("some-persisted-postgres-username")) Expect(job.Properties.Registry.Username).To(Equal("some-persisted-registry-username")) Expect(job.Properties.Registry.HTTP.User).To(Equal("some-persisted-registry-username")) Expect(job.Properties.Blobstore.Director.User).To(Equal("some-persisted-blobstore-director-username")) Expect(job.Properties.Blobstore.Agent.User).To(Equal("some-persisted-blobstore-agent-username")) Expect(job.Properties.Director.UserManagement.Local.Users).To(ContainElement(manifests.UserProperties{ Name: "some-persisted-hm-username", Password: "<PASSWORD>", })) Expect(job.Properties.HM.DirectorAccount.User).To(Equal("some-persisted-hm-username")) Expect(manifestProperties.Credentials.NatsUsername).To(Equal("some-persisted-nats-username")) Expect(manifestProperties.Credentials.PostgresUsername).To(Equal("some-persisted-postgres-username")) Expect(manifestProperties.Credentials.RegistryUsername).To(Equal("some-persisted-registry-username")) Expect(manifestProperties.Credentials.BlobstoreDirectorUsername).To(Equal("some-persisted-blobstore-director-username")) Expect(manifestProperties.Credentials.BlobstoreAgentUsername).To(Equal("some-persisted-blobstore-agent-username")) Expect(manifestProperties.Credentials.HMUsername).To(Equal("some-persisted-hm-username")) Expect(job.Properties.NATS.Password).To(Equal("some-persisted-nats-password")) Expect(job.Properties.Postgres.Password).To(Equal("some-persisted-postgres-password")) Expect(job.Properties.Registry.Password).To(Equal("some-persisted-registry-password")) Expect(job.Properties.Registry.HTTP.Password).To(Equal("some-persisted-registry-password")) Expect(job.Properties.Blobstore.Director.Password).To(Equal("some-persisted-blobstore-director-password")) Expect(job.Properties.Blobstore.Agent.Password).To(Equal("some-persisted-blobstore-agent-password")) Expect(job.Properties.HM.DirectorAccount.Password).To(Equal("some-persisted-hm-password")) Expect(manifestProperties.Credentials.NatsPassword).To(Equal("some-persisted-nats-password")) Expect(manifestProperties.Credentials.PostgresPassword).To(Equal("some-persisted-postgres-password")) Expect(manifestProperties.Credentials.RegistryPassword).To(Equal("some-persisted-registry-password")) Expect(manifestProperties.Credentials.BlobstoreDirectorPassword).To(Equal("some-persisted-blobstore-director-password")) Expect(manifestProperties.Credentials.BlobstoreAgentPassword).To(Equal("some-persisted-blobstore-agent-password")) Expect(manifestProperties.Credentials.HMPassword).To(Equal("some-persisted-hm-password")) }) It("uses the same credentials for NATS and the Agent", func() { jobs, _, err := jobsManifestBuilder.Build(manifests.ManifestProperties{ ElasticIP: "some-elastic-ip", AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", DefaultKeyName: "some-key-name", Region: "some-region", }) Expect(err).NotTo(HaveOccurred()) job := jobs[0] Expect(job.Properties.Agent.MBus).To(Equal("nats://nats-user-some-random-string:nats-some-random-string@10.0.0.6:4222")) Expect(job.Properties.NATS.User).To(Equal("nats-user-some-random-string")) Expect(job.Properties.NATS.Password).To(Equal("<PASSWORD>")) }) It("generates a password for postgres", func() { jobs, _, err := jobsManifestBuilder.Build(manifests.ManifestProperties{ ElasticIP: "some-elastic-ip", AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", DefaultKeyName: "some-key-name", Region: "some-region", }) Expect(err).NotTo(HaveOccurred()) job := jobs[0] Expect(job.Properties.Postgres.User).To(Equal("postgres-user-some-random-string")) Expect(job.Properties.Registry.DB.User).To(Equal("postgres-user-some-random-string")) Expect(job.Properties.Director.DB.User).To(Equal("postgres-user-some-random-string")) Expect(job.Properties.Postgres.Password).To(Equal("<PASSWORD>")) Expect(job.Properties.Registry.DB.Password).To(Equal("<PASSWORD>")) Expect(job.Properties.Director.DB.Password).To(Equal("postgres-some-random-string")) }) It("generates a password for blobstore director and agent", func() { jobs, _, err := jobsManifestBuilder.Build(manifests.ManifestProperties{ ElasticIP: "some-elastic-ip", AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", DefaultKeyName: "some-key-name", Region: "some-region", }) Expect(err).NotTo(HaveOccurred()) job := jobs[0] Expect(job.Properties.Blobstore.Director.User).To(Equal("blobstore-director-user-some-random-string")) Expect(job.Properties.Blobstore.Agent.User).To(Equal("blobstore-agent-user-some-random-string")) Expect(job.Properties.Blobstore.Director.Password).To(Equal("<PASSWORD>")) Expect(job.Properties.Blobstore.Agent.Password).To(Equal("<PASSWORD>")) }) It("generates a password for health monitor", func() { jobs, _, err := jobsManifestBuilder.Build(manifests.ManifestProperties{ ElasticIP: "some-elastic-ip", AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", DefaultKeyName: "some-key-name", Region: "some-region", }) Expect(err).NotTo(HaveOccurred()) job := jobs[0] Expect(job.Properties.HM.DirectorAccount.User).To(Equal("hm-user-some-random-string")) Expect(job.Properties.HM.DirectorAccount.Password).To(Equal("<PASSWORD>")) Expect(job.Properties.Director.UserManagement.Local.Users).To(ContainElement( manifests.UserProperties{ Name: "hm-user-some-random-string", Password: "<PASSWORD>", }, )) }) Context("failure cases", func() { It("returns an error when string generation fails", func() { stringGenerator.GenerateCall.Stub = nil stringGenerator.GenerateCall.Returns.Error = errors.New("string generation failed") _, _, err := jobsManifestBuilder.Build(manifests.ManifestProperties{}) Expect(err).To(MatchError("string generation failed")) }) }) }) }) <file_sep>/aws/iam/certificate_validator.go package iam import ( "crypto/rsa" "crypto/x509" "encoding/pem" "errors" "fmt" "io" "io/ioutil" "os" "github.com/cloudfoundry/multierror" ) var readAll func(r io.Reader) ([]byte, error) = ioutil.ReadAll var stat func(name string) (os.FileInfo, error) = os.Stat type CertificateValidator struct{} func NewCertificateValidator() CertificateValidator { return CertificateValidator{} } func (c CertificateValidator) Validate(command, certPath, keyPath, chainPath string) error { var err error var certificateData []byte var keyData []byte var chainData []byte validateErrors := multierror.NewMultiError(command) if certificateData, err = c.validateFileAndFormat("certificate", "--cert", certPath); err != nil { validateErrors.Add(err) } if keyData, err = c.validateFileAndFormat("key", "--key", keyPath); err != nil { validateErrors.Add(err) } if chainPath != "" { if chainData, err = c.validateFileAndFormat("chain", "--chain", chainPath); err != nil { validateErrors.Add(err) } } if validateErrors.Length() > 0 { return validateErrors } privateKey, err := c.parsePrivateKey(keyData) if err != nil { validateErrors.Add(err) } certificate, err := c.parseCertificate(certificateData) if err != nil { validateErrors.Add(err) } var certPool *x509.CertPool if chainPath != "" { certPool, err = c.parseChain(chainData) if err != nil { validateErrors.Add(err) } } if privateKey != nil && certificate != nil { if err := c.validateCertAndKey(certificate, privateKey); err != nil { validateErrors.Add(err) } } if certPool != nil && certificate != nil { if err := c.validateCertAndChain(certificate, certPool); err != nil { validateErrors.Add(err) } } if validateErrors.Length() > 0 { return validateErrors } return nil } func (CertificateValidator) validateFileAndFormat(propertyName string, flagName string, filePath string) ([]byte, error) { if filePath == "" { return []byte{}, fmt.Errorf("%s is required", flagName) } file, err := os.Open(filePath) if os.IsNotExist(err) { return []byte{}, fmt.Errorf(`%s file not found: %q`, propertyName, filePath) } else if err != nil { return []byte{}, err } fileInfo, err := stat(file.Name()) if err != nil { return []byte{}, fmt.Errorf("%s: %s", err, filePath) } if !fileInfo.Mode().IsRegular() { return []byte{}, fmt.Errorf(`%s is not a regular file: %q`, propertyName, filePath) } fileData, err := readAll(file) if err != nil { return []byte{}, fmt.Errorf("%s: %s", err, filePath) } p, _ := pem.Decode(fileData) if p == nil { return []byte{}, fmt.Errorf("%s is not PEM encoded: %q", propertyName, filePath) } return fileData, nil } func (c CertificateValidator) validateCertAndKey(certificate *x509.Certificate, privateKey *rsa.PrivateKey) error { publicKey := certificate.PublicKey.(*rsa.PublicKey) if privateKey.PublicKey.N.Cmp(publicKey.N) != 0 || privateKey.PublicKey.E != publicKey.E { return errors.New("certificate and key mismatch") } return nil } func (CertificateValidator) validateCertAndChain(certificate *x509.Certificate, certPool *x509.CertPool) error { opts := x509.VerifyOptions{ Roots: certPool, } if _, err := certificate.Verify(opts); err != nil { return fmt.Errorf("certificate and chain mismatch: %s", err.Error()) } return nil } func (CertificateValidator) parsePrivateKey(keyData []byte) (*rsa.PrivateKey, error) { pemKeyData, _ := pem.Decode(keyData) privateKey, err := x509.ParsePKCS1PrivateKey(pemKeyData.Bytes) if err != nil { return nil, fmt.Errorf("failed to parse private key: %s", err) } return privateKey, nil } func (CertificateValidator) parseCertificate(certificateData []byte) (*x509.Certificate, error) { pemCertData, _ := pem.Decode(certificateData) cert, err := x509.ParseCertificate(pemCertData.Bytes) if err != nil { return nil, fmt.Errorf("failed to parse certificate: %s", err) } return cert, nil } func (CertificateValidator) parseChain(chainData []byte) (*x509.CertPool, error) { roots := x509.NewCertPool() ok := roots.AppendCertsFromPEM(chainData) if !ok { return nil, fmt.Errorf("failed to parse chain") } return roots, nil } <file_sep>/aws/config.go package aws import ( goaws "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" ) type Config struct { AccessKeyID string SecretAccessKey string Region string EndpointOverride string } func (c Config) ClientConfig() *goaws.Config { awsConfig := &goaws.Config{ Credentials: credentials.NewStaticCredentials(c.AccessKeyID, c.SecretAccessKey, ""), Region: goaws.String(c.Region), } if c.EndpointOverride != "" { awsConfig.WithEndpoint(c.EndpointOverride) } return awsConfig } <file_sep>/commands/errors.go package commands import "errors" var BBLNotFound error = errors.New("a bbl environment could not be found, please create a new environment before running this command again") var LBNotFound error = errors.New("no load balancer has been found for this bbl environment") <file_sep>/aws/ec2/keypair_synchronizer_test.go package ec2_test import ( "errors" "github.com/cloudfoundry/bosh-bootloader/aws/ec2" "github.com/cloudfoundry/bosh-bootloader/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("KeyPairSynchronizer", func() { var ( synchronizer ec2.KeyPairSynchronizer keyPairManager *fakes.KeyPairManager ) BeforeEach(func() { keyPairManager = &fakes.KeyPairManager{} keyPairManager.SyncCall.Returns.KeyPair = ec2.KeyPair{ Name: "updated-keypair-name", PrivateKey: "updated-private-key", PublicKey: "updated-public-key", } synchronizer = ec2.NewKeyPairSynchronizer(keyPairManager) }) It("syncs the keypair", func() { keyPair, err := synchronizer.Sync(ec2.KeyPair{ Name: "some-keypair-name", PrivateKey: "some-private-key", PublicKey: "some-public-key", }) Expect(err).NotTo(HaveOccurred()) Expect(keyPairManager.SyncCall.Receives.KeyPair).To(Equal(ec2.KeyPair{ Name: "some-keypair-name", PrivateKey: "some-private-key", PublicKey: "some-public-key", })) Expect(keyPair).To(Equal(ec2.KeyPair{ Name: "updated-keypair-name", PublicKey: "updated-public-key", PrivateKey: "updated-private-key", })) }) Context("failure cases", func() { Context("when the key pair cannot by synced", func() { It("returns an error", func() { keyPairManager.SyncCall.Returns.Error = errors.New("failed to sync") _, err := synchronizer.Sync(ec2.KeyPair{}) Expect(err).To(MatchError("failed to sync")) }) }) }) }) <file_sep>/fakes/keypair_verifier.go package fakes type KeyPairVerifier struct { VerifyCall struct { Receives struct { Fingerprint string PEMData []byte } Returns struct { Error error } } } func (v *KeyPairVerifier) Verify(fingerprint string, pemData []byte) error { v.VerifyCall.Receives.Fingerprint = fingerprint v.VerifyCall.Receives.PEMData = pemData return v.VerifyCall.Returns.Error } <file_sep>/bbl/awsbackend/load_balancers.go package awsbackend import "sync" type LoadBalancer struct { Name string Instances []string } type LoadBalancers struct { mutex sync.Mutex store map[string]LoadBalancer } func NewLoadBalancers() *LoadBalancers { return &LoadBalancers{ store: make(map[string]LoadBalancer), } } func (s *LoadBalancers) Set(loadBalancer LoadBalancer) { s.mutex.Lock() defer s.mutex.Unlock() s.store[loadBalancer.Name] = loadBalancer } func (s *LoadBalancers) Get(name string) (LoadBalancer, bool) { s.mutex.Lock() defer s.mutex.Unlock() loadBalancer, ok := s.store[name] return loadBalancer, ok } func (s *LoadBalancers) Delete(name string) { s.mutex.Lock() defer s.mutex.Unlock() delete(s.store, name) } <file_sep>/aws/cloudformation/templates/internal_subnets_template_builder_test.go package templates_test import ( "fmt" "reflect" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("InternalSubnetsTemplateBuilder", func() { var internalSubnetsTemplateBuilder templates.InternalSubnetsTemplateBuilder BeforeEach(func() { internalSubnetsTemplateBuilder = templates.NewInternalSubnetsTemplateBuilder() }) Describe("InternalSubnets", func() { It("creates internal subnets for each availability zone", func() { template := internalSubnetsTemplateBuilder.InternalSubnets(2) Expect(template.Parameters).To(HaveLen(2)) Expect(template.Parameters["InternalSubnet1CIDR"].Default).To(Equal("10.0.16.0/20")) Expect(template.Parameters["InternalSubnet2CIDR"].Default).To(Equal("10.0.32.0/20")) Expect(HasSubnetWithAvailabilityZoneIndex(template, 0)).To(BeTrue()) Expect(HasSubnetWithAvailabilityZoneIndex(template, 1)).To(BeTrue()) }) }) }) func HasSubnetWithAvailabilityZoneIndex(template templates.Template, index int) bool { azIndex := fmt.Sprintf("%d", index) subnetName := fmt.Sprintf("InternalSubnet%d", index+1) subnetCIDRName := fmt.Sprintf("%sCIDR", subnetName) tagName := fmt.Sprintf("Internal%d", index+1) return reflect.DeepEqual(template.Resources[subnetName].Properties, templates.Subnet{ AvailabilityZone: map[string]interface{}{ "Fn::Select": []interface{}{ azIndex, map[string]templates.Ref{ "Fn::GetAZs": templates.Ref{"AWS::Region"}, }, }, }, CidrBlock: templates.Ref{subnetCIDRName}, VpcId: templates.Ref{"VPC"}, Tags: []templates.Tag{ { Key: "Name", Value: tagName, }, }, }) } <file_sep>/bbl/director_ca_cert_test.go package main_test import ( "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "github.com/cloudfoundry/bosh-bootloader/storage" "github.com/onsi/gomega/gexec" . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/extensions/table" . "github.com/onsi/gomega" ) var _ = Describe("director-ca-cert", func() { DescribeTable("prints CA used to sign the BOSH server cert", func(command string) { tempDirectory, err := ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) state := []byte(`{ "bosh": { "directorSSLCA": "some-ca-contents" } }`) err = ioutil.WriteFile(filepath.Join(tempDirectory, storage.StateFileName), state, os.ModePerm) Expect(err).NotTo(HaveOccurred()) args := []string{ "--state-dir", tempDirectory, command, } session, err := gexec.Start(exec.Command(pathToBBL, args...), GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session).Should(gexec.Exit(0)) Expect(session.Out.Contents()).To(ContainSubstring("some-ca-contents")) }, Entry("director-ca-cert", "director-ca-cert"), Entry("supporting bosh-ca-cert for backwards compatibility", "bosh-ca-cert"), ) It("returns a non zero exit code when the bbl-state.json does not exist", func() { tempDirectory, err := ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) args := []string{ "--state-dir", tempDirectory, "director-ca-cert", } session, err := gexec.Start(exec.Command(pathToBBL, args...), GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session).Should(gexec.Exit(1)) expectedErrorMessage := fmt.Sprintf("bbl-state.json not found in %q, ensure you're running this command in the proper state directory or create a new environment with bbl up", tempDirectory) Expect(session.Err.Contents()).To(ContainSubstring(expectedErrorMessage)) }) Context("bosh-ca-cert", func() { It("returns a non zero exit code when the bbl-state.json does not exist", func() { tempDirectory, err := ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) args := []string{ "--state-dir", tempDirectory, "bosh-ca-cert", } session, err := gexec.Start(exec.Command(pathToBBL, args...), GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session).Should(gexec.Exit(1)) expectedErrorMessage := fmt.Sprintf("bbl-state.json not found in %q, ensure you're running this command in the proper state directory or create a new environment with bbl up", tempDirectory) Expect(session.Err.Contents()).To(ContainSubstring(expectedErrorMessage)) }) It("prints a deprecation warning to STDERR", func() { tempDirectory, err := ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) state := []byte(`{}`) err = ioutil.WriteFile(filepath.Join(tempDirectory, storage.StateFileName), state, os.ModePerm) Expect(err).NotTo(HaveOccurred()) session, err := gexec.Start(exec.Command(pathToBBL, "--state-dir", tempDirectory, "bosh-ca-cert"), GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session).Should(gexec.Exit()) Expect(session.Err.Contents()).To(ContainSubstring("'bosh-ca-cert' has been deprecated and will be removed in future versions of bbl, please use 'director-ca-cert'")) }) }) }) <file_sep>/boshinit/manifests/init_test.go package manifests_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "testing" ) func TestManifests(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "boshinit/manifests") } const ( ca = `-----BEGIN CER<KEY> -----END CERTIFICATE-----` certificate = `-----BEGIN CERTIFICATE----- <KEY>2<KEY> -----END CERTIFICATE-----` privateKey = `-----<KEY>` ) <file_sep>/aws/ec2/vpc_status_checker.go package ec2 import ( "fmt" "strings" "github.com/aws/aws-sdk-go/aws" awsec2 "github.com/aws/aws-sdk-go/service/ec2" ) type ec2ClientProvider interface { GetEC2Client() Client } type VPCStatusChecker struct { ec2ClientProvider ec2ClientProvider } func NewVPCStatusChecker(ec2ClientProvider ec2ClientProvider) VPCStatusChecker { return VPCStatusChecker{ ec2ClientProvider: ec2ClientProvider, } } func (v VPCStatusChecker) ValidateSafeToDelete(vpcID string) error { output, err := v.ec2ClientProvider.GetEC2Client().DescribeInstances(&awsec2.DescribeInstancesInput{ Filters: []*awsec2.Filter{{ Name: aws.String("vpc-id"), Values: []*string{aws.String(vpcID)}, }}, }) if err != nil { return err } vms := v.flattenVMs(output.Reservations) vms = v.removeOneVM(vms, "NAT") vms = v.removeOneVM(vms, "bosh/0") if len(vms) > 0 { return fmt.Errorf("vpc %s is not safe to delete; vms still exist: [%s]", vpcID, strings.Join(vms, ", ")) } return nil } func (v VPCStatusChecker) flattenVMs(reservations []*awsec2.Reservation) []string { vms := []string{} for _, reservation := range reservations { for _, instance := range reservation.Instances { vms = append(vms, v.vmName(instance)) } } return vms } func (v VPCStatusChecker) vmName(instance *awsec2.Instance) string { name := "unnamed" for _, tag := range instance.Tags { if aws.StringValue(tag.Key) == "Name" && aws.StringValue(tag.Value) != "" { name = aws.StringValue(tag.Value) } } return name } func (v VPCStatusChecker) removeOneVM(vms []string, vmToRemove string) []string { for index, vm := range vms { if vm == vmToRemove { return append(vms[:index], vms[index+1:]...) } } return vms } <file_sep>/aws/cloudformation/templates/nat_template_builder.go package templates type NATTemplateBuilder struct{} func NewNATTemplateBuilder() NATTemplateBuilder { return NATTemplateBuilder{} } func (t NATTemplateBuilder) NAT() Template { return Template{ Mappings: map[string]interface{}{ "AWSNATAMI": map[string]AMI{ "us-east-1": {"ami-68115b02"}, "us-west-1": {"ami-ef1a718f"}, "us-west-2": {"ami-77a4b816"}, "eu-west-1": {"ami-c0993ab3"}, "eu-central-1": {"ami-0b322e67"}, "ap-southeast-1": {"ami-e2fc3f81"}, "ap-southeast-2": {"ami-e3217a80"}, "ap-northeast-1": {"ami-f885ae96"}, "ap-northeast-2": {"ami-4118d72f"}, "sa-east-1": {"ami-8631b5ea"}, }, }, Resources: map[string]Resource{ "NATSecurityGroup": Resource{ Type: "AWS::EC2::SecurityGroup", Properties: SecurityGroup{ VpcId: Ref{"VPC"}, GroupDescription: "NAT", SecurityGroupEgress: []SecurityGroupEgress{}, SecurityGroupIngress: []SecurityGroupIngress{ { SourceSecurityGroupId: Ref{"InternalSecurityGroup"}, IpProtocol: "tcp", FromPort: "0", ToPort: "65535", }, { SourceSecurityGroupId: Ref{"InternalSecurityGroup"}, IpProtocol: "udp", FromPort: "0", ToPort: "65535", }, }, }, }, "NATInstance": Resource{ Type: "AWS::EC2::Instance", Properties: Instance{ PrivateIpAddress: "10.0.0.7", InstanceType: "t2.medium", SubnetId: Ref{"BOSHSubnet"}, SourceDestCheck: false, ImageId: map[string]interface{}{ "Fn::FindInMap": []interface{}{ "AWSNATAMI", Ref{"AWS::Region"}, "AMI", }, }, KeyName: Ref{"SSHKeyPairName"}, SecurityGroupIds: []interface{}{ Ref{"NATSecurityGroup"}, }, Tags: []Tag{ { Key: "Name", Value: "NAT", }, }, }, }, "NATEIP": Resource{ DependsOn: "VPCGatewayAttachment", Type: "AWS::EC2::EIP", Properties: EIP{ Domain: "vpc", InstanceId: Ref{"NATInstance"}, }, }, }, } } <file_sep>/boshinit/executor_test.go package boshinit_test import ( "errors" "github.com/cloudfoundry/bosh-bootloader/aws/ec2" "github.com/cloudfoundry/bosh-bootloader/boshinit" "github.com/cloudfoundry/bosh-bootloader/boshinit/manifests" "github.com/cloudfoundry/bosh-bootloader/fakes" "github.com/cloudfoundry/bosh-bootloader/ssl" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Executor", func() { var ( manifestBuilder *fakes.BOSHInitManifestBuilder deployCommandRunner *fakes.BOSHInitCommandRunner deleteCommandRunner *fakes.BOSHInitCommandRunner executor boshinit.Executor logger *fakes.Logger infrastructureConfiguration boshinit.InfrastructureConfiguration sslKeyPair ssl.KeyPair ec2KeyPair ec2.KeyPair credentials map[string]string ) BeforeEach(func() { manifestBuilder = &fakes.BOSHInitManifestBuilder{} deployCommandRunner = &fakes.BOSHInitCommandRunner{} deleteCommandRunner = &fakes.BOSHInitCommandRunner{} logger = &fakes.Logger{} executor = boshinit.NewExecutor(manifestBuilder, deployCommandRunner, deleteCommandRunner, logger) infrastructureConfiguration = boshinit.InfrastructureConfiguration{ SubnetID: "subnet-12345", AvailabilityZone: "some-az", ElasticIP: "some-elastic-ip", AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", SecurityGroup: "some-security-group", AWSRegion: "some-aws-region", } sslKeyPair = ssl.KeyPair{ Certificate: []byte("some-certificate"), PrivateKey: []byte("some-private-key"), } ec2KeyPair = ec2.KeyPair{ Name: "some-keypair-name", PrivateKey: "some-private-key", PublicKey: "some-public-key", } credentials = map[string]string{ "mbusUsername": "some-mbus-username", "natsUsername": "some-nats-username", "postgresUsername": "some-postgres-username", "registryUsername": "some-registry-username", "blobstoreDirectorUsername": "some-blobstore-director-username", "blobstoreAgentUsername": "some-blobstore-agent-username", "hmUsername": "some-hm-username", "mbusPassword": "<PASSWORD>", "natsPassword": "<PASSWORD>", "postgresPassword": "<PASSWORD>", "registryPassword": "<PASSWORD>", "blobstoreDirectorPassword": "<PASSWORD>", "blobstoreAgentPassword": "<PASSWORD>", "hmPassword": "<PASSWORD>", } manifestBuilder.BuildCall.Returns.Properties = manifests.ManifestProperties{ DirectorUsername: "admin", DirectorPassword: "<PASSWORD>", CACommonName: "BOSH Bootloader", ElasticIP: "some-elastic-ip", SSLKeyPair: ssl.KeyPair{ Certificate: []byte("updated-certificate"), PrivateKey: []byte("updated-private-key"), }, Credentials: manifests.InternalCredentials{ MBusUsername: "some-mbus-username", NatsUsername: "some-nats-username", PostgresUsername: "some-postgres-username", RegistryUsername: "some-registry-username", BlobstoreDirectorUsername: "some-blobstore-director-username", BlobstoreAgentUsername: "some-blobstore-agent-username", HMUsername: "some-hm-username", MBusPassword: "<PASSWORD>", NatsPassword: "<PASSWORD>", PostgresPassword: "<PASSWORD>-<PASSWORD>", RegistryPassword: "<PASSWORD>", BlobstoreDirectorPassword: "<PASSWORD>", BlobstoreAgentPassword: "<PASSWORD>", HMPassword: "<PASSWORD>", }, } manifestBuilder.BuildCall.Returns.Manifest = manifests.Manifest{ Name: "bosh", } deployCommandRunner.ExecuteCall.Returns.State = boshinit.State{ "key": "value", } }) Describe("Delete", func() { It("deletes the bosh director given the state", func() { err := executor.Delete("bosh-init-manifest", boshinit.State{"key": "value"}, "ec2-private-key") Expect(err).NotTo(HaveOccurred()) Expect(deleteCommandRunner.ExecuteCall.Receives.Manifest).To(Equal([]byte("bosh-init-manifest"))) Expect(deleteCommandRunner.ExecuteCall.Receives.PrivateKey).To(Equal("ec2-private-key")) Expect(deleteCommandRunner.ExecuteCall.Receives.State).To(Equal(boshinit.State{"key": "value"})) }) It("prints out that the director is being destroyed", func() { err := executor.Delete("", boshinit.State{}, "") Expect(err).NotTo(HaveOccurred()) Expect(logger.StepCall.Receives.Message).To(Equal("destroying bosh director")) }) Context("failure cases", func() { Context("when the runner fails to delete", func() { It("returns an error", func() { deleteCommandRunner.ExecuteCall.Returns.Error = errors.New("failed to delete") err := executor.Delete("", boshinit.State{}, "") Expect(err).To(MatchError("failed to delete")) }) }) }) }) Describe("Deploy", func() { It("deploys bosh and returns a bosh output", func() { deployOutput, err := executor.Deploy(boshinit.DeployInput{ DirectorName: "some-director-name", DirectorUsername: "some-director-username", DirectorPassword: "<PASSWORD>", State: boshinit.State{ "key": "value", }, InfrastructureConfiguration: infrastructureConfiguration, SSLKeyPair: sslKeyPair, EC2KeyPair: ec2KeyPair, Credentials: credentials, }) Expect(err).NotTo(HaveOccurred()) Expect(manifestBuilder.BuildCall.Receives.Properties).To(Equal(manifests.ManifestProperties{ DirectorName: "some-director-name", DirectorUsername: "some-director-username", DirectorPassword: "<PASSWORD>", SubnetID: "subnet-12345", AvailabilityZone: "some-az", CACommonName: "BOSH Bootloader", ElasticIP: "some-elastic-ip", AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", DefaultKeyName: "some-keypair-name", Region: "some-aws-region", SecurityGroup: "some-security-group", SSLKeyPair: ssl.KeyPair{ Certificate: []byte("some-certificate"), PrivateKey: []byte("some-private-key"), }, Credentials: manifests.InternalCredentials{ MBusUsername: "some-mbus-username", NatsUsername: "some-nats-username", PostgresUsername: "some-postgres-username", RegistryUsername: "some-registry-username", BlobstoreDirectorUsername: "some-blobstore-director-username", BlobstoreAgentUsername: "some-blobstore-agent-username", HMUsername: "some-hm-username", MBusPassword: "<PASSWORD>", NatsPassword: "<PASSWORD>", PostgresPassword: "<PASSWORD>", RegistryPassword: "<PASSWORD>", BlobstoreDirectorPassword: "<PASSWORD>", BlobstoreAgentPassword: "<PASSWORD>", HMPassword: "<PASSWORD>", }, })) Expect(deployOutput.DirectorSSLKeyPair).To(Equal(ssl.KeyPair{ Certificate: []byte("updated-certificate"), PrivateKey: []byte("updated-private-key"), })) Expect(deployOutput.BOSHInitState).To(Equal(boshinit.State{ "key": "value", })) Expect(deployOutput.Credentials).To(Equal(map[string]string{ "mbusUsername": "some-mbus-username", "natsUsername": "some-nats-username", "postgresUsername": "some-postgres-username", "registryUsername": "some-registry-username", "blobstoreDirectorUsername": "some-blobstore-director-username", "blobstoreAgentUsername": "some-blobstore-agent-username", "hmUsername": "some-hm-username", "mbusPassword": "<PASSWORD>", "natsPassword": "<PASSWORD>", "postgresPassword": "<PASSWORD>", "registryPassword": "<PASSWORD>", "blobstoreDirectorPassword": "<PASSWORD>", "blobstoreAgentPassword": "<PASSWORD>", "hmPassword": "<PASSWORD>", })) Expect(deployOutput.BOSHInitManifest).To(ContainSubstring("name: bosh")) Expect(deployCommandRunner.ExecuteCall.Receives.Manifest).To(ContainSubstring("name: bosh")) Expect(deployCommandRunner.ExecuteCall.Receives.PrivateKey).To(ContainSubstring("some-private-key")) Expect(deployCommandRunner.ExecuteCall.Receives.State).To(Equal(boshinit.State{ "key": "value", })) }) It("prints out that the director is being deployed", func() { _, err := executor.Deploy(boshinit.DeployInput{ InfrastructureConfiguration: infrastructureConfiguration, SSLKeyPair: sslKeyPair, EC2KeyPair: ec2KeyPair, }) Expect(err).NotTo(HaveOccurred()) Expect(logger.StepCall.Receives.Message).To(Equal("deploying bosh director")) }) Context("failure cases", func() { Context("when the manifest cannot be built", func() { It("returns an error", func() { manifestBuilder.BuildCall.Returns.Error = errors.New("failed to build manifest") _, err := executor.Deploy(boshinit.DeployInput{}) Expect(err).To(MatchError("failed to build manifest")) }) }) Context("when the runner fails to deploy", func() { It("returns an error", func() { deployCommandRunner.ExecuteCall.Returns.Error = errors.New("failed to deploy") _, err := executor.Deploy(boshinit.DeployInput{}) Expect(err).To(MatchError("failed to deploy")) }) }) }) }) }) <file_sep>/bosh/cloud_config_manager.go package bosh import "gopkg.in/yaml.v2" type CloudConfigManager struct { logger logger cloudConfigGenerator cloudConfigGenerator } type cloudConfigGenerator interface { Generate(CloudConfigInput) (CloudConfig, error) } func NewCloudConfigManager(logger logger, cloudConfigGenerator cloudConfigGenerator) CloudConfigManager { return CloudConfigManager{ logger: logger, cloudConfigGenerator: cloudConfigGenerator, } } func (c CloudConfigManager) Update(input CloudConfigInput, boshClient Client) error { c.logger.Step("generating cloud config") cloudConfig, err := c.cloudConfigGenerator.Generate(input) if err != nil { return err } manifestYAML, err := yaml.Marshal(cloudConfig) if err != nil { return err } c.logger.Step("applying cloud config") if err := boshClient.UpdateCloudConfig(manifestYAML); err != nil { return err } return nil } <file_sep>/commands/up_test.go package commands_test import ( "errors" "fmt" "os" "github.com/cloudfoundry/bosh-bootloader/aws" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation" "github.com/cloudfoundry/bosh-bootloader/aws/ec2" "github.com/cloudfoundry/bosh-bootloader/aws/iam" "github.com/cloudfoundry/bosh-bootloader/bosh" "github.com/cloudfoundry/bosh-bootloader/boshinit" "github.com/cloudfoundry/bosh-bootloader/commands" "github.com/cloudfoundry/bosh-bootloader/fakes" "github.com/cloudfoundry/bosh-bootloader/ssl" "github.com/cloudfoundry/bosh-bootloader/storage" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Up", func() { Describe("Execute", func() { var ( command commands.Up boshDeployer *fakes.BOSHDeployer infrastructureManager *fakes.InfrastructureManager keyPairSynchronizer *fakes.KeyPairSynchronizer stringGenerator *fakes.StringGenerator cloudConfigurator *fakes.BoshCloudConfigurator availabilityZoneRetriever *fakes.AvailabilityZoneRetriever certificateDescriber *fakes.CertificateDescriber awsCredentialValidator *fakes.AWSCredentialValidator cloudConfigManager *fakes.CloudConfigManager boshClientProvider *fakes.BOSHClientProvider boshClient *fakes.BOSHClient envIDGenerator *fakes.EnvIDGenerator boshInitCredentials map[string]string stateStore *fakes.StateStore clientProvider *fakes.ClientProvider ) BeforeEach(func() { keyPairSynchronizer = &fakes.KeyPairSynchronizer{} keyPairSynchronizer.SyncCall.Returns.KeyPair = ec2.KeyPair{ Name: "keypair-bbl-lake-time:stamp", PrivateKey: "some-private-key", PublicKey: "some-public-key", } infrastructureManager = &fakes.InfrastructureManager{} infrastructureManager.CreateCall.Returns.Stack = cloudformation.Stack{ Name: "bbl-aws-some-random-string", Outputs: map[string]string{ "BOSHSubnet": "some-bosh-subnet", "BOSHSubnetAZ": "some-bosh-subnet-az", "BOSHEIP": "some-bosh-elastic-ip", "BOSHURL": "some-bosh-url", "BOSHUserAccessKey": "some-bosh-user-access-key", "BOSHUserSecretAccessKey": "some-bosh-user-secret-access-key", "BOSHSecurityGroup": "some-bosh-security-group", }, } boshDeployer = &fakes.BOSHDeployer{} boshDeployer.DeployCall.Returns.Output = boshinit.DeployOutput{ DirectorSSLKeyPair: ssl.KeyPair{ CA: []byte("updated-ca"), Certificate: []byte("updated-certificate"), PrivateKey: []byte("updated-private-key"), }, BOSHInitState: boshinit.State{ "updated-key": "updated-value", }, BOSHInitManifest: "name: bosh", } stringGenerator = &fakes.StringGenerator{} stringGenerator.GenerateCall.Stub = func(prefix string, length int) (string, error) { return fmt.Sprintf("%s%s", prefix, "some-random-string"), nil } cloudConfigurator = &fakes.BoshCloudConfigurator{} cloudConfigManager = &fakes.CloudConfigManager{} availabilityZoneRetriever = &fakes.AvailabilityZoneRetriever{} certificateDescriber = &fakes.CertificateDescriber{} awsCredentialValidator = &fakes.AWSCredentialValidator{} boshClient = &fakes.BOSHClient{} boshClientProvider = &fakes.BOSHClientProvider{} boshClientProvider.ClientCall.Returns.Client = boshClient envIDGenerator = &fakes.EnvIDGenerator{} envIDGenerator.GenerateCall.Returns.EnvID = "bbl-lake-time:stamp" stateStore = &fakes.StateStore{} clientProvider = &fakes.ClientProvider{} command = commands.NewUp( awsCredentialValidator, infrastructureManager, keyPairSynchronizer, boshDeployer, stringGenerator, cloudConfigurator, availabilityZoneRetriever, certificateDescriber, cloudConfigManager, boshClientProvider, envIDGenerator, stateStore, clientProvider, ) boshInitCredentials = map[string]string{ "mbusUsername": "some-mbus-username", "natsUsername": "some-nats-username", "postgresUsername": "some-postgres-username", "registryUsername": "some-registry-username", "blobstoreDirectorUsername": "some-blobstore-director-username", "blobstoreAgentUsername": "some-blobstore-agent-username", "hmUsername": "some-hm-username", "mbusPassword": "<PASSWORD>", "natsPassword": "<PASSWORD>", "postgresPassword": "<PASSWORD>", "registryPassword": "<PASSWORD>", "blobstoreDirectorPassword": "<PASSWORD>", "blobstoreAgentPassword": "<PASSWORD>", "hmPassword": "<PASSWORD>", } }) It("returns an error when aws credential validator fails", func() { awsCredentialValidator.ValidateCall.Returns.Error = errors.New("failed to validate aws credentials") err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("failed to validate aws credentials")) }) Context("when AWS creds are provided through environment variables", func() { BeforeEach(func() { os.Setenv("BBL_AWS_ACCESS_KEY_ID", "some-access-key") os.Setenv("BBL_AWS_SECRET_ACCESS_KEY", "some-access-secret") os.Setenv("BBL_AWS_REGION", "some-region") }) AfterEach(func() { os.Setenv("BBL_AWS_ACCESS_KEY_ID", "") os.Setenv("BBL_AWS_SECRET_ACCESS_KEY", "") os.Setenv("BBL_AWS_REGION", "") }) It("honors the environment variables to fetch the AWS creds", func() { err := command.Execute([]string{}, storage.State{ AWS: storage.AWS{ Region: "some-aws-region", SecretAccessKey: "some-secret-access-key", AccessKeyID: "some-access-key-id", }, KeyPair: storage.KeyPair{ Name: "some-keypair-name", PrivateKey: "some-private-key", PublicKey: "some-public-key", }, }) Expect(err).NotTo(HaveOccurred()) Expect(clientProvider.SetConfigCall.CallCount).To(Equal(1)) Expect(clientProvider.SetConfigCall.Receives.Config).To(Equal(aws.Config{ Region: "some-region", SecretAccessKey: "some-access-secret", AccessKeyID: "some-access-key", })) Expect(awsCredentialValidator.ValidateCall.CallCount).To(Equal(0)) }) It("honors missing creds passed as arguments", func() { os.Setenv("BBL_AWS_ACCESS_KEY_ID", "") err := command.Execute([]string{ "--aws-access-key-id", "access-key-from-arguments", }, storage.State{ AWS: storage.AWS{ Region: "some-aws-region", SecretAccessKey: "some-secret-access-key", AccessKeyID: "some-access-key-id", }, KeyPair: storage.KeyPair{ Name: "some-keypair-name", PrivateKey: "some-private-key", PublicKey: "some-public-key", }, }) Expect(err).NotTo(HaveOccurred()) Expect(clientProvider.SetConfigCall.CallCount).To(Equal(1)) Expect(clientProvider.SetConfigCall.Receives.Config).To(Equal(aws.Config{ Region: "some-region", SecretAccessKey: "some-access-secret", AccessKeyID: "access-key-from-arguments", })) Expect(awsCredentialValidator.ValidateCall.CallCount).To(Equal(0)) }) }) It("honors the cli flags", func() { err := command.Execute([]string{ "--aws-access-key-id", "new-aws-access-key-id", "--aws-secret-access-key", "new-aws-secret-access-key", "--aws-region", "new-aws-region", }, storage.State{ AWS: storage.AWS{ Region: "some-aws-region", SecretAccessKey: "some-secret-access-key", AccessKeyID: "some-access-key-id", }, KeyPair: storage.KeyPair{ Name: "some-keypair-name", PrivateKey: "some-private-key", PublicKey: "some-public-key", }, }) Expect(err).NotTo(HaveOccurred()) Expect(clientProvider.SetConfigCall.CallCount).To(Equal(1)) Expect(clientProvider.SetConfigCall.Receives.Config).To(Equal(aws.Config{ Region: "new-aws-region", SecretAccessKey: "new-aws-secret-access-key", AccessKeyID: "new-aws-access-key-id", })) Expect(awsCredentialValidator.ValidateCall.CallCount).To(Equal(0)) }) It("syncs the keypair", func() { err := command.Execute([]string{}, storage.State{ AWS: storage.AWS{ Region: "some-aws-region", SecretAccessKey: "some-secret-access-key", AccessKeyID: "some-access-key-id", }, KeyPair: storage.KeyPair{ Name: "some-keypair-name", PrivateKey: "some-private-key", PublicKey: "some-public-key", }, }) Expect(err).NotTo(HaveOccurred()) Expect(clientProvider.SetConfigCall.CallCount).To(Equal(0)) Expect(awsCredentialValidator.ValidateCall.CallCount).To(Equal(1)) Expect(keyPairSynchronizer.SyncCall.Receives.KeyPair).To(Equal(ec2.KeyPair{ Name: "some-keypair-name", PrivateKey: "some-private-key", PublicKey: "some-public-key", })) actualState := stateStore.SetCall.Receives.State Expect(actualState.KeyPair).To(Equal(storage.KeyPair{ Name: "some-keypair-name", PublicKey: "some-public-key", PrivateKey: "some-private-key", })) }) It("generates an bbl-env-id", func() { incomingState := storage.State{ AWS: storage.AWS{ Region: "some-aws-region", SecretAccessKey: "some-secret-access-key", AccessKeyID: "some-access-key-id", }, } err := command.Execute([]string{}, incomingState) Expect(err).NotTo(HaveOccurred()) Expect(envIDGenerator.GenerateCall.CallCount).To(Equal(1)) }) It("creates/updates the stack with the given name", func() { incomingState := storage.State{ AWS: storage.AWS{ Region: "some-aws-region", SecretAccessKey: "some-secret-access-key", AccessKeyID: "some-access-key-id", }, } availabilityZoneRetriever.RetrieveCall.Returns.AZs = []string{"some-retrieved-az"} err := command.Execute([]string{}, incomingState) Expect(err).NotTo(HaveOccurred()) Expect(infrastructureManager.CreateCall.Receives.StackName).To(Equal("stack-bbl-lake-time-stamp")) Expect(infrastructureManager.CreateCall.Receives.KeyPairName).To(Equal("keypair-bbl-lake-time:stamp")) Expect(infrastructureManager.CreateCall.Receives.NumberOfAvailabilityZones).To(Equal(1)) Expect(infrastructureManager.CreateCall.Receives.EnvID).To(Equal("bbl-lake-time:stamp")) Expect(infrastructureManager.CreateCall.Returns.Error).To(BeNil()) }) It("deploys bosh", func() { infrastructureManager.ExistsCall.Returns.Exists = true incomingState := storage.State{ AWS: storage.AWS{ Region: "some-aws-region", }, KeyPair: storage.KeyPair{ Name: "some-keypair-name", PrivateKey: "some-private-key", PublicKey: "some-public-key", }, } err := command.Execute([]string{}, incomingState) Expect(err).NotTo(HaveOccurred()) Expect(boshDeployer.DeployCall.Receives.Input).To(Equal(boshinit.DeployInput{ DirectorName: "bosh-bbl-lake-time:stamp", DirectorUsername: "user-some-random-string", DirectorPassword: "<PASSWORD>", State: map[string]interface{}{}, InfrastructureConfiguration: boshinit.InfrastructureConfiguration{ AWSRegion: "some-aws-region", SubnetID: "some-bosh-subnet", AvailabilityZone: "some-bosh-subnet-az", ElasticIP: "some-bosh-elastic-ip", AccessKeyID: "some-bosh-user-access-key", SecretAccessKey: "some-bosh-user-secret-access-key", SecurityGroup: "some-bosh-security-group", }, SSLKeyPair: ssl.KeyPair{}, EC2KeyPair: ec2.KeyPair{ Name: "some-keypair-name", PublicKey: "some-public-key", PrivateKey: "some-private-key", }, })) }) Context("when there is an lb", func() { It("attaches the lb certificate to the lb type in cloudformation", func() { certificateDescriber.DescribeCall.Returns.Certificate = iam.Certificate{ Name: "some-certificate-name", ARN: "some-certificate-arn", Body: "some-certificate-body", } err := command.Execute([]string{}, storage.State{ Stack: storage.Stack{ Name: "some-stack-name", LBType: "concourse", CertificateName: "some-certificate-name", }, }) Expect(err).NotTo(HaveOccurred()) Expect(infrastructureManager.CreateCall.Receives.LBCertificateARN).To(Equal("some-certificate-arn")) }) }) Describe("cloud configurator", func() { BeforeEach(func() { infrastructureManager.CreateCall.Stub = func(keyPairName string, numberOfAZs int, stackName, lbType, envID string) (cloudformation.Stack, error) { stack := cloudformation.Stack{ Name: "bbl-aws-some-random-string", Outputs: map[string]string{ "BOSHSubnet": "some-bosh-subnet", "BOSHSubnetAZ": "some-bosh-subnet-az", "BOSHEIP": "some-bosh-elastic-ip", "BOSHURL": "some-bosh-url", "BOSHUserAccessKey": "some-bosh-user-access-key", "BOSHUserSecretAccessKey": "some-bosh-user-secret-access-key", "BOSHSecurityGroup": "some-bosh-security-group", }, } switch lbType { case "concourse": stack.Outputs["ConcourseLoadBalancer"] = "some-lb-name" stack.Outputs["ConcourseLoadBalancerURL"] = "some-lb-url" case "cf": stack.Outputs["RouterLB"] = "some-router-lb-name" stack.Outputs["RouterLBURL"] = "some-router-lb-url" stack.Outputs["SSHProxyLB"] = "some-ssh-proxy-lb-name" stack.Outputs["SSHProxyLBURL"] = "some-ssh-proxy-lb-url" default: } return stack, nil } }) It("upload the cloud config to the director", func() { cloudConfigInput := bosh.CloudConfigInput{ AZs: []string{"az1", "az2", "az3"}, } cloudConfigurator.ConfigureCall.Returns.CloudConfigInput = cloudConfigInput err := command.Execute([]string{}, storage.State{}) Expect(err).NotTo(HaveOccurred()) Expect(boshClientProvider.ClientCall.Receives.DirectorAddress).To(Equal("some-bosh-url")) Expect(boshClientProvider.ClientCall.Receives.DirectorUsername).To(Equal("user-some-random-string")) Expect(boshClientProvider.ClientCall.Receives.DirectorPassword).To(Equal("<PASSWORD>")) Expect(cloudConfigManager.UpdateCall.Receives.CloudConfigInput).To(Equal(cloudConfigInput)) Expect(cloudConfigManager.UpdateCall.Receives.BOSHClient).To(Equal(boshClient)) }) Context("when no load balancer has been requested", func() { It("generates a cloud config", func() { availabilityZoneRetriever.RetrieveCall.Returns.AZs = []string{"some-retrieved-az"} err := command.Execute([]string{}, storage.State{}) Expect(err).NotTo(HaveOccurred()) Expect(cloudConfigurator.ConfigureCall.CallCount).To(Equal(1)) Expect(cloudConfigurator.ConfigureCall.Receives.Stack).To(Equal(cloudformation.Stack{ Name: "bbl-aws-some-random-string", Outputs: map[string]string{ "BOSHSecurityGroup": "some-bosh-security-group", "BOSHSubnet": "some-bosh-subnet", "BOSHSubnetAZ": "some-bosh-subnet-az", "BOSHEIP": "some-bosh-elastic-ip", "BOSHURL": "some-bosh-url", "BOSHUserAccessKey": "some-bosh-user-access-key", "BOSHUserSecretAccessKey": "some-bosh-user-secret-access-key", }, })) Expect(cloudConfigurator.ConfigureCall.Receives.AZs).To(ConsistOf("some-retrieved-az")) Expect(certificateDescriber.DescribeCall.CallCount).To(Equal(0)) }) }) Context("when the load balancer type is concourse", func() { It("generates a cloud config", func() { availabilityZoneRetriever.RetrieveCall.Returns.AZs = []string{"some-retrieved-az"} certificateDescriber.DescribeCall.Returns.Certificate = iam.Certificate{ Name: "some-certificate-name", ARN: "some-certificate-arn", Body: "some-certificate-body", } err := command.Execute([]string{}, storage.State{ Stack: storage.Stack{ LBType: "concourse", CertificateName: "some-certificate-name", }, }) Expect(err).NotTo(HaveOccurred()) Expect(cloudConfigurator.ConfigureCall.CallCount).To(Equal(1)) Expect(cloudConfigurator.ConfigureCall.Receives.Stack).To(Equal(cloudformation.Stack{ Name: "bbl-aws-some-random-string", Outputs: map[string]string{ "BOSHSecurityGroup": "some-bosh-security-group", "BOSHSubnet": "some-bosh-subnet", "BOSHSubnetAZ": "some-bosh-subnet-az", "BOSHEIP": "some-bosh-elastic-ip", "BOSHURL": "some-bosh-url", "BOSHUserAccessKey": "some-bosh-user-access-key", "BOSHUserSecretAccessKey": "some-bosh-user-secret-access-key", "ConcourseLoadBalancerURL": "some-lb-url", "ConcourseLoadBalancer": "some-lb-name", }, })) Expect(cloudConfigurator.ConfigureCall.Receives.AZs).To(ConsistOf("some-retrieved-az")) }) }) Context("when the load balancer type is cf", func() { It("generates a cloud config", func() { availabilityZoneRetriever.RetrieveCall.Returns.AZs = []string{"some-retrieved-az"} certificateDescriber.DescribeCall.Returns.Certificate = iam.Certificate{ Name: "some-certificate-name", ARN: "some-certificate-arn", Body: "some-certificate-body", } err := command.Execute([]string{}, storage.State{ Stack: storage.Stack{ LBType: "cf", CertificateName: "some-certificate-name", }, }) Expect(err).NotTo(HaveOccurred()) Expect(cloudConfigurator.ConfigureCall.CallCount).To(Equal(1)) Expect(cloudConfigurator.ConfigureCall.Receives.Stack).To(Equal(cloudformation.Stack{ Name: "bbl-aws-some-random-string", Outputs: map[string]string{ "BOSHSecurityGroup": "some-bosh-security-group", "BOSHSubnet": "some-bosh-subnet", "BOSHSubnetAZ": "some-bosh-subnet-az", "BOSHEIP": "some-bosh-elastic-ip", "BOSHURL": "some-bosh-url", "BOSHUserAccessKey": "some-bosh-user-access-key", "BOSHUserSecretAccessKey": "some-bosh-user-secret-access-key", "RouterLBURL": "some-router-lb-url", "RouterLB": "some-router-lb-name", "SSHProxyLBURL": "some-ssh-proxy-lb-url", "SSHProxyLB": "some-ssh-proxy-lb-name", }, })) Expect(cloudConfigurator.ConfigureCall.Receives.AZs).To(ConsistOf("some-retrieved-az")) }) }) }) Describe("reentrant", func() { Context("when the key pair fails to sync", func() { It("saves the keypair name and returns an error", func() { keyPairSynchronizer.SyncCall.Returns.Error = errors.New("error syncing key pair") err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("error syncing key pair")) Expect(stateStore.SetCall.CallCount).To(Equal(1)) Expect(stateStore.SetCall.Receives.State.KeyPair.Name).To(Equal("keypair-bbl-lake-time:stamp")) }) }) Context("when the availability zone retriever fails", func() { It("saves the public/private key and returns an error", func() { availabilityZoneRetriever.RetrieveCall.Returns.Error = errors.New("availability zone retrieve failed") err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("availability zone retrieve failed")) Expect(stateStore.SetCall.CallCount).To(Equal(2)) Expect(stateStore.SetCall.Receives.State.KeyPair.PrivateKey).To(Equal("some-private-key")) Expect(stateStore.SetCall.Receives.State.KeyPair.PublicKey).To(Equal("some-public-key")) }) }) Context("when the cloudformation fails", func() { It("saves the stack name and returns an error", func() { infrastructureManager.CreateCall.Returns.Error = errors.New("infrastructure creation failed") err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("infrastructure creation failed")) Expect(stateStore.SetCall.CallCount).To(Equal(3)) Expect(stateStore.SetCall.Receives.State.Stack.Name).To(Equal("stack-bbl-lake-time-stamp")) }) It("saves the private/public key and returns an error", func() { infrastructureManager.CreateCall.Returns.Error = errors.New("infrastructure creation failed") err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("infrastructure creation failed")) Expect(stateStore.SetCall.CallCount).To(Equal(3)) Expect(stateStore.SetCall.Receives.State.KeyPair.PrivateKey).To(Equal("some-private-key")) Expect(stateStore.SetCall.Receives.State.KeyPair.PublicKey).To(Equal("some-public-key")) }) }) Context("when the bosh cloud config fails", func() { It("saves the bosh properties and returns an error", func() { cloudConfigManager.UpdateCall.Returns.Error = errors.New("cloud config update failed") err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("cloud config update failed")) Expect(stateStore.SetCall.CallCount).To(Equal(4)) Expect(stateStore.SetCall.Receives.State.BOSH).To(Equal(storage.BOSH{ DirectorName: "bosh-bbl-lake-time:stamp", DirectorUsername: "user-some-random-string", DirectorPassword: "<PASSWORD>", DirectorAddress: "some-bosh-url", DirectorSSLCA: "updated-ca", DirectorSSLCertificate: "updated-certificate", DirectorSSLPrivateKey: "updated-private-key", State: boshinit.State{ "updated-key": "updated-value", }, Manifest: "name: bosh", })) }) }) }) Describe("state manipulation", func() { Context("aws credentials", func() { Context("when the credentials do not exist", func() { It("saves the credentials", func() { err := command.Execute([]string{ "--aws-access-key-id", "some-aws-access-key-id", "--aws-secret-access-key", "some-aws-secret-access-key", "--aws-region", "some-aws-region", }, storage.State{}) Expect(err).NotTo(HaveOccurred()) Expect(stateStore.SetCall.Receives.State.AWS).To(Equal(storage.AWS{ AccessKeyID: "some-aws-access-key-id", SecretAccessKey: "some-aws-secret-access-key", Region: "some-aws-region", })) }) Context("failure cases", func() { It("returns an error when saving the state fails", func() { stateStore.SetCall.Returns = []fakes.SetCallReturn{ { Error: errors.New("saving the state failed"), }, } err := command.Execute([]string{ "--aws-access-key-id", "some-aws-access-key-id", "--aws-secret-access-key", "some-aws-secret-access-key", "--aws-region", "some-aws-region", }, storage.State{}) Expect(err).To(MatchError("saving the state failed")) }) It("returns an error when parsing the flags fail", func() { err := command.Execute([]string{ "--aws-access-key-id", "some-aws-access-key-id", "--aws-secret-access-key", "some-aws-secret-access-key", "--unknown-flag", "some-value", "--aws-region", "some-aws-region", }, storage.State{}) Expect(err).To(MatchError("flag provided but not defined: -unknown-flag")) }) }) }) Context("when the credentials do exist", func() { It("overrides the credentials when they're passed in", func() { err := command.Execute([]string{ "--aws-access-key-id", "new-aws-access-key-id", "--aws-secret-access-key", "new-aws-secret-access-key", "--aws-region", "new-aws-region", }, storage.State{ AWS: storage.AWS{ AccessKeyID: "old-aws-access-key-id", SecretAccessKey: "old-aws-secret-access-key", Region: "old-aws-region", }, }) Expect(err).NotTo(HaveOccurred()) Expect(stateStore.SetCall.Receives.State.AWS).To(Equal(storage.AWS{ AccessKeyID: "new-aws-access-key-id", SecretAccessKey: "new-aws-secret-access-key", Region: "new-aws-region", })) }) It("does not override the credentials when they're not passed in", func() { err := command.Execute([]string{}, storage.State{ AWS: storage.AWS{ AccessKeyID: "aws-access-key-id", SecretAccessKey: "aws-secret-access-key", Region: "aws-region", }, }) Expect(err).NotTo(HaveOccurred()) Expect(stateStore.SetCall.Receives.State.AWS).To(Equal(storage.AWS{ AccessKeyID: "aws-access-key-id", SecretAccessKey: "aws-secret-access-key", Region: "aws-region", })) }) }) }) Context("aws keypair", func() { Context("when the keypair exists", func() { It("saves the given state unmodified", func() { keyPairSynchronizer.SyncCall.Returns.KeyPair = ec2.KeyPair{ Name: "some-existing-keypair", PrivateKey: "some-private-key", PublicKey: "some-public-key", } incomingState := storage.State{ KeyPair: storage.KeyPair{ Name: "some-existing-keypair", PrivateKey: "some-private-key", PublicKey: "some-public-key", }, } err := command.Execute([]string{}, incomingState) Expect(err).NotTo(HaveOccurred()) Expect(keyPairSynchronizer.SyncCall.Receives.KeyPair).To(Equal(ec2.KeyPair{ Name: "some-existing-keypair", PrivateKey: "some-private-key", PublicKey: "some-public-key", })) Expect(stateStore.SetCall.Receives.State.KeyPair).To(Equal(incomingState.KeyPair)) }) }) Context("when the keypair doesn't exist", func() { It("saves the state with a new key pair", func() { keyPairSynchronizer.SyncCall.Returns.KeyPair = ec2.KeyPair{ Name: "keypair-bbl-lake-time:stamp", PrivateKey: "some-private-key", PublicKey: "some-public-key", } err := command.Execute([]string{}, storage.State{}) Expect(err).NotTo(HaveOccurred()) Expect(keyPairSynchronizer.SyncCall.Receives.KeyPair).To(Equal(ec2.KeyPair{ Name: "keypair-bbl-lake-time:stamp", })) actualState := stateStore.SetCall.Receives.State Expect(actualState.KeyPair).To(Equal(storage.KeyPair{ Name: "keypair-bbl-lake-time:stamp", PrivateKey: "some-private-key", PublicKey: "some-public-key", })) }) }) }) Context("cloudformation", func() { Context("when the stack name doesn't exist", func() { It("populates a new stack name", func() { incomingState := storage.State{} err := command.Execute([]string{}, incomingState) Expect(err).NotTo(HaveOccurred()) state := stateStore.SetCall.Receives.State Expect(state.Stack.Name).To(Equal("stack-bbl-lake-time-stamp")) }) }) Context("when the stack name exists", func() { It("does not modify the state", func() { incomingState := storage.State{ Stack: storage.Stack{ Name: "some-other-stack-name", }, } err := command.Execute([]string{}, incomingState) Expect(err).NotTo(HaveOccurred()) state := stateStore.SetCall.Receives.State Expect(state.Stack.Name).To(Equal("some-other-stack-name")) }) }) }) Context("env id", func() { Context("when the env id doesn't exist", func() { It("populates a new bbl env id", func() { envIDGenerator.GenerateCall.Returns.EnvID = "bbl-lake-time:stamp" err := command.Execute([]string{}, storage.State{}) Expect(err).NotTo(HaveOccurred()) Expect(stateStore.SetCall.Receives.State.EnvID).To(Equal("bbl-lake-time:stamp")) }) }) Context("when the env id exists", func() { It("does not modify the state", func() { incomingState := storage.State{ EnvID: "bbl-lake-time:stamp", } err := command.Execute([]string{}, incomingState) Expect(err).NotTo(HaveOccurred()) state := stateStore.SetCall.Receives.State Expect(state.EnvID).To(Equal("bbl-lake-time:stamp")) }) }) }) Describe("bosh", func() { BeforeEach(func() { infrastructureManager.ExistsCall.Returns.Exists = true }) Context("boshinit manifest", func() { It("writes the boshinit manifest", func() { err := command.Execute([]string{}, storage.State{}) Expect(err).NotTo(HaveOccurred()) state := stateStore.SetCall.Receives.State Expect(state.BOSH.Manifest).To(ContainSubstring("name: bosh")) }) It("writes the updated boshinit manifest", func() { boshDeployer.DeployCall.Returns.Output = boshinit.DeployOutput{ BOSHInitManifest: "name: updated-bosh", } err := command.Execute([]string{}, storage.State{ BOSH: storage.BOSH{ Manifest: "name: bosh", }, }) Expect(err).NotTo(HaveOccurred()) state := stateStore.SetCall.Receives.State Expect(state.BOSH.Manifest).To(ContainSubstring("name: updated-bosh")) }) }) Context("bosh state", func() { It("writes the bosh state", func() { err := command.Execute([]string{}, storage.State{}) Expect(err).NotTo(HaveOccurred()) state := stateStore.SetCall.Receives.State Expect(state.BOSH.State).To(Equal(map[string]interface{}{ "updated-key": "updated-value", })) }) It("writes the updated boshinit manifest", func() { boshDeployer.DeployCall.Returns.Output = boshinit.DeployOutput{ BOSHInitState: boshinit.State{ "some-key": "some-value", "some-other-key": "some-other-value", }, } err := command.Execute([]string{}, storage.State{ BOSH: storage.BOSH{ Manifest: "name: bosh", State: boshinit.State{ "some-key": "some-value", }, }, }) Expect(err).NotTo(HaveOccurred()) state := stateStore.SetCall.Receives.State Expect(state.BOSH.State).To(Equal(map[string]interface{}{ "some-key": "some-value", "some-other-key": "some-other-value", })) }) }) It("writes the bosh director address", func() { err := command.Execute([]string{}, storage.State{}) Expect(err).NotTo(HaveOccurred()) state := stateStore.SetCall.Receives.State Expect(state.BOSH.DirectorAddress).To(ContainSubstring("some-bosh-url")) }) It("writes the bosh director name", func() { err := command.Execute([]string{}, storage.State{}) Expect(err).NotTo(HaveOccurred()) state := stateStore.SetCall.Receives.State Expect(state.BOSH.DirectorName).To(ContainSubstring("bosh-bbl-lake-time:stamp")) }) Context("when the bosh director ssl keypair exists", func() { It("returns the given state unmodified", func() { err := command.Execute([]string{}, storage.State{ BOSH: storage.BOSH{ DirectorSSLCA: "some-ca", DirectorSSLCertificate: "some-certificate", DirectorSSLPrivateKey: "some-private-key", }, }) Expect(err).NotTo(HaveOccurred()) state := stateStore.SetCall.Receives.State Expect(state.BOSH.DirectorSSLCA).To(Equal("some-ca")) Expect(state.BOSH.DirectorSSLCertificate).To(Equal("some-certificate")) Expect(state.BOSH.DirectorSSLPrivateKey).To(Equal("some-private-key")) }) }) Context("when the bosh director ssl keypair doesn't exist", func() { It("returns the state with a new key pair", func() { err := command.Execute([]string{}, storage.State{}) Expect(err).NotTo(HaveOccurred()) state := stateStore.SetCall.Receives.State Expect(state.BOSH.DirectorSSLCA).To(Equal("updated-ca")) Expect(state.BOSH.DirectorSSLCertificate).To(Equal("updated-certificate")) Expect(state.BOSH.DirectorSSLPrivateKey).To(Equal("updated-private-key")) Expect(state.BOSH.State).To(Equal(map[string]interface{}{ "updated-key": "updated-value", })) }) }) Context("when there are no director credentials", func() { It("deploys with randomized director credentials", func() { err := command.Execute([]string{}, storage.State{}) Expect(err).NotTo(HaveOccurred()) state := stateStore.SetCall.Receives.State Expect(boshDeployer.DeployCall.Receives.Input.DirectorUsername).To(Equal("user-some-random-string")) Expect(boshDeployer.DeployCall.Receives.Input.DirectorPassword).To(Equal("<PASSWORD>")) Expect(state.BOSH.DirectorPassword).To(Equal("<PASSWORD>-<PASSWORD>")) }) }) Context("when there are director credentials", func() { It("uses the old credentials", func() { incomingState := storage.State{ BOSH: storage.BOSH{ DirectorUsername: "some-director-username", DirectorPassword: "<PASSWORD>", }, } err := command.Execute([]string{}, incomingState) Expect(err).NotTo(HaveOccurred()) Expect(boshDeployer.DeployCall.Receives.Input.DirectorUsername).To(Equal("some-director-username")) Expect(boshDeployer.DeployCall.Receives.Input.DirectorPassword).To(Equal("<PASSWORD>")) }) }) Context("when the bosh credentials don't exist", func() { It("returns the state with random credentials", func() { boshDeployer.DeployCall.Returns.Output = boshinit.DeployOutput{ Credentials: boshInitCredentials, } err := command.Execute([]string{}, storage.State{}) Expect(err).NotTo(HaveOccurred()) state := stateStore.SetCall.Receives.State Expect(state.BOSH.Credentials).To(Equal(boshInitCredentials)) }) Context("when the bosh credentials exist in the bbl state", func() { It("deploys with those credentials and returns the state with the same credentials", func() { boshDeployer.DeployCall.Returns.Output = boshinit.DeployOutput{ Credentials: boshInitCredentials, } err := command.Execute([]string{}, storage.State{ BOSH: storage.BOSH{Credentials: boshInitCredentials}, }) Expect(err).NotTo(HaveOccurred()) state := stateStore.SetCall.Receives.State Expect(boshDeployer.DeployCall.Receives.Input.Credentials).To(Equal(boshInitCredentials)) Expect(state.BOSH.Credentials).To(Equal(boshInitCredentials)) }) }) }) }) }) Context("failure cases", func() { It("returns an error when the certificate cannot be described", func() { certificateDescriber.DescribeCall.Returns.Error = errors.New("failed to describe") err := command.Execute([]string{}, storage.State{ Stack: storage.Stack{ LBType: "concourse", }, }) Expect(err).To(MatchError("failed to describe")) }) It("returns an error when the cloud config cannot be uploaded", func() { cloudConfigManager.UpdateCall.Returns.Error = errors.New("failed to update") err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("failed to update")) }) It("returns an error when the BOSH state exists, but the cloudformation stack does not", func() { infrastructureManager.ExistsCall.Returns.Exists = false err := command.Execute([]string{}, storage.State{ AWS: storage.AWS{ Region: "some-aws-region", }, BOSH: storage.BOSH{ DirectorAddress: "some-director-address", }, Stack: storage.Stack{ Name: "some-stack-name", }, }) Expect(infrastructureManager.ExistsCall.Receives.StackName).To(Equal("some-stack-name")) Expect(err).To(MatchError("Found BOSH data in state directory, " + "but Cloud Formation stack \"some-stack-name\" cannot be found for region \"some-aws-region\" and given " + "AWS credentials. bbl cannot safely proceed. Open an issue on GitHub at " + "https://github.com/cloudfoundry/bosh-bootloader/issues/new if you need assistance.")) Expect(infrastructureManager.CreateCall.CallCount).To(Equal(0)) }) It("returns an error when checking if the infrastructure exists fails", func() { infrastructureManager.ExistsCall.Returns.Error = errors.New("error checking if stack exists") err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("error checking if stack exists")) }) It("returns an error when infrastructure cannot be created", func() { infrastructureManager.CreateCall.Returns.Error = errors.New("infrastructure creation failed") err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("infrastructure creation failed")) }) It("returns an error when bosh cannot be deployed", func() { boshDeployer.DeployCall.Returns.Error = errors.New("cannot deploy bosh") err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("cannot deploy bosh")) }) It("returns an error when it cannot generate a string for the bosh director credentials", func() { stringGenerator.GenerateCall.Stub = func(prefix string, length int) (string, error) { if prefix != "bbl-aws-" { return "", errors.New("cannot generate string") } return "", nil } err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("cannot generate string")) }) It("returns an error when availability zones cannot be retrieved", func() { availabilityZoneRetriever.RetrieveCall.Returns.Error = errors.New("availability zone could not be retrieved") err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("availability zone could not be retrieved")) }) It("returns an error when env id generator fails", func() { envIDGenerator.GenerateCall.Returns.Error = errors.New("env id generation failed") err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("env id generation failed")) }) It("returns an error when state store fails to set the state before syncing the keypair", func() { stateStore.SetCall.Returns = []fakes.SetCallReturn{{errors.New("failed to set state")}} err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("failed to set state")) }) It("returns an error when state store fails to set the state before retrieving availability zones", func() { stateStore.SetCall.Returns = []fakes.SetCallReturn{{}, {errors.New("failed to set state")}} err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("failed to set state")) }) It("returns an error when state store fails to set the state before creating the stack", func() { stateStore.SetCall.Returns = []fakes.SetCallReturn{{}, {}, {errors.New("failed to set state")}} err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("failed to set state")) }) It("returns an error when state store fails to set the state before updating the cloud config", func() { stateStore.SetCall.Returns = []fakes.SetCallReturn{{}, {}, {}, {errors.New("failed to set state")}} err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("failed to set state")) }) It("returns an error when state store fails to set the state before method exits", func() { stateStore.SetCall.Returns = []fakes.SetCallReturn{{}, {}, {}, {}, {errors.New("failed to set state")}} err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("failed to set state")) }) It("returns an error when only some of the AWS parameters are provided", func() { err := command.Execute([]string{"--aws-access-key-id", "some-key-id", "--aws-region", "some-region"}, storage.State{}) Expect(err).To(MatchError("AWS secret access key must be provided")) }) It("returns an error when no AWS parameters are provided and the bbl-state AWS values are empty", func() { awsCredentialValidator.ValidateCall.Returns.Error = errors.New("AWS secret access key must be provided") err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("AWS secret access key must be provided")) }) }) }) }) <file_sep>/boshinit/manifests/resource_pools_manifest_builder.go package manifests type ResourcePoolsManifestBuilder struct{} func NewResourcePoolsManifestBuilder() ResourcePoolsManifestBuilder { return ResourcePoolsManifestBuilder{} } func (r ResourcePoolsManifestBuilder) Build(manifestProperties ManifestProperties, stemcellURL string, stemcellSHA1 string) []ResourcePool { return []ResourcePool{ { Name: "vms", Network: "private", Stemcell: Stemcell{ URL: stemcellURL, SHA1: stemcellSHA1, }, CloudProperties: ResourcePoolCloudProperties{ InstanceType: "m3.xlarge", EphemeralDisk: EphemeralDisk{ Size: 25000, Type: "gp2", }, AvailabilityZone: manifestProperties.AvailabilityZone, }, }, } } <file_sep>/aws/clientmanager/client_provider.go package clientmanager import ( "github.com/cloudfoundry/bosh-bootloader/aws" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation" "github.com/cloudfoundry/bosh-bootloader/aws/ec2" "github.com/cloudfoundry/bosh-bootloader/aws/iam" ) type ClientProvider struct { EndpointOverride string ec2Client ec2.Client cloudformationClient cloudformation.Client iamClient iam.Client } func (c *ClientProvider) SetConfig(config aws.Config) { config.EndpointOverride = c.EndpointOverride c.ec2Client = ec2.NewClient(config) c.cloudformationClient = cloudformation.NewClient(config) c.iamClient = iam.NewClient(config) } func (c *ClientProvider) GetEC2Client() ec2.Client { return c.ec2Client } func (c *ClientProvider) GetCloudFormationClient() cloudformation.Client { return c.cloudformationClient } func (c *ClientProvider) GetIAMClient() iam.Client { return c.iamClient } <file_sep>/bosh/cloud_configurator.go package bosh import ( "fmt" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation" ) type CloudConfigurator struct { logger logger generator cloudConfigGenerator } type logger interface { Step(message string, a ...interface{}) Println(string) } func NewCloudConfigurator(logger logger, generator cloudConfigGenerator) CloudConfigurator { return CloudConfigurator{ logger: logger, generator: generator, } } func (c CloudConfigurator) Configure(stack cloudformation.Stack, azs []string) CloudConfigInput { var subnets []SubnetInput for az := range azs { az++ subnets = append(subnets, SubnetInput{ AZ: stack.Outputs[fmt.Sprintf("InternalSubnet%dAZ", az)], Subnet: stack.Outputs[fmt.Sprintf("InternalSubnet%dName", az)], CIDR: stack.Outputs[fmt.Sprintf("InternalSubnet%dCIDR", az)], SecurityGroups: []string{stack.Outputs["InternalSecurityGroup"]}, }) } cloudConfigInput := CloudConfigInput{ AZs: azs, Subnets: subnets, LBs: c.populateLBs(stack), } return cloudConfigInput } func (CloudConfigurator) populateLBs(stack cloudformation.Stack) []LoadBalancerExtension { lbs := []LoadBalancerExtension{} if value := stack.Outputs["ConcourseLoadBalancer"]; value != "" { lbs = append(lbs, LoadBalancerExtension{ Name: "lb", ELBName: value, SecurityGroups: []string{ stack.Outputs["ConcourseInternalSecurityGroup"], stack.Outputs["InternalSecurityGroup"], }, }) } if value := stack.Outputs["CFRouterLoadBalancer"]; value != "" { lbs = append(lbs, LoadBalancerExtension{ Name: "router-lb", ELBName: value, SecurityGroups: []string{ stack.Outputs["CFRouterInternalSecurityGroup"], stack.Outputs["InternalSecurityGroup"], }, }) } if value := stack.Outputs["CFSSHProxyLoadBalancer"]; value != "" { lbs = append(lbs, LoadBalancerExtension{ Name: "ssh-proxy-lb", ELBName: value, SecurityGroups: []string{ stack.Outputs["CFSSHProxyInternalSecurityGroup"], stack.Outputs["InternalSecurityGroup"], }, }) } return lbs } <file_sep>/aws/cloudformation/templates/security_group_template_builder_test.go package templates_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" ) var _ = Describe("SecurityGroupTemplateBuilder", func() { var builder templates.SecurityGroupTemplateBuilder BeforeEach(func() { builder = templates.NewSecurityGroupTemplateBuilder() }) Describe("InternalSecurityGroup", func() { It("returns a template containing all the fields for internal security group", func() { securityGroup := builder.InternalSecurityGroup() Expect(securityGroup.Resources).To(HaveLen(5)) Expect(securityGroup.Resources).To(HaveKeyWithValue("InternalSecurityGroup", templates.Resource{ Type: "AWS::EC2::SecurityGroup", Properties: templates.SecurityGroup{ VpcId: templates.Ref{"VPC"}, GroupDescription: "Internal", SecurityGroupEgress: []templates.SecurityGroupEgress{}, SecurityGroupIngress: []templates.SecurityGroupIngress{ { IpProtocol: "tcp", FromPort: "0", ToPort: "65535", }, { IpProtocol: "udp", FromPort: "0", ToPort: "65535", }, { CidrIp: "0.0.0.0/0", IpProtocol: "icmp", FromPort: "-1", ToPort: "-1", }, }, }, })) Expect(securityGroup.Resources).To(HaveKeyWithValue("InternalSecurityGroupIngressTCPfromBOSH", templates.Resource{ Type: "AWS::EC2::SecurityGroupIngress", Properties: templates.SecurityGroupIngress{ GroupId: templates.Ref{"InternalSecurityGroup"}, SourceSecurityGroupId: templates.Ref{"BOSHSecurityGroup"}, IpProtocol: "tcp", FromPort: "0", ToPort: "65535", }, })) Expect(securityGroup.Resources).To(HaveKeyWithValue("InternalSecurityGroupIngressUDPfromBOSH", templates.Resource{ Type: "AWS::EC2::SecurityGroupIngress", Properties: templates.SecurityGroupIngress{ GroupId: templates.Ref{"InternalSecurityGroup"}, SourceSecurityGroupId: templates.Ref{"BOSHSecurityGroup"}, IpProtocol: "udp", FromPort: "0", ToPort: "65535", }, })) Expect(securityGroup.Resources).To(HaveKeyWithValue("InternalSecurityGroupIngressTCPfromSelf", templates.Resource{ Type: "AWS::EC2::SecurityGroupIngress", Properties: templates.SecurityGroupIngress{ GroupId: templates.Ref{"InternalSecurityGroup"}, SourceSecurityGroupId: templates.Ref{"InternalSecurityGroup"}, IpProtocol: "tcp", FromPort: "0", ToPort: "65535", }, })) Expect(securityGroup.Resources).To(HaveKeyWithValue("InternalSecurityGroupIngressUDPfromSelf", templates.Resource{ Type: "AWS::EC2::SecurityGroupIngress", Properties: templates.SecurityGroupIngress{ GroupId: templates.Ref{"InternalSecurityGroup"}, SourceSecurityGroupId: templates.Ref{"InternalSecurityGroup"}, IpProtocol: "udp", FromPort: "0", ToPort: "65535", }, })) Expect(securityGroup.Outputs).To(HaveLen(1)) Expect(securityGroup.Outputs).To(HaveKeyWithValue("InternalSecurityGroup", templates.Output{ Value: templates.Ref{"InternalSecurityGroup"}, })) }) }) Describe("BOSHSecurityGroup", func() { It("returns a template containing the bosh security group", func() { securityGroup := builder.BOSHSecurityGroup() Expect(securityGroup.Parameters).To(HaveLen(1)) Expect(securityGroup.Parameters).To(HaveKeyWithValue("BOSHInboundCIDR", templates.Parameter{ Description: "CIDR to permit access to BOSH (e.g. 192.168.127.12/32 for your specific IP)", Type: "String", Default: "0.0.0.0/0", })) Expect(securityGroup.Outputs).To(HaveLen(1)) Expect(securityGroup.Outputs).To(HaveKeyWithValue("BOSHSecurityGroup", templates.Output{ Value: templates.Ref{"BOSHSecurityGroup"}, })) Expect(securityGroup.Resources).To(HaveLen(1)) Expect(securityGroup.Resources).To(HaveKeyWithValue("BOSHSecurityGroup", templates.Resource{ Type: "AWS::EC2::SecurityGroup", Properties: templates.SecurityGroup{ VpcId: templates.Ref{"VPC"}, GroupDescription: "BOSH", SecurityGroupEgress: []templates.SecurityGroupEgress{}, SecurityGroupIngress: []templates.SecurityGroupIngress{ { CidrIp: templates.Ref{"BOSHInboundCIDR"}, IpProtocol: "tcp", FromPort: "22", ToPort: "22", }, { CidrIp: templates.Ref{"BOSHInboundCIDR"}, IpProtocol: "tcp", FromPort: "6868", ToPort: "6868", }, { CidrIp: templates.Ref{"BOSHInboundCIDR"}, IpProtocol: "tcp", FromPort: "25555", ToPort: "25555", }, { SourceSecurityGroupId: templates.Ref{"InternalSecurityGroup"}, IpProtocol: "tcp", FromPort: "0", ToPort: "65535", }, { SourceSecurityGroupId: templates.Ref{"InternalSecurityGroup"}, IpProtocol: "udp", FromPort: "0", ToPort: "65535", }, }, }, })) }) }) Context("when building security groups for load balancers", func() { var ( loadBalancerTemplate templates.Template ) BeforeEach(func() { loadBalancerTemplate = templates.Template{ Resources: map[string]templates.Resource{ "some-load-balancer": { DependsOn: "VPCGatewayAttachment", Type: "AWS::ElasticLoadBalancing::LoadBalancer", Properties: templates.ElasticLoadBalancingLoadBalancer{ Listeners: []templates.Listener{ { Protocol: "tcp", LoadBalancerPort: "1000", InstanceProtocol: "tcp", InstancePort: "2222", }, { Protocol: "http", LoadBalancerPort: "80", InstanceProtocol: "http", InstancePort: "8080", }, { Protocol: "https", LoadBalancerPort: "4443", InstanceProtocol: "tcp", InstancePort: "8080", }, { Protocol: "ssl", LoadBalancerPort: "443", InstanceProtocol: "tcp", InstancePort: "8080", }, }, }, }, }, } }) Describe("LBSecurityGroup", func() { It("returns a load balancer security group based on load balancer template", func() { securityGroup := builder.LBSecurityGroup("some-security-group", "some-group-description", "some-load-balancer", loadBalancerTemplate) Expect(securityGroup.Resources).To(HaveLen(1)) Expect(securityGroup.Resources).To(HaveKeyWithValue("some-security-group", templates.Resource{ Type: "AWS::EC2::SecurityGroup", Properties: templates.SecurityGroup{ VpcId: templates.Ref{"VPC"}, GroupDescription: "some-group-description", SecurityGroupEgress: []templates.SecurityGroupEgress{}, SecurityGroupIngress: []templates.SecurityGroupIngress{ { CidrIp: "0.0.0.0/0", IpProtocol: "tcp", FromPort: "1000", ToPort: "1000", }, { CidrIp: "0.0.0.0/0", IpProtocol: "tcp", FromPort: "80", ToPort: "80", }, { CidrIp: "0.0.0.0/0", IpProtocol: "tcp", FromPort: "4443", ToPort: "4443", }, { CidrIp: "0.0.0.0/0", IpProtocol: "tcp", FromPort: "443", ToPort: "443", }, }, }, })) }) }) Describe("LBInternalSecurityGroup", func() { It("returns a load balancer internal security group based on load balancer template", func() { securityGroup := builder.LBInternalSecurityGroup("some-internal-security-group", "some-security-group", "some-group-description", "some-load-balancer", loadBalancerTemplate) Expect(securityGroup.Resources).To(HaveLen(1)) Expect(securityGroup.Resources).To(HaveKeyWithValue("some-internal-security-group", templates.Resource{ Type: "AWS::EC2::SecurityGroup", Properties: templates.SecurityGroup{ VpcId: templates.Ref{"VPC"}, GroupDescription: "some-group-description", SecurityGroupEgress: []templates.SecurityGroupEgress{}, SecurityGroupIngress: []templates.SecurityGroupIngress{ { SourceSecurityGroupId: templates.Ref{"some-security-group"}, IpProtocol: "tcp", FromPort: "2222", ToPort: "2222", }, { SourceSecurityGroupId: templates.Ref{"some-security-group"}, IpProtocol: "tcp", FromPort: "8080", ToPort: "8080", }, }, }, })) Expect(securityGroup.Outputs).To(HaveLen(1)) Expect(securityGroup.Outputs).To(HaveKeyWithValue("some-internal-security-group", templates.Output{ Value: templates.Ref{"some-internal-security-group"}, })) }) }) }) }) <file_sep>/aws/cloudformation/tags.go package cloudformation import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/cloudformation" ) type Tags []Tag type Tag struct { Key string Value string } func (t Tags) toAWSTags() []*cloudformation.Tag { awsTags := []*cloudformation.Tag{} for _, tag := range t { awsTags = append(awsTags, &cloudformation.Tag{ Key: aws.String(tag.Key), Value: aws.String(tag.Value), }) } return awsTags } <file_sep>/bosh/disk_types_generator_test.go package bosh_test import ( "github.com/cloudfoundry/bosh-bootloader/bosh" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("DiskTypesGenerator", func() { Describe("Generate", func() { It("returns a slice of disk types for cloud config", func() { generator := bosh.NewDiskTypesGenerator() diskTypes := generator.Generate() Expect(diskTypes).To(ConsistOf( bosh.DiskType{ Name: "1GB", DiskSize: 1024, CloudProperties: bosh.DiskTypeCloudProperties{ Type: "gp2", Encrypted: true, }, }, bosh.DiskType{ Name: "5GB", DiskSize: 5120, CloudProperties: bosh.DiskTypeCloudProperties{ Type: "gp2", Encrypted: true, }, }, bosh.DiskType{ Name: "10GB", DiskSize: 10240, CloudProperties: bosh.DiskTypeCloudProperties{ Type: "gp2", Encrypted: true, }, }, bosh.DiskType{ Name: "50GB", DiskSize: 51200, CloudProperties: bosh.DiskTypeCloudProperties{ Type: "gp2", Encrypted: true, }, }, bosh.DiskType{ Name: "100GB", DiskSize: 102400, CloudProperties: bosh.DiskTypeCloudProperties{ Type: "gp2", Encrypted: true, }, }, bosh.DiskType{ Name: "500GB", DiskSize: 512000, CloudProperties: bosh.DiskTypeCloudProperties{ Type: "gp2", Encrypted: true, }, }, bosh.DiskType{ Name: "1TB", DiskSize: 1048576, CloudProperties: bosh.DiskTypeCloudProperties{ Type: "gp2", Encrypted: true, }, }, )) }) }) }) <file_sep>/boshinit/manifests/networks_manifest_builder_test.go package manifests_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/cloudfoundry/bosh-bootloader/boshinit/manifests" ) var _ = Describe("NetworksManifestBuilder", func() { var networksManifestBuilder manifests.NetworksManifestBuilder BeforeEach(func() { networksManifestBuilder = manifests.NewNetworksManifestBuilder() }) Describe("Build", func() { It("returns all networks for manifest", func() { networks := networksManifestBuilder.Build(manifests.ManifestProperties{SubnetID: "subnet-12345"}) Expect(networks).To(HaveLen(2)) Expect(networks).To(ConsistOf([]manifests.Network{ { Name: "private", Type: "manual", Subnets: []manifests.Subnet{ { Range: "10.0.0.0/24", Gateway: "10.0.0.1", DNS: []string{"10.0.0.2"}, CloudProperties: manifests.NetworksCloudProperties{ Subnet: "subnet-12345", }, }, }, }, { Name: "public", Type: "vip", }, })) }) }) }) <file_sep>/ssl/keypair_generator_test.go package ssl_test import ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" "errors" "net" "strings" "github.com/cloudfoundry/bosh-bootloader/fakes" "github.com/cloudfoundry/bosh-bootloader/ssl" certstrappkix "github.com/square/certstrap/pkix" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("KeyPairGenerator", func() { var ( generator ssl.KeyPairGenerator fakePrivateKeyGenerator *fakes.PrivateKeyGenerator fakeCertstrapPKIX *fakes.CertstrapPKIX caPrivateKey *rsa.PrivateKey caPublicKey *rsa.PublicKey privateKey *rsa.PrivateKey publicKey *rsa.PublicKey ca *certstrappkix.Certificate csr *certstrappkix.CertificateSigningRequest signedCertificate *certstrappkix.Certificate ) BeforeEach(func() { fakePrivateKeyGenerator = &fakes.PrivateKeyGenerator{} fakeCertstrapPKIX = &fakes.CertstrapPKIX{} generator = ssl.NewKeyPairGenerator( fakePrivateKeyGenerator.GenerateKey, fakeCertstrapPKIX.CreateCertificateAuthority, fakeCertstrapPKIX.CreateCertificateSigningRequest, fakeCertstrapPKIX.CreateCertificateHost, ) var err error caPrivateKey, caPublicKey, err = decodeAndParsePrivateKey(caPrivateKeyPEM) Expect(err).NotTo(HaveOccurred()) privateKey, publicKey, err = decodeAndParsePrivateKey(privateKeyPEM) Expect(err).NotTo(HaveOccurred()) ca, err = certstrappkix.NewCertificateFromPEM([]byte(caPEM)) Expect(err).NotTo(HaveOccurred()) csr, err = certstrappkix.NewCertificateSigningRequestFromPEM([]byte(csrPEM)) Expect(err).NotTo(HaveOccurred()) signedCertificate, err = certstrappkix.NewCertificateFromPEM([]byte(certificatePEM)) Expect(err).NotTo(HaveOccurred()) fakeCertstrapPKIX.CreateCertificateAuthorityCall.Returns.Certificate = ca fakeCertstrapPKIX.CreateCertificateSigningRequestCall.Returns.CertificateSigningRequest = csr fakeCertstrapPKIX.CreateCertificateHostCall.Returns.Certificate = signedCertificate fakePrivateKeyGenerator.GenerateKeyCall.Stub = func() (*rsa.PrivateKey, error) { if fakePrivateKeyGenerator.GenerateKeyCall.CallCount == 0 { return caPrivateKey, nil } return privateKey, nil } }) Describe("Generate", func() { It("generates an SSL certificate signed by generated CA", func() { generatedKeyPair, err := generator.Generate("BOSH Bootloader", "127.0.0.1") Expect(err).NotTo(HaveOccurred()) Expect(fakePrivateKeyGenerator.GenerateKeyCall.CallCount).To(Equal(2)) Expect(fakePrivateKeyGenerator.GenerateKeyCall.Receives[0].Random).To(Equal(rand.Reader)) Expect(fakePrivateKeyGenerator.GenerateKeyCall.Receives[0].Bits).To(Equal(2048)) Expect(fakePrivateKeyGenerator.GenerateKeyCall.Receives[1].Random).To(Equal(rand.Reader)) Expect(fakePrivateKeyGenerator.GenerateKeyCall.Receives[1].Bits).To(Equal(2048)) Expect(fakeCertstrapPKIX.CreateCertificateAuthorityCall.CallCount).To(Equal(1)) Expect(fakeCertstrapPKIX.CreateCertificateAuthorityCall.Receives.Key.Private).To(Equal(caPrivateKey)) Expect(fakeCertstrapPKIX.CreateCertificateAuthorityCall.Receives.Key.Public).To(Equal(caPublicKey)) Expect(fakeCertstrapPKIX.CreateCertificateAuthorityCall.Receives.OrganizationalUnit).To(Equal("Cloud Foundry")) Expect(fakeCertstrapPKIX.CreateCertificateAuthorityCall.Receives.Years).To(Equal(2)) Expect(fakeCertstrapPKIX.CreateCertificateAuthorityCall.Receives.Organization).To(Equal("Cloud Foundry")) Expect(fakeCertstrapPKIX.CreateCertificateAuthorityCall.Receives.Country).To(Equal("USA")) Expect(fakeCertstrapPKIX.CreateCertificateAuthorityCall.Receives.Province).To(Equal("CA")) Expect(fakeCertstrapPKIX.CreateCertificateAuthorityCall.Receives.Locality).To(Equal("San Francisco")) Expect(fakeCertstrapPKIX.CreateCertificateAuthorityCall.Receives.CommonName).To(Equal("BOSH Bootloader")) Expect(fakeCertstrapPKIX.CreateCertificateSigningRequestCall.CallCount).To(Equal(1)) Expect(fakeCertstrapPKIX.CreateCertificateSigningRequestCall.Receives.Key.Private).To(Equal(privateKey)) Expect(fakeCertstrapPKIX.CreateCertificateSigningRequestCall.Receives.Key.Public).To(Equal(publicKey)) Expect(fakeCertstrapPKIX.CreateCertificateSigningRequestCall.Receives.OrganizationalUnit).To(Equal("Cloud Foundry")) Expect(fakeCertstrapPKIX.CreateCertificateSigningRequestCall.Receives.IpList).To(Equal([]net.IP{net.ParseIP("127.0.0.1")})) Expect(fakeCertstrapPKIX.CreateCertificateSigningRequestCall.Receives.DomainList).To(BeNil()) Expect(fakeCertstrapPKIX.CreateCertificateSigningRequestCall.Receives.Organization).To(Equal("Cloud Foundry")) Expect(fakeCertstrapPKIX.CreateCertificateSigningRequestCall.Receives.Country).To(Equal("USA")) Expect(fakeCertstrapPKIX.CreateCertificateSigningRequestCall.Receives.Province).To(Equal("CA")) Expect(fakeCertstrapPKIX.CreateCertificateSigningRequestCall.Receives.Locality).To(Equal("San Francisco")) Expect(fakeCertstrapPKIX.CreateCertificateSigningRequestCall.Receives.CommonName).To(Equal("127.0.0.1")) Expect(fakeCertstrapPKIX.CreateCertificateHostCall.CallCount).To(Equal(1)) Expect(fakeCertstrapPKIX.CreateCertificateHostCall.Receives.CrtAuth).To(Equal(ca)) Expect(fakeCertstrapPKIX.CreateCertificateHostCall.Receives.KeyAuth.Private).To(Equal(caPrivateKey)) Expect(fakeCertstrapPKIX.CreateCertificateHostCall.Receives.KeyAuth.Public).To(Equal(caPublicKey)) Expect(fakeCertstrapPKIX.CreateCertificateHostCall.Receives.Csr).To(Equal(csr)) Expect(fakeCertstrapPKIX.CreateCertificateHostCall.Receives.Years).To(Equal(2)) Expect(strings.TrimSpace(string(generatedKeyPair.CA))).To(Equal(caPEM)) Expect(strings.TrimSpace(string(generatedKeyPair.Certificate))).To(Equal(certificatePEM)) Expect(strings.TrimSpace(string(generatedKeyPair.PrivateKey))).To(Equal(privateKeyPEM)) }) Context("failure cases", func() { Context("when private key generation fails for CA", func() { It("returns error", func() { fakePrivateKeyGenerator.GenerateKeyCall.Stub = func() (*rsa.PrivateKey, error) { return nil, errors.New("private key generation failed for ca") } _, err := generator.Generate("", "127.0.0.1") Expect(err).To(MatchError("private key generation failed for ca")) }) }) Context("when private key generation fails for certificate", func() { It("returns error", func() { fakePrivateKeyGenerator.GenerateKeyCall.Stub = func() (*rsa.PrivateKey, error) { if fakePrivateKeyGenerator.GenerateKeyCall.CallCount != 0 { return nil, errors.New("private key generation failed for certificate") } return privateKey, nil } _, err := generator.Generate("", "127.0.0.1") Expect(err).To(MatchError("private key generation failed for certificate")) }) }) It("errors when create certificate authority fails", func() { fakeCertstrapPKIX.CreateCertificateAuthorityCall.Returns.Error = errors.New("create certificate authority failed") _, err := generator.Generate("", "127.0.0.1") Expect(err).To(MatchError("create certificate authority failed")) }) It("errors when create certificate signing request fails", func() { fakeCertstrapPKIX.CreateCertificateSigningRequestCall.Returns.Error = errors.New("create certificate signing request failed") _, err := generator.Generate("", "127.0.0.1") Expect(err).To(MatchError("create certificate signing request failed")) }) It("errors when create certificate host fails", func() { fakeCertstrapPKIX.CreateCertificateHostCall.Returns.Error = errors.New("could not generate certificate host") _, err := generator.Generate("", "127.0.0.1") Expect(err).To(MatchError("could not generate certificate host")) }) }) }) }) func decodeAndParsePrivateKey(privateKeyPEM string) (*rsa.PrivateKey, *rsa.PublicKey, error) { keyBlock, _ := pem.Decode([]byte(privateKeyPEM)) privateKey, err := x509.ParsePKCS1PrivateKey(keyBlock.Bytes) if err != nil { return nil, nil, err } return privateKey, &privateKey.PublicKey, nil } <file_sep>/boshinit/manifests/jobs_manifest_builder.go package manifests type JobsManifestBuilder struct { stringGenerator stringGenerator } func NewJobsManifestBuilder(stringGenerator stringGenerator) JobsManifestBuilder { return JobsManifestBuilder{ stringGenerator: stringGenerator, } } func (j JobsManifestBuilder) Build(manifestProperties ManifestProperties) ([]Job, ManifestProperties, error) { sharedPropertiesManifestBuilder := NewSharedPropertiesManifestBuilder() manifestProperties, err := j.generateInternalCredentials(manifestProperties) if err != nil { return nil, ManifestProperties{}, err } jobPropertiesManifestBuilder := NewJobPropertiesManifestBuilder( manifestProperties.Credentials.NatsUsername, manifestProperties.Credentials.PostgresUsername, manifestProperties.Credentials.RegistryUsername, manifestProperties.Credentials.BlobstoreDirectorUsername, manifestProperties.Credentials.BlobstoreAgentUsername, manifestProperties.Credentials.HMUsername, manifestProperties.Credentials.NatsPassword, manifestProperties.Credentials.PostgresPassword, manifestProperties.Credentials.RegistryPassword, manifestProperties.Credentials.BlobstoreDirectorPassword, manifestProperties.Credentials.BlobstoreAgentPassword, manifestProperties.Credentials.HMPassword, ) return []Job{ { Name: "bosh", Instances: 1, ResourcePool: "vms", PersistentDiskPool: "disks", Templates: []Template{ {Name: "nats", Release: "bosh"}, {Name: "postgres", Release: "bosh"}, {Name: "blobstore", Release: "bosh"}, {Name: "director", Release: "bosh"}, {Name: "health_monitor", Release: "bosh"}, {Name: "registry", Release: "bosh"}, {Name: "aws_cpi", Release: "bosh-aws-cpi"}, }, Networks: []JobNetwork{ { Name: "private", StaticIPs: []string{"10.0.0.6"}, Default: []string{"dns", "gateway"}, }, { Name: "public", StaticIPs: []string{manifestProperties.ElasticIP}, }, }, Properties: JobProperties{ NATS: jobPropertiesManifestBuilder.NATS(), Postgres: jobPropertiesManifestBuilder.Postgres(), Registry: jobPropertiesManifestBuilder.Registry(), Blobstore: jobPropertiesManifestBuilder.Blobstore(), Director: jobPropertiesManifestBuilder.Director(manifestProperties), HM: jobPropertiesManifestBuilder.HM(), AWS: sharedPropertiesManifestBuilder.AWS(manifestProperties), Agent: jobPropertiesManifestBuilder.Agent(), }, }, }, manifestProperties, nil } func (j JobsManifestBuilder) generateInternalCredentials(manifestProperties ManifestProperties) (ManifestProperties, error) { var credentials = map[string]*string{} credentials["nats-user-"] = &manifestProperties.Credentials.NatsUsername credentials["postgres-user-"] = &manifestProperties.Credentials.PostgresUsername credentials["registry-user-"] = &manifestProperties.Credentials.RegistryUsername credentials["blobstore-director-user-"] = &manifestProperties.Credentials.BlobstoreDirectorUsername credentials["blobstore-agent-user-"] = &manifestProperties.Credentials.BlobstoreAgentUsername credentials["hm-user-"] = &manifestProperties.Credentials.HMUsername credentials["nats-"] = &manifestProperties.Credentials.NatsPassword credentials["postgres-"] = &manifestProperties.Credentials.PostgresPassword credentials["registry-"] = &manifestProperties.Credentials.RegistryPassword credentials["blobstore-director-"] = &manifestProperties.Credentials.BlobstoreDirectorPassword credentials["blobstore-agent-"] = &manifestProperties.Credentials.BlobstoreAgentPassword credentials["hm-"] = &manifestProperties.Credentials.HMPassword for key, value := range credentials { if *value == "" { generatedString, err := j.stringGenerator.Generate(key, PASSWORD_LENGTH) if err != nil { return manifestProperties, err } *value = generatedString } } return manifestProperties, nil } <file_sep>/aws/ec2/keypair_manager.go package ec2 type KeyPairManager struct { creator keypairCreator checker keypairChecker logger logger } type keypairCreator interface { Create(keyPairName string) (KeyPair, error) } type keypairChecker interface { HasKeyPair(keypairName string) (bool, error) } type logger interface { Step(message string, a ...interface{}) } func NewKeyPairManager(creator keypairCreator, checker keypairChecker, logger logger) KeyPairManager { return KeyPairManager{ creator: creator, checker: checker, logger: logger, } } func (m KeyPairManager) Sync(keypair KeyPair) (KeyPair, error) { hasLocalKeyPair := len(keypair.PublicKey) != 0 || len(keypair.PrivateKey) != 0 m.logger.Step("checking if keypair %q exists", keypair.Name) hasRemoteKeyPair, err := m.checker.HasKeyPair(keypair.Name) if err != nil { return KeyPair{}, err } if !hasLocalKeyPair || !hasRemoteKeyPair { keyPairName := keypair.Name m.logger.Step("creating keypair") keypair, err = m.creator.Create(keyPairName) if err != nil { return KeyPair{}, err } } else { m.logger.Step("using existing keypair") } return keypair, nil } <file_sep>/bbl/awsbackend/instances.go package awsbackend import "sync" type Instance struct { Name string VPCID string } type Instances struct { mutex sync.Mutex store []Instance } func NewInstances() *Instances { return &Instances{} } func (i *Instances) Set(instances []Instance) { i.mutex.Lock() defer i.mutex.Unlock() i.store = instances } func (i *Instances) Get() []Instance { i.mutex.Lock() defer i.mutex.Unlock() return i.store } <file_sep>/bosh/client_provider_test.go package bosh_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/cloudfoundry/bosh-bootloader/bosh" ) var _ = Describe("Client Provider", func() { Describe("Client", func() { var ( clientProvider bosh.ClientProvider ) BeforeEach(func() { clientProvider = bosh.NewClientProvider() }) It("returns a bosh client", func() { boshClient := clientProvider.Client("some-director-address", "some-director-username", "some-director-password") _, ok := boshClient.(bosh.Client) Expect(ok).To(BeTrue()) }) }) }) <file_sep>/aws/cloudformation/templates/load_balancer_subnet_template_builder.go package templates import "fmt" type LoadBalancerSubnetTemplateBuilder struct{} func NewLoadBalancerSubnetTemplateBuilder() LoadBalancerSubnetTemplateBuilder { return LoadBalancerSubnetTemplateBuilder{} } func (LoadBalancerSubnetTemplateBuilder) LoadBalancerSubnet(azIndex int, subnetSuffix string, cidrBlock string) Template { subnetName := fmt.Sprintf("LoadBalancerSubnet%s", subnetSuffix) cidrName := fmt.Sprintf("%sCIDR", subnetName) az := fmt.Sprintf("%d", azIndex) tag := fmt.Sprintf("LoadBalancer%s", subnetSuffix) routeTableAssociationName := fmt.Sprintf("%sRouteTableAssociation", subnetName) return Template{ Parameters: map[string]Parameter{ cidrName: Parameter{ Description: "CIDR block for the ELB subnet.", Type: "String", Default: cidrBlock, }, }, Resources: map[string]Resource{ subnetName: Resource{ Type: "AWS::EC2::Subnet", Properties: Subnet{ AvailabilityZone: map[string]interface{}{ "Fn::Select": []interface{}{ az, map[string]Ref{ "Fn::GetAZs": Ref{"AWS::Region"}, }, }, }, CidrBlock: Ref{cidrName}, VpcId: Ref{"VPC"}, Tags: []Tag{ { Key: "Name", Value: tag, }, }, }, }, "LoadBalancerRouteTable": Resource{ Type: "AWS::EC2::RouteTable", Properties: RouteTable{ VpcId: Ref{"VPC"}, }, }, "LoadBalancerRoute": Resource{ Type: "AWS::EC2::Route", DependsOn: "VPCGatewayAttachment", Properties: Route{ DestinationCidrBlock: "0.0.0.0/0", GatewayId: Ref{"VPCGatewayInternetGateway"}, RouteTableId: Ref{"LoadBalancerRouteTable"}, }, }, routeTableAssociationName: { Type: "AWS::EC2::SubnetRouteTableAssociation", Properties: SubnetRouteTableAssociation{ RouteTableId: Ref{"LoadBalancerRouteTable"}, SubnetId: Ref{subnetName}, }, }, }, } } <file_sep>/aws/iam/certificate_describer.go package iam import ( "errors" "net/http" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" awsiam "github.com/aws/aws-sdk-go/service/iam" ) var CertificateNotFound error = errors.New("certificate not found") var CertificateDescriptionFailure error = errors.New("failed to describe certificate") type iamClientProvider interface { GetIAMClient() Client } type CertificateDescriber struct { iamClientProvider iamClientProvider } func NewCertificateDescriber(iamClientProvider iamClientProvider) CertificateDescriber { return CertificateDescriber{ iamClientProvider: iamClientProvider, } } func (c CertificateDescriber) Describe(certificateName string) (Certificate, error) { output, err := c.iamClientProvider.GetIAMClient().GetServerCertificate(&awsiam.GetServerCertificateInput{ ServerCertificateName: aws.String(certificateName), }) if err != nil { if e, ok := err.(awserr.RequestFailure); ok { if e.StatusCode() == http.StatusNotFound && e.Code() == "NoSuchEntity" { return Certificate{}, CertificateNotFound } } return Certificate{}, err } if output.ServerCertificate == nil || output.ServerCertificate.ServerCertificateMetadata == nil { return Certificate{}, CertificateDescriptionFailure } return Certificate{ Name: aws.StringValue(output.ServerCertificate.ServerCertificateMetadata.ServerCertificateName), ARN: aws.StringValue(output.ServerCertificate.ServerCertificateMetadata.Arn), Body: aws.StringValue(output.ServerCertificate.CertificateBody), Chain: aws.StringValue(output.ServerCertificate.CertificateChain), }, nil } <file_sep>/boshinit/executor.go package boshinit import ( "github.com/cloudfoundry/bosh-bootloader/boshinit/manifests" "gopkg.in/yaml.v2" ) const ( BOSH_BOOTLOADER_COMMON_NAME = "BOSH Bootloader" ) type Executor struct { manifestBuilder manifestBuilder deployCommand command deleteCommand command logger logger } type logger interface { Step(message string, a ...interface{}) Println(string) } type manifestBuilder interface { Build(manifests.ManifestProperties) (manifests.Manifest, manifests.ManifestProperties, error) } type command interface { Execute(manifest []byte, privateKey string, state State) (State, error) } func NewExecutor(manifestBuilder manifestBuilder, deployCommand command, deleteCommand command, logger logger) Executor { return Executor{ manifestBuilder: manifestBuilder, deployCommand: deployCommand, deleteCommand: deleteCommand, logger: logger, } } func (e Executor) Delete(boshInitManifest string, boshInitState State, ec2PrivateKey string) error { e.logger.Step("destroying bosh director") _, err := e.deleteCommand.Execute([]byte(boshInitManifest), ec2PrivateKey, boshInitState) if err != nil { return err } return nil } func (e Executor) Deploy(input DeployInput) (DeployOutput, error) { manifest, manifestProperties, err := e.manifestBuilder.Build(manifests.ManifestProperties{ DirectorName: input.DirectorName, DirectorUsername: input.DirectorUsername, DirectorPassword: input.DirectorPassword, SubnetID: input.InfrastructureConfiguration.SubnetID, AvailabilityZone: input.InfrastructureConfiguration.AvailabilityZone, CACommonName: BOSH_BOOTLOADER_COMMON_NAME, ElasticIP: input.InfrastructureConfiguration.ElasticIP, AccessKeyID: input.InfrastructureConfiguration.AccessKeyID, SecretAccessKey: input.InfrastructureConfiguration.SecretAccessKey, SecurityGroup: input.InfrastructureConfiguration.SecurityGroup, Region: input.InfrastructureConfiguration.AWSRegion, DefaultKeyName: input.EC2KeyPair.Name, SSLKeyPair: input.SSLKeyPair, Credentials: manifests.NewInternalCredentials(input.Credentials), }) if err != nil { return DeployOutput{}, err } manifestYAML, err := yaml.Marshal(manifest) if err != nil { return DeployOutput{}, err } e.logger.Step("deploying bosh director") state, err := e.deployCommand.Execute(manifestYAML, input.EC2KeyPair.PrivateKey, input.State) if err != nil { return DeployOutput{}, err } return DeployOutput{ BOSHInitState: state, DirectorSSLKeyPair: manifestProperties.SSLKeyPair, Credentials: manifestProperties.Credentials.ToMap(), BOSHInitManifest: string(manifestYAML), }, nil } <file_sep>/fakes/keypair_checker.go package fakes type KeyPairChecker struct { HasKeyPairCall struct { CallCount int Stub func(string) (bool, error) Recieves struct { Name string } Returns struct { Present bool Error error } } } func (k *KeyPairChecker) HasKeyPair(name string) (bool, error) { k.HasKeyPairCall.CallCount++ k.HasKeyPairCall.Recieves.Name = name if k.HasKeyPairCall.Stub != nil { return k.HasKeyPairCall.Stub(name) } return k.HasKeyPairCall.Returns.Present, k.HasKeyPairCall.Returns.Error } <file_sep>/boshinit/deploy_input_test.go package boshinit_test import ( "errors" "github.com/cloudfoundry/bosh-bootloader/aws/ec2" "github.com/cloudfoundry/bosh-bootloader/boshinit" "github.com/cloudfoundry/bosh-bootloader/fakes" "github.com/cloudfoundry/bosh-bootloader/ssl" "github.com/cloudfoundry/bosh-bootloader/storage" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("DeployInput", func() { var ( fakeStringGenerator *fakes.StringGenerator state storage.State infrastructureConfiguration boshinit.InfrastructureConfiguration envID string ) Describe("NewDeployInput", func() { BeforeEach(func() { fakeStringGenerator = &fakes.StringGenerator{} state = storage.State{ KeyPair: storage.KeyPair{ Name: "some-keypair-name", PrivateKey: "some-private-key", PublicKey: "some-public-key", }, BOSH: storage.BOSH{ DirectorSSLCertificate: "some-ssl-cert", DirectorSSLPrivateKey: "some-ssl-private-key", Credentials: map[string]string{ "some-user": "some-password", }, State: map[string]interface{}{ "some-state-key": "some-state-value", }, DirectorName: "some-director-name", DirectorUsername: "some-director-username", DirectorPassword: "<PASSWORD>", }, } infrastructureConfiguration = boshinit.InfrastructureConfiguration{ AWSRegion: "some-aws-region", SubnetID: "some-subnet-id", AvailabilityZone: "some-az", ElasticIP: "some-eip", AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", SecurityGroup: "some-security-group", } envID = "some-env-id" }) It("constructs a DeployInput given a state", func() { deployInput, err := boshinit.NewDeployInput(state, infrastructureConfiguration, fakeStringGenerator, envID) Expect(err).NotTo(HaveOccurred()) Expect(deployInput).To(Equal(boshinit.DeployInput{ DirectorName: "some-director-name", DirectorUsername: "some-director-username", DirectorPassword: "<PASSWORD>", State: map[string]interface{}{ "some-state-key": "some-state-value", }, InfrastructureConfiguration: boshinit.InfrastructureConfiguration{ AWSRegion: "some-aws-region", SubnetID: "some-subnet-id", AvailabilityZone: "some-az", ElasticIP: "some-eip", AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", SecurityGroup: "some-security-group", }, SSLKeyPair: ssl.KeyPair{ Certificate: []byte("some-ssl-cert"), PrivateKey: []byte("some-ssl-private-key"), }, EC2KeyPair: ec2.KeyPair{ Name: "some-keypair-name", PrivateKey: "some-private-key", PublicKey: "some-public-key", }, Credentials: map[string]string{ "some-user": "<PASSWORD>-password", }, })) }) Context("when existing state contains bosh state without director name", func() { It("sets director name to my-bosh", func() { state.BOSH.DirectorName = "" deployInput, err := boshinit.NewDeployInput(state, infrastructureConfiguration, fakeStringGenerator, envID) Expect(err).NotTo(HaveOccurred()) Expect(deployInput.DirectorName).To(Equal("my-bosh")) }) }) It("does not modify the struct references in the state", func() { state := storage.State{ AWS: storage.AWS{ Region: "some-aws-region", }, KeyPair: storage.KeyPair{ Name: "some-keypair-name", PrivateKey: "some-private-key", PublicKey: "some-public-key", }, BOSH: storage.BOSH{ DirectorSSLCertificate: "some-ssl-cert", DirectorSSLPrivateKey: "some-ssl-private-key", Credentials: map[string]string{ "some-user": "<PASSWORD>", }, State: map[string]interface{}{ "some-state-key": "some-state-value", }, DirectorName: "some-director-name", DirectorUsername: "some-director-username", DirectorPassword: "<PASSWORD>", }, } _, err := boshinit.NewDeployInput(state, boshinit.InfrastructureConfiguration{}, fakeStringGenerator, envID) Expect(err).NotTo(HaveOccurred()) Expect(state).To(Equal(storage.State{ AWS: storage.AWS{ Region: "some-aws-region", }, KeyPair: storage.KeyPair{ Name: "some-keypair-name", PrivateKey: "some-private-key", PublicKey: "some-public-key", }, BOSH: storage.BOSH{ DirectorSSLCertificate: "some-ssl-cert", DirectorSSLPrivateKey: "some-ssl-private-key", Credentials: map[string]string{ "some-user": "<PASSWORD>", }, State: map[string]interface{}{ "some-state-key": "some-state-value", }, DirectorName: "some-director-name", DirectorUsername: "some-director-username", DirectorPassword: "<PASSWORD>", }, })) }) It("handles empty state, by assigning director name and generating credentials if they don't exist", func() { fakeStringGenerator.GenerateCall.Stub = func(prefix string, length int) (string, error) { switch fakeStringGenerator.GenerateCall.CallCount { case 0: return "some-generated-username", nil case 1: return "some-generated-password", nil default: return "", errors.New("too many calls to password generator") } } deployInput, err := boshinit.NewDeployInput(storage.State{}, boshinit.InfrastructureConfiguration{}, fakeStringGenerator, envID) Expect(err).NotTo(HaveOccurred()) Expect(deployInput).To(Equal(boshinit.DeployInput{ State: map[string]interface{}{}, DirectorName: "bosh-some-env-id", DirectorUsername: "some-generated-username", DirectorPassword: "<PASSWORD>", })) Expect(fakeStringGenerator.GenerateCall.Receives.Prefixes).To(Equal([]string{"user-", "p-"})) Expect(fakeStringGenerator.GenerateCall.Receives.Lengths).To(Equal([]int{7, 15})) }) Describe("failure cases", func() { It("returns an error when director username generation fails", func() { fakeStringGenerator.GenerateCall.Returns.Error = errors.New("failed to generate username") _, err := boshinit.NewDeployInput(storage.State{}, boshinit.InfrastructureConfiguration{}, fakeStringGenerator, "") Expect(err).To(MatchError("failed to generate username")) }) It("returns an error when director username generation fails", func() { fakeStringGenerator.GenerateCall.Stub = func(prefix string, length int) (string, error) { switch fakeStringGenerator.GenerateCall.CallCount { case 0: return "", nil default: return "", errors.New("failed to generate password") } } _, err := boshinit.NewDeployInput(storage.State{}, boshinit.InfrastructureConfiguration{}, fakeStringGenerator, "") Expect(err).To(MatchError("failed to generate password")) }) }) }) }) <file_sep>/aws/ec2/keypair_creator.go package ec2 import "github.com/aws/aws-sdk-go/service/ec2" type guidGenerator interface { Generate() (string, error) } type KeyPairCreator struct { ec2ClientProvider ec2ClientProvider } func NewKeyPairCreator(ec2ClientProvider ec2ClientProvider) KeyPairCreator { return KeyPairCreator{ ec2ClientProvider: ec2ClientProvider, } } func (c KeyPairCreator) Create(keyPairName string) (KeyPair, error) { output, err := c.ec2ClientProvider.GetEC2Client().CreateKeyPair(&ec2.CreateKeyPairInput{ KeyName: &keyPairName, }) if err != nil { return KeyPair{}, err } var keyMaterial string if output.KeyMaterial != nil { keyMaterial = *output.KeyMaterial } return KeyPair{ Name: keyPairName, PrivateKey: keyMaterial, }, nil } <file_sep>/application/configuration_parser.go package application import "github.com/cloudfoundry/bosh-bootloader/storage" var getState func(string) (storage.State, error) = storage.GetState type commandLineParser interface { Parse(arguments []string) (CommandLineConfiguration, error) } type stateStore interface { Set(state storage.State) error } type ConfigurationParser struct { commandLineParser commandLineParser } func NewConfigurationParser(commandLineParser commandLineParser) ConfigurationParser { return ConfigurationParser{ commandLineParser: commandLineParser, } } func (p ConfigurationParser) Parse(arguments []string) (Configuration, error) { commandLineConfiguration, err := p.commandLineParser.Parse(arguments) if err != nil { return Configuration{}, err } configuration := Configuration{ Global: GlobalConfiguration{ StateDir: commandLineConfiguration.StateDir, EndpointOverride: commandLineConfiguration.EndpointOverride, }, Command: commandLineConfiguration.Command, SubcommandFlags: commandLineConfiguration.SubcommandFlags, State: storage.State{}, } if !p.isHelpOrVersion(configuration.Command, configuration.SubcommandFlags) { configuration.State, err = getState(configuration.Global.StateDir) if err != nil { return Configuration{}, err } } return configuration, nil } func (ConfigurationParser) isHelpOrVersion(command string, subcommandFlags StringSlice) bool { if command == "help" || command == "version" { return true } if subcommandFlags.ContainsAny("--help", "-h", "--version", "-v") { return true } return false } <file_sep>/boshinit/command_runner.go package boshinit import ( "encoding/json" "io/ioutil" "os" "path/filepath" ) const OS_READ_WRITE_MODE = os.FileMode(0644) type CommandRunner struct { directory string command executable } type State map[string]interface{} type executable interface { Run() error } func NewCommandRunner(dir string, command executable) CommandRunner { return CommandRunner{ directory: dir, command: command, } } func (r CommandRunner) Execute(manifest []byte, privateKey string, state State) (State, error) { stateJSONPath := filepath.Join(r.directory, "bosh-state.json") stateJSON, err := json.Marshal(state) if err != nil { return State{}, err } err = ioutil.WriteFile(stateJSONPath, stateJSON, OS_READ_WRITE_MODE) if err != nil { return State{}, err } err = ioutil.WriteFile(filepath.Join(r.directory, "bosh.yml"), manifest, OS_READ_WRITE_MODE) if err != nil { return State{}, err } err = ioutil.WriteFile(filepath.Join(r.directory, "bosh.pem"), []byte(privateKey), OS_READ_WRITE_MODE) if err != nil { return State{}, err } err = r.command.Run() if err != nil { return State{}, err } _, err = os.Stat(stateJSONPath) if err != nil { return State{}, nil } boshStateData, err := ioutil.ReadFile(stateJSONPath) if err != nil { return State{}, err } state = State{} err = json.Unmarshal(boshStateData, &state) if err != nil { return State{}, err } return state, nil } <file_sep>/bbl/upgrade_from_1.0.0_test.go package main_test import ( "errors" "fmt" "io/ioutil" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "runtime" "time" "github.com/cloudfoundry/bosh-bootloader/bbl/awsbackend" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/onsi/gomega/gexec" "github.com/rosenhouse/awsfaker" ) const ( LinuxReleaseURL = "https://github.com/cloudfoundry/bosh-bootloader/releases/download/v1.0.0/bbl-v1.0.0_linux_x86-64" MacReleaseURL = "https://github.com/cloudfoundry/bosh-bootloader/releases/download/v1.0.0/bbl-v1.0.0_osx" ) var _ = Describe("upgrade from 1.0.0", func() { var ( tmpDir string envID string pathToBBLv1 string fakeBOSH *fakeBOSHDirector fakeBOSHServer *httptest.Server fakeAWS *awsbackend.Backend fakeAWSServer *httptest.Server ) BeforeEach(func() { var err error tmpDir, err = ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) fakeBOSH = &fakeBOSHDirector{} fakeBOSHServer = httptest.NewServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) { fakeBOSH.ServeHTTP(responseWriter, request) })) fakeAWS = awsbackend.New(fakeBOSHServer.URL) fakeAWSServer = httptest.NewServer(awsfaker.New(fakeAWS)) }) bblUp := func(bbl string) (*gexec.Session, error) { args := []string{ fmt.Sprintf("--endpoint-override=%s", fakeAWSServer.URL), "--state-dir", tmpDir, "up", "--aws-access-key-id", "some-access-key", "--aws-secret-access-key", "some-access-secret", "--aws-region", "some-region", } session, err := gexec.Start(exec.Command(bbl, args...), GinkgoWriter, GinkgoWriter) return session, err } downloadBBLV1 := func() error { var releaseURL string if runtime.GOOS == "linux" { releaseURL = LinuxReleaseURL } else { releaseURL = MacReleaseURL } resp, err := http.Get(releaseURL) if err != nil { return err } if resp.StatusCode != http.StatusOK { // FIXME add more info to the error return errors.New("failed to download bbl v1") } bblBinary, err := ioutil.ReadAll(resp.Body) if err != nil { return err } pathToBBLv1 = filepath.Join(tmpDir, "bbl") err = ioutil.WriteFile(pathToBBLv1, bblBinary, os.ModePerm) if err != nil { return err } return nil } It("maintains env id", func() { By("downloading bbl v1.0.0", func() { err := downloadBBLV1() Expect(err).NotTo(HaveOccurred()) }) By("bbl-ing up with v1.0.0", func() { session, err := bblUp(pathToBBLv1) Expect(err).NotTo(HaveOccurred()) Eventually(session, 10*time.Second).Should(gexec.Exit(0)) }) By("retrieving the env-id from state file", func() { args := []string{"--state-dir", tmpDir, "env-id"} session, err := gexec.Start(exec.Command(pathToBBLv1, args...), GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session, 3*time.Second).Should(gexec.Exit(0)) stdout := session.Out.Contents() envID = string(stdout) }) By("bbl-ing up with dev version", func() { session, err := bblUp(pathToBBL) Expect(err).NotTo(HaveOccurred()) Eventually(session, 10*time.Second).Should(gexec.Exit(0)) }) By("asserting that the env-id has not changed", func() { args := []string{"--state-dir", tmpDir, "env-id"} session, err := gexec.Start(exec.Command(pathToBBL, args...), GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session, 3*time.Second).Should(gexec.Exit(0)) stdout := session.Out.Contents() Expect(string(stdout)).To(Equal(envID)) }) }) }) <file_sep>/bbl/awsbackend/stacks.go package awsbackend import ( "sync" "github.com/rosenhouse/awsfaker" ) type Stack struct { Name string Template string WasUpdated bool } type Stacks struct { mutex sync.Mutex store map[string]Stack createStack struct { returns struct { err *awsfaker.ErrorResponse } } deleteStack struct { returns struct { err *awsfaker.ErrorResponse } } } func NewStacks() *Stacks { return &Stacks{ store: make(map[string]Stack), } } func (s *Stacks) Set(stack Stack) { s.mutex.Lock() defer s.mutex.Unlock() s.store[stack.Name] = stack } func (s *Stacks) Get(name string) (Stack, bool) { s.mutex.Lock() defer s.mutex.Unlock() stack, ok := s.store[name] return stack, ok } func (s *Stacks) Delete(name string) { s.mutex.Lock() defer s.mutex.Unlock() delete(s.store, name) } func (s *Stacks) SetCreateStackReturnError(err *awsfaker.ErrorResponse) { s.mutex.Lock() defer s.mutex.Unlock() s.createStack.returns.err = err } func (s *Stacks) CreateStackReturnError() *awsfaker.ErrorResponse { s.mutex.Lock() defer s.mutex.Unlock() return s.createStack.returns.err } func (s *Stacks) SetDeleteStackReturnError(err *awsfaker.ErrorResponse) { s.mutex.Lock() defer s.mutex.Unlock() s.deleteStack.returns.err = err } func (s *Stacks) DeleteStackReturnError() *awsfaker.ErrorResponse { s.mutex.Lock() defer s.mutex.Unlock() return s.deleteStack.returns.err } <file_sep>/aws/cloudformation/stack_manager_test.go package cloudformation_test import ( "encoding/json" "errors" "fmt" "math/rand" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" awscloudformation "github.com/aws/aws-sdk-go/service/cloudformation" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" "github.com/cloudfoundry/bosh-bootloader/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/extensions/table" . "github.com/onsi/gomega" . "github.com/pivotal-cf-experimental/gomegamatchers" ) var _ = Describe("StackManager", func() { var ( cloudFormationClient *fakes.CloudFormationClient clientProvider *fakes.ClientProvider logger *fakes.Logger manager cloudformation.StackManager ) BeforeEach(func() { clientProvider = &fakes.ClientProvider{} cloudFormationClient = &fakes.CloudFormationClient{} logger = &fakes.Logger{} clientProvider.GetCloudFormationClientCall.Returns.CloudFormationClient = cloudFormationClient manager = cloudformation.NewStackManager(clientProvider, logger) }) Describe("Describe", func() { It("describes the stack with the given name", func() { cloudFormationClient.DescribeStacksCall.Returns.Output = &awscloudformation.DescribeStacksOutput{ Stacks: []*awscloudformation.Stack{{ StackName: aws.String("some-stack-name"), StackStatus: aws.String(awscloudformation.StackStatusUpdateComplete), Outputs: []*awscloudformation.Output{{ OutputKey: aws.String("some-output-key"), OutputValue: aws.String("some-output-value"), }}, }}, } stack, err := manager.Describe("some-stack-name") Expect(err).NotTo(HaveOccurred()) Expect(clientProvider.GetCloudFormationClientCall.CallCount).To(Equal(1)) Expect(cloudFormationClient.DescribeStacksCall.Receives.Input).To(Equal(&awscloudformation.DescribeStacksInput{ StackName: aws.String("some-stack-name"), })) Expect(stack).To(Equal(cloudformation.Stack{ Name: "some-stack-name", Status: "UPDATE_COMPLETE", Outputs: map[string]string{ "some-output-key": "some-output-value", }, })) }) Context("failure cases", func() { Context("when there is a response error", func() { It("returns an error when the RequestFailure response is not a 'StackNotFound'", func() { cloudFormationClient.DescribeStacksCall.Returns.Error = awserr.NewRequestFailure(awserr.New("ValidationError", "something bad happened", errors.New("")), 400, "0") _, err := manager.Describe("some-stack-name") Expect(err).To(MatchError(ContainSubstring("something bad happened"))) }) It("returns an error when the response is an unknown error", func() { cloudFormationClient.DescribeStacksCall.Returns.Error = errors.New("an unknown error occurred") _, err := manager.Describe("some-stack-name") Expect(err).To(MatchError(ContainSubstring("an unknown error occurred"))) }) }) Context("when stack output key or value is nil", func() { It("returns an error when the key in nil", func() { cloudFormationClient.DescribeStacksCall.Returns.Output = &awscloudformation.DescribeStacksOutput{ Stacks: []*awscloudformation.Stack{ { StackName: aws.String("some-stack-name"), StackStatus: aws.String(awscloudformation.StackStatusUpdateComplete), Outputs: []*awscloudformation.Output{{ OutputKey: nil, OutputValue: aws.String("some-value"), }}, }, }, } _, err := manager.Describe("some-stack-name") Expect(err).To(MatchError("failed to parse outputs")) }) It("assigns an empty string value when the value is nil", func() { cloudFormationClient.DescribeStacksCall.Returns.Output = &awscloudformation.DescribeStacksOutput{ Stacks: []*awscloudformation.Stack{ { StackName: aws.String("some-stack-name"), StackStatus: aws.String(awscloudformation.StackStatusUpdateComplete), Outputs: []*awscloudformation.Output{ { OutputKey: aws.String("first-key"), OutputValue: nil, }, { OutputKey: aws.String("second-key"), OutputValue: aws.String("second-value"), }, }, }, }, } stack, err := manager.Describe("some-stack-name") Expect(err).NotTo(HaveOccurred()) Expect(stack.Outputs["first-key"]).To(Equal("")) Expect(stack.Outputs["second-key"]).To(Equal("second-value")) }) }) It("returns a StackNotFound error when the stack doesn't exist", func() { stackName := fmt.Sprintf("some-stack-name-%d", rand.Int()) cloudFormationClient.DescribeStacksCall.Returns.Error = awserr.NewRequestFailure(awserr.New("ValidationError", fmt.Sprintf("Stack with id %s does not exist", stackName), errors.New("")), 400, "0") _, err := manager.Describe(stackName) Expect(err).To(MatchError(cloudformation.StackNotFound)) }) It("returns a StackNotFound error when the stack name is empty", func() { cloudFormationClient.DescribeStacksCall.Returns.Error = awserr.NewRequestFailure(awserr.New("", "", errors.New("")), 400, "0") _, err := manager.Describe("") Expect(err).To(MatchError(cloudformation.StackNotFound)) Expect(cloudFormationClient.DescribeStacksCall.CallCount).To(Equal(0)) }) Context("when the api returns no stacks", func() { It("returns a StackNotFound error", func() { cloudFormationClient.DescribeStacksCall.Returns.Output = &awscloudformation.DescribeStacksOutput{ Stacks: []*awscloudformation.Stack{}, } _, err := manager.Describe("some-stack-name") Expect(err).To(MatchError(cloudformation.StackNotFound)) }) }) Context("when the api returns more than one stack", func() { It("returns the correct stack", func() { cloudFormationClient.DescribeStacksCall.Returns.Output = &awscloudformation.DescribeStacksOutput{ Stacks: []*awscloudformation.Stack{ { StackName: aws.String("some-other-stack-name"), StackStatus: aws.String(awscloudformation.StackStatusUpdateComplete), }, { StackName: aws.String("some-stack-name"), StackStatus: aws.String(awscloudformation.StackStatusCreateComplete), }, }, } stack, err := manager.Describe("some-stack-name") Expect(err).NotTo(HaveOccurred()) Expect(cloudFormationClient.DescribeStacksCall.Receives.Input).To(Equal(&awscloudformation.DescribeStacksInput{ StackName: aws.String("some-stack-name"), })) Expect(stack).To(Equal(cloudformation.Stack{ Name: "some-stack-name", Status: "CREATE_COMPLETE", Outputs: map[string]string{}, })) }) }) Context("when the api returns a stack missing a name", func() { It("doesn't explode", func() { cloudFormationClient.DescribeStacksCall.Returns.Output = &awscloudformation.DescribeStacksOutput{ Stacks: []*awscloudformation.Stack{ { StackStatus: aws.String(awscloudformation.StackStatusUpdateComplete), }, { StackName: aws.String("some-stack-name"), StackStatus: aws.String(awscloudformation.StackStatusCreateComplete), }, }, } stack, err := manager.Describe("some-stack-name") Expect(err).NotTo(HaveOccurred()) Expect(cloudFormationClient.DescribeStacksCall.Receives.Input).To(Equal(&awscloudformation.DescribeStacksInput{ StackName: aws.String("some-stack-name"), })) Expect(stack).To(Equal(cloudformation.Stack{ Name: "some-stack-name", Status: "CREATE_COMPLETE", Outputs: map[string]string{}, })) }) }) Context("when the api returns a stack missing a status", func() { It("doesn't explode", func() { cloudFormationClient.DescribeStacksCall.Returns.Output = &awscloudformation.DescribeStacksOutput{ Stacks: []*awscloudformation.Stack{ { StackName: aws.String("some-other-stack-name"), StackStatus: aws.String(awscloudformation.StackStatusUpdateComplete), }, { StackName: aws.String("some-stack-name"), }, }, } stack, err := manager.Describe("some-stack-name") Expect(err).NotTo(HaveOccurred()) Expect(cloudFormationClient.DescribeStacksCall.Receives.Input).To(Equal(&awscloudformation.DescribeStacksInput{ StackName: aws.String("some-stack-name"), })) Expect(stack).To(Equal(cloudformation.Stack{ Name: "some-stack-name", Status: "UNKNOWN", Outputs: map[string]string{}, })) }) }) }) }) Describe("Update", func() { var ( template templates.Template templateJson []byte tags cloudformation.Tags ) BeforeEach(func() { var err error template = templates.Template{ Description: "testing template", } templateJson, err = json.Marshal(&template) Expect(err).NotTo(HaveOccurred()) tags = cloudformation.Tags{ { Key: "bbl-env-id", Value: "some-env-id", }, } }) It("updates the stack if the stack exists", func() { err := manager.Update("some-stack-name", template, tags) Expect(err).NotTo(HaveOccurred()) Expect(cloudFormationClient.UpdateStackCall.Receives.Input).To(Equal(&awscloudformation.UpdateStackInput{ StackName: aws.String("some-stack-name"), Capabilities: []*string{aws.String("CAPABILITY_IAM"), aws.String("CAPABILITY_NAMED_IAM")}, TemplateBody: aws.String(string(templateJson)), Tags: []*awscloudformation.Tag{ { Key: aws.String("bbl-env-id"), Value: aws.String("some-env-id"), }, }, })) Expect(logger.StepCall.Receives.Message).To(Equal("updating cloudformation stack")) }) It("does not return an error when no updates are to be performed", func() { cloudFormationClient.UpdateStackCall.Returns.Error = awserr.NewRequestFailure(awserr.New("ValidationError", "No updates are to be performed.", errors.New("")), 400, "0") err := manager.Update("some-stack-name", template, cloudformation.Tags{}) Expect(err).NotTo(HaveOccurred()) }) Context("failure cases", func() { Context("when update stack returns a validation error other than 'No updates to be performed'", func() { It("returns error", func() { cloudFormationClient.UpdateStackCall.Returns.Error = awserr.NewRequestFailure(awserr.New("ValidationError", "something bad happened", errors.New("")), 400, "0") err := manager.Update("some-stack-name", template, cloudformation.Tags{}) Expect(err).To(MatchError(ContainSubstring("something bad happened"))) }) }) Context("when update stack returns an unknown error", func() { It("returns error", func() { cloudFormationClient.UpdateStackCall.Returns.Error = errors.New("an unknown error has occurred") err := manager.Update("some-stack-name", template, cloudformation.Tags{}) Expect(err).To(MatchError("an unknown error has occurred")) }) }) Context("when the stack does not exist", func() { It("returns a StackNotFound error", func() { stackName := fmt.Sprintf("some-stack-name-%d", rand.Int()) cloudFormationClient.UpdateStackCall.Returns.Error = awserr.NewRequestFailure(awserr.New("ValidationError", fmt.Sprintf("Stack [%s] does not exist", stackName), errors.New("")), 400, "0") err := manager.Update(stackName, template, cloudformation.Tags{}) Expect(err).To(Equal(cloudformation.StackNotFound)) }) }) }) }) Describe("CreateOrUpdate", func() { var ( template templates.Template templateJson []byte ) BeforeEach(func() { var err error cloudFormationClient.DescribeStacksCall.Returns.Output = &awscloudformation.DescribeStacksOutput{ Stacks: []*awscloudformation.Stack{ { StackName: aws.String("some-stack-name"), StackStatus: aws.String(awscloudformation.StackStatusUpdateComplete), }, }, } template = templates.Template{ Description: "testing template", } templateJson, err = json.Marshal(&template) Expect(err).NotTo(HaveOccurred()) }) It("checks if the stack exists", func() { err := manager.CreateOrUpdate("some-stack-name", templates.Template{}, cloudformation.Tags{}) Expect(err).NotTo(HaveOccurred()) Expect(cloudFormationClient.DescribeStacksCall.Receives.Input).To(Equal(&awscloudformation.DescribeStacksInput{ StackName: aws.String("some-stack-name"), })) Expect(logger.StepCall.Messages).To(ContainElement(`checking if cloudformation stack "some-stack-name" exists`)) }) It("creates a stack if the stack does not exist", func() { cloudFormationClient.DescribeStacksCall.Returns.Error = cloudformation.StackNotFound template := templates.Template{ Description: "testing template", } templateJson, err := json.Marshal(&template) Expect(err).NotTo(HaveOccurred()) tags := cloudformation.Tags{ { Key: "bbl-env-id", Value: "some-env-id", }, } err = manager.CreateOrUpdate("some-stack-name", template, tags) Expect(err).NotTo(HaveOccurred()) Expect(cloudFormationClient.CreateStackCall.Receives.Input).To(Equal(&awscloudformation.CreateStackInput{ StackName: aws.String("some-stack-name"), Capabilities: []*string{aws.String("CAPABILITY_IAM"), aws.String("CAPABILITY_NAMED_IAM")}, TemplateBody: aws.String(string(templateJson)), Tags: []*awscloudformation.Tag{ { Key: aws.String("bbl-env-id"), Value: aws.String("some-env-id"), }, }, })) Expect(logger.StepCall.Messages).To(ContainSequence([]string{ `checking if cloudformation stack "some-stack-name" exists`, "creating cloudformation stack", })) }) It("updates the stack if the stack exists", func() { err := manager.CreateOrUpdate("some-stack-name", template, cloudformation.Tags{}) Expect(err).NotTo(HaveOccurred()) Expect(cloudFormationClient.UpdateStackCall.CallCount).To(Equal(1)) Expect(logger.StepCall.Messages).To(ContainSequence([]string{ `checking if cloudformation stack "some-stack-name" exists`, "updating cloudformation stack", })) }) Context("failure cases", func() { It("returns an error when the stack fails to update", func() { cloudFormationClient.UpdateStackCall.Returns.Error = errors.New("error updating stack") err := manager.CreateOrUpdate("some-stack-name", template, cloudformation.Tags{}) Expect(err).To(MatchError("error updating stack")) }) It("returns an error when the stack cannot be described", func() { cloudFormationClient.DescribeStacksCall.Returns.Error = errors.New("error describing stack") template := templates.Template{ Description: "testing template", } err := manager.CreateOrUpdate("some-stack-name", template, cloudformation.Tags{}) Expect(err).To(MatchError("error describing stack")) }) It("returns an error when the stack cannot be created", func() { cloudFormationClient.DescribeStacksCall.Returns.Error = cloudformation.StackNotFound cloudFormationClient.CreateStackCall.Returns.Error = errors.New("error creating stack") template := templates.Template{ Description: "testing template", } err := manager.CreateOrUpdate("some-stack-name", template, cloudformation.Tags{}) Expect(err).To(MatchError("error creating stack")) }) }) }) Describe("WaitForCompletion", func() { var stubDescribeStacksCall = func(startState string, endState string) { cloudFormationClient.DescribeStacksCall.Stub = func(input *awscloudformation.DescribeStacksInput) (*awscloudformation.DescribeStacksOutput, error) { status := startState if cloudFormationClient.DescribeStacksCall.CallCount > 2 { status = endState } return &awscloudformation.DescribeStacksOutput{ Stacks: []*awscloudformation.Stack{ { StackName: aws.String("some-stack-name"), StackStatus: aws.String(status), }, }, }, nil } } DescribeTable("waiting for a done state", func(startState, endState string, action string) { stubDescribeStacksCall(startState, endState) err := manager.WaitForCompletion("some-stack-name", 0*time.Millisecond, action) Expect(err).NotTo(HaveOccurred()) Expect(cloudFormationClient.DescribeStacksCall.Receives.Input).To(Equal(&awscloudformation.DescribeStacksInput{ StackName: aws.String("some-stack-name"), })) Expect(cloudFormationClient.DescribeStacksCall.CallCount).To(Equal(3)) Expect(logger.DotCall.CallCount).To(Equal(2)) Expect(logger.StepCall.Receives.Message).To(Equal(fmt.Sprintf("finished %s", action))) }, Entry("create succeeded", awscloudformation.StackStatusCreateInProgress, awscloudformation.StackStatusCreateComplete, "creating stack"), Entry("update succeeded", awscloudformation.StackStatusUpdateInProgress, awscloudformation.StackStatusUpdateComplete, "updating stack"), Entry("delete succeeded", awscloudformation.StackStatusDeleteInProgress, awscloudformation.StackStatusDeleteComplete, "deleting stack"), ) DescribeTable("waiting for a done state", func(startState, endState string, action string) { stubDescribeStacksCall(startState, endState) err := manager.WaitForCompletion("some-stack-name", 0*time.Millisecond, action) Expect(err).To(MatchError(`CloudFormation failure on stack 'some-stack-name'. Check the AWS console for error events related to this stack, and/or open a GitHub issue at https://github.com/cloudfoundry/bosh-bootloader/issues.`)) }, Entry("create failed", awscloudformation.StackStatusCreateInProgress, awscloudformation.StackStatusCreateFailed, "creating stack"), Entry("rollback complete", awscloudformation.StackStatusCreateInProgress, awscloudformation.StackStatusRollbackComplete, "creating stack"), Entry("rollback failed", awscloudformation.StackStatusCreateInProgress, awscloudformation.StackStatusRollbackFailed, "creating stack"), Entry("update failed, rollback succeeded", awscloudformation.StackStatusUpdateInProgress, awscloudformation.StackStatusUpdateRollbackComplete, "updating stack"), Entry("update failed, rollback failed", awscloudformation.StackStatusUpdateInProgress, awscloudformation.StackStatusUpdateRollbackFailed, "updating stack"), Entry("delete failed", awscloudformation.StackStatusDeleteInProgress, awscloudformation.StackStatusDeleteFailed, "deleting stack"), ) Context("when the stack does not exist", func() { It("does not error", func() { cloudFormationClient.DescribeStacksCall.Returns.Error = cloudformation.StackNotFound err := manager.WaitForCompletion("some-stack-name", 0*time.Millisecond, "foo") Expect(err).NotTo(HaveOccurred()) Expect(logger.StepCall.Receives.Message).To(Equal("finished foo")) }) }) Context("failures cases", func() { Context("when the describe stacks call fails", func() { It("returns an error", func() { cloudFormationClient.DescribeStacksCall.Returns.Error = errors.New("failed to describe stack") err := manager.WaitForCompletion("some-stack-name", 0*time.Millisecond, "foo") Expect(err).To(MatchError("failed to describe stack")) }) }) }) }) Describe("Delete", func() { It("deletes the stack", func() { err := manager.Delete("some-stack-name") Expect(err).NotTo(HaveOccurred()) Expect(cloudFormationClient.DeleteStackCall.Receives.Input).To(Equal(&awscloudformation.DeleteStackInput{ StackName: aws.String("some-stack-name"), })) Expect(logger.StepCall.Receives.Message).To(Equal("deleting cloudformation stack")) }) Context("failure cases", func() { Context("when the stack delete call fails", func() { It("returns an error", func() { cloudFormationClient.DeleteStackCall.Returns.Error = errors.New("failed to delete stack") err := manager.Delete("some-stack-name") Expect(err).To(MatchError("failed to delete stack")) }) }) }) }) Describe("GetPhysicalIDForResource", func() { It("gets the physical resource id for the given stack resource", func() { cloudFormationClient.DescribeStackResourceCall.Returns.Output = &awscloudformation.DescribeStackResourceOutput{ StackResourceDetail: &awscloudformation.StackResourceDetail{ PhysicalResourceId: aws.String("some-physical-resource-id"), }, } physicalID, err := manager.GetPhysicalIDForResource("some-stack-name", "some-logical-resource-id") Expect(err).NotTo(HaveOccurred()) Expect(cloudFormationClient.DescribeStackResourceCall.Receives.Input).To(Equal(&awscloudformation.DescribeStackResourceInput{ StackName: aws.String("some-stack-name"), LogicalResourceId: aws.String("some-logical-resource-id"), })) Expect(physicalID).To(Equal("some-physical-resource-id")) }) Context("failure cases", func() { It("returns an error in case the DescribeStackResource Call fails", func() { cloudFormationClient.DescribeStackResourceCall.Returns.Error = errors.New("DescribeStackResource Call Failed") _, err := manager.GetPhysicalIDForResource("some-stack-name", "some-logical-resource-id") Expect(err).To(MatchError("DescribeStackResource Call Failed")) }) }) }) }) <file_sep>/bbl/errors_test.go package main_test import ( "os/exec" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/onsi/gomega/gexec" ) var _ = Describe("bbl", func() { It("prints an error when configuration parsing fails", func() { session, err := gexec.Start(exec.Command(pathToBBL, "--state-dir", "invalid/state/dir", "up"), GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session).Should(gexec.Exit(1)) Expect(session.Err.Contents()).To(ContainSubstring("stat invalid/state/dir: no such file or directory")) }) It("prints an error when an unknown flag is provided", func() { session, err := gexec.Start(exec.Command(pathToBBL, "--some-unknown-flag", "up"), GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session).Should(gexec.Exit(1)) Expect(session.Err.Contents()).To(ContainSubstring("flag provided but not defined: -some-unknown-flag")) Expect(session.Out.Contents()).To(ContainSubstring("Usage")) }) It("prints an error when an unknown command is provided", func() { session, err := gexec.Start(exec.Command(pathToBBL, "some-unknown-command"), GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session).Should(gexec.Exit(1)) Expect(session.Err.Contents()).To(ContainSubstring("Unrecognized command 'some-unknown-command'")) Expect(session.Out.Contents()).To(ContainSubstring("Usage")) }) }) <file_sep>/aws/cloudformation/templates/bosh_iam_template_builder_test.go package templates_test import ( "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("BOSHIAMTemplateBuilder", func() { var ( builder templates.BOSHIAMTemplateBuilder ) BeforeEach(func() { builder = templates.NewBOSHIAMTemplateBuilder() }) Describe("BOSHIAMUser", func() { Context("when we create a new bbl that supports tagging", func() { It("returns a template with Username", func() { user := builder.BOSHIAMUser("bosh-iam-user-bbl-env-lake-name-2016-08-15-12-03-00") Expect(user.Resources).To(HaveLen(2)) IAMUser := user.Resources["BOSHUser"].Properties.(templates.IAMUser) Expect(IAMUser.UserName).To(Equal("bosh-iam-user-bbl-env-lake-name-2016-08-15-12-03-00")) }) }) Context("when we create a new bbl that does not support tagging", func() { It("returns a template for a BOSH IAM user", func() { user := builder.BOSHIAMUser("some-user-name") Expect(user.Resources).To(HaveLen(2)) Expect(user.Resources).To(HaveKeyWithValue("BOSHUser", templates.Resource{ Type: "AWS::IAM::User", Properties: templates.IAMUser{ Policies: []templates.IAMPolicy{ { PolicyName: "aws-cpi", PolicyDocument: templates.IAMPolicyDocument{ Version: "2012-10-17", Statement: []templates.IAMStatement{ { Action: []string{ "ec2:AssociateAddress", "ec2:AttachVolume", "ec2:CreateVolume", "ec2:DeleteSnapshot", "ec2:DeleteVolume", "ec2:DescribeAddresses", "ec2:DescribeImages", "ec2:DescribeInstances", "ec2:DescribeRegions", "ec2:DescribeSecurityGroups", "ec2:DescribeSnapshots", "ec2:DescribeSubnets", "ec2:DescribeVolumes", "ec2:DetachVolume", "ec2:CreateSnapshot", "ec2:CreateTags", "ec2:RunInstances", "ec2:TerminateInstances", "ec2:RegisterImage", "ec2:DeregisterImage", }, Effect: "Allow", Resource: "*", }, { Action: []string{"elasticloadbalancing:*"}, Effect: "Allow", Resource: "*", }, }, }, }, }, }, })) Expect(user.Resources).To(HaveKeyWithValue("BOSHUserAccessKey", templates.Resource{ Properties: templates.IAMAccessKey{ UserName: templates.Ref{"BOSHUser"}, }, Type: "AWS::IAM::AccessKey", })) Expect(user.Outputs).To(HaveLen(2)) Expect(user.Outputs).To(HaveKeyWithValue("BOSHUserAccessKey", templates.Output{ Value: templates.Ref{"BOSHUserAccessKey"}, })) Expect(user.Outputs).To(HaveKeyWithValue("BOSHUserSecretAccessKey", templates.Output{ Value: templates.FnGetAtt{ []string{ "BOSHUserAccessKey", "SecretAccessKey", }, }, })) }) }) }) }) <file_sep>/boshinit/deploy_input.go package boshinit import ( "fmt" "github.com/cloudfoundry/bosh-bootloader/aws/ec2" "github.com/cloudfoundry/bosh-bootloader/ssl" "github.com/cloudfoundry/bosh-bootloader/storage" ) const USERNAME_PREFIX = "user-" const USERNAME_LENGTH = 7 const PASSWORD_PREFIX = "p-" const PASSWORD_LENGTH = 15 type DeployInput struct { DirectorName string DirectorUsername string DirectorPassword string State State InfrastructureConfiguration InfrastructureConfiguration SSLKeyPair ssl.KeyPair EC2KeyPair ec2.KeyPair Credentials map[string]string } type InfrastructureConfiguration struct { AWSRegion string SubnetID string AvailabilityZone string ElasticIP string AccessKeyID string SecretAccessKey string SecurityGroup string } type DeployOutput struct { Credentials map[string]string BOSHInitState State DirectorSSLKeyPair ssl.KeyPair BOSHInitManifest string } type stringGenerator interface { Generate(prefix string, length int) (string, error) } func NewDeployInput(state storage.State, infrastructureConfiguration InfrastructureConfiguration, stringGenerator stringGenerator, envID string) (DeployInput, error) { deployInput := DeployInput{ State: map[string]interface{}{}, InfrastructureConfiguration: infrastructureConfiguration, SSLKeyPair: ssl.KeyPair{}, EC2KeyPair: ec2.KeyPair{}, } if !state.KeyPair.IsEmpty() { deployInput.EC2KeyPair.Name = state.KeyPair.Name deployInput.EC2KeyPair.PrivateKey = state.KeyPair.PrivateKey deployInput.EC2KeyPair.PublicKey = state.KeyPair.PublicKey } if !state.BOSH.IsEmpty() { deployInput.DirectorName = state.BOSH.DirectorName deployInput.DirectorUsername = state.BOSH.DirectorUsername deployInput.DirectorPassword = state.BOSH.DirectorPassword deployInput.State = state.BOSH.State deployInput.Credentials = state.BOSH.Credentials deployInput.SSLKeyPair.Certificate = []byte(state.BOSH.DirectorSSLCertificate) deployInput.SSLKeyPair.PrivateKey = []byte(state.BOSH.DirectorSSLPrivateKey) if deployInput.DirectorName == "" { deployInput.DirectorName = "my-bosh" } } if deployInput.DirectorName == "" { deployInput.DirectorName = fmt.Sprintf("bosh-%s", envID) } if deployInput.DirectorUsername == "" { var err error if deployInput.DirectorUsername, err = stringGenerator.Generate(USERNAME_PREFIX, USERNAME_LENGTH); err != nil { return DeployInput{}, err } } if deployInput.DirectorPassword == "" { var err error if deployInput.DirectorPassword, err = stringGenerator.Generate(PASSWORD_PREFIX, PASSWORD_LENGTH); err != nil { return DeployInput{}, err } } return deployInput, nil } <file_sep>/fakes/availability_zone_retriever.go package fakes type AvailabilityZoneRetriever struct { RetrieveCall struct { Receives struct { Region string } Returns struct { AZs []string Error error } } } func (a *AvailabilityZoneRetriever) Retrieve(region string) ([]string, error) { a.RetrieveCall.Receives.Region = region return a.RetrieveCall.Returns.AZs, a.RetrieveCall.Returns.Error } <file_sep>/ssl/keypair_generator.go package ssl import ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" "io" "net" certstrappkix "github.com/square/certstrap/pkix" ) type keyGenerator func(io.Reader, int) (*rsa.PrivateKey, error) type createCertificateAuthority func(key *certstrappkix.Key, organizationalUnit string, years int, organization string, country string, province string, locality string, commonName string) (*certstrappkix.Certificate, error) type createCertificateSigningRequest func(key *certstrappkix.Key, organizationalUnit string, ipList []net.IP, domainList []string, organization string, country string, province string, locality string, commonName string) (*certstrappkix.CertificateSigningRequest, error) type createCertificateHost func(crtAuth *certstrappkix.Certificate, keyAuth *certstrappkix.Key, csr *certstrappkix.CertificateSigningRequest, years int) (*certstrappkix.Certificate, error) type KeyPairGenerator struct { generateKey keyGenerator createCertificateAuthority createCertificateAuthority createCertificateSigningRequest createCertificateSigningRequest createCertificateHost createCertificateHost } type CAData struct { CA []byte PrivateKey []byte } func NewKeyPairGenerator( keyGenerator keyGenerator, createCertificateAuthority createCertificateAuthority, createCertificateSigningRequest createCertificateSigningRequest, createCertificateHost createCertificateHost, ) KeyPairGenerator { return KeyPairGenerator{ generateKey: keyGenerator, createCertificateAuthority: createCertificateAuthority, createCertificateSigningRequest: createCertificateSigningRequest, createCertificateHost: createCertificateHost, } } func (g KeyPairGenerator) Generate(caCommonName, commonName string) (KeyPair, error) { caPrivateKey, err := g.generateKey(rand.Reader, 2048) if err != nil { return KeyPair{}, err } caKey := certstrappkix.NewKey(&caPrivateKey.PublicKey, caPrivateKey) caCertificate, err := g.createCertificateAuthority(caKey, "Cloud Foundry", 2, "Cloud Foundry", "USA", "CA", "San Francisco", caCommonName) if err != nil { return KeyPair{}, err } certPrivateKey, err := g.generateKey(rand.Reader, 2048) if err != nil { return KeyPair{}, err } certKey := certstrappkix.NewKey(&certPrivateKey.PublicKey, certPrivateKey) ipList := []net.IP{ net.ParseIP(commonName), } csr, err := g.createCertificateSigningRequest(certKey, "Cloud Foundry", ipList, nil, "Cloud Foundry", "USA", "CA", "San Francisco", commonName) if err != nil { return KeyPair{}, err } certificate, err := g.createCertificateHost(caCertificate, caKey, csr, 2) if err != nil { return KeyPair{}, err } pemCA, err := caCertificate.Export() if err != nil { return KeyPair{}, err } pemCertificate, err := certificate.Export() if err != nil { return KeyPair{}, err } return KeyPair{ CA: pemCA, Certificate: pemCertificate, PrivateKey: pem.EncodeToMemory(&pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(certPrivateKey), }), }, nil } <file_sep>/boshinit/manifests/shared_properties_manifest_builder.go package manifests type SharedPropertiesManifestBuilder struct { } func NewSharedPropertiesManifestBuilder() *SharedPropertiesManifestBuilder { return &SharedPropertiesManifestBuilder{} } func (SharedPropertiesManifestBuilder) AWS(manifestProperties ManifestProperties) AWSProperties { return AWSProperties{ AccessKeyId: manifestProperties.AccessKeyID, SecretAccessKey: manifestProperties.SecretAccessKey, DefaultKeyName: manifestProperties.DefaultKeyName, DefaultSecurityGroups: []string{manifestProperties.SecurityGroup}, Region: manifestProperties.Region, } } <file_sep>/commands/update_lbs_test.go package commands_test import ( "errors" "github.com/cloudfoundry/bosh-bootloader/aws/iam" "github.com/cloudfoundry/bosh-bootloader/commands" "github.com/cloudfoundry/bosh-bootloader/fakes" "github.com/cloudfoundry/bosh-bootloader/storage" "github.com/cloudfoundry/bosh-bootloader/testhelpers" . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/extensions/table" . "github.com/onsi/gomega" ) var _ = Describe("Update LBs", func() { var ( command commands.UpdateLBs incomingState storage.State certFilePath string keyFilePath string chainFilePath string certificateManager *fakes.CertificateManager certificateValidator *fakes.CertificateValidator availabilityZoneRetriever *fakes.AvailabilityZoneRetriever infrastructureManager *fakes.InfrastructureManager awsCredentialValidator *fakes.AWSCredentialValidator boshClientProvider *fakes.BOSHClientProvider boshClient *fakes.BOSHClient logger *fakes.Logger guidGenerator *fakes.GuidGenerator stateStore *fakes.StateStore stateValidator *fakes.StateValidator ) var updateLBs = func(certificatePath, keyPath, chainPath string, state storage.State) error { return command.Execute([]string{ "--cert", certificatePath, "--key", keyPath, "--chain", chainPath, }, state) } BeforeEach(func() { var err error certificateManager = &fakes.CertificateManager{} certificateValidator = &fakes.CertificateValidator{} availabilityZoneRetriever = &fakes.AvailabilityZoneRetriever{} infrastructureManager = &fakes.InfrastructureManager{} awsCredentialValidator = &fakes.AWSCredentialValidator{} logger = &fakes.Logger{} guidGenerator = &fakes.GuidGenerator{} stateStore = &fakes.StateStore{} stateValidator = &fakes.StateValidator{} boshClient = &fakes.BOSHClient{} boshClientProvider = &fakes.BOSHClientProvider{} boshClientProvider.ClientCall.Returns.Client = boshClient availabilityZoneRetriever.RetrieveCall.Returns.AZs = []string{"a", "b", "c"} certificateManager.DescribeCall.Returns.Certificate = iam.Certificate{ Body: "some-old-certificate-contents", ARN: "some-certificate-arn", } guidGenerator.GenerateCall.Returns.Output = "abcd" infrastructureManager.ExistsCall.Returns.Exists = true incomingState = storage.State{ Stack: storage.Stack{ LBType: "concourse", CertificateName: "some-certificate-name", }, BOSH: storage.BOSH{ DirectorAddress: "some-director-address", DirectorUsername: "some-director-username", DirectorPassword: "<PASSWORD>", }, } certFilePath, err = testhelpers.WriteContentsToTempFile("some-certificate-contents") Expect(err).NotTo(HaveOccurred()) keyFilePath, err = testhelpers.WriteContentsToTempFile("some-key-contents") Expect(err).NotTo(HaveOccurred()) chainFilePath, err = testhelpers.WriteContentsToTempFile("some-chain-contents") Expect(err).NotTo(HaveOccurred()) command = commands.NewUpdateLBs(awsCredentialValidator, certificateManager, availabilityZoneRetriever, infrastructureManager, boshClientProvider, logger, certificateValidator, guidGenerator, stateStore, stateValidator) }) Describe("Execute", func() { It("returns an error when state validator fails", func() { stateValidator.ValidateCall.Returns.Error = errors.New("state validator failed") err := command.Execute([]string{}, storage.State{}) Expect(stateValidator.ValidateCall.CallCount).To(Equal(1)) Expect(err).To(MatchError("state validator failed")) }) It("creates the new certificate with private key", func() { updateLBs(certFilePath, keyFilePath, "", storage.State{ Stack: storage.Stack{ LBType: "cf", CertificateName: "some-old-certificate-name", }, AWS: storage.AWS{ AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", Region: "some-region", }, }) Expect(logger.StepCall.Messages).To(ContainElement("uploading new certificate")) Expect(certificateManager.CreateCall.Receives.Certificate).To(Equal(certFilePath)) Expect(certificateManager.CreateCall.Receives.PrivateKey).To(Equal(keyFilePath)) Expect(certificateManager.CreateCall.Receives.CertificateName).To(Equal("cf-elb-cert-abcd")) }) Context("when uploading with a chain", func() { It("creates the new certificate with private key and chain", func() { updateLBs(certFilePath, keyFilePath, chainFilePath, storage.State{ Stack: storage.Stack{ LBType: "cf", CertificateName: "some-old-certificate-name", }, AWS: storage.AWS{ AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", Region: "some-region", }, }) Expect(certificateManager.CreateCall.Receives.Certificate).To(Equal(certFilePath)) Expect(certificateManager.CreateCall.Receives.PrivateKey).To(Equal(keyFilePath)) Expect(certificateManager.CreateCall.Receives.Chain).To(Equal(chainFilePath)) }) }) It("updates cloudformation with the new certificate", func() { updateLBs(certFilePath, keyFilePath, "", storage.State{ Stack: storage.Stack{ Name: "some-stack", LBType: "concourse", }, AWS: storage.AWS{ AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", Region: "some-region", }, KeyPair: storage.KeyPair{ Name: "some-key-pair", }, EnvID: "some-env-id:timestamp", }) Expect(availabilityZoneRetriever.RetrieveCall.Receives.Region).To(Equal("some-region")) Expect(certificateManager.DescribeCall.Receives.CertificateName).To(Equal("concourse-elb-cert-abcd-some-env-id-timestamp")) Expect(infrastructureManager.UpdateCall.Receives.KeyPairName).To(Equal("some-key-pair")) Expect(infrastructureManager.UpdateCall.Receives.NumberOfAvailabilityZones).To(Equal(3)) Expect(infrastructureManager.UpdateCall.Receives.StackName).To(Equal("some-stack")) Expect(infrastructureManager.UpdateCall.Receives.LBType).To(Equal("concourse")) Expect(infrastructureManager.UpdateCall.Receives.LBCertificateARN).To(Equal("some-certificate-arn")) Expect(infrastructureManager.UpdateCall.Receives.EnvID).To(Equal("some-env-id:timestamp")) }) It("names the loadbalancer without EnvID when EnvID is not set", func() { updateLBs(certFilePath, keyFilePath, "", storage.State{ Stack: storage.Stack{ Name: "some-stack", LBType: "concourse", }, AWS: storage.AWS{ AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", Region: "some-region", }, KeyPair: storage.KeyPair{ Name: "some-key-pair", }, EnvID: "", }) Expect(certificateManager.DescribeCall.Receives.CertificateName).To(Equal("concourse-elb-cert-abcd")) }) It("deletes the existing certificate and private key", func() { updateLBs(certFilePath, keyFilePath, "", storage.State{ Stack: storage.Stack{ LBType: "cf", CertificateName: "some-certificate-name", }, }) Expect(logger.StepCall.Messages).To(ContainElement("deleting old certificate")) Expect(certificateManager.DeleteCall.Receives.CertificateName).To(Equal("some-certificate-name")) }) It("checks if the bosh director exists", func() { err := updateLBs(certFilePath, keyFilePath, "", incomingState) Expect(err).NotTo(HaveOccurred()) Expect(boshClientProvider.ClientCall.Receives.DirectorAddress).To(Equal("some-director-address")) Expect(boshClientProvider.ClientCall.Receives.DirectorUsername).To(Equal("some-director-username")) Expect(boshClientProvider.ClientCall.Receives.DirectorPassword).To(Equal("<PASSWORD>")) Expect(boshClient.InfoCall.CallCount).To(Equal(1)) }) Context("if the user hasn't bbl'd up yet", func() { It("returns an error if the stack does not exist", func() { infrastructureManager.ExistsCall.Returns.Exists = false err := updateLBs(certFilePath, keyFilePath, "", storage.State{}) Expect(err).To(MatchError(commands.BBLNotFound)) }) It("returns an error if the bosh director does not exist", func() { boshClient.InfoCall.Returns.Error = errors.New("director not found") err := updateLBs(certFilePath, keyFilePath, "", storage.State{ Stack: storage.Stack{ LBType: "concourse", CertificateName: "some-certificate-name", }, }) Expect(err).To(MatchError(commands.BBLNotFound)) }) }) It("returns an error if there is no lb", func() { err := updateLBs(certFilePath, keyFilePath, "", storage.State{ Stack: storage.Stack{ LBType: "none", }, }) Expect(err).To(MatchError(commands.LBNotFound)) }) It("does not update the certificate if the provided certificate is the same", func() { certificateManager.DescribeCall.Returns.Certificate = iam.Certificate{ Body: "\nsome-certificate-contents\n", Chain: "\nsome-chain-contents\n", } err := updateLBs(certFilePath, keyFilePath, chainFilePath, incomingState) Expect(err).NotTo(HaveOccurred()) Expect(logger.PrintlnCall.Receives.Message).To(Equal("no updates are to be performed")) Expect(certificateManager.CreateCall.CallCount).To(Equal(0)) Expect(certificateManager.DeleteCall.CallCount).To(Equal(0)) Expect(infrastructureManager.UpdateCall.CallCount).To(Equal(0)) }) It("returns an error if the certificate is the same and the chain has changed", func() { certificateManager.DescribeCall.Returns.Certificate = iam.Certificate{ Body: "\nsome-certificate-contents\n", } err := updateLBs(certFilePath, keyFilePath, chainFilePath, incomingState) Expect(err).To(MatchError("you cannot change the chain after the lb has been created, please delete and re-create the lb with the chain")) Expect(certificateManager.CreateCall.CallCount).To(Equal(0)) Expect(certificateManager.DeleteCall.CallCount).To(Equal(0)) Expect(infrastructureManager.UpdateCall.CallCount).To(Equal(0)) }) It("returns an error when the certificate validator fails", func() { certificateValidator.ValidateCall.Returns.Error = errors.New("failed to validate") err := command.Execute([]string{ "--cert", "/path/to/cert", "--key", "/path/to/key", "--chain", "/path/to/chain", }, storage.State{ Stack: storage.Stack{ LBType: "concourse", }, }) Expect(err).To(MatchError("failed to validate")) Expect(certificateValidator.ValidateCall.Receives.Command).To(Equal("update-lbs")) Expect(certificateValidator.ValidateCall.Receives.CertificatePath).To(Equal("/path/to/cert")) Expect(certificateValidator.ValidateCall.Receives.KeyPath).To(Equal("/path/to/key")) Expect(certificateValidator.ValidateCall.Receives.ChainPath).To(Equal("/path/to/chain")) Expect(certificateManager.CreateCall.CallCount).To(Equal(0)) Expect(certificateManager.DeleteCall.CallCount).To(Equal(0)) }) Context("when --skip-if-missing is provided", func() { It("no-ops when lb does not exist", func() { err := command.Execute([]string{ "--cert", certFilePath, "--key", keyFilePath, "--skip-if-missing", }, storage.State{}) Expect(err).NotTo(HaveOccurred()) Expect(infrastructureManager.UpdateCall.CallCount).To(Equal(0)) Expect(certificateManager.CreateCall.CallCount).To(Equal(0)) Expect(logger.PrintlnCall.Receives.Message).To(Equal(`no lb type exists, skipping...`)) }) DescribeTable("updates the lb if the lb exists", func(currentLBType string) { incomingState.Stack.LBType = currentLBType err := command.Execute([]string{ "--cert", certFilePath, "--key", keyFilePath, "--skip-if-missing", }, incomingState) Expect(err).NotTo(HaveOccurred()) Expect(infrastructureManager.UpdateCall.CallCount).To(Equal(1)) Expect(certificateManager.CreateCall.CallCount).To(Equal(1)) }, Entry("when the current lb-type is 'cf'", "cf"), Entry("when the current lb-type is 'concourse'", "concourse"), ) }) Describe("state manipulation", func() { It("updates the state with the new certificate name", func() { err := updateLBs(certFilePath, keyFilePath, "", storage.State{ Stack: storage.Stack{ LBType: "cf", CertificateName: "some-certificate-name", }, EnvID: "some-env:timestamp", }) Expect(err).NotTo(HaveOccurred()) state := stateStore.SetCall.Receives.State Expect(stateStore.SetCall.CallCount).To(Equal(1)) Expect(state.Stack.CertificateName).To(Equal("cf-elb-cert-abcd-some-env-timestamp")) }) }) Describe("failure cases", func() { It("returns an error when the chain file cannot be opened", func() { certificateManager.DescribeCall.Returns.Certificate = iam.Certificate{ Body: "some-certificate-contents", } err := updateLBs(certFilePath, keyFilePath, "/some/fake/path", storage.State{ Stack: storage.Stack{ LBType: "cf", CertificateName: "some-certificate-name", }, }) Expect(err).To(MatchError(ContainSubstring("no such file or directory"))) }) It("returns an error when aws credential validator fails", func() { awsCredentialValidator.ValidateCall.Returns.Error = errors.New("aws credentials validator failed") err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("aws credentials validator failed")) }) It("returns an error when the original certificate cannot be described", func() { certificateManager.DescribeCall.Stub = func(certificateName string) (iam.Certificate, error) { if certificateName == "some-certificate-name" { return iam.Certificate{}, errors.New("old certificate failed to describe") } return iam.Certificate{}, nil } err := updateLBs(certFilePath, keyFilePath, "", incomingState) Expect(err).To(MatchError("old certificate failed to describe")) }) It("returns an error when new certificate cannot be described", func() { certificateManager.DescribeCall.Stub = func(certificateName string) (iam.Certificate, error) { if certificateName == "concourse-elb-cert-abcd" { return iam.Certificate{}, errors.New("new certificate failed to describe") } return iam.Certificate{}, nil } err := updateLBs(certFilePath, keyFilePath, "", incomingState) Expect(err).To(MatchError("new certificate failed to describe")) }) It("returns an error when the certificate file cannot be read", func() { err := updateLBs("some-fake-file", keyFilePath, "", incomingState) Expect(err).To(MatchError(ContainSubstring("no such file or directory"))) }) It("returns an error when the infrastructure manager fails to check the existance of a stack", func() { infrastructureManager.ExistsCall.Returns.Error = errors.New("failed to check for stack") err := updateLBs(certFilePath, keyFilePath, "", incomingState) Expect(err).To(MatchError("failed to check for stack")) }) It("returns an error when invalid flags are provided", func() { err := command.Execute([]string{ "--invalid-flag", }, incomingState) Expect(err).To(MatchError(ContainSubstring("flag provided but not defined"))) Expect(awsCredentialValidator.ValidateCall.CallCount).To(Equal(0)) }) It("returns an error when infrastructure update fails", func() { infrastructureManager.UpdateCall.Returns.Error = errors.New("failed to update stack") err := updateLBs(certFilePath, keyFilePath, "", incomingState) Expect(err).To(MatchError("failed to update stack")) }) It("returns an error when availability zone retriever fails", func() { availabilityZoneRetriever.RetrieveCall.Returns.Error = errors.New("az retrieve failed") err := updateLBs(certFilePath, keyFilePath, "", incomingState) Expect(err).To(MatchError("az retrieve failed")) }) It("returns an error when certificate creation fails", func() { certificateManager.CreateCall.Returns.Error = errors.New("certificate creation failed") err := updateLBs(certFilePath, keyFilePath, "", incomingState) Expect(err).To(MatchError("certificate creation failed")) }) It("returns an error when certificate deletion fails", func() { certificateManager.DeleteCall.Returns.Error = errors.New("certificate deletion failed") err := updateLBs(certFilePath, keyFilePath, "", incomingState) Expect(err).To(MatchError("certificate deletion failed")) }) It("returns an error when a GUID cannot be generated", func() { guidGenerator.GenerateCall.Returns.Error = errors.New("Out of entropy in the universe") err := updateLBs(certFilePath, keyFilePath, "", incomingState) Expect(err).To(MatchError("Out of entropy in the universe")) }) It("returns an error when state cannot be set", func() { stateStore.SetCall.Returns = []fakes.SetCallReturn{{errors.New("failed to set state")}} err := updateLBs(certFilePath, keyFilePath, "", incomingState) Expect(err).To(MatchError("failed to set state")) }) }) }) }) <file_sep>/storage/keypair_test.go package storage_test import ( "github.com/cloudfoundry/bosh-bootloader/storage" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("KeyPair", func() { Describe("IsEmpty", func() { It("returns true if empty", func() { keypair := storage.KeyPair{} Expect(keypair.IsEmpty()).To(BeTrue()) }) It("returns false if not empty", func() { keypair := storage.KeyPair{ Name: "some-name", } Expect(keypair.IsEmpty()).To(BeFalse()) }) }) }) <file_sep>/fakes/certificate_validator.go package fakes type CertificateValidator struct { ValidateCall struct { Returns struct { Error error } Receives struct { Command string CertificatePath string KeyPath string ChainPath string } } } func (c *CertificateValidator) Validate(command, certificatePath, keyPath, chainPath string) error { c.ValidateCall.Receives.Command = command c.ValidateCall.Receives.CertificatePath = certificatePath c.ValidateCall.Receives.KeyPath = keyPath c.ValidateCall.Receives.ChainPath = chainPath return c.ValidateCall.Returns.Error } <file_sep>/fakes/cloudformation_client.go package fakes import "github.com/aws/aws-sdk-go/service/cloudformation" type CloudFormationClient struct { CreateStackCall struct { Receives struct { Input *cloudformation.CreateStackInput } Returns struct { Error error } } UpdateStackCall struct { CallCount int Receives struct { Input *cloudformation.UpdateStackInput } Returns struct { Error error } } DescribeStacksCall struct { CallCount int Stub func(*cloudformation.DescribeStacksInput) (*cloudformation.DescribeStacksOutput, error) Receives struct { Input *cloudformation.DescribeStacksInput } Returns struct { Output *cloudformation.DescribeStacksOutput Error error } } DeleteStackCall struct { Receives struct { Input *cloudformation.DeleteStackInput } Returns struct { Output *cloudformation.DeleteStackOutput Error error } } DescribeStackResourceCall struct { Receives struct { Input *cloudformation.DescribeStackResourceInput } Returns struct { Output *cloudformation.DescribeStackResourceOutput Error error } } } func (c *CloudFormationClient) CreateStack(input *cloudformation.CreateStackInput) (*cloudformation.CreateStackOutput, error) { c.CreateStackCall.Receives.Input = input return nil, c.CreateStackCall.Returns.Error } func (c *CloudFormationClient) UpdateStack(input *cloudformation.UpdateStackInput) (*cloudformation.UpdateStackOutput, error) { c.UpdateStackCall.CallCount++ c.UpdateStackCall.Receives.Input = input return nil, c.UpdateStackCall.Returns.Error } func (c *CloudFormationClient) DescribeStacks(input *cloudformation.DescribeStacksInput) (*cloudformation.DescribeStacksOutput, error) { c.DescribeStacksCall.CallCount++ c.DescribeStacksCall.Receives.Input = input if c.DescribeStacksCall.Stub != nil { return c.DescribeStacksCall.Stub(input) } return c.DescribeStacksCall.Returns.Output, c.DescribeStacksCall.Returns.Error } func (c *CloudFormationClient) DeleteStack(input *cloudformation.DeleteStackInput) (*cloudformation.DeleteStackOutput, error) { c.DeleteStackCall.Receives.Input = input return c.DeleteStackCall.Returns.Output, c.DeleteStackCall.Returns.Error } func (c *CloudFormationClient) DescribeStackResource(input *cloudformation.DescribeStackResourceInput) (*cloudformation.DescribeStackResourceOutput, error) { c.DescribeStackResourceCall.Receives.Input = input return c.DescribeStackResourceCall.Returns.Output, c.DescribeStackResourceCall.Returns.Error } <file_sep>/bosh/cloud_config_manager_test.go package bosh_test import ( "errors" "gopkg.in/yaml.v2" "github.com/cloudfoundry/bosh-bootloader/bosh" "github.com/cloudfoundry/bosh-bootloader/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("CloudConfigManager", func() { Describe("Update", func() { var ( logger *fakes.Logger cloudConfigGenerator *fakes.CloudConfigGenerator boshClient *fakes.BOSHClient cloudConfigManager bosh.CloudConfigManager cloudConfigInput bosh.CloudConfigInput ) BeforeEach(func() { logger = &fakes.Logger{} cloudConfigGenerator = &fakes.CloudConfigGenerator{} boshClient = &fakes.BOSHClient{} cloudConfigManager = bosh.NewCloudConfigManager(logger, cloudConfigGenerator) cloudConfigGenerator.GenerateCall.Returns.CloudConfig = bosh.CloudConfig{ VMTypes: []bosh.VMType{ { Name: "some-vm-type", }, }, } cloudConfigInput = bosh.CloudConfigInput{ AZs: []string{ "us-east-1a", "us-east-1b", "us-east-1c", "us-east-1e", }, Subnets: []bosh.SubnetInput{ { AZ: "us-east-1a", Subnet: "some-internal-subnet-1", CIDR: "some-cidr-block-1", SecurityGroups: []string{"some-internal-security-group"}, }, { AZ: "us-east-1b", Subnet: "some-internal-subnet-2", CIDR: "some-cidr-block-2", SecurityGroups: []string{"some-internal-security-group"}, }, { AZ: "us-east-1c", Subnet: "some-internal-subnet-3", CIDR: "some-cidr-block-3", SecurityGroups: []string{"some-internal-security-group"}, }, { AZ: "us-east-1e", Subnet: "some-internal-subnet-4", CIDR: "some-cidr-block-4", SecurityGroups: []string{"some-internal-security-group"}, }, }, LBs: []bosh.LoadBalancerExtension{}, } }) It("generates and applies a cloud config", func() { err := cloudConfigManager.Update(cloudConfigInput, boshClient) Expect(err).NotTo(HaveOccurred()) manifestYAML, err := yaml.Marshal(bosh.CloudConfig{ VMTypes: []bosh.VMType{ { Name: "some-vm-type", }, }, }) Expect(err).NotTo(HaveOccurred()) Expect(boshClient.UpdateCloudConfigCall.CallCount).To(Equal(1)) Expect(boshClient.UpdateCloudConfigCall.Receives.Yaml).To(Equal(manifestYAML)) Expect(cloudConfigGenerator.GenerateCall.Receives.CloudConfigInput).To(Equal(cloudConfigInput)) }) Context("failure cases", func() { It("returns an error when the generate fails", func() { cloudConfigGenerator.GenerateCall.Returns.Error = errors.New("generate failed") err := cloudConfigManager.Update(cloudConfigInput, boshClient) Expect(err).To(MatchError("generate failed")) }) It("returns an error when the bosh client fails to upload the cloud config", func() { boshClient.UpdateCloudConfigCall.Returns.Error = errors.New("failed to upload") err := cloudConfigManager.Update(cloudConfigInput, boshClient) Expect(err).To(MatchError("failed to upload")) }) }) }) }) <file_sep>/bbl/fakeboshinit/main.go package main import ( "crypto/md5" "encoding/json" "fmt" "io/ioutil" "os" yaml "gopkg.in/yaml.v2" ) var ( FailFast = "false" ) func main() { fmt.Printf("bosh-init was called with %+v\n", os.Args) if FailFast == "true" { fmt.Fprintln(os.Stderr, "failing fast...") os.Exit(1) } contents, err := ioutil.ReadFile("bosh-state.json") if err != nil { fmt.Println(err) os.Exit(1) } fmt.Printf("bosh-state.json: %s\n", contents) var stateJson map[string]string err = json.Unmarshal(contents, &stateJson) if err != nil { fmt.Println(err) os.Exit(1) } oldManifestChecksum := stateJson["md5checksum"] manifestContents, err := ioutil.ReadFile("bosh.yml") if err != nil { fmt.Println(err) os.Exit(1) } fmt.Printf("bosh director name: %s\n", extractDirectorName(manifestContents)) newManifestChecksum := fmt.Sprintf("%x", md5.Sum(manifestContents)) stateContents := fmt.Sprintf(`{"key": "value", "md5checksum": %q}`, newManifestChecksum) err = ioutil.WriteFile("bosh-state.json", []byte(stateContents), os.FileMode(0644)) if err != nil { fmt.Println(err) os.Exit(1) } if oldManifestChecksum == newManifestChecksum { fmt.Println("No new changes, skipping deployment...") } } func extractDirectorName(manifestContents []byte) string { var manifest struct { Jobs []struct { Properties struct { Director struct { Name string } } } } err := yaml.Unmarshal(manifestContents, &manifest) if err != nil { fmt.Println(err) os.Exit(1) } if len(manifest.Jobs) == 0 { return "" } return manifest.Jobs[0].Properties.Director.Name } <file_sep>/aws/cloudformation/templates/load_balancer_subnets_template_builder_test.go package templates_test import ( "fmt" "reflect" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("LoadBalancerSubnetsTemplateBuilder", func() { var loadBalancerSubnetsTemplateBuilder templates.LoadBalancerSubnetsTemplateBuilder BeforeEach(func() { loadBalancerSubnetsTemplateBuilder = templates.NewLoadBalancerSubnetsTemplateBuilder() }) Describe("LoadBalancerSubnets", func() { It("creates load balancer subnets for each availability zone", func() { template := loadBalancerSubnetsTemplateBuilder.LoadBalancerSubnets(2) Expect(template.Parameters).To(HaveLen(2)) Expect(template.Parameters["LoadBalancerSubnet1CIDR"].Default).To(Equal("10.0.2.0/24")) Expect(template.Parameters["LoadBalancerSubnet2CIDR"].Default).To(Equal("10.0.3.0/24")) Expect(hasLBSubnetWithAvailabilityZoneIndex(template, 0)).To(BeTrue()) Expect(hasLBSubnetWithAvailabilityZoneIndex(template, 1)).To(BeTrue()) }) }) }) func hasLBSubnetWithAvailabilityZoneIndex(template templates.Template, index int) bool { azIndex := fmt.Sprintf("%d", index) subnetName := fmt.Sprintf("LoadBalancerSubnet%d", index+1) subnetCIDRName := fmt.Sprintf("%sCIDR", subnetName) tagName := fmt.Sprintf("LoadBalancer%d", index+1) return reflect.DeepEqual(template.Resources[subnetName].Properties, templates.Subnet{ AvailabilityZone: map[string]interface{}{ "Fn::Select": []interface{}{ azIndex, map[string]templates.Ref{ "Fn::GetAZs": templates.Ref{"AWS::Region"}, }, }, }, CidrBlock: templates.Ref{subnetCIDRName}, VpcId: templates.Ref{"VPC"}, Tags: []templates.Tag{ { Key: "Name", Value: tagName, }, }, }) } <file_sep>/bosh/cloud_configurator_test.go package bosh_test import ( "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation" "github.com/cloudfoundry/bosh-bootloader/bosh" "github.com/cloudfoundry/bosh-bootloader/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("CloudConfigurator", func() { Describe("Configure", func() { var ( logger *fakes.Logger cloudConfigGenerator *fakes.CloudConfigGenerator boshClient *fakes.BOSHClient cloudFormationStack cloudformation.Stack azs []string cloudConfigurator bosh.CloudConfigurator ) BeforeEach(func() { logger = &fakes.Logger{} cloudConfigGenerator = &fakes.CloudConfigGenerator{} boshClient = &fakes.BOSHClient{} cloudConfigurator = bosh.NewCloudConfigurator(logger, cloudConfigGenerator) cloudConfigGenerator.GenerateCall.Returns.CloudConfig = bosh.CloudConfig{ VMTypes: []bosh.VMType{ { Name: "some-vm-type", }, }, } cloudFormationStack = cloudformation.Stack{ Outputs: map[string]string{ "InternalSubnet1AZ": "us-east-1a", "InternalSubnet2AZ": "us-east-1b", "InternalSubnet3AZ": "us-east-1c", "InternalSubnet4AZ": "us-east-1e", "InternalSubnet1Name": "some-internal-subnet-1", "InternalSubnet2Name": "some-internal-subnet-2", "InternalSubnet3Name": "some-internal-subnet-3", "InternalSubnet4Name": "some-internal-subnet-4", "InternalSubnet1CIDR": "some-cidr-block-1", "InternalSubnet2CIDR": "some-cidr-block-2", "InternalSubnet3CIDR": "some-cidr-block-3", "InternalSubnet4CIDR": "some-cidr-block-4", "InternalSecurityGroup": "some-internal-security-group", "BOSHEIP": "bosh-director-url", }, } azs = []string{"us-east-1a", "us-east-1b", "us-east-1c", "us-east-1e"} }) It("returns a cloud config input", func() { cloudConfigInput := cloudConfigurator.Configure(cloudFormationStack, azs) Expect(cloudConfigInput).To(Equal(bosh.CloudConfigInput{ AZs: []string{ "us-east-1a", "us-east-1b", "us-east-1c", "us-east-1e", }, Subnets: []bosh.SubnetInput{ { AZ: "us-east-1a", Subnet: "some-internal-subnet-1", CIDR: "some-cidr-block-1", SecurityGroups: []string{"some-internal-security-group"}, }, { AZ: "us-east-1b", Subnet: "some-internal-subnet-2", CIDR: "some-cidr-block-2", SecurityGroups: []string{"some-internal-security-group"}, }, { AZ: "us-east-1c", Subnet: "some-internal-subnet-3", CIDR: "some-cidr-block-3", SecurityGroups: []string{"some-internal-security-group"}, }, { AZ: "us-east-1e", Subnet: "some-internal-subnet-4", CIDR: "some-cidr-block-4", SecurityGroups: []string{"some-internal-security-group"}, }, }, LBs: []bosh.LoadBalancerExtension{}, })) }) Context("vm extensions", func() { Context("when there is no lb", func() { It("generates a cloud config with no lb vm extension", func() { cloudFormationStack.Outputs["ConcourseLoadBalancer"] = "" cloudConfigInput := cloudConfigurator.Configure(cloudFormationStack, azs) Expect(cloudConfigInput.LBs).To(HaveLen(0)) }) }) Context("when the load balancer type is concourse", func() { It("generates a cloud config with a concourse lb vm extension", func() { cloudFormationStack.Outputs["ConcourseLoadBalancer"] = "some-lb" cloudFormationStack.Outputs["ConcourseInternalSecurityGroup"] = "some-concourse-internal-security-group" cloudFormationStack.Outputs["InternalSecurityGroup"] = "some-internal-security-group" cloudConfigInput := cloudConfigurator.Configure(cloudFormationStack, azs) Expect(cloudConfigInput.LBs).To(Equal([]bosh.LoadBalancerExtension{{ Name: "lb", ELBName: "some-lb", SecurityGroups: []string{ "some-concourse-internal-security-group", "some-internal-security-group", }, }})) }) }) Context("when the load balancer type is cf", func() { It("generates a cloud config with router-lb and ssh-proxy-lb vm extensions", func() { cloudFormationStack.Outputs["CFRouterLoadBalancer"] = "some-cf-router-load-balancer" cloudFormationStack.Outputs["CFSSHProxyLoadBalancer"] = "some-cf-ssh-proxy-load-balancer" cloudFormationStack.Outputs["InternalSecurityGroup"] = "some-internal-security-group" cloudFormationStack.Outputs["CFRouterInternalSecurityGroup"] = "some-cf-router-internal-security-group" cloudFormationStack.Outputs["CFSSHProxyInternalSecurityGroup"] = "some-cf-ssh-proxy-internal-security-group" cloudConfigInput := cloudConfigurator.Configure(cloudFormationStack, azs) Expect(cloudConfigInput.LBs).To(Equal([]bosh.LoadBalancerExtension{ { Name: "router-lb", ELBName: "some-cf-router-load-balancer", SecurityGroups: []string{ "some-cf-router-internal-security-group", "some-internal-security-group", }, }, { Name: "ssh-proxy-lb", ELBName: "some-cf-ssh-proxy-load-balancer", SecurityGroups: []string{ "some-cf-ssh-proxy-internal-security-group", "some-internal-security-group", }, }, })) }) }) }) }) }) <file_sep>/bosh/compilation_generator.go package bosh type CompilationGenerator struct{} type Compilation struct { Workers int `yaml:"workers"` Network string `yaml:"network"` AZ string `yaml:"az"` ReuseCompilationVMs bool `yaml:"reuse_compilation_vms"` VMType string `yaml:"vm_type"` VMExtensions []string `yaml:"vm_extensions"` } func NewCompilationGenerator() CompilationGenerator { return CompilationGenerator{} } func (CompilationGenerator) Generate() *Compilation { return &Compilation{ Workers: 6, Network: "private", AZ: "z1", ReuseCompilationVMs: true, VMType: "c3.large", VMExtensions: []string{"100GB_ephemeral_disk"}, } } <file_sep>/scripts/bbl #!/bin/bash -exu go install github.com/cloudfoundry/bosh-bootloader/bbl bbl "${@:-""}" <file_sep>/aws/cloudformation/infrastructure_manager.go package cloudformation import ( "fmt" "strings" "time" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" ) const bblTagKey = "bbl-env-id" type templateBuilder interface { Build(keypairName string, numberOfAvailabilityZones int, lbType string, lbCertificateARN string, iamUserName string, envID string) templates.Template } type stackManager interface { CreateOrUpdate(stackName string, template templates.Template, tags Tags) error Update(stackName string, template templates.Template, tags Tags) error WaitForCompletion(stackName string, sleepInterval time.Duration, action string) error Describe(stackName string) (Stack, error) Delete(stackName string) error GetPhysicalIDForResource(stackName string, logicalResourceID string) (string, error) } type InfrastructureManager struct { templateBuilder templateBuilder stackManager stackManager } func NewInfrastructureManager(builder templateBuilder, stackManager stackManager) InfrastructureManager { return InfrastructureManager{ templateBuilder: builder, stackManager: stackManager, } } func (m InfrastructureManager) Create(keyPairName string, numberOfAvailabilityZones int, stackName, lbType, lbCertificateARN, envID string) (Stack, error) { iamUserName := generateIAMUserName(envID) stackExists, err := m.Exists(stackName) if err != nil { return Stack{}, err } if stackExists { iamUserName, err = m.stackManager.GetPhysicalIDForResource(stackName, "BOSHUser") if err != nil { return Stack{}, err } } template := m.templateBuilder.Build(keyPairName, numberOfAvailabilityZones, lbType, lbCertificateARN, iamUserName, envID) tags := Tags{ { Key: bblTagKey, Value: envID, }, } if err := m.stackManager.CreateOrUpdate(stackName, template, tags); err != nil { return Stack{}, err } if err := m.stackManager.WaitForCompletion(stackName, 15*time.Second, "applying cloudformation template"); err != nil { return Stack{}, err } return m.stackManager.Describe(stackName) } func (m InfrastructureManager) Update(keyPairName string, numberOfAvailabilityZones int, stackName, lbType, lbCertificateARN, envID string) (Stack, error) { iamUserName, err := m.stackManager.GetPhysicalIDForResource(stackName, "BOSHUser") if err != nil { return Stack{}, err } template := m.templateBuilder.Build(keyPairName, numberOfAvailabilityZones, lbType, lbCertificateARN, iamUserName, envID) if err := m.stackManager.Update(stackName, template, Tags{{Key: bblTagKey, Value: envID}}); err != nil { return Stack{}, err } if err := m.stackManager.WaitForCompletion(stackName, 15*time.Second, "applying cloudformation template"); err != nil { return Stack{}, err } return m.stackManager.Describe(stackName) } func (m InfrastructureManager) Exists(stackName string) (bool, error) { _, err := m.stackManager.Describe(stackName) switch err { case nil: return true, nil case StackNotFound: return false, nil default: return false, err } } func (m InfrastructureManager) Describe(stackName string) (Stack, error) { return m.stackManager.Describe(stackName) } func (m InfrastructureManager) Delete(stackName string) error { err := m.stackManager.Delete(stackName) if err != nil { return err } err = m.stackManager.WaitForCompletion(stackName, 15*time.Second, "deleting cloudformation stack") if err != nil && err != StackNotFound { return err } return nil } func generateIAMUserName(envID string) string { return fmt.Sprintf("bosh-iam-user-%s", strings.Replace(envID, ":", "-", -1)) } <file_sep>/commands/lbs_test.go package commands_test import ( "bytes" "errors" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation" "github.com/cloudfoundry/bosh-bootloader/commands" "github.com/cloudfoundry/bosh-bootloader/fakes" "github.com/cloudfoundry/bosh-bootloader/storage" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("LBs", func() { var ( awsCredentialValidator *fakes.AWSCredentialValidator infrastructureManager *fakes.InfrastructureManager stateValidator *fakes.StateValidator lbsCommand commands.LBs stdout *bytes.Buffer ) BeforeEach(func() { awsCredentialValidator = &fakes.AWSCredentialValidator{} infrastructureManager = &fakes.InfrastructureManager{} stateValidator = &fakes.StateValidator{} stdout = bytes.NewBuffer([]byte{}) lbsCommand = commands.NewLBs(awsCredentialValidator, stateValidator, infrastructureManager, stdout) }) Describe("Execute", func() { It("prints LB names and URLs for lb type cf", func() { infrastructureManager.DescribeCall.Returns.Stack = cloudformation.Stack{ Name: "some-stack-name", Outputs: map[string]string{ "CFRouterLoadBalancer": "some-lb-name", "CFRouterLoadBalancerURL": "http://some.lb.url", "CFSSHProxyLoadBalancer": "some-other-lb-name", "CFSSHProxyLoadBalancerURL": "http://some.other.lb.url", }, } err := lbsCommand.Execute([]string{}, storage.State{ Stack: storage.Stack{ LBType: "cf", Name: "some-stack-name", }, }) Expect(err).NotTo(HaveOccurred()) Expect(awsCredentialValidator.ValidateCall.CallCount).To(Equal(1)) Expect(infrastructureManager.DescribeCall.Receives.StackName).To(Equal("some-stack-name")) Expect(stdout.String()).To(ContainSubstring("CF Router LB: some-lb-name [http://some.lb.url]")) Expect(stdout.String()).To(ContainSubstring("CF SSH Proxy LB: some-other-lb-name [http://some.other.lb.url]")) }) It("prints LB names and URLs for lb type concourse", func() { infrastructureManager.DescribeCall.Returns.Stack = cloudformation.Stack{ Name: "some-stack-name", Outputs: map[string]string{ "ConcourseLoadBalancer": "some-lb-name", "ConcourseLoadBalancerURL": "http://some.lb.url", }, } err := lbsCommand.Execute([]string{}, storage.State{ Stack: storage.Stack{ LBType: "concourse", Name: "some-stack-name", }, }) Expect(err).NotTo(HaveOccurred()) Expect(awsCredentialValidator.ValidateCall.CallCount).To(Equal(1)) Expect(infrastructureManager.DescribeCall.Receives.StackName).To(Equal("some-stack-name")) Expect(stdout.String()).To(ContainSubstring("Concourse LB: some-lb-name [http://some.lb.url]")) }) It("returns error when lb type is not cf or concourse", func() { err := lbsCommand.Execute([]string{}, storage.State{ Stack: storage.Stack{ LBType: "", }, }) Expect(err).To(MatchError("no lbs found")) }) Context("failure cases", func() { Context("when credential validator fails", func() { It("returns an error", func() { awsCredentialValidator.ValidateCall.Returns.Error = errors.New("validator failed") err := lbsCommand.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("validator failed")) }) }) Context("when infrastructure manager fails", func() { It("returns an error", func() { infrastructureManager.DescribeCall.Returns.Error = errors.New("infrastructure manager failed") err := lbsCommand.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("infrastructure manager failed")) }) }) It("returns an error when state validator fails", func() { stateValidator.ValidateCall.Returns.Error = errors.New("state validator failed") err := lbsCommand.Execute([]string{}, storage.State{}) Expect(stateValidator.ValidateCall.CallCount).To(Equal(1)) Expect(err).To(MatchError("state validator failed")) }) }) }) }) <file_sep>/aws/iam/certificate_deleter_test.go package iam_test import ( "errors" "github.com/aws/aws-sdk-go/aws" awsiam "github.com/aws/aws-sdk-go/service/iam" "github.com/cloudfoundry/bosh-bootloader/aws/iam" "github.com/cloudfoundry/bosh-bootloader/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("CertificateDeleter", func() { var ( iamClient *fakes.IAMClient iamClientProvider *fakes.ClientProvider deleter iam.CertificateDeleter ) BeforeEach(func() { iamClient = &fakes.IAMClient{} iamClientProvider = &fakes.ClientProvider{} iamClientProvider.GetIAMClientCall.Returns.IAMClient = iamClient deleter = iam.NewCertificateDeleter(iamClientProvider) }) Describe("Delete", func() { It("deletes the certificates with the given name", func() { iamClient.DeleteServerCertificateCall.Returns.Output = &awsiam.DeleteServerCertificateOutput{} err := deleter.Delete("some-certificate") Expect(err).NotTo(HaveOccurred()) Expect(iamClient.DeleteServerCertificateCall.Receives.Input.ServerCertificateName).To(Equal(aws.String("some-certificate"))) }) Context("failure cases", func() { It("returns an error when it fails to delete", func() { iamClient.DeleteServerCertificateCall.Returns.Error = errors.New("failed to delete certificate") err := deleter.Delete("some-certificate") Expect(err).To(MatchError("failed to delete certificate")) }) }) }) }) <file_sep>/commands/version.go package commands import ( "fmt" "io" "runtime" "github.com/cloudfoundry/bosh-bootloader/storage" ) const ( VersionCommand = "version" BBLDevVersion = "dev" ) type Version struct { stdout io.Writer version string } func NewVersion(version string, stdout io.Writer) Version { if version == "" { version = BBLDevVersion } return Version{ stdout: stdout, version: fmt.Sprintf("%s (%s/%s)", version, runtime.GOOS, runtime.GOARCH), } } func (v Version) Execute(subcommandFlags []string, state storage.State) error { fmt.Fprintln(v.stdout, fmt.Sprintf("bbl %s", v.version)) return nil } <file_sep>/aws/cloudformation/templates/internal_subnets_template_builder.go package templates import "fmt" type InternalSubnetsTemplateBuilder struct{} func NewInternalSubnetsTemplateBuilder() InternalSubnetsTemplateBuilder { return InternalSubnetsTemplateBuilder{} } func (InternalSubnetsTemplateBuilder) InternalSubnets(numberOfAvailabilityZones int) Template { internalSubnetTemplateBuilder := NewInternalSubnetTemplateBuilder() template := Template{} for index := 1; index <= numberOfAvailabilityZones; index++ { template = template.Merge(internalSubnetTemplateBuilder.InternalSubnet( index-1, fmt.Sprintf("%d", index), fmt.Sprintf("10.0.%d.0/20", 16*(index)), )) } return template } <file_sep>/helpers/string_generator_test.go package helpers_test import ( "crypto/rand" "errors" "github.com/cloudfoundry/bosh-bootloader/fakes" "github.com/cloudfoundry/bosh-bootloader/helpers" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("StringGenerator", func() { Describe("Generate", func() { It("generates random alphanumeric values of a given length", func() { generator := helpers.NewStringGenerator(rand.Reader) randomString, err := generator.Generate("prefix-", 15) Expect(err).NotTo(HaveOccurred()) Expect(randomString).To(MatchRegexp(`prefix-\w{15}`)) var randomStrings []string for i := 0; i < 10; i++ { randomString, err := generator.Generate("prefix-", 15) Expect(err).NotTo(HaveOccurred()) randomStrings = append(randomStrings, randomString) } Expect(HasUniqueValues(randomStrings)).To(BeTrue()) }) Context("failure cases", func() { It("returns an error when the reader fails", func() { reader := &fakes.Reader{} generator := helpers.NewStringGenerator(reader) reader.ReadCall.Returns.Error = errors.New("reader failed") _, err := generator.Generate("prefix", 1) Expect(err).To(MatchError("reader failed")) }) }) }) }) <file_sep>/aws/ec2/keypair_manager_test.go package ec2_test import ( "errors" "github.com/cloudfoundry/bosh-bootloader/aws/ec2" "github.com/cloudfoundry/bosh-bootloader/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/pivotal-cf-experimental/gomegamatchers" ) var _ = Describe("KeyPairManager", func() { Describe("Sync", func() { var ( stateKeyPair ec2.KeyPair creator *fakes.KeyPairCreator checker *fakes.KeyPairChecker logger *fakes.Logger manager ec2.KeyPairManager ) BeforeEach(func() { creator = &fakes.KeyPairCreator{} checker = &fakes.KeyPairChecker{} logger = &fakes.Logger{} manager = ec2.NewKeyPairManager(creator, checker, logger) }) It("checks if keypair already exists", func() { stateKeyPair = ec2.KeyPair{Name: "keypair-some-env-id"} _, err := manager.Sync(stateKeyPair) Expect(err).NotTo(HaveOccurred()) Expect(checker.HasKeyPairCall.CallCount).To(Equal(1)) Expect(logger.StepCall.Messages).To(ContainElement(`checking if keypair "keypair-some-env-id" exists`)) }) Context("no keypair in state file", func() { BeforeEach(func() { stateKeyPair = ec2.KeyPair{Name: "keypair-some-env-id"} checker.HasKeyPairCall.Returns.Present = false }) It("creates a keypair", func() { creator.CreateCall.Returns.KeyPair = ec2.KeyPair{ Name: "keypair-some-env-id", PublicKey: "public", PrivateKey: "private", } keypair, err := manager.Sync(stateKeyPair) Expect(err).NotTo(HaveOccurred()) Expect(keypair).To(Equal(ec2.KeyPair{ Name: "keypair-some-env-id", PublicKey: "public", PrivateKey: "private", })) Expect(creator.CreateCall.Receives.KeyPairName).To(Equal("keypair-some-env-id")) Expect(logger.StepCall.Messages).To(ContainSequence([]string{ `checking if keypair "keypair-some-env-id" exists`, "creating keypair", })) }) Context("error cases", func() { Context("when the keypair cannot be created", func() { It("returns an error", func() { creator.CreateCall.Returns.Error = errors.New("failed to create key pair") _, err := manager.Sync(stateKeyPair) Expect(err).To(MatchError("failed to create key pair")) }) }) Context("when remote keypair retrieve fails", func() { It("returns an error", func() { checker.HasKeyPairCall.Stub = nil checker.HasKeyPairCall.Returns.Error = errors.New("keypair retrieve failed") _, err := manager.Sync(stateKeyPair) Expect(err).To(MatchError("keypair retrieve failed")) }) }) }) }) Context("when the keypair is in the state file, but not on ec2", func() { BeforeEach(func() { stateKeyPair = ec2.KeyPair{ Name: "my-keypair", PublicKey: "public", PrivateKey: "private", } checker.HasKeyPairCall.Stub = func(name string) (bool, error) { if checker.HasKeyPairCall.CallCount == 1 { return false, nil } return true, nil } }) It("creates a keypair", func() { creator.CreateCall.Returns.KeyPair = ec2.KeyPair{ Name: "my-keypair", PublicKey: "public", PrivateKey: "private", } keypair, err := manager.Sync(stateKeyPair) Expect(err).NotTo(HaveOccurred()) Expect(keypair).To(Equal(ec2.KeyPair{ Name: "my-keypair", PublicKey: "public", PrivateKey: "private", })) Expect(checker.HasKeyPairCall.CallCount).To(Equal(1)) }) Context("failure cases", func() { Context("when the keypair cannot be created", func() { It("returns an error", func() { creator.CreateCall.Returns.Error = errors.New("failed to create key pair") _, err := manager.Sync(stateKeyPair) Expect(err).To(MatchError("failed to create key pair")) }) }) Context("remote keypair retrieve fails", func() { It("returns an error", func() { checker.HasKeyPairCall.Stub = nil checker.HasKeyPairCall.Returns.Error = errors.New("keypair retrieve failed") _, err := manager.Sync(ec2.KeyPair{}) Expect(err).To(MatchError("keypair retrieve failed")) }) }) }) }) Context("when the keypair is in the state file and on ec2", func() { BeforeEach(func() { stateKeyPair = ec2.KeyPair{ Name: "my-keypair", PublicKey: "public", PrivateKey: "private", } checker.HasKeyPairCall.Returns.Present = true }) It("logs that the existing keypair will be used", func() { _, err := manager.Sync(stateKeyPair) Expect(err).NotTo(HaveOccurred()) Expect(logger.StepCall.Messages).To(ContainSequence([]string{ `checking if keypair "my-keypair" exists`, "using existing keypair", })) }) }) }) }) <file_sep>/aws/ec2/keypair_deleter.go package ec2 import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" ) type KeyPairDeleter struct { ec2ClientProvider ec2ClientProvider logger logger } func NewKeyPairDeleter(ec2ClientProvider ec2ClientProvider, logger logger) KeyPairDeleter { return KeyPairDeleter{ ec2ClientProvider: ec2ClientProvider, logger: logger, } } func (d KeyPairDeleter) Delete(name string) error { d.logger.Step("deleting keypair") _, err := d.ec2ClientProvider.GetEC2Client().DeleteKeyPair(&ec2.DeleteKeyPairInput{ KeyName: aws.String(name), }) if err != nil { return err } return nil } <file_sep>/integration-test/actors/boshcli.go package actors import "os/exec" type BOSHCLI struct{} func NewBOSHCLI() BOSHCLI { return BOSHCLI{} } func (BOSHCLI) DirectorExists(address, caCertPath string) (bool, error) { _, err := exec.Command("bosh", "--ca-cert", caCertPath, "env", address, ).Output() return err == nil, err } <file_sep>/fakes/iam_client.go package fakes import "github.com/aws/aws-sdk-go/service/iam" type IAMClient struct { UploadServerCertificateCall struct { CallCount int Receives struct { Input *iam.UploadServerCertificateInput } Returns struct { Output *iam.UploadServerCertificateOutput Error error } } GetServerCertificateCall struct { CallCount int Receives struct { Input *iam.GetServerCertificateInput } Returns struct { Output *iam.GetServerCertificateOutput Error error } } DeleteServerCertificateCall struct { CallCount int Receives struct { Input *iam.DeleteServerCertificateInput } Returns struct { Output *iam.DeleteServerCertificateOutput Error error } } } func (c *IAMClient) UploadServerCertificate(input *iam.UploadServerCertificateInput) (*iam.UploadServerCertificateOutput, error) { c.UploadServerCertificateCall.CallCount++ c.UploadServerCertificateCall.Receives.Input = input return c.UploadServerCertificateCall.Returns.Output, c.UploadServerCertificateCall.Returns.Error } func (c *IAMClient) GetServerCertificate(input *iam.GetServerCertificateInput) (*iam.GetServerCertificateOutput, error) { c.GetServerCertificateCall.CallCount++ c.GetServerCertificateCall.Receives.Input = input return c.GetServerCertificateCall.Returns.Output, c.GetServerCertificateCall.Returns.Error } func (c *IAMClient) DeleteServerCertificate(input *iam.DeleteServerCertificateInput) (*iam.DeleteServerCertificateOutput, error) { c.DeleteServerCertificateCall.CallCount++ c.DeleteServerCertificateCall.Receives.Input = input return c.DeleteServerCertificateCall.Returns.Output, c.DeleteServerCertificateCall.Returns.Error } <file_sep>/fakes/keypair_manager.go package fakes import "github.com/cloudfoundry/bosh-bootloader/aws/ec2" type KeyPairManager struct { SyncCall struct { Receives struct { KeyPair ec2.KeyPair } Returns struct { KeyPair ec2.KeyPair Error error } } } func (k *KeyPairManager) Sync(keyPair ec2.KeyPair) (ec2.KeyPair, error) { k.SyncCall.Receives.KeyPair = keyPair return k.SyncCall.Returns.KeyPair, k.SyncCall.Returns.Error } <file_sep>/boshinit/manifests/resource_pools_manifest_builder_test.go package manifests_test import ( "github.com/cloudfoundry/bosh-bootloader/boshinit/manifests" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("ResourcePoolsManifestBuilder", func() { var resourcePoolsManifestBuilder manifests.ResourcePoolsManifestBuilder BeforeEach(func() { resourcePoolsManifestBuilder = manifests.NewResourcePoolsManifestBuilder() }) Describe("ResourcePools", func() { It("returns all resource pools for manifest", func() { resourcePools := resourcePoolsManifestBuilder.Build(manifests.ManifestProperties{AvailabilityZone: "some-az"}, "some-stemcell-url", "some-stemcell-sha1") Expect(resourcePools).To(HaveLen(1)) Expect(resourcePools).To(ConsistOf([]manifests.ResourcePool{ { Name: "vms", Network: "private", Stemcell: manifests.Stemcell{ URL: "some-stemcell-url", SHA1: "some-stemcell-sha1", }, CloudProperties: manifests.ResourcePoolCloudProperties{ InstanceType: "m3.xlarge", EphemeralDisk: manifests.EphemeralDisk{ Size: 25000, Type: "gp2", }, AvailabilityZone: "some-az", }, }, })) }) }) }) <file_sep>/boshinit/manifests/cloud_provider_manifest_builder.go package manifests import "fmt" const MBUS_USERNAME_PREFIX = "mbus-user-" const MBUS_PASSWORD_PREFIX = "<PASSWORD>-" type CloudProviderManifestBuilder struct { stringGenerator stringGenerator sharedPropertiesManifestBuilder SharedPropertiesManifestBuilder } func NewCloudProviderManifestBuilder(stringGenerator stringGenerator) CloudProviderManifestBuilder { return CloudProviderManifestBuilder{ stringGenerator: stringGenerator, } } func (c CloudProviderManifestBuilder) Build(manifestProperties ManifestProperties) (CloudProvider, ManifestProperties, error) { sharedPropertiesManifestBuilder := NewSharedPropertiesManifestBuilder() username := manifestProperties.Credentials.MBusUsername if username == "" { var err error username, err = c.stringGenerator.Generate(MBUS_USERNAME_PREFIX, PASSWORD_LENGTH) if err != nil { return CloudProvider{}, ManifestProperties{}, err } manifestProperties.Credentials.MBusUsername = username } password := manifestProperties.Credentials.MBusPassword if password == "" { var err error password, err = c.stringGenerator.Generate(MBUS_PASSWORD_PREFIX, PASSWORD_LENGTH) if err != nil { return CloudProvider{}, ManifestProperties{}, err } manifestProperties.Credentials.MBusPassword = <PASSWORD> } return CloudProvider{ Template: Template{ Name: "aws_cpi", Release: "bosh-aws-cpi", }, SSHTunnel: SSHTunnel{ Host: manifestProperties.ElasticIP, Port: 22, User: "vcap", PrivateKey: "./bosh.pem", }, MBus: fmt.Sprintf("https://%s:%s@%s:6868", username, password, manifestProperties.ElasticIP), Properties: CloudProviderProperties{ AWS: sharedPropertiesManifestBuilder.AWS(manifestProperties), Agent: AgentProperties{ MBus: fmt.Sprintf("https://%s:%s@0.0.0.0:6868", username, password), }, Blobstore: BlobstoreProperties{ Provider: "local", Path: "/var/vcap/micro_bosh/data/cache", }, }, }, manifestProperties, nil } <file_sep>/integration-test/actors/bosh.go package actors import "github.com/cloudfoundry/bosh-bootloader/bosh" type BOSH struct{} func NewBOSH() BOSH { return BOSH{} } func (BOSH) DirectorExists(address, username, password string) bool { client := bosh.NewClient(address, username, password) _, err := client.Info() return err == nil } <file_sep>/aws/cloudformation/templates/nat_template_builder_test.go package templates_test import ( "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("NATTemplateBuilder", func() { var builder templates.NATTemplateBuilder BeforeEach(func() { builder = templates.NewNATTemplateBuilder() }) Describe("NAT", func() { It("returns a template containing all of the NAT fields", func() { nat := builder.NAT() Expect(nat.Mappings).To(HaveLen(1)) Expect(nat.Mappings).To(HaveKeyWithValue("AWSNATAMI", map[string]templates.AMI{ "us-east-1": {"ami-68115b02"}, "us-west-1": {"ami-ef1a718f"}, "us-west-2": {"ami-77a4b816"}, "eu-west-1": {"ami-c0993ab3"}, "eu-central-1": {"ami-0b322e67"}, "ap-southeast-1": {"ami-e2fc3f81"}, "ap-southeast-2": {"ami-e3217a80"}, "ap-northeast-1": {"ami-f885ae96"}, "ap-northeast-2": {"ami-4118d72f"}, "sa-east-1": {"ami-8631b5ea"}, })) Expect(nat.Resources).To(HaveLen(3)) Expect(nat.Resources).To(HaveKeyWithValue("NATSecurityGroup", templates.Resource{ Type: "AWS::EC2::SecurityGroup", Properties: templates.SecurityGroup{ VpcId: templates.Ref{"VPC"}, GroupDescription: "NAT", SecurityGroupEgress: []templates.SecurityGroupEgress{}, SecurityGroupIngress: []templates.SecurityGroupIngress{ { SourceSecurityGroupId: templates.Ref{"InternalSecurityGroup"}, IpProtocol: "tcp", FromPort: "0", ToPort: "65535", }, { SourceSecurityGroupId: templates.Ref{"InternalSecurityGroup"}, IpProtocol: "udp", FromPort: "0", ToPort: "65535", }, }, }, })) Expect(nat.Resources).To(HaveKeyWithValue("NATInstance", templates.Resource{ Type: "AWS::EC2::Instance", Properties: templates.Instance{ InstanceType: "t2.medium", SubnetId: templates.Ref{"BOSHSubnet"}, SourceDestCheck: false, PrivateIpAddress: "10.0.0.7", ImageId: map[string]interface{}{ "Fn::FindInMap": []interface{}{ "AWSNATAMI", templates.Ref{"AWS::Region"}, "AMI", }, }, KeyName: templates.Ref{"SSHKeyPairName"}, SecurityGroupIds: []interface{}{ templates.Ref{"NATSecurityGroup"}, }, Tags: []templates.Tag{ { Key: "Name", Value: "NAT", }, }, }, })) Expect(nat.Resources).To(HaveKeyWithValue("NATEIP", templates.Resource{ Type: "AWS::EC2::EIP", DependsOn: "VPCGatewayAttachment", Properties: templates.EIP{ Domain: "vpc", InstanceId: templates.Ref{"NATInstance"}, }, })) }) }) }) <file_sep>/aws/ec2/keypair_checker_test.go package ec2_test import ( "errors" goaws "github.com/aws/aws-sdk-go/aws" awsec2 "github.com/aws/aws-sdk-go/service/ec2" "github.com/cloudfoundry/bosh-bootloader/aws/ec2" "github.com/cloudfoundry/bosh-bootloader/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("KeyPairChecker", func() { var ( ec2Client *fakes.EC2Client checker ec2.KeyPairChecker ec2ClientProvider *fakes.ClientProvider ) BeforeEach(func() { ec2Client = &fakes.EC2Client{} ec2ClientProvider = &fakes.ClientProvider{} ec2ClientProvider.GetEC2ClientCall.Returns.EC2Client = ec2Client checker = ec2.NewKeyPairChecker(ec2ClientProvider) }) Describe("HasKeyPair", func() { Context("when the keypair exists on AWS", func() { BeforeEach(func() { ec2Client.DescribeKeyPairsCall.Returns.Output = &awsec2.DescribeKeyPairsOutput{ KeyPairs: []*awsec2.KeyPairInfo{ { KeyFingerprint: goaws.String("some-finger-print"), KeyName: goaws.String("some-key-name"), }, }, } }) It("returns true", func() { present, err := checker.HasKeyPair("some-key-name") Expect(err).NotTo(HaveOccurred()) Expect(present).To(BeTrue()) Expect(ec2ClientProvider.GetEC2ClientCall.CallCount).To(Equal(1)) Expect(ec2Client.DescribeKeyPairsCall.Receives.Input).To(Equal(&awsec2.DescribeKeyPairsInput{ KeyNames: []*string{ goaws.String("some-key-name"), }, })) }) }) Context("when the keypair does not exist on AWS", func() { It("returns false when the keypair name can not be found", func() { ec2Client.DescribeKeyPairsCall.Returns.Error = errors.New("InvalidKeyPair.NotFound") present, err := checker.HasKeyPair("some-key-name") Expect(err).NotTo(HaveOccurred()) Expect(present).To(BeFalse()) }) It("returns false when the keypair name is empty", func() { ec2Client.DescribeKeyPairsCall.Returns.Error = errors.New("InvalidParameterValue: Invalid value '' for keyPairNames. It should not be blank") present, err := checker.HasKeyPair("") Expect(err).NotTo(HaveOccurred()) Expect(present).To(BeFalse()) }) }) Context("failure cases", func() { It("returns an error when AWS communication fails", func() { ec2Client.DescribeKeyPairsCall.Returns.Error = errors.New("something bad happened") _, err := checker.HasKeyPair("some-key-name") Expect(err).To(MatchError("something bad happened")) }) }) }) }) <file_sep>/fakes/certificate_uploader.go package fakes type CertificateUploader struct { UploadCall struct { CallCount int Receives struct { CertificatePath string PrivateKeyPath string ChainPath string CertificateName string } Returns struct { Error error } } } func (c *CertificateUploader) Upload(certificatePath, privateKeyPath, chainPath, certificateName string) error { c.UploadCall.CallCount++ c.UploadCall.Receives.CertificatePath = certificatePath c.UploadCall.Receives.PrivateKeyPath = privateKeyPath c.UploadCall.Receives.ChainPath = chainPath c.UploadCall.Receives.CertificateName = certificateName return c.UploadCall.Returns.Error } <file_sep>/aws/cloudformation/templates/bosh_subnet_template_builder.go package templates type BOSHSubnetTemplateBuilder struct{} func NewBOSHSubnetTemplateBuilder() BOSHSubnetTemplateBuilder { return BOSHSubnetTemplateBuilder{} } func (BOSHSubnetTemplateBuilder) BOSHSubnet() Template { return Template{ Parameters: map[string]Parameter{ "BOSHSubnetCIDR": Parameter{ Description: "CIDR block for the BOSH subnet.", Type: "String", Default: "10.0.0.0/24", }, }, Resources: map[string]Resource{ "BOSHSubnet": Resource{ Type: "AWS::EC2::Subnet", Properties: Subnet{ VpcId: Ref{"VPC"}, CidrBlock: Ref{"BOSHSubnetCIDR"}, Tags: []Tag{ { Key: "Name", Value: "BOSH", }, }, }, }, "BOSHRouteTable": Resource{ Type: "AWS::EC2::RouteTable", Properties: RouteTable{ VpcId: Ref{"VPC"}, }, }, "BOSHRoute": Resource{ DependsOn: "VPCGatewayAttachment", Type: "AWS::EC2::Route", Properties: Route{ DestinationCidrBlock: "0.0.0.0/0", GatewayId: Ref{"VPCGatewayInternetGateway"}, RouteTableId: Ref{"BOSHRouteTable"}, }, }, "BOSHSubnetRouteTableAssociation": Resource{ Type: "AWS::EC2::SubnetRouteTableAssociation", Properties: SubnetRouteTableAssociation{ RouteTableId: Ref{"BOSHRouteTable"}, SubnetId: Ref{"BOSHSubnet"}, }, }, }, Outputs: map[string]Output{ "BOSHSubnet": Output{ Value: Ref{"BOSHSubnet"}, }, "BOSHSubnetAZ": Output{ Value: FnGetAtt{ []string{ "BOSHSubnet", "AvailabilityZone", }, }, }, }, } } <file_sep>/aws/cloudformation/templates/security_group_template_builder.go package templates type SecurityGroupTemplateBuilder struct{} func NewSecurityGroupTemplateBuilder() SecurityGroupTemplateBuilder { return SecurityGroupTemplateBuilder{} } func (s SecurityGroupTemplateBuilder) LBSecurityGroup(securityGroupName, securityGroupDescription, loadBalancerName string, template Template) Template { securityGroupIngress := []SecurityGroupIngress{} properties := template.Resources[loadBalancerName].Properties.(ElasticLoadBalancingLoadBalancer) for _, listener := range properties.Listeners { securityGroupIngress = append(securityGroupIngress, s.securityGroupIngress( "0.0.0.0/0", s.determineSecurityGroupProtocol(listener.Protocol), listener.LoadBalancerPort, listener.LoadBalancerPort, nil, )) } return Template{ Resources: map[string]Resource{ securityGroupName: Resource{ Type: "AWS::EC2::SecurityGroup", Properties: SecurityGroup{ VpcId: Ref{"VPC"}, GroupDescription: securityGroupDescription, SecurityGroupEgress: []SecurityGroupEgress{}, SecurityGroupIngress: securityGroupIngress, }, }, }, } } func (s SecurityGroupTemplateBuilder) LBInternalSecurityGroup(securityGroupName, lbSecurityGroupName, securityGroupDescription, loadBalancerName string, template Template) Template { securityGroupIngress := []SecurityGroupIngress{} securityGroupPorts := map[string]bool{} properties := template.Resources[loadBalancerName].Properties.(ElasticLoadBalancingLoadBalancer) for _, listener := range properties.Listeners { if !securityGroupPorts[listener.InstancePort] { securityGroupIngress = append(securityGroupIngress, SecurityGroupIngress{ SourceSecurityGroupId: Ref{lbSecurityGroupName}, IpProtocol: s.determineSecurityGroupProtocol(listener.Protocol), FromPort: listener.InstancePort, ToPort: listener.InstancePort, }) securityGroupPorts[listener.InstancePort] = true } } return Template{ Resources: map[string]Resource{ securityGroupName: Resource{ Type: "AWS::EC2::SecurityGroup", Properties: SecurityGroup{ VpcId: Ref{"VPC"}, GroupDescription: securityGroupDescription, SecurityGroupEgress: []SecurityGroupEgress{}, SecurityGroupIngress: securityGroupIngress, }, }, }, Outputs: map[string]Output{ securityGroupName: Output{ Value: Ref{securityGroupName}, }, }, } } func (s SecurityGroupTemplateBuilder) InternalSecurityGroup() Template { return Template{ Resources: map[string]Resource{ "InternalSecurityGroup": Resource{ Type: "AWS::EC2::SecurityGroup", Properties: SecurityGroup{ VpcId: Ref{"VPC"}, GroupDescription: "Internal", SecurityGroupEgress: []SecurityGroupEgress{}, SecurityGroupIngress: []SecurityGroupIngress{ s.securityGroupIngress(nil, "tcp", "0", "65535", nil), s.securityGroupIngress(nil, "udp", "0", "65535", nil), s.securityGroupIngress("0.0.0.0/0", "icmp", "-1", "-1", nil), }, }, }, "InternalSecurityGroupIngressTCPfromBOSH": s.internalSecurityGroupIngress("BOSHSecurityGroup", "tcp"), "InternalSecurityGroupIngressUDPfromBOSH": s.internalSecurityGroupIngress("BOSHSecurityGroup", "udp"), "InternalSecurityGroupIngressTCPfromSelf": s.internalSecurityGroupIngress("InternalSecurityGroup", "tcp"), "InternalSecurityGroupIngressUDPfromSelf": s.internalSecurityGroupIngress("InternalSecurityGroup", "udp"), }, Outputs: map[string]Output{ "InternalSecurityGroup": {Value: Ref{"InternalSecurityGroup"}}, }, } } func (s SecurityGroupTemplateBuilder) BOSHSecurityGroup() Template { return Template{ Parameters: map[string]Parameter{ "BOSHInboundCIDR": Parameter{ Description: "CIDR to permit access to BOSH (e.g. 192.168.127.12/32 for your specific IP)", Type: "String", Default: "0.0.0.0/0", }, }, Resources: map[string]Resource{ "BOSHSecurityGroup": Resource{ Type: "AWS::EC2::SecurityGroup", Properties: SecurityGroup{ VpcId: Ref{"VPC"}, GroupDescription: "BOSH", SecurityGroupEgress: []SecurityGroupEgress{}, SecurityGroupIngress: []SecurityGroupIngress{ s.securityGroupIngress(Ref{"BOSHInboundCIDR"}, "tcp", "22", "22", nil), s.securityGroupIngress(Ref{"BOSHInboundCIDR"}, "tcp", "6868", "6868", nil), s.securityGroupIngress(Ref{"BOSHInboundCIDR"}, "tcp", "25555", "25555", nil), s.securityGroupIngress(nil, "tcp", "0", "65535", Ref{"InternalSecurityGroup"}), s.securityGroupIngress(nil, "udp", "0", "65535", Ref{"InternalSecurityGroup"}), }, }, }, }, Outputs: map[string]Output{ "BOSHSecurityGroup": Output{Value: Ref{"BOSHSecurityGroup"}}, }, } } func (SecurityGroupTemplateBuilder) internalSecurityGroupIngress(sourceSecurityGroupId, ipProtocol string) Resource { return Resource{ Type: "AWS::EC2::SecurityGroupIngress", Properties: SecurityGroupIngress{ GroupId: Ref{"InternalSecurityGroup"}, SourceSecurityGroupId: Ref{sourceSecurityGroupId}, IpProtocol: ipProtocol, FromPort: "0", ToPort: "65535", }, } } func (SecurityGroupTemplateBuilder) securityGroupIngress( cidrIP interface{}, ipProtocol string, fromPort string, toPort string, sourceSecurityGroupId interface{}) SecurityGroupIngress { return SecurityGroupIngress{ CidrIp: cidrIP, IpProtocol: ipProtocol, FromPort: fromPort, ToPort: toPort, SourceSecurityGroupId: sourceSecurityGroupId, } } func (SecurityGroupTemplateBuilder) determineSecurityGroupProtocol(listenerProtocol string) string { switch listenerProtocol { case "ssl": return "tcp" case "http", "https": return "tcp" default: return listenerProtocol } } <file_sep>/storage/exports_test.go package storage import ( "io" "os" ) func SetEncode(f func(io.Writer, interface{}) error) { encode = f } func ResetEncode() { encode = encodeFile } func SetRename(f func(string, string) error) { rename = f } func ResetRename() { rename = os.Rename } <file_sep>/aws/iam/client.go package iam import ( "github.com/cloudfoundry/bosh-bootloader/aws" "github.com/aws/aws-sdk-go/aws/session" awsiam "github.com/aws/aws-sdk-go/service/iam" ) type Client interface { UploadServerCertificate(*awsiam.UploadServerCertificateInput) (*awsiam.UploadServerCertificateOutput, error) GetServerCertificate(*awsiam.GetServerCertificateInput) (*awsiam.GetServerCertificateOutput, error) DeleteServerCertificate(*awsiam.DeleteServerCertificateInput) (*awsiam.DeleteServerCertificateOutput, error) } func NewClient(config aws.Config) Client { return awsiam.New(session.New(config.ClientConfig())) } <file_sep>/commands/update_lbs.go package commands import ( "errors" "io/ioutil" "strings" "github.com/cloudfoundry/bosh-bootloader/flags" "github.com/cloudfoundry/bosh-bootloader/storage" ) const UpdateLBsCommand = "update-lbs" type updateLBConfig struct { certPath string keyPath string chainPath string skipIfMissing bool } type UpdateLBs struct { certificateManager certificateManager availabilityZoneRetriever availabilityZoneRetriever infrastructureManager infrastructureManager awsCredentialValidator awsCredentialValidator boshClientProvider boshClientProvider logger logger certificateValidator certificateValidator guidGenerator guidGenerator stateStore stateStore stateValidator stateValidator } func NewUpdateLBs(awsCredentialValidator awsCredentialValidator, certificateManager certificateManager, availabilityZoneRetriever availabilityZoneRetriever, infrastructureManager infrastructureManager, boshClientProvider boshClientProvider, logger logger, certificateValidator certificateValidator, guidGenerator guidGenerator, stateStore stateStore, stateValidator stateValidator) UpdateLBs { return UpdateLBs{ awsCredentialValidator: awsCredentialValidator, certificateManager: certificateManager, availabilityZoneRetriever: availabilityZoneRetriever, infrastructureManager: infrastructureManager, boshClientProvider: boshClientProvider, logger: logger, certificateValidator: certificateValidator, guidGenerator: guidGenerator, stateStore: stateStore, stateValidator: stateValidator, } } func (c UpdateLBs) Execute(subcommandFlags []string, state storage.State) error { config, err := c.parseFlags(subcommandFlags) if err != nil { return err } if config.skipIfMissing && !lbExists(state.Stack.LBType) { c.logger.Println("no lb type exists, skipping...") return nil } err = c.stateValidator.Validate() if err != nil { return err } err = c.awsCredentialValidator.Validate() if err != nil { return err } err = c.certificateValidator.Validate(UpdateLBsCommand, config.certPath, config.keyPath, config.chainPath) if err != nil { return err } if err := checkBBLAndLB(state, c.boshClientProvider, c.infrastructureManager); err != nil { return err } if match, err := c.checkCertificateAndChain(config.certPath, config.chainPath, state.Stack.CertificateName); err != nil { return err } else if match { c.logger.Println("no updates are to be performed") return nil } c.logger.Step("uploading new certificate") certificateName, err := certificateNameFor(state.Stack.LBType, c.guidGenerator, state.EnvID) if err != nil { return err } err = c.certificateManager.Create(config.certPath, config.keyPath, config.chainPath, certificateName) if err != nil { return err } if err := c.updateStack(certificateName, state.KeyPair.Name, state.Stack.Name, state.Stack.LBType, state.AWS.Region, state.EnvID); err != nil { return err } c.logger.Step("deleting old certificate") err = c.certificateManager.Delete(state.Stack.CertificateName) if err != nil { return err } state.Stack.CertificateName = certificateName err = c.stateStore.Set(state) if err != nil { return err } return nil } func (c UpdateLBs) checkCertificateAndChain(certPath string, chainPath string, oldCertName string) (bool, error) { localCertificate, err := ioutil.ReadFile(certPath) if err != nil { return false, err } remoteCertificate, err := c.certificateManager.Describe(oldCertName) if err != nil { return false, err } if strings.TrimSpace(string(localCertificate)) != strings.TrimSpace(remoteCertificate.Body) { return false, nil } if chainPath != "" { localChain, err := ioutil.ReadFile(chainPath) if err != nil { return false, err } if strings.TrimSpace(string(localChain)) != strings.TrimSpace(remoteCertificate.Chain) { return false, errors.New("you cannot change the chain after the lb has been created, please delete and re-create the lb with the chain") } } return true, nil } func (UpdateLBs) parseFlags(subcommandFlags []string) (updateLBConfig, error) { lbFlags := flags.New("update-lbs") config := updateLBConfig{} lbFlags.String(&config.certPath, "cert", "") lbFlags.String(&config.keyPath, "key", "") lbFlags.String(&config.chainPath, "chain", "") lbFlags.Bool(&config.skipIfMissing, "skip-if-missing", "", false) err := lbFlags.Parse(subcommandFlags) if err != nil { return config, err } return config, nil } func (c UpdateLBs) updateStack(certificateName string, keyPairName string, stackName string, lbType string, awsRegion, envID string) error { availabilityZones, err := c.availabilityZoneRetriever.Retrieve(awsRegion) if err != nil { return err } certificate, err := c.certificateManager.Describe(certificateName) if err != nil { return err } _, err = c.infrastructureManager.Update(keyPairName, len(availabilityZones), stackName, lbType, certificate.ARN, envID) if err != nil { return err } return nil } <file_sep>/commands/create_lbs_test.go package commands_test import ( "errors" "fmt" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation" "github.com/cloudfoundry/bosh-bootloader/aws/iam" "github.com/cloudfoundry/bosh-bootloader/bosh" "github.com/cloudfoundry/bosh-bootloader/commands" "github.com/cloudfoundry/bosh-bootloader/fakes" "github.com/cloudfoundry/bosh-bootloader/storage" . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/extensions/table" . "github.com/onsi/gomega" ) var _ = Describe("Create LBs", func() { Describe("Execute", func() { var ( command commands.CreateLBs certificateManager *fakes.CertificateManager infrastructureManager *fakes.InfrastructureManager boshClient *fakes.BOSHClient boshClientProvider *fakes.BOSHClientProvider availabilityZoneRetriever *fakes.AvailabilityZoneRetriever boshCloudConfigurator *fakes.BoshCloudConfigurator awsCredentialValidator *fakes.AWSCredentialValidator logger *fakes.Logger cloudConfigManager *fakes.CloudConfigManager certificateValidator *fakes.CertificateValidator guidGenerator *fakes.GuidGenerator stateStore *fakes.StateStore stateValidator *fakes.StateValidator incomingState storage.State ) BeforeEach(func() { certificateManager = &fakes.CertificateManager{} infrastructureManager = &fakes.InfrastructureManager{} availabilityZoneRetriever = &fakes.AvailabilityZoneRetriever{} boshCloudConfigurator = &fakes.BoshCloudConfigurator{} boshClient = &fakes.BOSHClient{} boshClientProvider = &fakes.BOSHClientProvider{} awsCredentialValidator = &fakes.AWSCredentialValidator{} logger = &fakes.Logger{} cloudConfigManager = &fakes.CloudConfigManager{} certificateValidator = &fakes.CertificateValidator{} guidGenerator = &fakes.GuidGenerator{} stateStore = &fakes.StateStore{} stateValidator = &fakes.StateValidator{} boshClientProvider.ClientCall.Returns.Client = boshClient infrastructureManager.ExistsCall.Returns.Exists = true guidGenerator.GenerateCall.Returns.Output = "abcd" incomingState = storage.State{ Stack: storage.Stack{ Name: "some-stack", }, AWS: storage.AWS{ AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", Region: "some-region", }, KeyPair: storage.KeyPair{ Name: "some-key-pair", }, BOSH: storage.BOSH{ DirectorAddress: "some-director-address", DirectorUsername: "some-director-username", DirectorPassword: "<PASSWORD>", }, EnvID: "some-env-id:timestamp", } command = commands.NewCreateLBs(logger, awsCredentialValidator, certificateManager, infrastructureManager, availabilityZoneRetriever, boshClientProvider, boshCloudConfigurator, cloudConfigManager, certificateValidator, guidGenerator, stateStore, stateValidator) }) It("returns an error when state validator fails", func() { stateValidator.ValidateCall.Returns.Error = errors.New("state validator failed") err := command.Execute([]string{}, storage.State{}) Expect(stateValidator.ValidateCall.CallCount).To(Equal(1)) Expect(err).To(MatchError("state validator failed")) }) It("returns an error if aws credential validator fails", func() { awsCredentialValidator.ValidateCall.Returns.Error = errors.New("failed to validate aws credentials") err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("failed to validate aws credentials")) }) It("uploads a cert and key", func() { err := command.Execute([]string{ "--type", "concourse", "--cert", "temp/some-cert.crt", "--key", "temp/some-key.key", }, incomingState) Expect(err).NotTo(HaveOccurred()) Expect(certificateManager.CreateCall.Receives.Certificate).To(Equal("temp/some-cert.crt")) Expect(certificateManager.CreateCall.Receives.PrivateKey).To(Equal("temp/some-key.key")) Expect(certificateManager.CreateCall.Receives.CertificateName).To(Equal("concourse-elb-cert-abcd-some-env-id-timestamp")) Expect(logger.StepCall.Messages).To(ContainElement("uploading certificate")) }) It("uploads a cert and key with chain", func() { err := command.Execute([]string{ "--type", "concourse", "--cert", "temp/some-cert.crt", "--key", "temp/some-key.key", "--chain", "temp/some-chain.crt", }, storage.State{}) Expect(err).NotTo(HaveOccurred()) Expect(certificateManager.CreateCall.Receives.Chain).To(Equal("temp/some-chain.crt")) Expect(certificateValidator.ValidateCall.Receives.Command).To(Equal("create-lbs")) Expect(certificateValidator.ValidateCall.Receives.CertificatePath).To(Equal("temp/some-cert.crt")) Expect(certificateValidator.ValidateCall.Receives.KeyPath).To(Equal("temp/some-key.key")) Expect(certificateValidator.ValidateCall.Receives.ChainPath).To(Equal("temp/some-chain.crt")) }) It("creates a load balancer in cloudformation with certificate", func() { availabilityZoneRetriever.RetrieveCall.Returns.AZs = []string{"a", "b", "c"} certificateManager.DescribeCall.Returns.Certificate = iam.Certificate{ ARN: "some-certificate-arn", } err := command.Execute([]string{ "--type", "concourse", "--cert", "temp/some-cert.crt", "--key", "temp/some-key.key", }, incomingState) Expect(err).NotTo(HaveOccurred()) Expect(availabilityZoneRetriever.RetrieveCall.Receives.Region).To(Equal("some-region")) Expect(certificateManager.DescribeCall.Receives.CertificateName).To(Equal("concourse-elb-cert-abcd-some-env-id-timestamp")) Expect(infrastructureManager.UpdateCall.Receives.KeyPairName).To(Equal("some-key-pair")) Expect(infrastructureManager.UpdateCall.Receives.NumberOfAvailabilityZones).To(Equal(3)) Expect(infrastructureManager.UpdateCall.Receives.StackName).To(Equal("some-stack")) Expect(infrastructureManager.UpdateCall.Receives.LBType).To(Equal("concourse")) Expect(infrastructureManager.UpdateCall.Receives.LBCertificateARN).To(Equal("some-certificate-arn")) Expect(infrastructureManager.UpdateCall.Receives.EnvID).To(Equal("some-env-id:timestamp")) }) It("names the loadbalancer without EnvID when EnvID is not set", func() { incomingState.EnvID = "" availabilityZoneRetriever.RetrieveCall.Returns.AZs = []string{"a", "b", "c"} certificateManager.DescribeCall.Returns.Certificate = iam.Certificate{ ARN: "some-certificate-arn", } err := command.Execute([]string{ "--type", "concourse", "--cert", "temp/some-cert.crt", "--key", "temp/some-key.key", }, incomingState) Expect(err).NotTo(HaveOccurred()) Expect(certificateManager.DescribeCall.Receives.CertificateName).To(Equal("concourse-elb-cert-abcd")) }) It("updates the cloud config with lb type", func() { infrastructureManager.UpdateCall.Returns.Stack = cloudformation.Stack{ Name: "some-stack", } availabilityZoneRetriever.RetrieveCall.Returns.AZs = []string{"a", "b", "c"} boshCloudConfigurator.ConfigureCall.Returns.CloudConfigInput = bosh.CloudConfigInput{ AZs: []string{"a", "b", "c"}, } err := command.Execute([]string{ "--type", "concourse", "--cert", "temp/some-cert.crt", "--key", "temp/some-key.key", }, incomingState) Expect(err).NotTo(HaveOccurred()) Expect(boshCloudConfigurator.ConfigureCall.Receives.Stack).To(Equal(cloudformation.Stack{ Name: "some-stack", })) Expect(boshCloudConfigurator.ConfigureCall.Receives.AZs).To(Equal([]string{"a", "b", "c"})) Expect(cloudConfigManager.UpdateCall.Receives.CloudConfigInput).To(Equal(bosh.CloudConfigInput{ AZs: []string{"a", "b", "c"}, })) }) Context("when --skip-if-exists is provided", func() { It("no-ops when lb exists", func() { incomingState.Stack.LBType = "cf" err := command.Execute([]string{ "--type", "concourse", "--cert", "temp/some-cert.crt", "--key", "temp/some-key.key", "--skip-if-exists", }, incomingState) Expect(err).NotTo(HaveOccurred()) Expect(infrastructureManager.UpdateCall.CallCount).To(Equal(0)) Expect(certificateManager.CreateCall.CallCount).To(Equal(0)) Expect(logger.PrintlnCall.Receives.Message).To(Equal(`lb type "cf" exists, skipping...`)) }) DescribeTable("creates the lb if the lb does not exist", func(currentLBType string) { incomingState.Stack.LBType = currentLBType err := command.Execute([]string{ "--type", "concourse", "--cert", "temp/some-cert.crt", "--key", "temp/some-key.key", "--skip-if-exists", }, incomingState) Expect(err).NotTo(HaveOccurred()) Expect(infrastructureManager.UpdateCall.CallCount).To(Equal(1)) Expect(certificateManager.CreateCall.CallCount).To(Equal(1)) }, Entry("when the current lb-type is 'none'", "none"), Entry("when the current lb-type is ''", ""), ) }) Context("invalid lb type", func() { It("returns an error", func() { err := command.Execute([]string{ "--type", "some-invalid-lb", "--cert", "temp/some-cert.crt", "--key", "temp/some-key.key", }, storage.State{}) Expect(err).To(MatchError("\"some-invalid-lb\" is not a valid lb type, valid lb types are: concourse and cf")) }) }) Context("fast fail if the stack or BOSH director does not exist", func() { It("returns an error when the stack does not exist", func() { infrastructureManager.ExistsCall.Returns.Exists = false err := command.Execute([]string{ "--type", "concourse", "--cert", "temp/some-cert.crt", "--key", "temp/some-key.key", }, incomingState) Expect(infrastructureManager.ExistsCall.Receives.StackName).To(Equal("some-stack")) Expect(err).To(MatchError(commands.BBLNotFound)) }) It("returns an error when the BOSH director does not exist", func() { boshClient.InfoCall.Returns.Error = errors.New("director not found") infrastructureManager.ExistsCall.Returns.Exists = true err := command.Execute([]string{ "--type", "concourse", "--cert", "temp/some-cert.crt", "--key", "temp/some-key.key", }, incomingState) Expect(boshClientProvider.ClientCall.Receives.DirectorAddress).To(Equal("some-director-address")) Expect(boshClientProvider.ClientCall.Receives.DirectorUsername).To(Equal("some-director-username")) Expect(boshClientProvider.ClientCall.Receives.DirectorPassword).To(Equal("<PASSWORD>")) Expect(boshClient.InfoCall.CallCount).To(Equal(1)) Expect(err).To(MatchError(commands.BBLNotFound)) }) }) Context("state manipulation", func() { Context("when the env id does not exist", func() { It("saves state with new certificate name and lb type", func() { err := command.Execute([]string{ "--type", "concourse", "--cert", "temp/some-cert.crt", "--key", "temp/some-key.key", }, storage.State{}) Expect(err).NotTo(HaveOccurred()) state := stateStore.SetCall.Receives.State Expect(stateStore.SetCall.CallCount).To(Equal(1)) Expect(state.Stack.CertificateName).To(Equal("concourse-elb-cert-abcd")) Expect(state.Stack.LBType).To(Equal("concourse")) }) }) Context("when the env id exists", func() { It("saves state with new certificate name and lb type", func() { err := command.Execute([]string{ "--type", "concourse", "--cert", "temp/some-cert.crt", "--key", "temp/some-key.key", }, storage.State{ EnvID: "some-env-id:timestamp", }) Expect(err).NotTo(HaveOccurred()) state := stateStore.SetCall.Receives.State Expect(stateStore.SetCall.CallCount).To(Equal(1)) Expect(state.Stack.CertificateName).To(Equal("concourse-elb-cert-abcd-some-env-id-timestamp")) Expect(state.Stack.LBType).To(Equal("concourse")) }) }) }) Context("required args", func() { It("returns an error when certificate validator fails for cert and key", func() { certificateValidator.ValidateCall.Returns.Error = errors.New("failed to validate") err := command.Execute([]string{ "--type", "concourse", "--cert", "/path/to/cert", "--key", "/path/to/key", }, storage.State{}) Expect(err).To(MatchError("failed to validate")) Expect(certificateValidator.ValidateCall.Receives.Command).To(Equal("create-lbs")) Expect(certificateValidator.ValidateCall.Receives.CertificatePath).To(Equal("/path/to/cert")) Expect(certificateValidator.ValidateCall.Receives.KeyPath).To(Equal("/path/to/key")) Expect(certificateValidator.ValidateCall.Receives.ChainPath).To(Equal("")) Expect(certificateManager.CreateCall.CallCount).To(Equal(0)) }) }) Context("failure cases", func() { DescribeTable("returns an error when an lb already exists", func(newLbType, oldLbType string) { err := command.Execute([]string{ "--type", "concourse", "--cert", "/path/to/cert", "--key", "/path/to/key", }, storage.State{ Stack: storage.Stack{ LBType: oldLbType, }, }) Expect(err).To(MatchError(fmt.Sprintf("bbl already has a %s load balancer attached, please remove the previous load balancer before attaching a new one", oldLbType))) }, Entry("when the previous lb type is concourse", "concourse", "cf"), Entry("when the previous lb type is cf", "cf", "concourse"), ) It("returns an error when the infrastructure manager fails to check the existance of a stack", func() { infrastructureManager.ExistsCall.Returns.Error = errors.New("failed to check for stack") err := command.Execute([]string{ "--type", "concourse", "--cert", "/path/to/cert", "--key", "/path/to/key", }, storage.State{}) Expect(err).To(MatchError("failed to check for stack")) }) Context("when an invalid command line flag is supplied", func() { It("returns an error", func() { err := command.Execute([]string{"--invalid-flag"}, storage.State{}) Expect(err).To(MatchError("flag provided but not defined: -invalid-flag")) Expect(awsCredentialValidator.ValidateCall.CallCount).To(Equal(0)) }) }) Context("when availability zone retriever fails", func() { It("returns an error", func() { availabilityZoneRetriever.RetrieveCall.Returns.Error = errors.New("failed to retrieve azs") err := command.Execute([]string{ "--type", "concourse", "--cert", "/path/to/cert", "--key", "/path/to/key", }, storage.State{}) Expect(err).To(MatchError("failed to retrieve azs")) }) }) Context("when update infrastructure manager fails", func() { It("returns an error", func() { infrastructureManager.UpdateCall.Returns.Error = errors.New("failed to update infrastructure") err := command.Execute([]string{ "--type", "concourse", "--cert", "/path/to/cert", "--key", "/path/to/key", }, storage.State{}) Expect(err).To(MatchError("failed to update infrastructure")) }) }) Context("when certificate manager fails to create a certificate", func() { It("returns an error", func() { certificateManager.CreateCall.Returns.Error = errors.New("failed to create cert") err := command.Execute([]string{ "--type", "concourse", "--cert", "/path/to/cert", "--key", "/path/to/key", }, storage.State{}) Expect(err).To(MatchError("failed to create cert")) }) }) Context("when cloud config manager update fails", func() { It("returns an error", func() { cloudConfigManager.UpdateCall.Returns.Error = errors.New("failed to update cloud config") err := command.Execute([]string{ "--type", "concourse", "--cert", "/path/to/cert", "--key", "/path/to/key", }, storage.State{}) Expect(err).To(MatchError("failed to update cloud config")) }) }) It("returns an error when a GUID cannot be generated", func() { guidGenerator.GenerateCall.Returns.Error = errors.New("Out of entropy in the universe") err := command.Execute([]string{ "--type", "concourse", "--cert", "/path/to/cert", "--key", "/path/to/key", }, storage.State{}) Expect(err).To(MatchError("Out of entropy in the universe")) }) It("returns an error when the state fails to save", func() { stateStore.SetCall.Returns = []fakes.SetCallReturn{{errors.New("failed to save state")}} err := command.Execute([]string{ "--type", "concourse", "--cert", "/path/to/cert", "--key", "/path/to/key", }, storage.State{}) Expect(err).To(MatchError("failed to save state")) }) }) }) }) <file_sep>/commands/lbs.go package commands import ( "errors" "fmt" "io" "github.com/cloudfoundry/bosh-bootloader/storage" ) const ( LBsCommand = "lbs" ) type LBs struct { awsCredentialValidator awsCredentialValidator infrastructureManager infrastructureManager stateValidator stateValidator stdout io.Writer } func NewLBs(awsCredentialValidator awsCredentialValidator, stateValidator stateValidator, infrastructureManager infrastructureManager, stdout io.Writer) LBs { return LBs{ awsCredentialValidator: awsCredentialValidator, infrastructureManager: infrastructureManager, stateValidator: stateValidator, stdout: stdout, } } func (c LBs) Execute(subcommandFlags []string, state storage.State) error { err := c.stateValidator.Validate() if err != nil { return err } err = c.awsCredentialValidator.Validate() if err != nil { return err } stack, err := c.infrastructureManager.Describe(state.Stack.Name) if err != nil { return err } switch state.Stack.LBType { case "cf": fmt.Fprintf(c.stdout, "CF Router LB: %s [%s]\n", stack.Outputs["CFRouterLoadBalancer"], stack.Outputs["CFRouterLoadBalancerURL"]) fmt.Fprintf(c.stdout, "CF SSH Proxy LB: %s [%s]\n", stack.Outputs["CFSSHProxyLoadBalancer"], stack.Outputs["CFSSHProxyLoadBalancerURL"]) case "concourse": fmt.Fprintf(c.stdout, "Concourse LB: %s [%s]\n", stack.Outputs["ConcourseLoadBalancer"], stack.Outputs["ConcourseLoadBalancerURL"]) default: return errors.New("no lbs found") } return nil } <file_sep>/aws/cloudformation/templates/load_balancer_subnets_template_builder.go package templates import "fmt" type LoadBalancerSubnetsTemplateBuilder struct{} func NewLoadBalancerSubnetsTemplateBuilder() LoadBalancerSubnetsTemplateBuilder { return LoadBalancerSubnetsTemplateBuilder{} } func (LoadBalancerSubnetsTemplateBuilder) LoadBalancerSubnets(azCount int) Template { loadBalancerSubnetTemplateBuilder := NewLoadBalancerSubnetTemplateBuilder() template := Template{} for index := 1; index <= azCount; index++ { template = template.Merge(loadBalancerSubnetTemplateBuilder.LoadBalancerSubnet( index-1, fmt.Sprintf("%d", index), fmt.Sprintf("10.0.%d.0/24", index+1), )) } return template } <file_sep>/fakes/bosh_cloud_configurator.go package fakes import ( "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation" "github.com/cloudfoundry/bosh-bootloader/bosh" ) type BoshCloudConfigurator struct { ConfigureCall struct { CallCount int Receives struct { Stack cloudformation.Stack AZs []string } Returns struct { CloudConfigInput bosh.CloudConfigInput } } } func (b *BoshCloudConfigurator) Configure(stack cloudformation.Stack, azs []string) bosh.CloudConfigInput { b.ConfigureCall.CallCount++ b.ConfigureCall.Receives.Stack = stack b.ConfigureCall.Receives.AZs = azs return b.ConfigureCall.Returns.CloudConfigInput } <file_sep>/fakes/keypair_deleter.go package fakes type KeyPairDeleter struct { DeleteCall struct { Receives struct { Name string } Returns struct { Error error } } } func (d *KeyPairDeleter) Delete(name string) error { d.DeleteCall.Receives.Name = name return d.DeleteCall.Returns.Error } <file_sep>/aws/iam/certificate_manager_test.go package iam_test import ( "errors" "io/ioutil" "os" "github.com/cloudfoundry/bosh-bootloader/aws/iam" "github.com/cloudfoundry/bosh-bootloader/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("CertificateManager", func() { var ( certificateUploader *fakes.CertificateUploader certificateDescriber *fakes.CertificateDescriber certificateDeleter *fakes.CertificateDeleter manager iam.CertificateManager certificateFile *os.File privateKeyFile *os.File chainFile *os.File ) BeforeEach(func() { var err error certificateUploader = &fakes.CertificateUploader{} certificateDescriber = &fakes.CertificateDescriber{} certificateDeleter = &fakes.CertificateDeleter{} manager = iam.NewCertificateManager(certificateUploader, certificateDescriber, certificateDeleter) certificateFile, err = ioutil.TempFile("", "") Expect(err).NotTo(HaveOccurred()) privateKeyFile, err = ioutil.TempFile("", "") Expect(err).NotTo(HaveOccurred()) chainFile, err = ioutil.TempFile("", "") Expect(err).NotTo(HaveOccurred()) }) Describe("Create", func() { It("creates the given certificate", func() { certificateName := "certificate-name" err := manager.Create(certificateFile.Name(), privateKeyFile.Name(), chainFile.Name(), certificateName) Expect(err).NotTo(HaveOccurred()) Expect(certificateUploader.UploadCall.CallCount).To(Equal(1)) Expect(certificateUploader.UploadCall.Receives.CertificatePath).To(Equal(certificateFile.Name())) Expect(certificateUploader.UploadCall.Receives.PrivateKeyPath).To(Equal(privateKeyFile.Name())) Expect(certificateUploader.UploadCall.Receives.ChainPath).To(Equal(chainFile.Name())) Expect(certificateUploader.UploadCall.Receives.CertificateName).To(Equal("certificate-name")) }) Context("failure cases", func() { Context("when certificate uploader fails to upload", func() { It("returns an error", func() { certificateUploader.UploadCall.Returns.Error = errors.New("upload failed") err := manager.Create(certificateFile.Name(), privateKeyFile.Name(), chainFile.Name(), "cert-name") Expect(err).To(MatchError("upload failed")) }) }) }) }) Describe("Delete", func() { It("deletes the given certificate", func() { err := manager.Delete("some-certificate-name") Expect(err).NotTo(HaveOccurred()) Expect(certificateDeleter.DeleteCall.Receives.CertificateName).To(Equal("some-certificate-name")) }) Context("failure cases", func() { It("returns an error when certificate fails to delete", func() { certificateDeleter.DeleteCall.Returns.Error = errors.New("unknown certificate error") err := manager.Delete("some-non-existant-certificate") Expect(err).To(MatchError("unknown certificate error")) }) }) }) Describe("Describe", func() { It("returns a certificate", func() { certificateDescriber.DescribeCall.Returns.Certificate = iam.Certificate{ Name: "some-certificate-name", ARN: "some-certificate-arn", Body: "some-certificate-body", } certificate, err := manager.Describe("some-certificate-name") Expect(err).NotTo(HaveOccurred()) Expect(certificate).To(Equal(iam.Certificate{ Name: "some-certificate-name", ARN: "some-certificate-arn", Body: "some-certificate-body", })) Expect(certificateDescriber.DescribeCall.Receives.CertificateName).To(Equal("some-certificate-name")) }) Context("failure cases", func() { It("returns an error when the describe fails", func() { certificateDescriber.DescribeCall.Returns.Error = errors.New("unknown certificate error") _, err := manager.Describe("some-non-existant-certificate") Expect(err).To(MatchError("unknown certificate error")) }) }) }) }) <file_sep>/commands/state_query_test.go package commands_test import ( "errors" "fmt" "math/rand" "github.com/cloudfoundry/bosh-bootloader/commands" "github.com/cloudfoundry/bosh-bootloader/fakes" "github.com/cloudfoundry/bosh-bootloader/storage" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("StateQuery", func() { var ( fakeLogger *fakes.Logger fakeStateValidator *fakes.StateValidator ) BeforeEach(func() { fakeLogger = &fakes.Logger{} fakeStateValidator = &fakes.StateValidator{} }) Describe("Execute", func() { It("prints out the director address", func() { command := commands.NewStateQuery(fakeLogger, fakeStateValidator, "director address", func(state storage.State) string { return state.BOSH.DirectorAddress }) state := storage.State{ BOSH: storage.BOSH{ DirectorAddress: "some-director-address", }, } err := command.Execute([]string{}, state) Expect(err).NotTo(HaveOccurred()) Expect(fakeLogger.PrintlnCall.Receives.Message).To(Equal("some-director-address")) }) It("returns an error when the state validator fails", func() { fakeStateValidator.ValidateCall.Returns.Error = errors.New("state validator failed") command := commands.NewStateQuery(fakeLogger, fakeStateValidator, "", func(state storage.State) string { return "" }) err := command.Execute([]string{}, storage.State{ BOSH: storage.BOSH{}, }) Expect(err).To(MatchError("state validator failed")) }) It("returns an error when the state value is empty", func() { propertyName := fmt.Sprintf("%s-%d", "some-name", rand.Int()) command := commands.NewStateQuery(fakeLogger, fakeStateValidator, propertyName, func(state storage.State) string { return "" }) err := command.Execute([]string{}, storage.State{ BOSH: storage.BOSH{}, }) Expect(err).To(MatchError(fmt.Sprintf("Could not retrieve %s, please make sure you are targeting the proper state dir.", propertyName))) Expect(fakeLogger.PrintlnCall.CallCount).To(Equal(0)) }) }) }) <file_sep>/scripts/local_ci #!/bin/bash -eu ROOT_DIRECTORY="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )" pushd "${ROOT_DIRECTORY}" set -e docker pull cfinfrastructure/golang docker run -v $PWD:/bosh-bootloader \ -v ${MEGA_CI:-"${GOPATH}/src/github.com/cloudfoundry/mega-ci"}:/mega-ci \ cfinfrastructure/golang ${TEST_TASK:-"/mega-ci/scripts/ci/bosh-bootloader/test"} popd <file_sep>/commands/create_lbs.go package commands import ( "fmt" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation" "github.com/cloudfoundry/bosh-bootloader/aws/iam" "github.com/cloudfoundry/bosh-bootloader/bosh" "github.com/cloudfoundry/bosh-bootloader/flags" "github.com/cloudfoundry/bosh-bootloader/storage" ) const CreateLBsCommand = "create-lbs" type CreateLBs struct { logger logger certificateManager certificateManager infrastructureManager infrastructureManager boshClientProvider boshClientProvider availabilityZoneRetriever availabilityZoneRetriever boshCloudConfigurator boshCloudConfigurator awsCredentialValidator awsCredentialValidator cloudConfigManager cloudConfigManager certificateValidator certificateValidator guidGenerator guidGenerator stateStore stateStore stateValidator stateValidator } type lbConfig struct { lbType string certPath string keyPath string chainPath string skipIfExists bool } type certificateManager interface { Create(certificate, privateKey, chain, certificateName string) error Describe(certificateName string) (iam.Certificate, error) Delete(certificateName string) error } type boshClientProvider interface { Client(directorAddress, directorUsername, directorPassword string) bosh.Client } type boshCloudConfigurator interface { Configure(stack cloudformation.Stack, azs []string) bosh.CloudConfigInput } type certificateValidator interface { Validate(command, certPath, keyPath, chainPath string) error } type guidGenerator interface { Generate() (string, error) } func NewCreateLBs(logger logger, awsCredentialValidator awsCredentialValidator, certificateManager certificateManager, infrastructureManager infrastructureManager, availabilityZoneRetriever availabilityZoneRetriever, boshClientProvider boshClientProvider, boshCloudConfigurator boshCloudConfigurator, cloudConfigManager cloudConfigManager, certificateValidator certificateValidator, guidGenerator guidGenerator, stateStore stateStore, stateValidator stateValidator) CreateLBs { return CreateLBs{ logger: logger, certificateManager: certificateManager, infrastructureManager: infrastructureManager, boshClientProvider: boshClientProvider, availabilityZoneRetriever: availabilityZoneRetriever, boshCloudConfigurator: boshCloudConfigurator, awsCredentialValidator: awsCredentialValidator, cloudConfigManager: cloudConfigManager, certificateValidator: certificateValidator, guidGenerator: guidGenerator, stateStore: stateStore, stateValidator: stateValidator, } } func (c CreateLBs) Execute(subcommandFlags []string, state storage.State) error { config, err := c.parseFlags(subcommandFlags) if err != nil { return err } err = c.stateValidator.Validate() if err != nil { return err } err = c.awsCredentialValidator.Validate() if err != nil { return err } err = c.certificateValidator.Validate(CreateLBsCommand, config.certPath, config.keyPath, config.chainPath) if err != nil { return err } if config.skipIfExists && lbExists(state.Stack.LBType) { c.logger.Println(fmt.Sprintf("lb type %q exists, skipping...", state.Stack.LBType)) return nil } boshClient := c.boshClientProvider.Client(state.BOSH.DirectorAddress, state.BOSH.DirectorUsername, state.BOSH.DirectorPassword) if err := c.checkFastFails(config.lbType, state.Stack.LBType, state.Stack.Name, boshClient); err != nil { return err } c.logger.Step("uploading certificate") certificateName, err := certificateNameFor(config.lbType, c.guidGenerator, state.EnvID) if err != nil { return err } err = c.certificateManager.Create(config.certPath, config.keyPath, config.chainPath, certificateName) if err != nil { return err } state.Stack.CertificateName = certificateName state.Stack.LBType = config.lbType if err := c.updateStackAndBOSH(state.AWS.Region, certificateName, state.KeyPair.Name, state.Stack.Name, config.lbType, boshClient, state.EnvID); err != nil { return err } err = c.stateStore.Set(state) if err != nil { return err } return nil } func (CreateLBs) parseFlags(subcommandFlags []string) (lbConfig, error) { lbFlags := flags.New("create-lbs") config := lbConfig{} lbFlags.String(&config.lbType, "type", "") lbFlags.String(&config.certPath, "cert", "") lbFlags.String(&config.keyPath, "key", "") lbFlags.String(&config.chainPath, "chain", "") lbFlags.Bool(&config.skipIfExists, "skip-if-exists", "", false) err := lbFlags.Parse(subcommandFlags) if err != nil { return config, err } return config, nil } func (CreateLBs) isValidLBType(lbType string) bool { return lbType == "concourse" || lbType == "cf" } func (c CreateLBs) checkFastFails(newLBType string, currentLBType string, stackName string, boshClient bosh.Client) error { if !c.isValidLBType(newLBType) { return fmt.Errorf("%q is not a valid lb type, valid lb types are: concourse and cf", newLBType) } if lbExists(currentLBType) { return fmt.Errorf("bbl already has a %s load balancer attached, please remove the previous load balancer before attaching a new one", currentLBType) } return bblExists(stackName, c.infrastructureManager, boshClient) } func (c CreateLBs) updateStackAndBOSH( awsRegion string, certificateName string, keyPairName string, stackName string, lbType string, boshClient bosh.Client, envID string, ) error { availabilityZones, err := c.availabilityZoneRetriever.Retrieve(awsRegion) if err != nil { return err } certificate, err := c.certificateManager.Describe(certificateName) stack, err := c.infrastructureManager.Update(keyPairName, len(availabilityZones), stackName, lbType, certificate.ARN, envID) if err != nil { return err } cloudConfigInput := c.boshCloudConfigurator.Configure(stack, availabilityZones) err = c.cloudConfigManager.Update(cloudConfigInput, boshClient) if err != nil { return err } return nil } <file_sep>/bosh/azs_generator.go package bosh import "fmt" type AZsGenerator struct { awsNames []string } type AZ struct { Name string `yaml:"name"` CloudProperties AZCloudProperties `yaml:"cloud_properties"` } type AZCloudProperties struct { AvailabilityZone string `yaml:"availability_zone"` } func NewAZsGenerator(awsNames ...string) AZsGenerator { return AZsGenerator{ awsNames: awsNames, } } func (g AZsGenerator) Generate() []AZ { AZs := []AZ{} for i, awsName := range g.awsNames { AZs = append(AZs, AZ{ Name: fmt.Sprintf("z%d", i+1), CloudProperties: AZCloudProperties{ AvailabilityZone: awsName, }, }) } return AZs } <file_sep>/commands/destroy.go package commands import ( "fmt" "io" "reflect" "strings" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation" "github.com/cloudfoundry/bosh-bootloader/boshinit" "github.com/cloudfoundry/bosh-bootloader/flags" "github.com/cloudfoundry/bosh-bootloader/storage" ) const ( DestroyCommand = "destroy" ) type Destroy struct { awsCredentialValidator awsCredentialValidator logger logger stdin io.Reader boshDeleter boshDeleter vpcStatusChecker vpcStatusChecker stackManager stackManager stringGenerator stringGenerator infrastructureManager infrastructureManager keyPairDeleter keyPairDeleter certificateDeleter certificateDeleter stateStore stateStore stateValidator stateValidator } type destroyConfig struct { NoConfirm bool SkipIfMissing bool } type keyPairDeleter interface { Delete(name string) error } type boshDeleter interface { Delete(boshInitManifest string, boshInitState boshinit.State, ec2PrivateKey string) error } type vpcStatusChecker interface { ValidateSafeToDelete(string) error } type stackManager interface { Describe(string) (cloudformation.Stack, error) } type stringGenerator interface { Generate(prefix string, length int) (string, error) } type certificateDeleter interface { Delete(certificateName string) error } type stateValidator interface { Validate() error } func NewDestroy(awsCredentialValidator awsCredentialValidator, logger logger, stdin io.Reader, boshDeleter boshDeleter, vpcStatusChecker vpcStatusChecker, stackManager stackManager, stringGenerator stringGenerator, infrastructureManager infrastructureManager, keyPairDeleter keyPairDeleter, certificateDeleter certificateDeleter, stateStore stateStore, stateValidator stateValidator) Destroy { return Destroy{ awsCredentialValidator: awsCredentialValidator, logger: logger, stdin: stdin, boshDeleter: boshDeleter, vpcStatusChecker: vpcStatusChecker, stackManager: stackManager, stringGenerator: stringGenerator, infrastructureManager: infrastructureManager, keyPairDeleter: keyPairDeleter, certificateDeleter: certificateDeleter, stateStore: stateStore, stateValidator: stateValidator, } } func (d Destroy) Execute(subcommandFlags []string, state storage.State) error { config, err := d.parseFlags(subcommandFlags) if err != nil { return err } if config.SkipIfMissing && state.Stack.Name == "" { d.logger.Step("state file not found, and —skip-if-missing flag provided, exiting") return nil } err = d.stateValidator.Validate() if err != nil { return err } err = d.awsCredentialValidator.Validate() if err != nil { return err } if !config.NoConfirm { d.logger.Prompt(fmt.Sprintf("Are you sure you want to delete infrastructure for %q? This operation cannot be undone!", state.EnvID)) var proceed string fmt.Fscanln(d.stdin, &proceed) proceed = strings.ToLower(proceed) if proceed != "yes" && proceed != "y" { d.logger.Step("exiting") return nil } } stackExists := true stack, err := d.stackManager.Describe(state.Stack.Name) switch err { case cloudformation.StackNotFound: stackExists = false case nil: break default: return err } if stackExists { var vpcID = stack.Outputs["VPCID"] if err := d.vpcStatusChecker.ValidateSafeToDelete(vpcID); err != nil { return err } } state, err = d.deleteBOSH(stack, state) if err != nil { return err } if err := d.stateStore.Set(state); err != nil { return err } d.logger.Step("destroying AWS stack") state, err = d.deleteStack(stack, state) if err != nil { return err } if err := d.stateStore.Set(state); err != nil { return err } if state.Stack.CertificateName != "" { d.logger.Step("deleting certificate") err = d.certificateDeleter.Delete(state.Stack.CertificateName) if err != nil { return err } state.Stack.CertificateName = "" if err := d.stateStore.Set(state); err != nil { return err } } err = d.keyPairDeleter.Delete(state.KeyPair.Name) if err != nil { return err } err = d.stateStore.Set(storage.State{}) if err != nil { return err } return nil } func (d Destroy) parseFlags(subcommandFlags []string) (destroyConfig, error) { destroyFlags := flags.New("destroy") config := destroyConfig{} destroyFlags.Bool(&config.NoConfirm, "n", "no-confirm", false) destroyFlags.Bool(&config.SkipIfMissing, "", "skip-if-missing", false) err := destroyFlags.Parse(subcommandFlags) if err != nil { return config, err } return config, nil } func (d Destroy) deleteBOSH(stack cloudformation.Stack, state storage.State) (storage.State, error) { emptyBOSH := storage.BOSH{} if reflect.DeepEqual(state.BOSH, emptyBOSH) { d.logger.Println("no BOSH director, skipping...") return state, nil } if err := d.boshDeleter.Delete(state.BOSH.Manifest, state.BOSH.State, state.KeyPair.PrivateKey); err != nil { return state, err } state.BOSH = storage.BOSH{} return state, nil } func (d Destroy) deleteStack(stack cloudformation.Stack, state storage.State) (storage.State, error) { if state.Stack.Name == "" { d.logger.Println("no AWS stack, skipping...") return state, nil } if err := d.infrastructureManager.Delete(state.Stack.Name); err != nil { return state, err } state.Stack.Name = "" state.Stack.LBType = "" return state, nil } <file_sep>/bbl/state_rename_test.go package main_test import ( "io/ioutil" "os" "os/exec" "path/filepath" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/onsi/gomega/gexec" ) var _ = Describe("state rename", func() { var ( tempDirectory string ) BeforeEach(func() { var err error tempDirectory, err = ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) }) Context("when state.json exists", func() { It("renames to bbl-state.json", func() { state := []byte("{}") err := ioutil.WriteFile(filepath.Join(tempDirectory, "state.json"), state, os.ModePerm) Expect(err).NotTo(HaveOccurred()) args := []string{ "--state-dir", tempDirectory, "create-lbs", } session, err := gexec.Start(exec.Command(pathToBBL, args...), GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session.Err.Contents).Should(ContainSubstring("renaming state.json to bbl-state.json")) Expect(filepath.Join(tempDirectory, "state.json")).NotTo(BeAnExistingFile()) Expect(filepath.Join(tempDirectory, "bbl-state.json")).To(BeAnExistingFile()) }) }) }) <file_sep>/boshinit/manifests/manifest.go package manifests import "github.com/cloudfoundry/bosh-bootloader/ssl" const PASSWORD_LENGTH = 15 type Manifest struct { Name string `yaml:"name"` Releases []Release `yaml:"releases"` ResourcePools []ResourcePool `yaml:"resource_pools"` DiskPools []DiskPool `yaml:"disk_pools"` Networks []Network `yaml:"networks"` Jobs []Job `yaml:"jobs"` CloudProvider CloudProvider `yaml:"cloud_provider"` } func (m Manifest) DirectorSSLKeyPair() ssl.KeyPair { if len(m.Jobs) < 1 { return ssl.KeyPair{} } return ssl.KeyPair{ Certificate: []byte(m.Jobs[0].Properties.Director.SSL.Cert), PrivateKey: []byte(m.Jobs[0].Properties.Director.SSL.Key), } } type Release struct { Name string `yaml:"name"` URL string `yaml:"url"` SHA1 string `yaml:"sha1"` } type ResourcePool struct { Name string `yaml:"name"` Network string `yaml:"network"` Stemcell Stemcell `yaml:"stemcell"` CloudProperties ResourcePoolCloudProperties `yaml:"cloud_properties"` } type Stemcell struct { URL string `yaml:"url"` SHA1 string `yaml:"sha1"` } type ResourcePoolCloudProperties struct { InstanceType string `yaml:"instance_type"` EphemeralDisk EphemeralDisk `yaml:"ephemeral_disk"` AvailabilityZone string `yaml:"availability_zone"` } type EphemeralDisk struct { Size int `yaml:"size"` Type string `yaml:"type"` } type DiskPool struct { Name string `yaml:"name"` DiskSize int `yaml:"disk_size"` CloudProperties DiskPoolsCloudProperties `yaml:"cloud_properties"` } type DiskPoolsCloudProperties struct { Type string `yaml:"type"` Encrypted bool `yaml:"encrypted"` } type Network struct { Name string `yaml:"name"` Type string `yaml:"type"` Subnets []Subnet `yaml:"subnets,omitempty"` } type Subnet struct { Range string `yaml:"range"` Gateway string `yaml:"gateway"` DNS []string `yaml:"dns"` CloudProperties NetworksCloudProperties `yaml:"cloud_properties"` } type NetworksCloudProperties struct { Subnet string `yaml:"subnet"` } type Job struct { Name string `yaml:"name"` Instances int `yaml:"instances"` ResourcePool string `yaml:"resource_pool"` PersistentDiskPool string `yaml:"persistent_disk_pool"` Templates []Template `yaml:"templates"` Networks []JobNetwork `yaml:"networks"` Properties JobProperties `yaml:"properties"` } type Template struct { Name string `yaml:"name"` Release string `yaml:"release"` } type JobNetwork struct { Name string `yaml:"name"` StaticIPs []string `yaml:"static_ips"` Default []string `yaml:"default,omitempty"` } type CloudProvider struct { Template Template `yaml:"template"` SSHTunnel SSHTunnel `yaml:"ssh_tunnel"` MBus string `yaml:"mbus"` Properties CloudProviderProperties `yaml:"properties"` } type SSHTunnel struct { Host string `yaml:"host"` Port int `yaml:"port"` User string `yaml:"user"` PrivateKey string `yaml:"private_key"` } type CloudProviderProperties struct { AWS AWSProperties `yaml:"aws"` Agent AgentProperties `yaml:"agent"` Blobstore BlobstoreProperties `yaml:"blobstore"` } type BlobstoreProperties struct { Provider string `yaml:"provider"` Path string `yaml:"path"` } type AWSProperties struct { AccessKeyId string `yaml:"access_key_id"` SecretAccessKey string `yaml:"secret_access_key"` DefaultKeyName string `yaml:"default_key_name"` DefaultSecurityGroups []string `yaml:"default_security_groups"` Region string `yaml:"region"` } type AgentProperties struct { MBus string `yaml:"mbus"` } type PostgresProperties struct { User string `yaml:"user"` Password string `yaml:"<PASSWORD>"` } type RegistryPostgresProperties struct { User string `yaml:"user"` Password string `yaml:"<PASSWORD>"` Database string `yaml:"database"` } <file_sep>/aws/cloudformation/templates/bosh_subnet_template_builder_test.go package templates_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" ) var _ = Describe("BOSHSubnetTemplateBuilder", func() { var builder templates.BOSHSubnetTemplateBuilder BeforeEach(func() { builder = templates.NewBOSHSubnetTemplateBuilder() }) Describe("BOSHSubnet", func() { It("returns a template with all fields for the BOSH subnet", func() { subnet := builder.BOSHSubnet() Expect(subnet.Resources).To(HaveLen(4)) Expect(subnet.Resources).To(HaveKeyWithValue("BOSHSubnet", templates.Resource{ Type: "AWS::EC2::Subnet", Properties: templates.Subnet{ VpcId: templates.Ref{"VPC"}, CidrBlock: templates.Ref{"BOSHSubnetCIDR"}, Tags: []templates.Tag{ { Key: "Name", Value: "BOSH", }, }, }, })) Expect(subnet.Resources).To(HaveKeyWithValue("BOSHRouteTable", templates.Resource{ Type: "AWS::EC2::RouteTable", Properties: templates.RouteTable{ VpcId: templates.Ref{"VPC"}, }, })) Expect(subnet.Resources).To(HaveKeyWithValue("BOSHRoute", templates.Resource{ DependsOn: "VPCGatewayAttachment", Type: "AWS::EC2::Route", Properties: templates.Route{ DestinationCidrBlock: "0.0.0.0/0", GatewayId: templates.Ref{"VPCGatewayInternetGateway"}, RouteTableId: templates.Ref{"BOSHRouteTable"}, }, })) Expect(subnet.Resources).To(HaveKeyWithValue("BOSHSubnetRouteTableAssociation", templates.Resource{ Type: "AWS::EC2::SubnetRouteTableAssociation", Properties: templates.SubnetRouteTableAssociation{ RouteTableId: templates.Ref{"BOSHRouteTable"}, SubnetId: templates.Ref{"BOSHSubnet"}, }, })) Expect(subnet.Parameters).To(HaveLen(1)) Expect(subnet.Parameters).To(HaveKeyWithValue("BOSHSubnetCIDR", templates.Parameter{ Description: "CIDR block for the BOSH subnet.", Type: "String", Default: "10.0.0.0/24", })) Expect(subnet.Outputs).To(HaveLen(2)) Expect(subnet.Outputs).To(HaveKeyWithValue("BOSHSubnet", templates.Output{ Value: templates.Ref{"BOSHSubnet"}, })) Expect(subnet.Outputs).To(HaveKeyWithValue("BOSHSubnetAZ", templates.Output{ Value: templates.FnGetAtt{ []string{ "BOSHSubnet", "AvailabilityZone", }, }, })) }) }) }) <file_sep>/aws/iam/certificate_manager.go package iam type CertificateManager struct { certificateUploader certificateUploader certificateDescriber certificateDescriber certificateDeleter certificateDeleter } type Certificate struct { Name string Body string ARN string Chain string } type certificateUploader interface { Upload(certificatePath, privateKeyPath, chainPath, certificateName string) error } type certificateDescriber interface { Describe(certificateName string) (Certificate, error) } type certificateDeleter interface { Delete(certificateName string) error } func NewCertificateManager(certificateUploader certificateUploader, certificateDescriber certificateDescriber, certificateDeleter certificateDeleter) CertificateManager { return CertificateManager{ certificateUploader: certificateUploader, certificateDescriber: certificateDescriber, certificateDeleter: certificateDeleter, } } func (c CertificateManager) Create(certificatePath, privateKeyPath, chainPath, certificateName string) error { return c.certificateUploader.Upload(certificatePath, privateKeyPath, chainPath, certificateName) } func (c CertificateManager) Delete(certificateName string) error { return c.certificateDeleter.Delete(certificateName) } func (c CertificateManager) Describe(certificateName string) (Certificate, error) { return c.certificateDescriber.Describe(certificateName) } <file_sep>/aws/cloudformation/templates/template.go package templates import "encoding/json" type AMI struct { AMI string `json:",omitempty"` } type Ref struct { Ref string `json:",omitempty"` } type Tag struct { Key string `json:",omitempty"` Value string `json:",omitempty"` } type FnGetAtt struct { FnGetAtt []string `json:"Fn::GetAtt"` } type FnJoin struct { Delimeter string Values []interface{} } func (j FnJoin) MarshalJSON() ([]byte, error) { return json.Marshal(map[string][]interface{}{ "Fn::Join": {j.Delimeter, j.Values}, }) } type Template struct { AWSTemplateFormatVersion string `json:",omitempty"` Description string `json:",omitempty"` Parameters map[string]Parameter `json:",omitempty"` Mappings map[string]interface{} `json:",omitempty"` Resources map[string]Resource `json:",omitempty"` Outputs map[string]Output `json:",omitempty"` } func (t Template) Merge(templates ...Template) Template { if t.Parameters == nil { t.Parameters = map[string]Parameter{} } if t.Mappings == nil { t.Mappings = map[string]interface{}{} } if t.Resources == nil { t.Resources = map[string]Resource{} } if t.Outputs == nil { t.Outputs = map[string]Output{} } for _, template := range templates { for name, parameter := range template.Parameters { t.Parameters[name] = parameter } for name, mapping := range template.Mappings { t.Mappings[name] = mapping } for name, resource := range template.Resources { t.Resources[name] = resource } for name, output := range template.Outputs { t.Outputs[name] = output } } return t } type Output struct { Value interface{} } type Parameter struct { Type string Default string Description string `json:",omitempty"` } type Resource struct { Type string Properties interface{} `json:",omitempty"` DependsOn interface{} `json:",omitempty"` CreationPolicy interface{} `json:",omitempty"` UpdatePolicy interface{} `json:",omitempty"` DeletionPolicy interface{} `json:",omitempty"` } type SecurityGroup struct { VpcId interface{} `json:",omitempty"` GroupDescription string `json:",omitempty"` SecurityGroupIngress []SecurityGroupIngress `json:",omitempty"` SecurityGroupEgress []SecurityGroupEgress } type SecurityGroupEgress struct { SourceSecurityGroupId interface{} `json:",omitempty"` IpProtocol string `json:",omitempty"` FromPort string `json:",omitempty"` ToPort string `json:",omitempty"` } type SecurityGroupIngress struct { GroupId interface{} `json:",omitempty"` SourceSecurityGroupId interface{} `json:",omitempty"` CidrIp interface{} `json:",omitempty"` IpProtocol string `json:",omitempty"` FromPort string `json:",omitempty"` ToPort string `json:",omitempty"` } type SubnetRouteTableAssociation struct { RouteTableId interface{} `json:",omitempty"` SubnetId interface{} `json:",omitempty"` } type Route struct { DestinationCidrBlock string `json:",omitempty"` GatewayId interface{} `json:",omitempty"` RouteTableId interface{} `json:",omitempty"` InstanceId interface{} `json:",omitempty"` } type Instance struct { InstanceType string `json:",omitempty"` PrivateIpAddress string `json:",omitempty"` SubnetId interface{} `json:",omitempty"` ImageId map[string]interface{} `json:",omitempty"` KeyName interface{} `json:",omitempty"` SecurityGroupIds []interface{} `json:",omitempty"` Tags []Tag `json:",omitempty"` SourceDestCheck bool } type EIP struct { Domain string `json:",omitempty"` InstanceId interface{} `json:",omitempty"` } type Subnet struct { AvailabilityZone map[string]interface{} `json:",omitempty"` CidrBlock interface{} `json:",omitempty"` VpcId interface{} `json:",omitempty"` Tags []Tag `json:",omitempty"` } type RouteTable struct { VpcId interface{} `json:",omitempty"` } type IAMUser struct { Policies []IAMPolicy UserName string `json:",omitempty"` } type IAMPolicy struct { PolicyName string PolicyDocument IAMPolicyDocument } type IAMPolicyDocument struct { Version string Statement []IAMStatement } type IAMStatement struct { Action []string Effect string Resource string } type IAMAccessKey struct { UserName Ref } type VPC struct { CidrBlock Ref `json:"CidrBlock,omitempty"` Tags []Tag `json:"Tags,omitempty"` } type VPCGatewayAttachment struct { VpcId Ref `json:"VpcId,omitempty"` InternetGatewayId Ref `json:"InternetGatewayId,omitempty"` } type ElasticLoadBalancingLoadBalancer struct { Subnets []interface{} `json:"Subnets,omitempty"` SecurityGroups []interface{} `json:"SecurityGroups,omitempty"` HealthCheck HealthCheck `json:"HealthCheck,omitempty"` Listeners []Listener `json:"Listeners,omitempty"` CrossZone bool `json:"CrossZone,omitempty"` } type Listener struct { Protocol string `json:"Protocol,omitempty"` LoadBalancerPort string `json:"LoadBalancerPort,omitempty"` InstanceProtocol string `json:"InstanceProtocol,omitempty"` InstancePort string `json:"InstancePort,omitempty"` SSLCertificateID string `json:"SSLCertificateId,omitempty"` } type HealthCheck struct { HealthyThreshold string `json:"HealthyThreshold,omitempty"` Interval string `json:"Interval,omitempty"` Target string `json:"Target,omitempty"` Timeout string `json:"Timeout,omitempty"` UnhealthyThreshold string `json:"UnhealthyThreshold,omitempty"` } <file_sep>/bbl/fakeboshinit/bosh_init_test.go package main_test import ( "io/ioutil" "os" "os/exec" "path/filepath" "time" "github.com/onsi/gomega/gexec" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("fakeboshinit", func() { Describe("main", func() { var ( pathToFake string tempDir string manifestData []byte ) BeforeEach(func() { var err error pathToFake, err = gexec.Build("github.com/cloudfoundry/bosh-bootloader/bbl/fakeboshinit") Expect(err).NotTo(HaveOccurred()) tempDir, err = ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) manifestData = []byte(`--- name: bosh-init jobs: - name: bosh properties: director: name: my-bosh `) }) It("fails fast if compiled with FailFast flag", func() { var err error pathToFake, err = gexec.Build("github.com/cloudfoundry/bosh-bootloader/bbl/fakeboshinit", "-ldflags", "-X main.FailFast=true") Expect(err).NotTo(HaveOccurred()) session := runFakeBoshInit(pathToFake, tempDir, 1) Expect(session.Err.Contents()).To(ContainSubstring(`failing fast`)) }) It("reads and prints the bosh state", func() { err := ioutil.WriteFile(filepath.Join(tempDir, "bosh.yml"), manifestData, os.FileMode(0644)) Expect(err).NotTo(HaveOccurred()) err = ioutil.WriteFile(filepath.Join(tempDir, "bosh-state.json"), []byte("{}"), os.FileMode(0644)) Expect(err).NotTo(HaveOccurred()) session := runFakeBoshInit(pathToFake, tempDir, 0) Expect(session.Out.Contents()).To(ContainSubstring(`bosh-state.json: {}`)) }) It("prints director name from bosh manifest", func() { err := ioutil.WriteFile(filepath.Join(tempDir, "bosh.yml"), manifestData, os.FileMode(0644)) Expect(err).NotTo(HaveOccurred()) err = ioutil.WriteFile(filepath.Join(tempDir, "bosh-state.json"), []byte("{}"), os.FileMode(0644)) Expect(err).NotTo(HaveOccurred()) session := runFakeBoshInit(pathToFake, tempDir, 0) Expect(session.Out.Contents()).To(ContainSubstring(`bosh director name: my-bosh`)) }) It("prints no name for the bosh director if it doesn't exist", func() { manifestData = []byte(`--- name: bosh-init`) err := ioutil.WriteFile(filepath.Join(tempDir, "bosh.yml"), manifestData, os.FileMode(0644)) Expect(err).NotTo(HaveOccurred()) err = ioutil.WriteFile(filepath.Join(tempDir, "bosh-state.json"), []byte("{}"), os.FileMode(0644)) Expect(err).NotTo(HaveOccurred()) session := runFakeBoshInit(pathToFake, tempDir, 0) Expect(session.Out.Contents()).To(ContainSubstring(`bosh director name:`)) }) It("skips deployment on a second deploy with same manifest and bosh state", func() { err := ioutil.WriteFile(filepath.Join(tempDir, "bosh.yml"), manifestData, os.FileMode(0644)) Expect(err).NotTo(HaveOccurred()) err = ioutil.WriteFile(filepath.Join(tempDir, "bosh-state.json"), []byte("{}"), os.FileMode(0644)) Expect(err).NotTo(HaveOccurred()) session := runFakeBoshInit(pathToFake, tempDir, 0) session = runFakeBoshInit(pathToFake, tempDir, 0) Expect(session.Out.Contents()).To(ContainSubstring("No new changes, skipping deployment...")) }) It("updates deployment on a second deploy with different manifest", func() { err := ioutil.WriteFile(filepath.Join(tempDir, "bosh.yml"), manifestData, os.FileMode(0644)) Expect(err).NotTo(HaveOccurred()) err = ioutil.WriteFile(filepath.Join(tempDir, "bosh-state.json"), []byte("{}"), os.FileMode(0644)) Expect(err).NotTo(HaveOccurred()) session := runFakeBoshInit(pathToFake, tempDir, 0) manifestData = []byte(`--- name: bosh-init-updated jobs: - name: bosh properties: director: name: my-bosh `) err = ioutil.WriteFile(filepath.Join(tempDir, "bosh.yml"), manifestData, os.FileMode(0644)) Expect(err).NotTo(HaveOccurred()) session = runFakeBoshInit(pathToFake, tempDir, 0) Expect(session.Out.Contents()).NotTo(ContainSubstring("No new changes, skipping deployment...")) }) }) }) func runFakeBoshInit(pathToFake, tempDir string, exitCode int) *gexec.Session { cmd := &exec.Cmd{ Path: pathToFake, Args: []string{ filepath.Base(pathToFake), "deploy", "bosh.yml", }, Dir: tempDir, Stdout: os.Stdout, Stderr: os.Stderr, } session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session, 10*time.Second).Should(gexec.Exit(exitCode)) return session } <file_sep>/commands/up.go package commands import ( "errors" "fmt" "os" "strings" "github.com/cloudfoundry/bosh-bootloader/aws" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation" "github.com/cloudfoundry/bosh-bootloader/aws/ec2" "github.com/cloudfoundry/bosh-bootloader/aws/iam" "github.com/cloudfoundry/bosh-bootloader/boshinit" "github.com/cloudfoundry/bosh-bootloader/flags" "github.com/cloudfoundry/bosh-bootloader/storage" ) const ( UpCommand = "up" ) type keyPairSynchronizer interface { Sync(keypair ec2.KeyPair) (ec2.KeyPair, error) } type infrastructureManager interface { Create(keyPairName string, numberOfAZs int, stackName, lbType, lbCertificateARN, envID string) (cloudformation.Stack, error) Update(keyPairName string, numberOfAZs int, stackName, lbType, lbCertificateARN, envID string) (cloudformation.Stack, error) Exists(stackName string) (bool, error) Delete(stackName string) error Describe(stackName string) (cloudformation.Stack, error) } type boshDeployer interface { Deploy(boshinit.DeployInput) (boshinit.DeployOutput, error) } type availabilityZoneRetriever interface { Retrieve(region string) ([]string, error) } type awsCredentialValidator interface { Validate() error } type logger interface { Step(string, ...interface{}) Println(string) Prompt(string) } type stateStore interface { Set(state storage.State) error } type certificateDescriber interface { Describe(certificateName string) (iam.Certificate, error) } type envIDGenerator interface { Generate() (string, error) } type configProvider interface { SetConfig(config aws.Config) } type Up struct { awsCredentialValidator awsCredentialValidator infrastructureManager infrastructureManager keyPairSynchronizer keyPairSynchronizer boshDeployer boshDeployer stringGenerator stringGenerator boshCloudConfigurator boshCloudConfigurator availabilityZoneRetriever availabilityZoneRetriever certificateDescriber certificateDescriber cloudConfigManager cloudConfigManager boshClientProvider boshClientProvider envIDGenerator envIDGenerator stateStore stateStore configProvider configProvider } type upConfig struct { awsAccessKeyID string awsSecretAccessKey string awsRegion string } func NewUp( awsCredentialValidator awsCredentialValidator, infrastructureManager infrastructureManager, keyPairSynchronizer keyPairSynchronizer, boshDeployer boshDeployer, stringGenerator stringGenerator, boshCloudConfigurator boshCloudConfigurator, availabilityZoneRetriever availabilityZoneRetriever, certificateDescriber certificateDescriber, cloudConfigManager cloudConfigManager, boshClientProvider boshClientProvider, envIDGenerator envIDGenerator, stateStore stateStore, configProvider configProvider) Up { return Up{ awsCredentialValidator: awsCredentialValidator, infrastructureManager: infrastructureManager, keyPairSynchronizer: keyPairSynchronizer, boshDeployer: boshDeployer, stringGenerator: stringGenerator, boshCloudConfigurator: boshCloudConfigurator, availabilityZoneRetriever: availabilityZoneRetriever, certificateDescriber: certificateDescriber, cloudConfigManager: cloudConfigManager, boshClientProvider: boshClientProvider, envIDGenerator: envIDGenerator, stateStore: stateStore, configProvider: configProvider, } } func (u Up) Execute(subcommandFlags []string, state storage.State) error { config, err := u.parseFlags(subcommandFlags) if err != nil { return err } if u.awsCredentialsPresent(config) { state.AWS.AccessKeyID = config.awsAccessKeyID state.AWS.SecretAccessKey = config.awsSecretAccessKey state.AWS.Region = config.awsRegion if err := u.stateStore.Set(state); err != nil { return err } u.configProvider.SetConfig(aws.Config{ AccessKeyID: config.awsAccessKeyID, SecretAccessKey: config.awsSecretAccessKey, Region: config.awsRegion, }) } else if u.awsCredentialsNotPresent(config) { err := u.awsCredentialValidator.Validate() if err != nil { return err } } else { return u.awsMissingCredentials(config) } err = u.checkForFastFails(state) if err != nil { return err } if state.EnvID == "" { state.EnvID, err = u.envIDGenerator.Generate() if err != nil { return err } } if state.KeyPair.Name == "" { state.KeyPair.Name = fmt.Sprintf("keypair-%s", state.EnvID) } if err := u.stateStore.Set(state); err != nil { return err } keyPair, err := u.keyPairSynchronizer.Sync(ec2.KeyPair{ Name: state.KeyPair.Name, PublicKey: state.KeyPair.PublicKey, PrivateKey: state.KeyPair.PrivateKey, }) if err != nil { return err } state.KeyPair.PublicKey = keyPair.PublicKey state.KeyPair.PrivateKey = keyPair.PrivateKey if err := u.stateStore.Set(state); err != nil { return err } availabilityZones, err := u.availabilityZoneRetriever.Retrieve(state.AWS.Region) if err != nil { return err } if state.Stack.Name == "" { stackEnvID := strings.Replace(state.EnvID, ":", "-", -1) state.Stack.Name = fmt.Sprintf("stack-%s", stackEnvID) if err := u.stateStore.Set(state); err != nil { return err } } var certificateARN string if lbExists(state.Stack.LBType) { certificate, err := u.certificateDescriber.Describe(state.Stack.CertificateName) if err != nil { return err } certificateARN = certificate.ARN } stack, err := u.infrastructureManager.Create(state.KeyPair.Name, len(availabilityZones), state.Stack.Name, state.Stack.LBType, certificateARN, state.EnvID) if err != nil { return err } infrastructureConfiguration := boshinit.InfrastructureConfiguration{ AWSRegion: state.AWS.Region, SubnetID: stack.Outputs["BOSHSubnet"], AvailabilityZone: stack.Outputs["BOSHSubnetAZ"], ElasticIP: stack.Outputs["BOSHEIP"], AccessKeyID: stack.Outputs["BOSHUserAccessKey"], SecretAccessKey: stack.Outputs["BOSHUserSecretAccessKey"], SecurityGroup: stack.Outputs["BOSHSecurityGroup"], } deployInput, err := boshinit.NewDeployInput(state, infrastructureConfiguration, u.stringGenerator, state.EnvID) if err != nil { return err } deployOutput, err := u.boshDeployer.Deploy(deployInput) if err != nil { return err } if state.BOSH.IsEmpty() { state.BOSH = storage.BOSH{ DirectorName: deployInput.DirectorName, DirectorAddress: stack.Outputs["BOSHURL"], DirectorUsername: deployInput.DirectorUsername, DirectorPassword: deployInput.DirectorPassword, DirectorSSLCA: string(deployOutput.DirectorSSLKeyPair.CA), DirectorSSLCertificate: string(deployOutput.DirectorSSLKeyPair.Certificate), DirectorSSLPrivateKey: string(deployOutput.DirectorSSLKeyPair.PrivateKey), Credentials: deployOutput.Credentials, } } state.BOSH.State = deployOutput.BOSHInitState state.BOSH.Manifest = deployOutput.BOSHInitManifest err = u.stateStore.Set(state) if err != nil { return err } boshClient := u.boshClientProvider.Client(state.BOSH.DirectorAddress, state.BOSH.DirectorUsername, state.BOSH.DirectorPassword) cloudConfigInput := u.boshCloudConfigurator.Configure(stack, availabilityZones) err = u.cloudConfigManager.Update(cloudConfigInput, boshClient) if err != nil { return err } err = u.stateStore.Set(state) if err != nil { return err } return nil } func (u Up) checkForFastFails(state storage.State) error { stackExists, err := u.infrastructureManager.Exists(state.Stack.Name) if err != nil { return err } if !state.BOSH.IsEmpty() && !stackExists { return fmt.Errorf( "Found BOSH data in state directory, but Cloud Formation stack %q cannot be found "+ "for region %q and given AWS credentials. bbl cannot safely proceed. Open an issue on GitHub at "+ "https://github.com/cloudfoundry/bosh-bootloader/issues/new if you need assistance.", state.Stack.Name, state.AWS.Region) } return nil } func (Up) parseFlags(subcommandFlags []string) (upConfig, error) { upFlags := flags.New("up") config := upConfig{} upFlags.String(&config.awsAccessKeyID, "aws-access-key-id", os.Getenv("BBL_AWS_ACCESS_KEY_ID")) upFlags.String(&config.awsSecretAccessKey, "aws-secret-access-key", os.Getenv("BBL_AWS_SECRET_ACCESS_KEY")) upFlags.String(&config.awsRegion, "aws-region", os.Getenv("BBL_AWS_REGION")) err := upFlags.Parse(subcommandFlags) if err != nil { return config, err } return config, nil } func (Up) awsCredentialsPresent(config upConfig) bool { return config.awsAccessKeyID != "" && config.awsSecretAccessKey != "" && config.awsRegion != "" } func (Up) awsCredentialsNotPresent(config upConfig) bool { return config.awsAccessKeyID == "" && config.awsSecretAccessKey == "" && config.awsRegion == "" } func (Up) awsMissingCredentials(config upConfig) error { switch { case config.awsAccessKeyID == "": return errors.New("AWS access key ID must be provided") case config.awsSecretAccessKey == "": return errors.New("AWS secret access key must be provided") case config.awsRegion == "": return errors.New("AWS region must be provided") } return nil } <file_sep>/aws/cloudformation/templates/internal_subnet_template_builder.go package templates import "fmt" type InternalSubnetTemplateBuilder struct{} func NewInternalSubnetTemplateBuilder() InternalSubnetTemplateBuilder { return InternalSubnetTemplateBuilder{} } func (s InternalSubnetTemplateBuilder) InternalSubnet(azIndex int, suffix, cidrBlock string) Template { subnetName := fmt.Sprintf("InternalSubnet%s", suffix) subnetTag := fmt.Sprintf("Internal%s", suffix) subnetCIDRName := fmt.Sprintf("%sCIDR", subnetName) cidrDescription := fmt.Sprintf("CIDR block for %s.", subnetName) subnetRouteTableAssociationName := fmt.Sprintf("%sRouteTableAssociation", subnetName) return Template{ Outputs: map[string]Output{ fmt.Sprintf("%sName", subnetName): Output{ Value: Ref{subnetName}, }, fmt.Sprintf("%sAZ", subnetName): Output{ FnGetAtt{ []string{ subnetName, "AvailabilityZone", }, }, }, subnetCIDRName: Output{ Value: Ref{subnetCIDRName}, }, }, Parameters: map[string]Parameter{ subnetCIDRName: Parameter{ Description: cidrDescription, Type: "String", Default: cidrBlock, }, }, Resources: map[string]Resource{ subnetName: Resource{ Type: "AWS::EC2::Subnet", Properties: Subnet{ AvailabilityZone: map[string]interface{}{ "Fn::Select": []interface{}{ fmt.Sprintf("%d", azIndex), map[string]Ref{ "Fn::GetAZs": Ref{"AWS::Region"}, }, }, }, CidrBlock: Ref{subnetCIDRName}, VpcId: Ref{"VPC"}, Tags: []Tag{ { Key: "Name", Value: subnetTag, }, }, }, }, "InternalRouteTable": { Type: "AWS::EC2::RouteTable", Properties: RouteTable{ VpcId: Ref{"VPC"}, }, }, "InternalRoute": { Type: "AWS::EC2::Route", DependsOn: "NATInstance", Properties: Route{ DestinationCidrBlock: "0.0.0.0/0", RouteTableId: Ref{"InternalRouteTable"}, InstanceId: Ref{"NATInstance"}, }, }, subnetRouteTableAssociationName: Resource{ Type: "AWS::EC2::SubnetRouteTableAssociation", Properties: SubnetRouteTableAssociation{ RouteTableId: Ref{"InternalRouteTable"}, SubnetId: Ref{subnetName}, }, }, }, } } <file_sep>/integration-test/state.go package integration import ( "crypto/md5" "encoding/json" "fmt" "io/ioutil" "os" "path/filepath" "github.com/cloudfoundry/bosh-bootloader/storage" . "github.com/onsi/gomega" ) type State struct { stateFilePath string } type stack struct { Name string `json:"name"` CertificateName string `json:"certificateName"` } type state struct { Stack stack `json:"stack"` } func NewState(stateDirectory string) State { return State{ stateFilePath: filepath.Join(stateDirectory, storage.StateFileName), } } func (s State) Checksum() string { buf, err := ioutil.ReadFile(s.stateFilePath) Expect(err).NotTo(HaveOccurred()) return fmt.Sprintf("%x", md5.Sum(buf)) } func (s State) StackName() string { state := s.readStateFile() return state.Stack.Name } func (s State) CertificateName() string { state := s.readStateFile() return state.Stack.CertificateName } func (s State) readStateFile() state { stateFile, err := os.Open(s.stateFilePath) Expect(err).NotTo(HaveOccurred()) defer stateFile.Close() var state state err = json.NewDecoder(stateFile).Decode(&state) Expect(err).NotTo(HaveOccurred()) return state } <file_sep>/integration-test/config.go package integration import ( "encoding/json" "errors" "fmt" "io/ioutil" "os" "strings" ) type Config struct { AWSAccessKeyID string AWSSecretAccessKey string AWSRegion string StateFileDir string } var tempDir func(string, string) (string, error) = ioutil.TempDir func LoadConfig() (Config, error) { config, err := loadConfigJson() if err != nil { return Config{}, err } if config.AWSAccessKeyID == "" { return Config{}, errors.New("aws access key id is missing") } if config.AWSSecretAccessKey == "" { return Config{}, errors.New("aws secret access key is missing") } if config.AWSRegion == "" { return Config{}, errors.New("aws region is missing") } if config.StateFileDir == "" { dir, err := tempDir("", "") if err != nil { return Config{}, err } config.StateFileDir = dir } return config, nil } func loadConfigJson() (Config, error) { path, err := configPath() if err != nil { return Config{}, err } configFile, err := os.Open(path) if err != nil { return Config{}, err } var config Config if err := json.NewDecoder(configFile).Decode(&config); err != nil { return Config{}, err } return config, nil } func configPath() (string, error) { path := os.Getenv("BIT_CONFIG") if path == "" || !strings.HasPrefix(path, "/") { return "", fmt.Errorf("$BIT_CONFIG %q does not specify an absolute path to test config file", path) } return path, nil } <file_sep>/aws/cloudformation/templates/bosh_iam_template_builder.go package templates import "strings" type BOSHIAMTemplateBuilder struct{} func NewBOSHIAMTemplateBuilder() BOSHIAMTemplateBuilder { return BOSHIAMTemplateBuilder{} } func getUserName(userName string) string { if strings.HasPrefix(userName, "bosh-iam-user-") { return userName } return "" } func (t BOSHIAMTemplateBuilder) BOSHIAMUser(userName string) Template { return Template{ Resources: map[string]Resource{ "BOSHUser": Resource{ Type: "AWS::IAM::User", Properties: IAMUser{ UserName: getUserName(userName), Policies: []IAMPolicy{ { PolicyName: "aws-cpi", PolicyDocument: IAMPolicyDocument{ Version: "2012-10-17", Statement: []IAMStatement{ { Action: []string{ "ec2:AssociateAddress", "ec2:AttachVolume", "ec2:CreateVolume", "ec2:DeleteSnapshot", "ec2:DeleteVolume", "ec2:DescribeAddresses", "ec2:DescribeImages", "ec2:DescribeInstances", "ec2:DescribeRegions", "ec2:DescribeSecurityGroups", "ec2:DescribeSnapshots", "ec2:DescribeSubnets", "ec2:DescribeVolumes", "ec2:DetachVolume", "ec2:CreateSnapshot", "ec2:CreateTags", "ec2:RunInstances", "ec2:TerminateInstances", "ec2:RegisterImage", "ec2:DeregisterImage", }, Effect: "Allow", Resource: "*", }, { Action: []string{"elasticloadbalancing:*"}, Effect: "Allow", Resource: "*", }, }, }, }, }, }, }, "BOSHUserAccessKey": Resource{ Properties: IAMAccessKey{ UserName: Ref{"BOSHUser"}, }, Type: "AWS::IAM::AccessKey", }, }, Outputs: map[string]Output{ "BOSHUserAccessKey": Output{ Value: Ref{"BOSHUserAccessKey"}, }, "BOSHUserSecretAccessKey": Output{ Value: FnGetAtt{ []string{ "BOSHUserAccessKey", "SecretAccessKey", }, }, }, }, } } <file_sep>/fakes/infrastructure_manager.go package fakes import "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation" type InfrastructureManager struct { CreateCall struct { CallCount int Stub func(string, int, string, string, string) (cloudformation.Stack, error) Receives struct { KeyPairName string StackName string LBType string LBCertificateARN string NumberOfAvailabilityZones int EnvID string } Returns struct { Stack cloudformation.Stack Error error } } UpdateCall struct { CallCount int Receives struct { KeyPairName string NumberOfAvailabilityZones int StackName string LBType string LBCertificateARN string EnvID string } Returns struct { Stack cloudformation.Stack Error error } } ExistsCall struct { Receives struct { StackName string } Returns struct { Exists bool Error error } } DeleteCall struct { CallCount int Receives struct { StackName string } Returns struct { Error error } } DescribeCall struct { Receives struct { StackName string } Returns struct { Stack cloudformation.Stack Error error } } } func (m *InfrastructureManager) Create(keyPairName string, numberOfAZs int, stackName, lbType, lbCertificateARN, envID string) (cloudformation.Stack, error) { m.CreateCall.CallCount++ m.CreateCall.Receives.StackName = stackName m.CreateCall.Receives.LBType = lbType m.CreateCall.Receives.LBCertificateARN = lbCertificateARN m.CreateCall.Receives.KeyPairName = keyPairName m.CreateCall.Receives.NumberOfAvailabilityZones = numberOfAZs m.CreateCall.Receives.EnvID = envID if m.CreateCall.Stub != nil { return m.CreateCall.Stub(keyPairName, numberOfAZs, stackName, lbType, envID) } return m.CreateCall.Returns.Stack, m.CreateCall.Returns.Error } func (m *InfrastructureManager) Update(keyPairName string, numberOfAZs int, stackName, lbType, lbCertificateARN, envID string) (cloudformation.Stack, error) { m.UpdateCall.CallCount++ m.UpdateCall.Receives.KeyPairName = keyPairName m.UpdateCall.Receives.NumberOfAvailabilityZones = numberOfAZs m.UpdateCall.Receives.StackName = stackName m.UpdateCall.Receives.LBType = lbType m.UpdateCall.Receives.LBCertificateARN = lbCertificateARN m.UpdateCall.Receives.EnvID = envID return m.UpdateCall.Returns.Stack, m.UpdateCall.Returns.Error } func (m *InfrastructureManager) Exists(stackName string) (bool, error) { m.ExistsCall.Receives.StackName = stackName return m.ExistsCall.Returns.Exists, m.ExistsCall.Returns.Error } func (m *InfrastructureManager) Delete(stackName string) error { m.DeleteCall.CallCount++ m.DeleteCall.Receives.StackName = stackName return m.DeleteCall.Returns.Error } func (m *InfrastructureManager) Describe(stackName string) (cloudformation.Stack, error) { m.DescribeCall.Receives.StackName = stackName return m.DescribeCall.Returns.Stack, m.DescribeCall.Returns.Error } <file_sep>/aws/cloudformation/templates/ssh_keypair_template_builder.go package templates type SSHKeyPairTemplateBuilder struct{} func NewSSHKeyPairTemplateBuilder() SSHKeyPairTemplateBuilder { return SSHKeyPairTemplateBuilder{} } func (t SSHKeyPairTemplateBuilder) SSHKeyPairName(keyPairName string) Template { return Template{ Parameters: map[string]Parameter{ "SSHKeyPairName": Parameter{ Type: "AWS::EC2::KeyPair::KeyName", Default: keyPairName, Description: "SSH KeyPair to use for instances", }, }, } } <file_sep>/bosh/networks_generator.go package bosh import "fmt" type NetworksGenerator struct { subnetInputs []SubnetInput azAssociations map[string]string } type Network struct { Name string `yaml:"name"` Type string `yaml:"type"` Subnets []NetworkSubnet `yaml:"subnets"` } type NetworkSubnet struct { AZ string `yaml:"az"` Gateway string `yaml:"gateway"` Range string `yaml:"range"` Reserved []string `yaml:"reserved"` Static []string `yaml:"static"` CloudProperties SubnetCloudProperties `yaml:"cloud_properties"` } type SubnetCloudProperties struct { Subnet string `yaml:"subnet"` SecurityGroups []string `yaml:"security_groups"` } func NewNetworksGenerator(inputs []SubnetInput, azAssociations map[string]string) NetworksGenerator { return NetworksGenerator{ subnetInputs: inputs, azAssociations: azAssociations, } } func (n NetworksGenerator) Generate() ([]Network, error) { const MINIMUM_CIDR_SIZE = 5 network := Network{ Name: "private", Type: "manual", } for _, subnet := range n.subnetInputs { parsedCidr, err := ParseCIDRBlock(subnet.CIDR) if err != nil { return []Network{}, err } if parsedCidr.CIDRSize < MINIMUM_CIDR_SIZE { return []Network{}, fmt.Errorf(`not enough IPs allocated in CIDR block for subnet "%s"`, subnet.Subnet) } gateway := parsedCidr.GetFirstIP().Add(1).String() firstReserved := parsedCidr.GetFirstIP().Add(2).String() secondReserved := parsedCidr.GetFirstIP().Add(3).String() lastReserved := parsedCidr.GetLastIP().String() lastStatic := parsedCidr.GetLastIP().Subtract(1).String() firstStatic := parsedCidr.GetLastIP().Subtract(65).String() networkSubnet := NetworkSubnet{ AZ: n.azAssociations[subnet.AZ], Gateway: gateway, Range: subnet.CIDR, Reserved: []string{ fmt.Sprintf("%s-%s", firstReserved, secondReserved), fmt.Sprintf("%s", lastReserved), }, Static: []string{ fmt.Sprintf("%s-%s", firstStatic, lastStatic), }, CloudProperties: SubnetCloudProperties{ Subnet: subnet.Subnet, SecurityGroups: subnet.SecurityGroups, }, } network.Subnets = append(network.Subnets, networkSubnet) } return []Network{ network, }, nil } <file_sep>/aws/iam/certificate_validator_test.go package iam_test import ( "errors" "fmt" "io" "io/ioutil" "os" "github.com/cloudfoundry/multierror" "github.com/cloudfoundry/bosh-bootloader/aws/iam" "github.com/cloudfoundry/bosh-bootloader/testhelpers" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("CertificateValidator", func() { Describe("Validate", func() { var ( certificateValidator iam.CertificateValidator certFilePath string keyFilePath string chainFilePath string certNonPEMFilePath string keyNonPEMFilePath string chainNonPEMFilePath string otherKeyFilePath string otherCertFilePath string otherChainFilePath string ) BeforeEach(func() { var err error certificateValidator = iam.NewCertificateValidator() chainFilePath, err = testhelpers.WriteContentsToTempFile(testhelpers.BBL_CHAIN) Expect(err).NotTo(HaveOccurred()) certFilePath, err = testhelpers.WriteContentsToTempFile(testhelpers.BBL_CERT) Expect(err).NotTo(HaveOccurred()) keyFilePath, err = testhelpers.WriteContentsToTempFile(testhelpers.BBL_KEY) Expect(err).NotTo(HaveOccurred()) otherChainFilePath, err = testhelpers.WriteContentsToTempFile(testhelpers.OTHER_BBL_CHAIN) Expect(err).NotTo(HaveOccurred()) otherCertFilePath, err = testhelpers.WriteContentsToTempFile(testhelpers.OTHER_BBL_CERT) Expect(err).NotTo(HaveOccurred()) otherKeyFilePath, err = testhelpers.WriteContentsToTempFile(testhelpers.OTHER_BBL_KEY) Expect(err).NotTo(HaveOccurred()) certNonPEMFilePath, err = testhelpers.WriteContentsToTempFile("") Expect(err).NotTo(HaveOccurred()) keyNonPEMFilePath, err = testhelpers.WriteContentsToTempFile("") Expect(err).NotTo(HaveOccurred()) chainNonPEMFilePath, err = testhelpers.WriteContentsToTempFile("") Expect(err).NotTo(HaveOccurred()) iam.ResetStat() iam.ResetReadAll() }) It("does not return an error when cert and key are valid", func() { err := certificateValidator.Validate("some-command-name", certFilePath, keyFilePath, "") Expect(err).NotTo(HaveOccurred()) }) It("does not return an error when cert, key, and chain are valid", func() { err := certificateValidator.Validate("some-command-name", certFilePath, keyFilePath, chainFilePath) Expect(err).NotTo(HaveOccurred()) }) It("returns an error if cert and key are not provided", func() { err := certificateValidator.Validate("some-command-name", "", "", "") expectedErr := multierror.NewMultiError("some-command-name") expectedErr.Add(errors.New("--cert is required")) expectedErr.Add(errors.New("--key is required")) Expect(err).To(Equal(expectedErr)) }) It("returns an error if the cert key file does not exist", func() { err := certificateValidator.Validate("some-command-name", "/some/fake/cert/path", "/some/fake/key/path", "") expectedErr := multierror.NewMultiError("some-command-name") expectedErr.Add(errors.New(`certificate file not found: "/some/fake/cert/path"`)) expectedErr.Add(errors.New(`key file not found: "/some/fake/key/path"`)) Expect(err).To(Equal(expectedErr)) }) It("returns an error if the cert and key are not regular files", func() { err := certificateValidator.Validate("some-command-name", "/dev/null", "/dev/null", "") expectedErr := multierror.NewMultiError("some-command-name") expectedErr.Add(errors.New(`certificate is not a regular file: "/dev/null"`)) expectedErr.Add(errors.New(`key is not a regular file: "/dev/null"`)) Expect(err).To(Equal(expectedErr)) }) It("returns an error if the cert and key are not PEM encoded", func() { err := certificateValidator.Validate("some-command-name", certNonPEMFilePath, keyNonPEMFilePath, "") expectedErr := multierror.NewMultiError("some-command-name") expectedErr.Add(fmt.Errorf(`certificate is not PEM encoded: %q`, certNonPEMFilePath)) expectedErr.Add(fmt.Errorf(`key is not PEM encoded: %q`, keyNonPEMFilePath)) Expect(err).To(Equal(expectedErr)) }) It("returns an error if the key and cert are not compatible", func() { err := certificateValidator.Validate("some-command-name", certFilePath, otherKeyFilePath, "") expectedErr := multierror.NewMultiError("some-command-name") expectedErr.Add(errors.New("certificate and key mismatch")) Expect(err).To(Equal(expectedErr)) }) Context("chain is provided", func() { It("returns an error when chain file does not exist", func() { err := certificateValidator.Validate("some-command-name", certFilePath, keyFilePath, "/some/fake/chain/path") expectedErr := multierror.NewMultiError("some-command-name") expectedErr.Add(errors.New(`chain file not found: "/some/fake/chain/path"`)) Expect(err).To(Equal(expectedErr)) }) It("returns an error when chain file is not a regular file", func() { err := certificateValidator.Validate("some-command-name", certFilePath, keyFilePath, "/dev/null") expectedErr := multierror.NewMultiError("some-command-name") expectedErr.Add(errors.New(`chain is not a regular file: "/dev/null"`)) Expect(err).To(Equal(expectedErr)) }) It("returns an error if the chain is not PEM encoded", func() { err := certificateValidator.Validate("some-command-name", certFilePath, keyFilePath, chainNonPEMFilePath) expectedErr := multierror.NewMultiError("some-command-name") expectedErr.Add(fmt.Errorf(`chain is not PEM encoded: %q`, chainNonPEMFilePath)) Expect(err).To(Equal(expectedErr)) }) It("returns an error if the chain and cert are not compatible", func() { err := certificateValidator.Validate("some-command-name", certFilePath, keyFilePath, otherChainFilePath) expectedErr := multierror.NewMultiError("some-command-name") expectedErr.Add(errors.New("certificate and chain mismatch: x509: certificate signed by unknown authority")) Expect(err).To(Equal(expectedErr)) }) It("returns multiple errors if the cert, key and chain are incompatiable", func() { err := certificateValidator.Validate("some-command-name", certFilePath, otherKeyFilePath, otherChainFilePath) expectedErr := multierror.NewMultiError("some-command-name") expectedErr.Add(errors.New("certificate and key mismatch")) expectedErr.Add(errors.New("certificate and chain mismatch: x509: certificate signed by unknown authority")) Expect(err).To(Equal(expectedErr)) }) }) Context("failure cases", func() { It("returns an error when the certificate, key, and chain cannot be read", func() { createTempFile := func() string { file, err := ioutil.TempFile("", "") Expect(err).NotTo(HaveOccurred()) defer file.Close() err = os.Chmod(file.Name(), 0100) Expect(err).NotTo(HaveOccurred()) return file.Name() } certFile := createTempFile() keyFile := createTempFile() chainFile := createTempFile() err := certificateValidator.Validate("some-command-name", certFile, keyFile, chainFile) expectedErr := multierror.NewMultiError("some-command-name") expectedErr.Add(fmt.Errorf("open %s: permission denied", certFile)) expectedErr.Add(fmt.Errorf("open %s: permission denied", keyFile)) expectedErr.Add(fmt.Errorf("open %s: permission denied", chainFile)) Expect(err).To(Equal(expectedErr)) }) It("returns an error when file info cannot be retrieved", func() { iam.SetStat(func(string) (os.FileInfo, error) { return nil, errors.New("failed to retrieve file info") }) err := certificateValidator.Validate("some-command-name", certFilePath, keyFilePath, chainFilePath) expectedErr := multierror.NewMultiError("some-command-name") expectedErr.Add(fmt.Errorf("failed to retrieve file info: %s", certFilePath)) expectedErr.Add(fmt.Errorf("failed to retrieve file info: %s", keyFilePath)) expectedErr.Add(fmt.Errorf("failed to retrieve file info: %s", chainFilePath)) Expect(err).To(Equal(expectedErr)) }) It("returns an error when the file cannot be read", func() { iam.SetReadAll(func(io.Reader) ([]byte, error) { return []byte{}, errors.New("bad read") }) err := certificateValidator.Validate("some-command-name", certFilePath, keyFilePath, chainFilePath) expectedErr := multierror.NewMultiError("some-command-name") expectedErr.Add(fmt.Errorf("bad read: %s", certFilePath)) expectedErr.Add(fmt.Errorf("bad read: %s", keyFilePath)) expectedErr.Add(fmt.Errorf("bad read: %s", chainFilePath)) Expect(err).To(Equal(expectedErr)) }) It("returns an error when the private key is not valid rsa", func() { file, err := ioutil.TempFile("", "") Expect(err).NotTo(HaveOccurred()) defer file.Close() err = ioutil.WriteFile(file.Name(), []byte(` -----BEGIN RSA PRIVATE KEY----- -----END RSA PRIVATE KEY----- `), os.ModePerm) Expect(err).NotTo(HaveOccurred()) err = certificateValidator.Validate("some-command-name", certFilePath, file.Name(), chainFilePath) expectedErr := multierror.NewMultiError("some-command-name") expectedErr.Add(errors.New("failed to parse private key: asn1: syntax error: sequence truncated")) Expect(err).To(Equal(expectedErr)) }) It("returns an error when the certificate is not valid", func() { file, err := ioutil.TempFile("", "") Expect(err).NotTo(HaveOccurred()) defer file.Close() err = ioutil.WriteFile(file.Name(), []byte(` -----BEGIN CERTIFICATE----- -----END CERTIFICATE----- `), os.ModePerm) Expect(err).NotTo(HaveOccurred()) err = certificateValidator.Validate("some-command-name", file.Name(), keyFilePath, chainFilePath) expectedErr := multierror.NewMultiError("some-command-name") expectedErr.Add(errors.New("failed to parse certificate: asn1: syntax error: sequence truncated")) Expect(err).To(Equal(expectedErr)) }) It("returns an error when the chain is not valid", func() { file, err := ioutil.TempFile("", "") Expect(err).NotTo(HaveOccurred()) defer file.Close() err = ioutil.WriteFile(file.Name(), []byte(` -----BEGIN CERTIFICATE----- -----END CERTIFICATE----- `), os.ModePerm) Expect(err).NotTo(HaveOccurred()) err = certificateValidator.Validate("some-command-name", certFilePath, keyFilePath, file.Name()) expectedErr := multierror.NewMultiError("some-command-name") expectedErr.Add(errors.New("failed to parse chain")) Expect(err).To(Equal(expectedErr)) }) }) }) }) <file_sep>/fakes/bosh_deployer.go package fakes import "github.com/cloudfoundry/bosh-bootloader/boshinit" type BOSHDeployer struct { DeployCall struct { Receives struct { Input boshinit.DeployInput } Returns struct { Output boshinit.DeployOutput Error error } } } func (d *BOSHDeployer) Deploy(input boshinit.DeployInput) (boshinit.DeployOutput, error) { d.DeployCall.Receives.Input = input return d.DeployCall.Returns.Output, d.DeployCall.Returns.Error } <file_sep>/bbl/load_balancers_test.go package main_test import ( "fmt" "io/ioutil" "net/http" "net/http/httptest" "os/exec" "time" "github.com/cloudfoundry/bosh-bootloader/bbl/awsbackend" "github.com/cloudfoundry/bosh-bootloader/commands" "github.com/cloudfoundry/bosh-bootloader/storage" "github.com/cloudfoundry/bosh-bootloader/testhelpers" "github.com/onsi/gomega/gexec" "github.com/rosenhouse/awsfaker" . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/extensions/table" . "github.com/onsi/gomega" . "github.com/pivotal-cf-experimental/gomegamatchers" ) var _ = Describe("load balancers", func() { var ( fakeAWS *awsbackend.Backend fakeAWSServer *httptest.Server fakeBOSHServer *httptest.Server fakeBOSH *fakeBOSHDirector tempDirectory string lbCertPath string lbChainPath string lbKeyPath string otherLBCertPath string otherLBChainPath string otherLBKeyPath string ) BeforeEach(func() { fakeBOSH = &fakeBOSHDirector{} fakeBOSHServer = httptest.NewServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) { fakeBOSH.ServeHTTP(responseWriter, request) })) fakeAWS = awsbackend.New(fakeBOSHServer.URL) fakeAWSServer = httptest.NewServer(awsfaker.New(fakeAWS)) var err error tempDirectory, err = ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) up(fakeAWSServer.URL, tempDirectory, 0) lbCertPath, err = testhelpers.WriteContentsToTempFile(testhelpers.BBL_CERT) Expect(err).NotTo(HaveOccurred()) lbChainPath, err = testhelpers.WriteContentsToTempFile(testhelpers.BBL_CHAIN) Expect(err).NotTo(HaveOccurred()) lbKeyPath, err = testhelpers.WriteContentsToTempFile(testhelpers.BBL_KEY) Expect(err).NotTo(HaveOccurred()) otherLBCertPath, err = testhelpers.WriteContentsToTempFile(testhelpers.OTHER_BBL_CERT) Expect(err).NotTo(HaveOccurred()) otherLBChainPath, err = testhelpers.WriteContentsToTempFile(testhelpers.OTHER_BBL_CHAIN) Expect(err).NotTo(HaveOccurred()) otherLBKeyPath, err = testhelpers.WriteContentsToTempFile(testhelpers.OTHER_BBL_KEY) Expect(err).NotTo(HaveOccurred()) }) Describe("create-lbs", func() { DescribeTable("creates lbs with the specified cert, key, and chain attached", func(lbType, fixtureLocation string) { contents, err := ioutil.ReadFile(fixtureLocation) Expect(err).NotTo(HaveOccurred()) createLBs(fakeAWSServer.URL, tempDirectory, lbCertPath, lbKeyPath, lbChainPath, lbType, 0, false) certificates := fakeAWS.Certificates.All() Expect(certificates).To(HaveLen(1)) Expect(certificates[0].CertificateBody).To(Equal(testhelpers.BBL_CERT)) Expect(certificates[0].PrivateKey).To(Equal(testhelpers.BBL_KEY)) Expect(certificates[0].Chain).To(Equal(testhelpers.BBL_CHAIN)) Expect(certificates[0].Name).To(MatchRegexp(fmt.Sprintf(`%s-elb-cert-\w{8}-\w{4}-\w{4}-\w{4}-\w{12}`, lbType))) Expect(fakeBOSH.GetCloudConfig()).To(MatchYAML(string(contents))) }, Entry("attaches a cf lb type", "cf", "fixtures/cloud-config-cf-elb.yml"), Entry("attaches a concourse lb type", "concourse", "fixtures/cloud-config-concourse-elb.yml"), ) It("logs all the steps", func() { session := createLBs(fakeAWSServer.URL, tempDirectory, lbCertPath, lbKeyPath, lbChainPath, "concourse", 0, false) stdout := session.Out.Contents() Expect(stdout).To(ContainSubstring("step: uploading certificate")) Expect(stdout).To(ContainSubstring("step: generating cloudformation template")) Expect(stdout).To(ContainSubstring("step: finished applying cloudformation template")) Expect(stdout).To(ContainSubstring("step: generating cloud config")) Expect(stdout).To(ContainSubstring("step: applying cloud config")) }) It("no-ops if --skip-if-exists is provided and an lb exists", func() { createLBs(fakeAWSServer.URL, tempDirectory, lbCertPath, lbKeyPath, lbChainPath, "cf", 0, false) certificates := fakeAWS.Certificates.All() Expect(certificates).To(HaveLen(1)) originalCertificate := certificates[0] session := createLBs(fakeAWSServer.URL, tempDirectory, lbCertPath, lbKeyPath, lbChainPath, "cf", 0, true) certificates = fakeAWS.Certificates.All() Expect(certificates).To(HaveLen(1)) Expect(certificates[0].Name).To(Equal(originalCertificate.Name)) stdout := session.Out.Contents() Expect(stdout).To(ContainSubstring(`lb type "cf" exists, skipping...`)) }) Context("failure cases", func() { Context("when an lb already exists", func() { BeforeEach(func() { createLBs(fakeAWSServer.URL, tempDirectory, lbCertPath, lbKeyPath, lbChainPath, "concourse", 0, false) }) It("exits 1", func() { session := createLBs(fakeAWSServer.URL, tempDirectory, lbCertPath, lbKeyPath, lbChainPath, "cf", 1, false) stderr := session.Err.Contents() Expect(stderr).To(ContainSubstring("bbl already has a concourse load balancer attached, please remove the previous load balancer before attaching a new one")) }) }) It("exits 1 when an unknown lb-type is supplied", func() { session := createLBs(fakeAWSServer.URL, tempDirectory, lbCertPath, lbKeyPath, lbChainPath, "some-fake-lb-type", 1, false) stderr := session.Err.Contents() Expect(stderr).To(ContainSubstring("\"some-fake-lb-type\" is not a valid lb type, valid lb types are: concourse and cf")) }) Context("when the environment has not been provisioned", func() { It("exits 1 when the cloudformation stack does not exist", func() { state := readStateJson(tempDirectory) fakeAWS.Stacks.Delete(state.Stack.Name) session := createLBs(fakeAWSServer.URL, tempDirectory, lbCertPath, lbKeyPath, lbChainPath, "cf", 1, false) stderr := session.Err.Contents() Expect(stderr).To(ContainSubstring(commands.BBLNotFound.Error())) }) It("exits 1 when the BOSH director does not exist", func() { writeStateJson(storage.State{ AWS: storage.AWS{ AccessKeyID: "some-access-key", SecretAccessKey: "some-access-secret", Region: "some-region", }, Stack: storage.Stack{ Name: "some-stack-name", }, BOSH: storage.BOSH{ DirectorUsername: "admin", DirectorPassword: "<PASSWORD>", DirectorAddress: "", }, }, tempDirectory) session := createLBs(fakeAWSServer.URL, tempDirectory, lbCertPath, lbKeyPath, lbChainPath, "cf", 1, false) stderr := session.Err.Contents() Expect(stderr).To(ContainSubstring(commands.BBLNotFound.Error())) }) }) Context("when bbl-state.json does not exist", func() { It("exits with status 1 and outputs helpful error message", func() { tempDirectory, err := ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) args := []string{ "--state-dir", tempDirectory, "create-lbs", } cmd := exec.Command(pathToBBL, args...) session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session, 10*time.Second).Should(gexec.Exit(1)) Expect(session.Err.Contents()).To(ContainSubstring(fmt.Sprintf("bbl-state.json not found in %q, ensure you're running this command in the proper state directory or create a new environment with bbl up", tempDirectory))) }) }) }) }) Describe("update-lbs", func() { It("updates the load balancer with the given cert, key and chain", func() { writeStateJson(storage.State{ AWS: storage.AWS{ AccessKeyID: "some-access-key", SecretAccessKey: "some-access-secret", Region: "some-region", }, Stack: storage.Stack{ Name: "some-stack-name", LBType: "cf", CertificateName: "bbl-cert-old-certificate", }, BOSH: storage.BOSH{ DirectorUsername: "admin", DirectorPassword: "<PASSWORD>", DirectorAddress: fakeBOSHServer.URL, }, }, tempDirectory) fakeAWS.Stacks.Set(awsbackend.Stack{ Name: "some-stack-name", }) fakeAWS.Certificates.Set(awsbackend.Certificate{ Name: "bbl-cert-old-certificate", CertificateBody: "some-old-certificate-body", PrivateKey: "some-old-private-key", }) updateLBs(fakeAWSServer.URL, tempDirectory, otherLBCertPath, otherLBKeyPath, otherLBChainPath, 0, false) certificates := fakeAWS.Certificates.All() Expect(certificates).To(HaveLen(1)) Expect(certificates[0].Chain).To(Equal(testhelpers.OTHER_BBL_CHAIN)) Expect(certificates[0].CertificateBody).To(Equal(testhelpers.OTHER_BBL_CERT)) Expect(certificates[0].PrivateKey).To(Equal(testhelpers.OTHER_BBL_KEY)) Expect(certificates[0].Name).To(MatchRegexp(`cf-elb-cert-\w{8}-\w{4}-\w{4}-\w{4}-\w{12}`)) stack, ok := fakeAWS.Stacks.Get("some-stack-name") Expect(ok).To(BeTrue()) Expect(stack.WasUpdated).To(BeTrue()) }) It("does nothing if the certificate is unchanged", func() { writeStateJson(storage.State{ AWS: storage.AWS{ AccessKeyID: "some-access-key", SecretAccessKey: "some-access-secret", Region: "some-region", }, Stack: storage.Stack{ Name: "some-stack-name", LBType: "cf", CertificateName: "bbl-cert-certificate", }, BOSH: storage.BOSH{ DirectorUsername: "admin", DirectorPassword: "<PASSWORD>", DirectorAddress: fakeBOSHServer.URL, }, }, tempDirectory) fakeAWS.Stacks.Set(awsbackend.Stack{ Name: "some-stack-name", }) fakeAWS.Certificates.Set(awsbackend.Certificate{ Name: "bbl-cert-certificate", CertificateBody: testhelpers.BBL_CERT, PrivateKey: testhelpers.BBL_KEY, }) session := updateLBs(fakeAWSServer.URL, tempDirectory, lbCertPath, lbKeyPath, "", 0, false) stdout := session.Out.Contents() Expect(stdout).To(ContainSubstring("no updates are to be performed")) stack, ok := fakeAWS.Stacks.Get("some-stack-name") Expect(ok).To(BeTrue()) Expect(stack.WasUpdated).To(BeFalse()) }) It("logs all the steps", func() { createLBs(fakeAWSServer.URL, tempDirectory, lbCertPath, lbKeyPath, lbChainPath, "concourse", 0, false) session := updateLBs(fakeAWSServer.URL, tempDirectory, otherLBCertPath, otherLBKeyPath, "", 0, false) stdout := session.Out.Contents() Expect(stdout).To(ContainSubstring("step: uploading new certificate")) Expect(stdout).To(ContainSubstring("step: generating cloudformation template")) Expect(stdout).To(ContainSubstring("step: updating cloudformation stack")) Expect(stdout).To(ContainSubstring("step: finished applying cloudformation template")) Expect(stdout).To(ContainSubstring("step: deleting old certificate")) }) It("no-ops if --skip-if-missing is provided and an lb does not exist", func() { certificates := fakeAWS.Certificates.All() Expect(certificates).To(HaveLen(0)) session := updateLBs(fakeAWSServer.URL, tempDirectory, lbCertPath, lbKeyPath, "", 0, true) certificates = fakeAWS.Certificates.All() Expect(certificates).To(HaveLen(0)) stdout := session.Out.Contents() Expect(stdout).To(ContainSubstring(`no lb type exists, skipping...`)) }) Context("failure cases", func() { Context("when an lb type does not exist", func() { It("exits 1", func() { session := updateLBs(fakeAWSServer.URL, tempDirectory, lbCertPath, lbKeyPath, "", 1, false) stderr := session.Err.Contents() Expect(stderr).To(ContainSubstring("no load balancer has been found for this bbl environment")) }) }) Context("when bbl environment is not up", func() { It("exits 1 when the cloudformation stack does not exist", func() { writeStateJson(storage.State{ AWS: storage.AWS{ AccessKeyID: "some-access-key", SecretAccessKey: "some-access-secret", Region: "some-region", }, }, tempDirectory) session := updateLBs(fakeAWSServer.URL, tempDirectory, lbCertPath, lbKeyPath, "", 1, false) stderr := session.Err.Contents() Expect(stderr).To(ContainSubstring(commands.BBLNotFound.Error())) }) It("exits 1 when the BOSH director does not exist", func() { fakeAWS.Stacks.Set(awsbackend.Stack{ Name: "some-stack-name", }) writeStateJson(storage.State{ AWS: storage.AWS{ AccessKeyID: "some-access-key", SecretAccessKey: "some-access-secret", Region: "some-region", }, Stack: storage.Stack{ Name: "some-stack-name", }, }, tempDirectory) session := updateLBs(fakeAWSServer.URL, tempDirectory, lbCertPath, lbKeyPath, "", 1, false) stderr := session.Err.Contents() Expect(stderr).To(ContainSubstring(commands.BBLNotFound.Error())) }) }) Context("when bbl-state.json does not exist", func() { It("exits with status 1 and outputs helpful error message", func() { tempDirectory, err := ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) args := []string{ "--state-dir", tempDirectory, "update-lbs", } cmd := exec.Command(pathToBBL, args...) session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session, 10*time.Second).Should(gexec.Exit(1)) Expect(session.Err.Contents()).To(ContainSubstring(fmt.Sprintf("bbl-state.json not found in %q, ensure you're running this command in the proper state directory or create a new environment with bbl up", tempDirectory))) }) }) }) }) Describe("delete-lbs", func() { It("deletes the load balancer", func() { cloudformationNoELB, err := ioutil.ReadFile("fixtures/cloudformation-no-elb.json") Expect(err).NotTo(HaveOccurred()) cloudConfigFixture, err := ioutil.ReadFile("fixtures/cloud-config-no-elb.yml") Expect(err).NotTo(HaveOccurred()) writeStateJson(storage.State{ AWS: storage.AWS{ AccessKeyID: "some-access-key", SecretAccessKey: "some-access-secret", Region: "some-region", }, Stack: storage.Stack{ Name: "some-stack-name", LBType: "cf", CertificateName: "bbl-cert-old-certificate", }, BOSH: storage.BOSH{ DirectorUsername: "admin", DirectorPassword: "<PASSWORD>", DirectorAddress: fakeBOSHServer.URL, }, KeyPair: storage.KeyPair{ Name: "some-keypair-name", }, EnvID: "bbl-env-lake-timestamp", }, tempDirectory) fakeAWS.Stacks.Set(awsbackend.Stack{ Name: "some-stack-name", }) fakeAWS.Certificates.Set(awsbackend.Certificate{ Name: "bbl-cert-old-certificate", }) deleteLBs(fakeAWSServer.URL, tempDirectory, 0, false) certificates := fakeAWS.Certificates.All() Expect(certificates).To(HaveLen(0)) stack, ok := fakeAWS.Stacks.Get("some-stack-name") Expect(ok).To(BeTrue()) Expect(stack.WasUpdated).To(BeTrue()) Expect(stack.Template).To(MatchJSON(string(cloudformationNoELB))) Expect(fakeBOSH.GetCloudConfig()).To(MatchYAML(string(cloudConfigFixture))) }) It("logs all the steps", func() { createLBs(fakeAWSServer.URL, tempDirectory, lbCertPath, lbKeyPath, lbChainPath, "concourse", 0, false) session := deleteLBs(fakeAWSServer.URL, tempDirectory, 0, false) stdout := session.Out.Contents() Expect(stdout).To(ContainSubstring("step: generating cloud config")) Expect(stdout).To(ContainSubstring("step: applying cloud config")) Expect(stdout).To(ContainSubstring("step: generating cloudformation template")) Expect(stdout).To(ContainSubstring("step: updating cloudformation stack")) Expect(stdout).To(ContainSubstring("step: finished applying cloudformation template")) Expect(stdout).To(ContainSubstring("step: deleting certificate")) }) It("no-ops if --skip-if-missing is provided and an lb does not exist", func() { certificates := fakeAWS.Certificates.All() Expect(certificates).To(HaveLen(0)) session := deleteLBs(fakeAWSServer.URL, tempDirectory, 0, true) certificates = fakeAWS.Certificates.All() Expect(certificates).To(HaveLen(0)) stdout := session.Out.Contents() Expect(stdout).To(ContainSubstring(`no lb type exists, skipping...`)) }) Context("failure cases", func() { Context("when the environment has not been provisioned", func() { It("exits 1 when the cloudformation stack does not exist", func() { state := readStateJson(tempDirectory) fakeAWS.Stacks.Delete(state.Stack.Name) session := deleteLBs(fakeAWSServer.URL, tempDirectory, 1, false) stderr := session.Err.Contents() Expect(stderr).To(ContainSubstring(commands.BBLNotFound.Error())) }) It("exits 1 when the BOSH director does not exist", func() { fakeAWS.Stacks.Set(awsbackend.Stack{ Name: "some-stack-name", }) writeStateJson(storage.State{ AWS: storage.AWS{ AccessKeyID: "some-access-key", SecretAccessKey: "some-access-secret", Region: "some-region", }, Stack: storage.Stack{ Name: "some-stack-name", }, }, tempDirectory) session := deleteLBs(fakeAWSServer.URL, tempDirectory, 1, false) stderr := session.Err.Contents() Expect(stderr).To(ContainSubstring(commands.BBLNotFound.Error())) }) }) Context("when bbl-state.json does not exist", func() { It("exits with status 1 and outputs helpful error message", func() { tempDirectory, err := ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) args := []string{ "--state-dir", tempDirectory, "delete-lbs", } cmd := exec.Command(pathToBBL, args...) session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session, 10*time.Second).Should(gexec.Exit(1)) Expect(session.Err.Contents()).To(ContainSubstring(fmt.Sprintf("bbl-state.json not found in %q, ensure you're running this command in the proper state directory or create a new environment with bbl up", tempDirectory))) }) }) }) }) Describe("lbs", func() { It("prints out the currently attached lb names and urls", func() { createLBs(fakeAWSServer.URL, tempDirectory, lbCertPath, lbKeyPath, lbChainPath, "cf", 0, false) session := lbs(fakeAWSServer.URL, tempDirectory, 0) stdout := session.Out.Contents() Expect(stdout).To(ContainSubstring("CF Router LB: some-cf-router-lb [some-cf-router-lb-url]")) Expect(stdout).To(ContainSubstring("CF SSH Proxy LB: some-cf-ssh-proxy-lb [some-cf-ssh-proxy-lb-url]")) }) Context("when bbl-state.json does not exist", func() { It("exits with status 1 and outputs helpful error message", func() { tempDirectory, err := ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) args := []string{ "--state-dir", tempDirectory, "lbs", } cmd := exec.Command(pathToBBL, args...) session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session, 10*time.Second).Should(gexec.Exit(1)) Expect(session.Err.Contents()).To(ContainSubstring(fmt.Sprintf("bbl-state.json not found in %q, ensure you're running this command in the proper state directory or create a new environment with bbl up", tempDirectory))) }) }) }) }) func lbs(endpointOverrideURL string, stateDir string, exitCode int) *gexec.Session { args := []string{ fmt.Sprintf("--endpoint-override=%s", endpointOverrideURL), "--state-dir", stateDir, "lbs", } return executeCommand(args, exitCode) } func deleteLBs(endpointOverrideURL string, stateDir string, exitCode int, skipIfMissing bool) *gexec.Session { args := []string{ fmt.Sprintf("--endpoint-override=%s", endpointOverrideURL), "--state-dir", stateDir, "delete-lbs", } if skipIfMissing { args = append(args, "--skip-if-missing") } return executeCommand(args, exitCode) } func updateLBs(endpointOverrideURL string, stateDir string, certName string, keyName string, chainName string, exitCode int, skipIfMissing bool) *gexec.Session { args := []string{ fmt.Sprintf("--endpoint-override=%s", endpointOverrideURL), "--state-dir", stateDir, "update-lbs", "--cert", certName, "--key", keyName, "--chain", chainName, } if skipIfMissing { args = append(args, "--skip-if-missing") } return executeCommand(args, exitCode) } func createLBs(endpointOverrideURL string, stateDir string, certName string, keyName string, chainName string, lbType string, exitCode int, skipIfExists bool) *gexec.Session { args := []string{ fmt.Sprintf("--endpoint-override=%s", endpointOverrideURL), "--state-dir", stateDir, "create-lbs", "--type", lbType, "--cert", certName, "--key", keyName, "--chain", chainName, } if skipIfExists { args = append(args, "--skip-if-exists") } return executeCommand(args, exitCode) } <file_sep>/application/command_finder_test.go package application_test import ( "github.com/cloudfoundry/bosh-bootloader/application" . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/extensions/table" . "github.com/onsi/gomega" ) var _ = Describe("CommandFinder", func() { DescribeTable("FindCommand", func(input []string, expectedOutput application.CommandFinderResult) { parserOutput := application.NewCommandFinder().FindCommand(input) Expect(parserOutput).To(Equal(expectedOutput)) }, Entry("parses the first non-hyphenated word as the attempted command", []string{"--badflag", "x", "help", "delete-lbs", "--other-flag"}, application.CommandFinderResult{GlobalFlags: []string{"--badflag"}, Command: "x", OtherArgs: []string{"help", "delete-lbs", "--other-flag"}}), Entry("parses the first non-hyphenated word as the state-dir if it directly follows state-dir", []string{"--state-dir", "help", "delete-errthing", "--other-flag"}, application.CommandFinderResult{GlobalFlags: []string{"--state-dir", "help"}, Command: "delete-errthing", OtherArgs: []string{"--other-flag"}}), Entry("parses the first non-hyphenated word as the state-dir if it directly follows state-dir", []string{"-state-dir", "help", "delete-errthing", "--other-flag"}, application.CommandFinderResult{GlobalFlags: []string{"-state-dir", "help"}, Command: "delete-errthing", OtherArgs: []string{"--other-flag"}}), Entry("parses the first non-hyphenated word as the attempted command if --state-dir=x is provided", []string{"--state-dir=some-dir", "help", "--other-flag"}, application.CommandFinderResult{GlobalFlags: []string{"--state-dir=some-dir"}, Command: "help", OtherArgs: []string{"--other-flag"}}), Entry("parses correctly if no global flags given", []string{"help", "foo", "--other-flag"}, application.CommandFinderResult{GlobalFlags: []string{}, Command: "help", OtherArgs: []string{"foo", "--other-flag"}}), Entry("parses correctly if no other flags given", []string{"help"}, application.CommandFinderResult{GlobalFlags: []string{}, Command: "help", OtherArgs: []string{}}), ) }) <file_sep>/bbl/awsbackend/certificates.go package awsbackend import "sync" type Certificate struct { Name string CertificateBody string PrivateKey string Chain string } type Certificates struct { mutex sync.Mutex store map[string]Certificate } func NewCertificates() *Certificates { return &Certificates{ store: make(map[string]Certificate), } } func (c *Certificates) Set(certificate Certificate) { c.mutex.Lock() defer c.mutex.Unlock() c.store[certificate.Name] = certificate } func (c *Certificates) Get(name string) (Certificate, bool) { c.mutex.Lock() defer c.mutex.Unlock() certificate, ok := c.store[name] return certificate, ok } func (c *Certificates) Delete(name string) { c.mutex.Lock() defer c.mutex.Unlock() delete(c.store, name) } func (c *Certificates) All() []Certificate { var certificates []Certificate c.mutex.Lock() defer c.mutex.Unlock() for _, certificate := range c.store { certificates = append(certificates, certificate) } return certificates } <file_sep>/integration-test/exports_test.go package integration import "io/ioutil" func SetTempDir(f func(string, string) (string, error)) { tempDir = f } func ResetTempDir() { tempDir = ioutil.TempDir } <file_sep>/boshinit/manifests/manifest_test.go package manifests_test import ( "github.com/cloudfoundry/bosh-bootloader/boshinit/manifests" "github.com/cloudfoundry/bosh-bootloader/ssl" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Manifest", func() { Describe("DirectorSSLKeyPair", func() { It("returns the director ssl keypair from a built manifest", func() { manifest := manifests.Manifest{ Jobs: []manifests.Job{{ Properties: manifests.JobProperties{ Director: manifests.DirectorJobProperties{ SSL: manifests.SSLProperties{ Cert: "some-cert", Key: "some-key", }, }, }, }}, } keyPair := manifest.DirectorSSLKeyPair() Expect(keyPair).To(Equal(ssl.KeyPair{ Certificate: []byte("some-cert"), PrivateKey: []byte("some-key"), })) }) It("returns an empty keypair if there are no jobs", func() { manifest := manifests.Manifest{} keyPair := manifest.DirectorSSLKeyPair() Expect(keyPair).To(Equal(ssl.KeyPair{})) }) }) }) <file_sep>/storage/state_test.go package storage_test import ( "errors" "io" "io/ioutil" "os" "path/filepath" "github.com/cloudfoundry/bosh-bootloader/fakes" "github.com/cloudfoundry/bosh-bootloader/storage" "github.com/pivotal-cf-experimental/gomegamatchers" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Store", func() { var ( store storage.Store tempDir string ) BeforeEach(func() { var err error tempDir, err = ioutil.TempDir("", "") store = storage.NewStore(tempDir) Expect(err).NotTo(HaveOccurred()) }) AfterEach(func() { storage.ResetEncode() }) Describe("Set", func() { It("stores the state into a file", func() { err := store.Set(storage.State{ AWS: storage.AWS{ AccessKeyID: "some-aws-access-key-id", SecretAccessKey: "some-aws-secret-access-key", Region: "some-region", }, KeyPair: storage.KeyPair{ Name: "some-name", PrivateKey: "some-private", PublicKey: "some-public", }, BOSH: storage.BOSH{ DirectorName: "some-director-name", DirectorUsername: "some-director-username", DirectorPassword: "<PASSWORD>", DirectorAddress: "some-director-address", DirectorSSLCA: "some-bosh-ssl-ca", DirectorSSLCertificate: "some-bosh-ssl-certificate", DirectorSSLPrivateKey: "some-bosh-ssl-private-key", State: map[string]interface{}{ "key": "value", }, Manifest: "name: bosh", Credentials: map[string]string{ "mbusUsername": "some-mbus-username", "natsUsername": "some-nats-username", "postgresUsername": "some-postgres-username", "registryUsername": "some-registry-username", "blobstoreDirectorUsername": "some-blobstore-director-username", "blobstoreAgentUsername": "some-blobstore-agent-username", "hmUsername": "some-hm-username", "mbusPassword": "<PASSWORD>", "natsPassword": "<PASSWORD>", "postgresPassword": "<PASSWORD>", "registryPassword": "<PASSWORD>", "blobstoreDirectorPassword": "<PASSWORD>", "blobstoreAgentPassword": "<PASSWORD>", "hmPassword": "<PASSWORD>", }, }, Stack: storage.Stack{ Name: "some-stack-name", LBType: "some-lb-type", CertificateName: "some-certificate-name", }, EnvID: "some-env-id", }) Expect(err).NotTo(HaveOccurred()) data, err := ioutil.ReadFile(filepath.Join(tempDir, "bbl-state.json")) Expect(err).NotTo(HaveOccurred()) Expect(data).To(MatchJSON(`{ "version": 1, "aws": { "accessKeyId": "some-aws-access-key-id", "secretAccessKey": "some-aws-secret-access-key", "region": "some-region" }, "keyPair": { "name": "some-name", "privateKey": "some-private", "publicKey": "some-public" }, "bosh":{ "directorName": "some-director-name", "directorUsername": "some-director-username", "directorPassword": "<PASSWORD>", "directorAddress": "some-director-address", "directorSSLCA": "some-bosh-ssl-ca", "directorSSLCertificate": "some-bosh-ssl-certificate", "directorSSLPrivateKey": "some-bosh-ssl-private-key", "credentials": { "mbusUsername": "some-mbus-username", "natsUsername": "some-nats-username", "postgresUsername": "some-postgres-username", "registryUsername": "some-registry-username", "blobstoreDirectorUsername": "some-blobstore-director-username", "blobstoreAgentUsername": "some-blobstore-agent-username", "hmUsername": "some-hm-username", "mbusPassword": "<PASSWORD>", "natsPassword": "<PASSWORD>", "postgresPassword": "<PASSWORD>", "registryPassword": "<PASSWORD>", "blobstoreDirectorPassword": "<PASSWORD>", "blobstoreAgentPassword": "<PASSWORD>", "hmPassword": "<PASSWORD>" }, "manifest": "name: bosh", "state": { "key": "value" } }, "stack": { "name": "some-stack-name", "lbType": "some-lb-type", "certificateName": "some-certificate-name" }, "envID": "some-env-id" }`)) fileInfo, err := os.Stat(filepath.Join(tempDir, "bbl-state.json")) Expect(err).NotTo(HaveOccurred()) Expect(fileInfo.Mode()).To(Equal(os.FileMode(0644))) }) Context("when the state is empty", func() { It("removes the bbl-state.json file", func() { err := ioutil.WriteFile(filepath.Join(tempDir, "bbl-state.json"), []byte("{}"), os.ModePerm) Expect(err).NotTo(HaveOccurred()) err = store.Set(storage.State{}) Expect(err).NotTo(HaveOccurred()) _, err = os.Stat(filepath.Join(tempDir, "bbl-state.json")) Expect(os.IsNotExist(err)).To(BeTrue()) }) Context("when the bbl-state.json file does not exist", func() { It("does nothing", func() { err := store.Set(storage.State{}) Expect(err).NotTo(HaveOccurred()) _, err = os.Stat(filepath.Join(tempDir, "bbl-state.json")) Expect(os.IsNotExist(err)).To(BeTrue()) }) }) Context("failure cases", func() { Context("when the bbl-state.json file cannot be removed", func() { It("returns an error", func() { err := os.Chmod(tempDir, 0000) Expect(err).NotTo(HaveOccurred()) err = store.Set(storage.State{}) Expect(err).To(MatchError(ContainSubstring("permission denied"))) }) }) }) }) Context("failure cases", func() { It("fails when the directory does not exist", func() { store = storage.NewStore("non-valid-dir") err := store.Set(storage.State{}) Expect(err).To(MatchError(ContainSubstring("no such file or directory"))) }) It("fails to open the bbl-state.json file", func() { err := os.Chmod(tempDir, 0000) Expect(err).NotTo(HaveOccurred()) err = store.Set(storage.State{ Stack: storage.Stack{ Name: "some-stack-name", }, }) Expect(err).To(MatchError(ContainSubstring("permission denied"))) }) It("fails to write the bbl-state.json file", func() { storage.SetEncode(func(io.Writer, interface{}) error { return errors.New("failed to encode") }) err := store.Set(storage.State{ Stack: storage.Stack{ Name: "some-stack-name", }, }) Expect(err).To(MatchError("failed to encode")) }) }) }) Describe("GetState", func() { var logger *fakes.Logger BeforeEach(func() { logger = &fakes.Logger{} storage.GetStateLogger = logger }) It("returns the stored state information", func() { err := ioutil.WriteFile(filepath.Join(tempDir, "bbl-state.json"), []byte(`{ "version": 1, "aws": { "accessKeyId": "some-aws-access-key-id", "secretAccessKey": "some-aws-secret-access-key", "region": "some-aws-region" }, "keyPair": { "name": "some-name", "privateKey": "some-private-key", "publicKey": "some-public-key" }, "bosh": { "directorAddress": "some-director-address", "directorSSLCA": "some-bosh-ssl-ca", "directorSSLCertificate": "some-bosh-ssl-certificate", "directorSSLPrivateKey": "some-bosh-ssl-private-key", "manifest": "name: bosh" }, "stack": { "name": "some-stack-name", "lbType": "some-lb", "certificateName": "some-certificate-name" } }`), os.ModePerm) Expect(err).NotTo(HaveOccurred()) state, err := storage.GetState(tempDir) Expect(err).NotTo(HaveOccurred()) Expect(state).To(Equal(storage.State{ Version: 1, AWS: storage.AWS{ AccessKeyID: "some-aws-access-key-id", SecretAccessKey: "some-aws-secret-access-key", Region: "some-aws-region", }, KeyPair: storage.KeyPair{ Name: "some-name", PrivateKey: "some-private-key", PublicKey: "some-public-key", }, BOSH: storage.BOSH{ DirectorAddress: "some-director-address", DirectorSSLCA: "some-bosh-ssl-ca", DirectorSSLCertificate: "some-bosh-ssl-certificate", DirectorSSLPrivateKey: "some-bosh-ssl-private-key", Manifest: "name: bosh", }, Stack: storage.Stack{ Name: "some-stack-name", LBType: "some-lb", CertificateName: "some-certificate-name", }, })) }) Context("when the bbl-state.json file doesn't exist", func() { It("returns an empty state object", func() { state, err := storage.GetState(tempDir) Expect(err).NotTo(HaveOccurred()) Expect(state).To(Equal(storage.State{})) }) Context("when state.json exists", func() { BeforeEach(func() { err := ioutil.WriteFile(filepath.Join(tempDir, "state.json"), []byte(`{ "version": 1, "aws": { "accessKeyId": "some-aws-access-key-id", "secretAccessKey": "some-aws-secret-access-key", "region": "some-aws-region" } }`), os.ModePerm) Expect(err).NotTo(HaveOccurred()) }) AfterEach(func() { storage.ResetRename() }) It("renames state.json to bbl-state.json and returns its state", func() { state, err := storage.GetState(tempDir) Expect(err).NotTo(HaveOccurred()) _, err = os.Stat(filepath.Join(tempDir, "state.json")) Expect(err).To(gomegamatchers.BeAnOsIsNotExistError()) _, err = os.Stat(filepath.Join(tempDir, "bbl-state.json")) Expect(err).NotTo(HaveOccurred()) Expect(state).To(Equal(storage.State{ Version: 1, AWS: storage.AWS{ AccessKeyID: "some-aws-access-key-id", SecretAccessKey: "some-aws-secret-access-key", Region: "some-aws-region", }, })) Expect(logger.PrintlnCall.CallCount).To(Equal(1)) Expect(logger.PrintlnCall.Receives.Message).To(Equal("renaming state.json to bbl-state.json")) }) Context("failure cases", func() { Context("when checking if state file exists fails", func() { It("returns an error", func() { err := os.Chmod(tempDir, os.FileMode(0000)) Expect(err).NotTo(HaveOccurred()) _, err = storage.GetState(tempDir) Expect(err).To(MatchError(ContainSubstring("permission denied"))) }) }) Context("when renaming the file fails", func() { It("returns an error", func() { storage.SetRename(func(src, dst string) error { return errors.New("renaming failed") }) _, err := storage.GetState(tempDir) Expect(err).To(MatchError("renaming failed")) }) }) }) }) }) Context("failure cases", func() { It("fails when the directory does not exist", func() { _, err := storage.GetState("some-fake-directory") Expect(err).To(MatchError(ContainSubstring("no such file or directory"))) }) It("fails to open the bbl-state.json file", func() { err := os.Chmod(tempDir, 0000) Expect(err).NotTo(HaveOccurred()) _, err = storage.GetState(tempDir) Expect(err).To(MatchError(ContainSubstring("permission denied"))) }) It("fails to decode the bbl-state.json file", func() { err := ioutil.WriteFile(filepath.Join(tempDir, "bbl-state.json"), []byte(`%%%%`), os.ModePerm) Expect(err).NotTo(HaveOccurred()) _, err = storage.GetState(tempDir) Expect(err).To(MatchError(ContainSubstring("invalid character"))) }) It("returns error when bbl-state.json and state.json exists", func() { err := ioutil.WriteFile(filepath.Join(tempDir, "state.json"), []byte(`{}`), os.ModePerm) Expect(err).NotTo(HaveOccurred()) err = ioutil.WriteFile(filepath.Join(tempDir, "bbl-state.json"), []byte(`{}`), os.ModePerm) Expect(err).NotTo(HaveOccurred()) _, err = storage.GetState(tempDir) Expect(err).To(MatchError(ContainSubstring("Cannot proceed with state.json and bbl-state.json present. Please delete one of the files."))) }) }) }) }) <file_sep>/boshinit/manifests/release_manifest_builder.go package manifests type ReleaseManifestBuilder struct{} func NewReleaseManifestBuilder() ReleaseManifestBuilder { return ReleaseManifestBuilder{} } func (r ReleaseManifestBuilder) Build(boshURL, boshSHA1, boshAWSCPIURL, boshAWSCPISHA1 string) []Release { return []Release{ { Name: "bosh", URL: boshURL, SHA1: boshSHA1, }, { Name: "bosh-aws-cpi", URL: boshAWSCPIURL, SHA1: boshAWSCPISHA1, }, } } <file_sep>/aws/iam/certificate_deleter.go package iam import ( "github.com/aws/aws-sdk-go/aws" awsiam "github.com/aws/aws-sdk-go/service/iam" ) type CertificateDeleter struct { iamClientProvider iamClientProvider } type logger interface { Step(message string) } func NewCertificateDeleter(iamClientProvider iamClientProvider) CertificateDeleter { return CertificateDeleter{ iamClientProvider: iamClientProvider, } } func (c CertificateDeleter) Delete(certificateName string) error { _, err := c.iamClientProvider.GetIAMClient().DeleteServerCertificate(&awsiam.DeleteServerCertificateInput{ ServerCertificateName: aws.String(certificateName), }) return err } <file_sep>/boshinit/manifests/internal_credentials.go package manifests type InternalCredentials struct { MBusUsername string `json:"mbusUsername"` NatsUsername string `json:"natsUsername"` PostgresUsername string `json:"postgresUsername"` RegistryUsername string `json:"registryUsername"` BlobstoreDirectorUsername string `json:"blobstoreDirectorUsername"` BlobstoreAgentUsername string `json:"blobstoreAgentUsername"` HMUsername string `json:"hmUsername"` MBusPassword string `json:"mbusPassword"` NatsPassword string `json:"natsPassword"` PostgresPassword string `json:"postgresPassword"` RegistryPassword string `json:"registryPassword"` BlobstoreDirectorPassword string `json:"blobstoreDirectorPassword"` BlobstoreAgentPassword string `json:"blobstoreAgentPassword"` HMPassword string `json:"hmPassword"` } func NewInternalCredentials(credentials map[string]string) InternalCredentials { return InternalCredentials{ MBusUsername: credentials["mbusUsername"], NatsUsername: credentials["natsUsername"], PostgresUsername: credentials["postgresUsername"], RegistryUsername: credentials["registryUsername"], BlobstoreDirectorUsername: credentials["blobstoreDirectorUsername"], BlobstoreAgentUsername: credentials["blobstoreAgentUsername"], HMUsername: credentials["hmUsername"], MBusPassword: credentials["mbusPassword"], NatsPassword: credentials["natsPassword"], PostgresPassword: credentials["postgresPassword"], RegistryPassword: credentials["registryPassword"], BlobstoreDirectorPassword: credentials["blobstoreDirectorPassword"], BlobstoreAgentPassword: credentials["blobstoreAgentPassword"], HMPassword: credentials["hmPassword"], } } func (c InternalCredentials) ToMap() map[string]string { return map[string]string{ "mbusUsername": c.MBusUsername, "natsUsername": c.NatsUsername, "postgresUsername": c.PostgresUsername, "registryUsername": c.RegistryUsername, "blobstoreDirectorUsername": c.BlobstoreDirectorUsername, "blobstoreAgentUsername": c.BlobstoreAgentUsername, "hmUsername": c.HMUsername, "mbusPassword": c.<PASSWORD>, "natsPassword": c.NatsPassword, "postgresPassword": c.PostgresPassword, "registryPassword": c.RegistryPassword, "blobstoreDirectorPassword": c.BlobstoreDirectorPassword, "blobstoreAgentPassword": c.BlobstoreAgentPassword, "hmPassword": c.HMPassword, } } <file_sep>/bosh/disk_types_generator.go package bosh type DiskTypesGenerator struct{} type DiskType struct { Name string `yaml:"name"` DiskSize int `yaml:"disk_size"` CloudProperties DiskTypeCloudProperties `yaml:"cloud_properties"` } type DiskTypeCloudProperties struct { Type string `yaml:"type"` Encrypted bool `yaml:"encrypted"` } func NewDiskTypesGenerator() DiskTypesGenerator { return DiskTypesGenerator{} } func (DiskTypesGenerator) Generate() []DiskType { return []DiskType{ { Name: "1GB", DiskSize: 1024, CloudProperties: DiskTypeCloudProperties{ Type: "gp2", Encrypted: true, }, }, { Name: "5GB", DiskSize: 5120, CloudProperties: DiskTypeCloudProperties{ Type: "gp2", Encrypted: true, }, }, { Name: "10GB", DiskSize: 10240, CloudProperties: DiskTypeCloudProperties{ Type: "gp2", Encrypted: true, }, }, { Name: "50GB", DiskSize: 51200, CloudProperties: DiskTypeCloudProperties{ Type: "gp2", Encrypted: true, }, }, { Name: "100GB", DiskSize: 102400, CloudProperties: DiskTypeCloudProperties{ Type: "gp2", Encrypted: true, }, }, { Name: "500GB", DiskSize: 512000, CloudProperties: DiskTypeCloudProperties{ Type: "gp2", Encrypted: true, }, }, { Name: "1TB", DiskSize: 1048576, CloudProperties: DiskTypeCloudProperties{ Type: "gp2", Encrypted: true, }, }, } } <file_sep>/application/command_line_parser_test.go package application_test import ( "errors" "strings" "github.com/cloudfoundry/bosh-bootloader/application" "github.com/cloudfoundry/bosh-bootloader/commands" . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/extensions/table" . "github.com/onsi/gomega" ) var _ = Describe("CommandLineParser", func() { var ( commandLineParser application.CommandLineParser usageCallCount int ) BeforeEach(func() { usageCallCount = 0 usageFunc := func() { usageCallCount++ } commandSet := application.CommandSet{ commands.UpCommand: nil, commands.VersionCommand: nil, commands.HelpCommand: nil, } commandLineParser = application.NewCommandLineParser(usageFunc, commandSet) }) Describe("Parse", func() { It("returns a command line configuration with correct global flags based on arguments passed in", func() { args := []string{ "--endpoint-override=some-endpoint-override", "--state-dir", "some/state/dir", "up", "--subcommand-flag", "some-value", } commandLineConfiguration, err := commandLineParser.Parse(args) Expect(err).NotTo(HaveOccurred()) Expect(commandLineConfiguration.EndpointOverride).To(Equal("some-endpoint-override")) Expect(commandLineConfiguration.StateDir).To(Equal("some/state/dir")) }) It("returns a command line configuration with correct command with subcommand flags based on arguments passed in", func() { args := []string{ "up", "--subcommand-flag", "some-value", } commandLineConfiguration, err := commandLineParser.Parse(args) Expect(err).NotTo(HaveOccurred()) Expect(commandLineConfiguration.Command).To(Equal("up")) Expect(commandLineConfiguration.SubcommandFlags).To(Equal([]string{"--subcommand-flag", "some-value"})) }) DescribeTable("returns an error when --state-dir is provided twice", func(arguments string) { args := strings.Split(arguments, " ") _, err := commandLineParser.Parse(args) Expect(err).To(MatchError("Invalid usage: cannot specify global 'state-dir' flag more than once.")) }, Entry("--state-dir with spaces", "--state-dir /some/state/dir --state-dir /some/other/state/dir up"), Entry("--state-dir with equal signs", "--state-dir=/some/state/dir --state-dir=/some/other/state/dir up"), Entry("--state-dir with mixed spaces/equal signs", "--state-dir=/some/state/dir --state-dir /some/other/state/dir up"), Entry("-state-dir with spaces", "-state-dir /some/state/dir -state-dir /some/other/state/dir up"), Entry("-state-dir with equal signs", "-state-dir=/some/state/dir -state-dir=/some/other/state/dir up"), Entry("-state-dir with mixed spaces/equal signs", "-state-dir=/some/state/dir -state-dir /some/other/state/dir up"), Entry("--state-dir/-state-dir", "--state-dir=/some/state/dir -state-dir /some/other/state/dir up"), ) Context("when no --state-dir is provided", func() { BeforeEach(func() { application.SetGetwd(func() (string, error) { return "some/state/dir", nil }) }) AfterEach(func() { application.ResetGetwd() }) It("uses the current working directory as the state directory", func() { commandLineConfiguration, err := commandLineParser.Parse([]string{ "up", }) Expect(err).NotTo(HaveOccurred()) Expect(commandLineConfiguration.StateDir).To(Equal("some/state/dir")) }) }) DescribeTable("when a command is requested using a flag", func(commandLineArgument string, desiredCommand string) { commandLineConfiguration, err := commandLineParser.Parse([]string{ commandLineArgument, }) Expect(err).NotTo(HaveOccurred()) Expect(commandLineConfiguration.Command).To(Equal(desiredCommand)) }, Entry("returns the help command provided --help", "--help", "help"), Entry("returns the help command provided --h", "--h", "help"), Entry("returns the help command provided help", "help", "help"), Entry("returns the version command provided version", "version", "version"), ) It("runs help without error if more arguments are provided to help", func() { commandLineConfiguration, err := commandLineParser.Parse([]string{ "--help", "up", "--aws-stuff", }) Expect(err).NotTo(HaveOccurred()) Expect(commandLineConfiguration.Command).To(Equal("help")) Expect(commandLineConfiguration.SubcommandFlags).To(Equal([]string{"up", "--aws-stuff"})) }) It("runs help without error", func() { commandLineConfiguration, err := commandLineParser.Parse([]string{}) Expect(err).NotTo(HaveOccurred()) Expect(commandLineConfiguration.Command).To(Equal("help")) Expect(commandLineConfiguration.SubcommandFlags).To(BeEmpty()) }) Context("failure cases", func() { It("returns an error and prints usage when an invalid flag is provided", func() { _, err := commandLineParser.Parse([]string{ "--invalid-flag", "up", }) Expect(err).To(Equal(errors.New("flag provided but not defined: -invalid-flag"))) Expect(usageCallCount).To(Equal(1)) }) It("returns an error and prints usage when an invalid flag is provided to help", func() { _, err := commandLineParser.Parse([]string{ "--help", "badcmd", }) Expect(err).To(Equal(errors.New("Unrecognized command 'badcmd'"))) Expect(usageCallCount).To(Equal(1)) }) It("returns an error when it cannot get working directory", func() { application.SetGetwd(func() (string, error) { return "", errors.New("failed to get working directory") }) defer application.ResetGetwd() _, err := commandLineParser.Parse([]string{ "up", }) Expect(err).To(MatchError("failed to get working directory")) }) It("validates the command before it validates the global arguments", func() { _, err := commandLineParser.Parse([]string{ "--badflag", "x", "help", "delete-lbs", "--other-flag", }) Expect(err).To(Equal(errors.New("Unrecognized command 'x'"))) Expect(usageCallCount).To(Equal(1)) }) }) }) }) <file_sep>/README.md # bosh-bootloader --- This is a command line utility for standing up a CloudFoundry or Concourse installation on an IAAS. This CLI is currently under heavy development, and the initial goal is to support bootstrapping a CloudFoundry installation on AWS. * [CI](https://mega.ci.cf-app.com/pipelines/bosh-bootloader) * [Tracker](https://www.pivotaltracker.com/n/projects/1488988) ## Prerequisites ### Install Dependencies The following should be installed on your local machine - Golang >= 1.5 (install with `brew install go`) - bosh-init ([installation instructions](http://bosh.io/docs/install-bosh-init.html)) NOTE: Golang 1.7 is highly recommended ### Install bosh-bootloader bosh-bootloader can be installed with go get: ``` go get github.com/cloudfoundry/bosh-bootloader/bbl ``` ### Configure AWS The AWS IAM user that is provided to bbl will need the following policy: ``` { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ec2:*", "cloudformation:*", "elasticloadbalancing:*", "iam:*" ], "Resource": [ "*" ] } ] } ``` ## Usage The `bbl` command can be invoked on the command line and will display its usage. ``` $ bbl Usage: bbl [GLOBAL OPTIONS] COMMAND [OPTIONS] Global Options: --help [-h] Print usage --version [-v] Print version --state-dir Directory containing bbl-state.json Commands: create-lbs Attaches load balancer(s) delete-lbs Deletes attached load balancer(s) destroy Tears down BOSH director infrastructure director-address Prints BOSH director address director-username Prints BOSH director username director-password Prints BOSH director password director-ca-cert Prints BOSH director CA certificate env-id Prints environment ID help Prints usage lbs Prints attached load balancer(s) ssh-key Prints SSH private key up Deploys BOSH director on AWS update-lbs Updates load balancer(s) version Prints version Use "bbl [command] --help" for more information about a command. ``` <file_sep>/aws/iam/certificate_describer_test.go package iam_test import ( "errors" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/cloudfoundry/bosh-bootloader/aws/iam" "github.com/cloudfoundry/bosh-bootloader/fakes" awsiam "github.com/aws/aws-sdk-go/service/iam" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("CertificateDescriber", func() { var ( iamClient *fakes.IAMClient describer iam.CertificateDescriber iamClientProvider *fakes.ClientProvider ) BeforeEach(func() { iamClient = &fakes.IAMClient{} iamClientProvider = &fakes.ClientProvider{} iamClientProvider.GetIAMClientCall.Returns.IAMClient = iamClient describer = iam.NewCertificateDescriber(iamClientProvider) }) Describe("Describe", func() { It("describes the certificate with the given name", func() { iamClient.GetServerCertificateCall.Returns.Output = &awsiam.GetServerCertificateOutput{ ServerCertificate: &awsiam.ServerCertificate{ CertificateBody: aws.String("some-certificate-body"), CertificateChain: aws.String("some-chain-body"), ServerCertificateMetadata: &awsiam.ServerCertificateMetadata{ Path: aws.String("some-certificate-path"), Arn: aws.String("some-certificate-arn"), ServerCertificateId: aws.String("some-server-certificate-id"), ServerCertificateName: aws.String("some-certificate"), }, }, } certificate, err := describer.Describe("some-certificate") Expect(err).NotTo(HaveOccurred()) Expect(iamClientProvider.GetIAMClientCall.CallCount).To(Equal(1)) Expect(iamClient.GetServerCertificateCall.Receives.Input.ServerCertificateName).To(Equal(aws.String("some-certificate"))) Expect(certificate.Name).To(Equal("some-certificate")) Expect(certificate.Body).To(Equal("some-certificate-body")) Expect(certificate.Chain).To(Equal("some-chain-body")) Expect(certificate.ARN).To(Equal("some-certificate-arn")) }) Context("failure cases", func() { It("returns an error when the ServerCertificate is nil", func() { iamClient.GetServerCertificateCall.Returns.Output = &awsiam.GetServerCertificateOutput{ ServerCertificate: nil, } _, err := describer.Describe("some-certificate") Expect(err).To(MatchError(iam.CertificateDescriptionFailure)) }) It("returns an error when the ServerCertificateMetadata is nil", func() { iamClient.GetServerCertificateCall.Returns.Output = &awsiam.GetServerCertificateOutput{ ServerCertificate: &awsiam.ServerCertificate{ ServerCertificateMetadata: nil, }, } _, err := describer.Describe("some-certificate") Expect(err).To(MatchError(iam.CertificateDescriptionFailure)) }) It("returns an error when the certificate cannot be described", func() { iamClient.GetServerCertificateCall.Returns.Error = awserr.NewRequestFailure( awserr.New("boom", "something bad happened", errors.New(""), ), 404, "0", ) _, err := describer.Describe("some-certificate") Expect(err).To(MatchError(ContainSubstring("something bad happened"))) }) It("returns a CertificateNotFound error when the certificate does not exist", func() { iamClient.GetServerCertificateCall.Returns.Error = awserr.NewRequestFailure( awserr.New("NoSuchEntity", "The Server Certificate with name some-certificate cannot be found.", errors.New(""), ), 404, "0", ) _, err := describer.Describe("some-certificate") Expect(err).To(MatchError(iam.CertificateNotFound)) }) }) }) }) <file_sep>/application/logger_test.go package application_test import ( "bytes" "fmt" "math/rand" "github.com/cloudfoundry/bosh-bootloader/application" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Logger", func() { var ( buffer *bytes.Buffer logger *application.Logger ) BeforeEach(func() { buffer = bytes.NewBuffer([]byte{}) logger = application.NewLogger(buffer) }) Describe("Step", func() { It("prints the step message", func() { logger.Step("creating key pair") Expect(buffer.String()).To(Equal("step: creating key pair\n")) }) It("prints the step message with dynamic values", func() { randomInt := rand.Int() logger.Step("Random variable is: %d", randomInt) Expect(buffer.String()).To(Equal(fmt.Sprintf("step: Random variable is: %d\n", randomInt))) }) }) Describe("Dot", func() { It("prints a dot", func() { logger.Dot() logger.Dot() logger.Dot() Expect(buffer.String()).To(Equal("\u2022\u2022\u2022")) }) }) Describe("Println", func() { It("prints out the message", func() { logger.Println("hello world") Expect(buffer.String()).To(Equal("hello world\n")) }) }) Describe("Prompt", func() { It("prompts for the given messge", func() { logger.Prompt("do you like cheese?") Expect(buffer.String()).To(Equal("do you like cheese? (y/N): ")) }) }) Describe("mixing steps, dots and printlns", func() { It("prints out a coherent set of lines", func() { logger.Step("creating keypair") logger.Step("generating cloudformation template") logger.Step("applying cloudformation template") logger.Dot() logger.Dot() logger.Step("completed applying cloudformation template") logger.Dot() logger.Dot() logger.Prompt("do you like turtles?") logger.Println("**bosh manifest**") logger.Step("doing more stuff") logger.Dot() logger.Dot() logger.Println("SUCCESS!") Expect(buffer.String()).To(Equal(`step: creating keypair step: generating cloudformation template step: applying cloudformation template •• step: completed applying cloudformation template •• do you like turtles? (y/N): **bosh manifest** step: doing more stuff •• SUCCESS! `)) }) }) }) <file_sep>/boshinit/manifests/cloud_provider_manifest_builder_test.go package manifests_test import ( "fmt" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/cloudfoundry/bosh-bootloader/boshinit/manifests" "github.com/cloudfoundry/bosh-bootloader/fakes" ) var _ = Describe("CloudProviderManifestBuilder", func() { var ( cloudProviderManifestBuilder manifests.CloudProviderManifestBuilder stringGenerator *fakes.StringGenerator ) BeforeEach(func() { stringGenerator = &fakes.StringGenerator{} cloudProviderManifestBuilder = manifests.NewCloudProviderManifestBuilder(stringGenerator) stringGenerator.GenerateCall.Stub = func(prefix string, length int) (string, error) { return fmt.Sprintf("%s%s", prefix, "some-random-string"), nil } }) Describe("Build", func() { It("returns all cloud provider fields for manifest", func() { cloudProvider, _, err := cloudProviderManifestBuilder.Build(manifests.ManifestProperties{ ElasticIP: "some-elastic-ip", AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", DefaultKeyName: "some-key-name", Region: "some-region", SecurityGroup: "some-security-group", }) Expect(err).NotTo(HaveOccurred()) Expect(cloudProvider).To(Equal(manifests.CloudProvider{ Template: manifests.Template{ Name: "aws_cpi", Release: "bosh-aws-cpi", }, SSHTunnel: manifests.SSHTunnel{ Host: "some-elastic-ip", Port: 22, User: "vcap", PrivateKey: "./bosh.pem", }, MBus: "https://mbus-user-some-random-string:mbus-some-random-string@some-elastic-ip:6868", Properties: manifests.CloudProviderProperties{ AWS: manifests.AWSProperties{ AccessKeyId: "some-access-key-id", SecretAccessKey: "some-secret-access-key", DefaultKeyName: "some-key-name", DefaultSecurityGroups: []string{"some-security-group"}, Region: "some-region", }, Agent: manifests.AgentProperties{ MBus: "https://mbus-user-some-random-string:mbus-some-random-string@0.0.0.0:6868", }, Blobstore: manifests.BlobstoreProperties{ Provider: "local", Path: "/var/vcap/micro_bosh/data/cache", }, }, })) Expect(stringGenerator.GenerateCall.Receives.Prefixes).To(Equal([]string{"mbus-user-", "mbus-"})) Expect(stringGenerator.GenerateCall.Receives.Lengths).To(Equal([]int{15, 15})) }) It("returns manifest properties with new credentials", func() { _, manifestProperties, err := cloudProviderManifestBuilder.Build(manifests.ManifestProperties{}) Expect(err).NotTo(HaveOccurred()) Expect(manifestProperties.Credentials.MBusUsername).To(Equal("mbus-user-some-random-string")) Expect(manifestProperties.Credentials.MBusPassword).To(Equal("<PASSWORD>-some-random-string")) }) It("returns manifest and manifest properties with existing credentials", func() { cloudProvider, manifestProperties, err := cloudProviderManifestBuilder.Build(manifests.ManifestProperties{ ElasticIP: "some-elastic-ip", AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", DefaultKeyName: "some-key-name", Region: "some-region", SecurityGroup: "some-security-group", Credentials: manifests.InternalCredentials{ MBusUsername: "some-persisted-mbus-username", MBusPassword: "<PASSWORD>", }, }) Expect(err).NotTo(HaveOccurred()) Expect(cloudProvider.MBus).To(Equal("https://some-persisted-mbus-username:some-persisted-mbus-password@some-elastic-ip:6868")) Expect(cloudProvider.Properties.Agent.MBus).To(Equal("https://some-persisted-mbus-username:some-persisted-mbus-password@0.0.0.0:6868")) Expect(manifestProperties.Credentials.MBusPassword).To(Equal("<PASSWORD>us-password")) }) Context("when string generator cannot generated a string", func() { BeforeEach(func() { stringGenerator.GenerateCall.Stub = nil stringGenerator.GenerateCall.Returns.Error = fmt.Errorf("foo") }) It("forwards the error", func() { _, _, err := cloudProviderManifestBuilder.Build(manifests.ManifestProperties{}) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(Equal("foo")) }) }) }) }) <file_sep>/fakes/cloud_provider_manifest_builder.go package fakes import "github.com/cloudfoundry/bosh-bootloader/boshinit/manifests" type CloudProviderManifestBuilder struct { BuildCall struct { Returns struct { Error error } } } func (c CloudProviderManifestBuilder) Build(manifestProperties manifests.ManifestProperties) (manifests.CloudProvider, manifests.ManifestProperties, error) { return manifests.CloudProvider{}, manifestProperties, c.BuildCall.Returns.Error } <file_sep>/bosh/vm_types_generator.go package bosh type VMTypesGenerator struct { } type VMType struct { Name string `yaml:"name,omitempty"` CloudProperties *VMTypeCloudProperties `yaml:"cloud_properties,omitempty"` } type VMTypeCloudProperties struct { InstanceType string `yaml:"instance_type,omitempty"` EphemeralDisk *EphemeralDisk `yaml:"ephemeral_disk,omitempty"` } type EphemeralDisk struct { Size int `yaml:"size,omitempty"` Type string `yaml:"type,omitempty"` } func NewVMTypesGenerator() VMTypesGenerator { return VMTypesGenerator{} } func (g VMTypesGenerator) Generate() []VMType { return []VMType{ createVMType("m3.medium"), createVMType("m3.large"), createVMType("m3.xlarge"), createVMType("m3.2xlarge"), createVMType("m4.large"), createVMType("m4.xlarge"), createVMType("m4.2xlarge"), createVMType("m4.4xlarge"), createVMType("m4.10xlarge"), createVMType("c3.large"), createVMType("c3.xlarge"), createVMType("c3.2xlarge"), createVMType("c3.4xlarge"), createVMType("c3.8xlarge"), createVMType("c4.large"), createVMType("c4.xlarge"), createVMType("c4.2xlarge"), createVMType("c4.4xlarge"), createVMType("c4.8xlarge"), createVMType("r3.large"), createVMType("r3.xlarge"), createVMType("r3.2xlarge"), createVMType("r3.4xlarge"), createVMType("r3.8xlarge"), createVMType("t2.nano"), createVMType("t2.micro"), createVMType("t2.small"), createVMType("t2.medium"), createVMType("t2.large"), } } func createVMType(instanceType string) VMType { return VMType{ Name: instanceType, CloudProperties: &VMTypeCloudProperties{ InstanceType: instanceType, EphemeralDisk: &EphemeralDisk{ Size: 1024, Type: "gp2", }, }, } } <file_sep>/integration-test/concourse/deploy_test.go package integration_test import ( "bufio" "fmt" "io" "io/ioutil" "net/http" "regexp" "strings" "github.com/cloudfoundry/bosh-bootloader/integration-test" "github.com/cloudfoundry/bosh-bootloader/integration-test/actors" "github.com/cloudfoundry/bosh-bootloader/testhelpers" "github.com/pivotal-cf-experimental/bosh-test/bosh" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) const ( ConcourseExampleManifestURL = "https://raw.githubusercontent.com/concourse/concourse/master/docs/setting-up/installing.any" ConcourseReleaseURL = "https://bosh.io/d/github.com/concourse/concourse" GardenReleaseURL = "https://bosh.io/d/github.com/cloudfoundry-incubator/garden-runc-release" GardenReleaseName = "garden-runc" StemcellURL = "https://bosh.io/d/stemcells/bosh-aws-xen-hvm-ubuntu-trusty-go_agent" StemcellName = "bosh-aws-xen-hvm-ubuntu-trusty-go_agent" ) var _ = Describe("bosh deployment tests", func() { var ( bbl actors.BBL aws actors.AWS state integration.State ) BeforeEach(func() { var err error configuration, err := integration.LoadConfig() Expect(err).NotTo(HaveOccurred()) bbl = actors.NewBBL(configuration.StateFileDir, pathToBBL, configuration) aws = actors.NewAWS(configuration) state = integration.NewState(configuration.StateFileDir) }) It("is able to deploy concourse", func() { bbl.Up() certPath, err := testhelpers.WriteContentsToTempFile(testhelpers.BBL_CERT) Expect(err).NotTo(HaveOccurred()) keyPath, err := testhelpers.WriteContentsToTempFile(testhelpers.BBL_KEY) Expect(err).NotTo(HaveOccurred()) bbl.CreateLB("concourse", certPath, keyPath, "") boshClient := bosh.NewClient(bosh.Config{ URL: bbl.DirectorAddress(), Username: bbl.DirectorUsername(), Password: <PASSWORD>(), AllowInsecureSSL: true, }) err = downloadAndUploadRelease(boshClient, ConcourseReleaseURL) Expect(err).NotTo(HaveOccurred()) err = downloadAndUploadRelease(boshClient, GardenReleaseURL) Expect(err).NotTo(HaveOccurred()) err = downloadAndUploadStemcell(boshClient, StemcellURL) Expect(err).NotTo(HaveOccurred()) concourseExampleManifest, err := downloadConcourseExampleManifest() Expect(err).NotTo(HaveOccurred()) info, err := boshClient.Info() Expect(err).NotTo(HaveOccurred()) lbURL := fmt.Sprintf("http://%s", aws.LoadBalancers(state.StackName())["ConcourseLoadBalancerURL"]) stemcell, err := boshClient.Stemcell(StemcellName) Expect(err).NotTo(HaveOccurred()) concourseRelease, err := boshClient.Release("concourse") Expect(err).NotTo(HaveOccurred()) gardenRelease, err := boshClient.Release(GardenReleaseName) Expect(err).NotTo(HaveOccurred()) concourseManifestInputs := concourseManifestInputs{ boshDirectorUUID: info.UUID, webExternalURL: lbURL, stemcellVersion: stemcell.Latest(), concourseReleaseVersion: concourseRelease.Latest(), gardenReleaseVersion: gardenRelease.Latest(), } concourseManifest, err := populateManifest(concourseExampleManifest, concourseManifestInputs) Expect(err).NotTo(HaveOccurred()) _, err = boshClient.Deploy([]byte(concourseManifest)) Expect(err).NotTo(HaveOccurred()) Eventually(func() ([]bosh.VM, error) { return boshClient.DeploymentVMs("concourse") }, "1m", "10s").Should(ConsistOf([]bosh.VM{ {JobName: "worker", Index: 0, State: "running"}, {JobName: "db", Index: 0, State: "running"}, {JobName: "web", Index: 0, State: "running"}, })) resp, err := http.Get(lbURL) Expect(err).NotTo(HaveOccurred()) Expect(resp.StatusCode).To(Equal(http.StatusOK)) body, err := ioutil.ReadAll(resp.Body) Expect(err).NotTo(HaveOccurred()) Expect(string(body)).To(ContainSubstring("<title>Concourse</title>")) err = boshClient.DeleteDeployment("concourse") Expect(err).NotTo(HaveOccurred()) bbl.Destroy() }) }) func downloadAndUploadStemcell(boshClient bosh.Client, stemcell string) error { file, size, err := download(stemcell) if err != nil { return err } _, err = boshClient.UploadStemcell(bosh.NewSizeReader(file, size)) return err } func downloadAndUploadRelease(boshClient bosh.Client, release string) error { file, size, err := download(release) if err != nil { return err } _, err = boshClient.UploadRelease(bosh.NewSizeReader(file, size)) return err } func downloadConcourseExampleManifest() (string, error) { resp, _, err := download(ConcourseExampleManifestURL) if err != nil { return "", err } var lines []string scanner := bufio.NewScanner(resp) for scanner.Scan() { lines = append(lines, scanner.Text()) } startIndexOfYamlCode := -1 endIndexOfYamlCode := -1 for index, line := range lines { startMatched, startErr := regexp.MatchString(`^\s*\\codeblock{yaml}{$`, line) endMatched, endErr := regexp.MatchString(`^\s*}$`, line) if endErr != nil { return "", endErr } if startErr != nil { panic(startErr) } if startMatched && startIndexOfYamlCode < 0 { startIndexOfYamlCode = index + 1 } if endMatched && endIndexOfYamlCode < 0 && startIndexOfYamlCode > 0 { endIndexOfYamlCode = index } } yamlDocument := lines[startIndexOfYamlCode:endIndexOfYamlCode] re := regexp.MustCompile(`^(\s*)---`) results := re.FindAllStringSubmatch(yamlDocument[0], -1) indentation := results[0][1] for index, line := range yamlDocument { indentationRegexp := regexp.MustCompile(fmt.Sprintf(`^%s`, indentation)) escapesRegexp := regexp.MustCompile(`\\([{}])`) tlsRegexp := regexp.MustCompile("^.*(tls_key|tls_cert).*$") line = indentationRegexp.ReplaceAllString(line, "") line = escapesRegexp.ReplaceAllString(line, "$1") line = tlsRegexp.ReplaceAllString(line, "") yamlDocument[index] = line } yamlString := strings.Join(yamlDocument, "\n") return yamlString, nil } func download(location string) (io.Reader, int64, error) { resp, err := http.Get(location) if err != nil { return nil, 0, err } return resp.Body, resp.ContentLength, nil } <file_sep>/application/logger.go package application import ( "fmt" "io" ) type Logger struct { newline bool writer io.Writer } func NewLogger(writer io.Writer) *Logger { return &Logger{ newline: true, writer: writer, } } func (l *Logger) clear() { if l.newline { return } l.writer.Write([]byte("\n")) l.newline = true } func (l *Logger) Step(message string, a ...interface{}) { l.clear() fmt.Fprintf(l.writer, "step: %s\n", fmt.Sprintf(message, a...)) l.newline = true } func (l *Logger) Dot() { l.writer.Write([]byte("\u2022")) l.newline = false } func (l *Logger) Println(message string) { l.clear() fmt.Fprintf(l.writer, "%s\n", message) } func (l *Logger) Prompt(message string) { l.clear() fmt.Fprintf(l.writer, "%s (y/N): ", message) l.newline = true } <file_sep>/fakes/stack_manager.go package fakes import ( "time" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" ) type StackManager struct { DescribeCall struct { Receives struct { StackName string } Returns struct { Stack cloudformation.Stack Error error } Stub func(string) (cloudformation.Stack, error) } CreateOrUpdateCall struct { Receives struct { StackName string Template templates.Template Tags cloudformation.Tags } Returns struct { Error error } } UpdateCall struct { Receives struct { StackName string Template templates.Template Tags cloudformation.Tags } Returns struct { Error error } } WaitForCompletionCall struct { Receives struct { StackName string SleepInterval time.Duration Action string } Returns struct { Error error } } DeleteCall struct { Receives struct { StackName string } Returns struct { Error error } } GetPhysicalIDForResourceCall struct { Receives struct { StackName string LogicalResourceID string } Returns struct { PhysicalResourceID string Error error } } } func (m *StackManager) CreateOrUpdate(stackName string, template templates.Template, tags cloudformation.Tags) error { m.CreateOrUpdateCall.Receives.StackName = stackName m.CreateOrUpdateCall.Receives.Template = template m.CreateOrUpdateCall.Receives.Tags = tags return m.CreateOrUpdateCall.Returns.Error } func (m *StackManager) Update(stackName string, template templates.Template, tags cloudformation.Tags) error { m.UpdateCall.Receives.StackName = stackName m.UpdateCall.Receives.Template = template m.UpdateCall.Receives.Tags = tags return m.UpdateCall.Returns.Error } func (m *StackManager) WaitForCompletion(stackName string, sleepInterval time.Duration, action string) error { m.WaitForCompletionCall.Receives.StackName = stackName m.WaitForCompletionCall.Receives.SleepInterval = sleepInterval m.WaitForCompletionCall.Receives.Action = action return m.WaitForCompletionCall.Returns.Error } func (m *StackManager) Describe(stackName string) (cloudformation.Stack, error) { m.DescribeCall.Receives.StackName = stackName if m.DescribeCall.Stub != nil { return m.DescribeCall.Stub(stackName) } return m.DescribeCall.Returns.Stack, m.DescribeCall.Returns.Error } func (m *StackManager) Delete(stackName string) error { m.DeleteCall.Receives.StackName = stackName return m.DeleteCall.Returns.Error } func (m *StackManager) GetPhysicalIDForResource(stackName string, logicalResourceID string) (string, error) { m.GetPhysicalIDForResourceCall.Receives.StackName = stackName m.GetPhysicalIDForResourceCall.Receives.LogicalResourceID = logicalResourceID return m.GetPhysicalIDForResourceCall.Returns.PhysicalResourceID, m.GetPhysicalIDForResourceCall.Returns.Error } <file_sep>/aws/iam/certificate_uploader.go package iam import ( "fmt" "io/ioutil" "strings" "github.com/aws/aws-sdk-go/aws" awsiam "github.com/aws/aws-sdk-go/service/iam" ) type CertificateUploader struct { iamClientProvider iamClientProvider } func NewCertificateUploader(iamClientProvider iamClientProvider) CertificateUploader { return CertificateUploader{ iamClientProvider: iamClientProvider, } } func (c CertificateUploader) Upload(certificatePath, privateKeyPath, chainPath, certificateName string) error { if strings.ContainsAny(certificateName, ":") { return fmt.Errorf("%q is an invalid certificate name, it must not contain %q", certificateName, ":") } certificate, err := ioutil.ReadFile(certificatePath) if err != nil { return err } privateKey, err := ioutil.ReadFile(privateKeyPath) if err != nil { return err } var chain *string if chainPath != "" { chainContents, err := ioutil.ReadFile(chainPath) chain = aws.String(string(chainContents)) if err != nil { return err } } _, err = c.iamClientProvider.GetIAMClient().UploadServerCertificate(&awsiam.UploadServerCertificateInput{ CertificateBody: aws.String(string(certificate)), PrivateKey: aws.String(string(privateKey)), CertificateChain: chain, ServerCertificateName: aws.String(certificateName), }) if err != nil { return err } return nil } <file_sep>/boshinit/manifests/release_manifest_builder_test.go package manifests_test import ( "github.com/cloudfoundry/bosh-bootloader/boshinit/manifests" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("ReleaseManifestBuilder", func() { var releaseManifestBuilder manifests.ReleaseManifestBuilder BeforeEach(func() { releaseManifestBuilder = manifests.NewReleaseManifestBuilder() }) Describe("Build", func() { It("returns all releases for manifest", func() { releases := releaseManifestBuilder.Build("some-bosh-url", "some-bosh-sha1", "some-bosh-aws-cpi-url", "some-bosh-aws-cpi-sha1") Expect(releases).To(HaveLen(2)) Expect(releases).To(ConsistOf([]manifests.Release{ { Name: "bosh", URL: "some-bosh-url", SHA1: "some-bosh-sha1", }, { Name: "bosh-aws-cpi", URL: "some-bosh-aws-cpi-url", SHA1: "some-bosh-aws-cpi-sha1", }, })) }) }) }) <file_sep>/aws/cloudformation/templates/load_balancer_subnet_template_builder_test.go package templates_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" ) var _ = Describe("LoadBalancerSubnetTemplateBuilder", func() { var builder templates.LoadBalancerSubnetTemplateBuilder BeforeEach(func() { builder = templates.NewLoadBalancerSubnetTemplateBuilder() }) Describe("LoadBalancerSubnet", func() { It("returns a template with all fields for the load balancer subnet", func() { subnet := builder.LoadBalancerSubnet(0, "1", "10.0.2.0/24") Expect(subnet.Parameters).To(HaveLen(1)) Expect(subnet.Parameters).To(HaveKeyWithValue("LoadBalancerSubnet1CIDR", templates.Parameter{ Description: "CIDR block for the ELB subnet.", Type: "String", Default: "10.0.2.0/24", })) Expect(subnet.Resources).To(HaveLen(4)) Expect(subnet.Resources).To(HaveKeyWithValue("LoadBalancerSubnet1", templates.Resource{ Type: "AWS::EC2::Subnet", Properties: templates.Subnet{ AvailabilityZone: map[string]interface{}{ "Fn::Select": []interface{}{ "0", map[string]templates.Ref{ "Fn::GetAZs": templates.Ref{"AWS::Region"}, }, }, }, CidrBlock: templates.Ref{"LoadBalancerSubnet1CIDR"}, VpcId: templates.Ref{"VPC"}, Tags: []templates.Tag{ { Key: "Name", Value: "LoadBalancer1", }, }, }, })) Expect(subnet.Resources).To(HaveKeyWithValue("LoadBalancerRouteTable", templates.Resource{ Type: "AWS::EC2::RouteTable", Properties: templates.RouteTable{ VpcId: templates.Ref{"VPC"}, }, })) Expect(subnet.Resources).To(HaveKeyWithValue("LoadBalancerRoute", templates.Resource{ Type: "AWS::EC2::Route", DependsOn: "VPCGatewayAttachment", Properties: templates.Route{ DestinationCidrBlock: "0.0.0.0/0", GatewayId: templates.Ref{"VPCGatewayInternetGateway"}, RouteTableId: templates.Ref{"LoadBalancerRouteTable"}, }, })) Expect(subnet.Resources).To(HaveKeyWithValue("LoadBalancerSubnet1RouteTableAssociation", templates.Resource{ Type: "AWS::EC2::SubnetRouteTableAssociation", Properties: templates.SubnetRouteTableAssociation{ RouteTableId: templates.Ref{"LoadBalancerRouteTable"}, SubnetId: templates.Ref{"LoadBalancerSubnet1"}, }, })) }) It("returns subnet with az 1", func() { subnet := builder.LoadBalancerSubnet(1, "1", "10.0.3.0/24") Expect(subnet.Parameters).To(HaveLen(1)) Expect(subnet.Parameters).To(HaveKeyWithValue("LoadBalancerSubnet1CIDR", templates.Parameter{ Description: "CIDR block for the ELB subnet.", Type: "String", Default: "10.0.3.0/24", })) Expect(subnet.Resources).To(HaveKeyWithValue("LoadBalancerSubnet1", templates.Resource{ Type: "AWS::EC2::Subnet", Properties: templates.Subnet{ AvailabilityZone: map[string]interface{}{ "Fn::Select": []interface{}{ "1", map[string]templates.Ref{ "Fn::GetAZs": templates.Ref{"AWS::Region"}, }, }, }, CidrBlock: templates.Ref{"LoadBalancerSubnet1CIDR"}, VpcId: templates.Ref{"VPC"}, Tags: []templates.Tag{ { Key: "Name", Value: "LoadBalancer1", }, }, }, })) }) }) }) <file_sep>/bbl/main.go package main import ( "crypto/rand" "crypto/rsa" "fmt" "io/ioutil" "os" "os/exec" "github.com/cloudfoundry/bosh-bootloader/application" "github.com/cloudfoundry/bosh-bootloader/aws" "github.com/cloudfoundry/bosh-bootloader/aws/clientmanager" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" "github.com/cloudfoundry/bosh-bootloader/aws/ec2" "github.com/cloudfoundry/bosh-bootloader/aws/iam" "github.com/cloudfoundry/bosh-bootloader/bbl/constants" "github.com/cloudfoundry/bosh-bootloader/bosh" "github.com/cloudfoundry/bosh-bootloader/boshinit" "github.com/cloudfoundry/bosh-bootloader/boshinit/manifests" "github.com/cloudfoundry/bosh-bootloader/commands" "github.com/cloudfoundry/bosh-bootloader/helpers" "github.com/cloudfoundry/bosh-bootloader/ssl" "github.com/cloudfoundry/bosh-bootloader/storage" "github.com/square/certstrap/pkix" ) var ( Version string ) func main() { // Command Set commandSet := application.CommandSet{ commands.HelpCommand: nil, commands.VersionCommand: nil, commands.UpCommand: nil, commands.DestroyCommand: nil, commands.DirectorAddressCommand: nil, commands.DirectorUsernameCommand: nil, commands.DirectorPasswordCommand: nil, commands.DirectorCACertCommand: nil, commands.BOSHCACertCommand: nil, commands.SSHKeyCommand: nil, commands.CreateLBsCommand: nil, commands.UpdateLBsCommand: nil, commands.DeleteLBsCommand: nil, commands.LBsCommand: nil, commands.EnvIDCommand: nil, } // Utilities uuidGenerator := helpers.NewUUIDGenerator(rand.Reader) stringGenerator := helpers.NewStringGenerator(rand.Reader) envIDGenerator := helpers.NewEnvIDGenerator(rand.Reader) logger := application.NewLogger(os.Stdout) stderrLogger := application.NewLogger(os.Stderr) sslKeyPairGenerator := ssl.NewKeyPairGenerator(rsa.GenerateKey, pkix.CreateCertificateAuthority, pkix.CreateCertificateSigningRequest, pkix.CreateCertificateHost) // Usage Command usage := commands.NewUsage(os.Stdout) storage.GetStateLogger = stderrLogger commandLineParser := application.NewCommandLineParser(usage.Print, commandSet) configurationParser := application.NewConfigurationParser(commandLineParser) configuration, err := configurationParser.Parse(os.Args[1:]) if err != nil { fail(err) } stateStore := storage.NewStore(configuration.Global.StateDir) stateValidator := application.NewStateValidator(configuration.Global.StateDir) // Amazon awsConfiguration := aws.Config{ AccessKeyID: configuration.State.AWS.AccessKeyID, SecretAccessKey: configuration.State.AWS.SecretAccessKey, Region: configuration.State.AWS.Region, EndpointOverride: configuration.Global.EndpointOverride, } clientProvider := &clientmanager.ClientProvider{EndpointOverride: configuration.Global.EndpointOverride} clientProvider.SetConfig(awsConfiguration) awsCredentialValidator := application.NewAWSCredentialValidator(configuration) vpcStatusChecker := ec2.NewVPCStatusChecker(clientProvider) keyPairCreator := ec2.NewKeyPairCreator(clientProvider) keyPairDeleter := ec2.NewKeyPairDeleter(clientProvider, logger) keyPairChecker := ec2.NewKeyPairChecker(clientProvider) keyPairManager := ec2.NewKeyPairManager(keyPairCreator, keyPairChecker, logger) keyPairSynchronizer := ec2.NewKeyPairSynchronizer(keyPairManager) availabilityZoneRetriever := ec2.NewAvailabilityZoneRetriever(clientProvider) templateBuilder := templates.NewTemplateBuilder(logger) stackManager := cloudformation.NewStackManager(clientProvider, logger) infrastructureManager := cloudformation.NewInfrastructureManager(templateBuilder, stackManager) certificateUploader := iam.NewCertificateUploader(clientProvider) certificateDescriber := iam.NewCertificateDescriber(clientProvider) certificateDeleter := iam.NewCertificateDeleter(clientProvider) certificateManager := iam.NewCertificateManager(certificateUploader, certificateDescriber, certificateDeleter) certificateValidator := iam.NewCertificateValidator() // bosh-init tempDir, err := ioutil.TempDir("", "bosh-init") if err != nil { fail(err) } boshInitPath, err := exec.LookPath("bosh-init") if err != nil { fail(err) } cloudProviderManifestBuilder := manifests.NewCloudProviderManifestBuilder(stringGenerator) jobsManifestBuilder := manifests.NewJobsManifestBuilder(stringGenerator) boshinitManifestBuilder := manifests.NewManifestBuilder(manifests.ManifestBuilderInput{ BOSHURL: constants.BOSHURL, BOSHSHA1: constants.BOSHSHA1, BOSHAWSCPIURL: constants.BOSHAWSCPIURL, BOSHAWSCPISHA1: constants.BOSHAWSCPISHA1, StemcellURL: constants.StemcellURL, StemcellSHA1: constants.StemcellSHA1, }, logger, sslKeyPairGenerator, stringGenerator, cloudProviderManifestBuilder, jobsManifestBuilder, ) boshinitCommandBuilder := boshinit.NewCommandBuilder(boshInitPath, tempDir, os.Stdout, os.Stderr) boshinitDeployCommand := boshinitCommandBuilder.DeployCommand() boshinitDeleteCommand := boshinitCommandBuilder.DeleteCommand() boshinitDeployRunner := boshinit.NewCommandRunner(tempDir, boshinitDeployCommand) boshinitDeleteRunner := boshinit.NewCommandRunner(tempDir, boshinitDeleteCommand) boshinitExecutor := boshinit.NewExecutor( boshinitManifestBuilder, boshinitDeployRunner, boshinitDeleteRunner, logger, ) // BOSH boshClientProvider := bosh.NewClientProvider() cloudConfigGenerator := bosh.NewCloudConfigGenerator() cloudConfigurator := bosh.NewCloudConfigurator(logger, cloudConfigGenerator) cloudConfigManager := bosh.NewCloudConfigManager(logger, cloudConfigGenerator) // Commands commandSet[commands.HelpCommand] = commands.NewUsage(os.Stdout) commandSet[commands.VersionCommand] = commands.NewVersion(Version, os.Stdout) commandSet[commands.UpCommand] = commands.NewUp( awsCredentialValidator, infrastructureManager, keyPairSynchronizer, boshinitExecutor, stringGenerator, cloudConfigurator, availabilityZoneRetriever, certificateDescriber, cloudConfigManager, boshClientProvider, envIDGenerator, stateStore, clientProvider, ) commandSet[commands.DestroyCommand] = commands.NewDestroy( awsCredentialValidator, logger, os.Stdin, boshinitExecutor, vpcStatusChecker, stackManager, stringGenerator, infrastructureManager, keyPairDeleter, certificateDeleter, stateStore, stateValidator, ) commandSet[commands.CreateLBsCommand] = commands.NewCreateLBs( logger, awsCredentialValidator, certificateManager, infrastructureManager, availabilityZoneRetriever, boshClientProvider, cloudConfigurator, cloudConfigManager, certificateValidator, uuidGenerator, stateStore, stateValidator, ) commandSet[commands.UpdateLBsCommand] = commands.NewUpdateLBs(awsCredentialValidator, certificateManager, availabilityZoneRetriever, infrastructureManager, boshClientProvider, logger, certificateValidator, uuidGenerator, stateStore, stateValidator) commandSet[commands.DeleteLBsCommand] = commands.NewDeleteLBs( awsCredentialValidator, availabilityZoneRetriever, certificateManager, infrastructureManager, logger, cloudConfigurator, cloudConfigManager, boshClientProvider, stateStore, stateValidator, ) commandSet[commands.LBsCommand] = commands.NewLBs(awsCredentialValidator, stateValidator, infrastructureManager, os.Stdout) commandSet[commands.DirectorAddressCommand] = commands.NewStateQuery(logger, stateValidator, commands.DirectorAddressPropertyName, func(state storage.State) string { return state.BOSH.DirectorAddress }) commandSet[commands.DirectorUsernameCommand] = commands.NewStateQuery(logger, stateValidator, commands.DirectorUsernamePropertyName, func(state storage.State) string { return state.BOSH.DirectorUsername }) commandSet[commands.DirectorPasswordCommand] = commands.NewStateQuery(logger, stateValidator, commands.DirectorPasswordPropertyName, func(state storage.State) string { return state.BOSH.DirectorPassword }) commandSet[commands.DirectorCACertCommand] = commands.NewStateQuery(logger, stateValidator, commands.DirectorCACertPropertyName, func(state storage.State) string { return state.BOSH.DirectorSSLCA }) commandSet[commands.BOSHCACertCommand] = commands.NewStateQuery(logger, stateValidator, commands.BOSHCACertPropertyName, func(state storage.State) string { fmt.Fprintln(os.Stderr, "'bosh-ca-cert' has been deprecated and will be removed in future versions of bbl, please use 'director-ca-cert'") return state.BOSH.DirectorSSLCA }) commandSet[commands.SSHKeyCommand] = commands.NewStateQuery(logger, stateValidator, commands.SSHKeyPropertyName, func(state storage.State) string { return state.KeyPair.PrivateKey }) commandSet[commands.EnvIDCommand] = commands.NewStateQuery(logger, stateValidator, commands.EnvIDPropertyName, func(state storage.State) string { return state.EnvID }) app := application.New(commandSet, configuration, stateStore, usage) err = app.Run() if err != nil { fail(err) } } func fail(err error) { fmt.Fprintf(os.Stderr, "\n\n%s\n", err) os.Exit(1) } <file_sep>/aws/cloudformation/templates/bosh_eip_template_builder.go package templates type BOSHEIPTemplateBuilder struct{} func NewBOSHEIPTemplateBuilder() BOSHEIPTemplateBuilder { return BOSHEIPTemplateBuilder{} } func (t BOSHEIPTemplateBuilder) BOSHEIP() Template { return Template{ Resources: map[string]Resource{ "BOSHEIP": Resource{ DependsOn: "VPCGatewayAttachment", Type: "AWS::EC2::EIP", Properties: EIP{ Domain: "vpc", }, }, }, Outputs: map[string]Output{ "BOSHEIP": {Value: Ref{"BOSHEIP"}}, "BOSHURL": { Value: FnJoin{ Delimeter: "", Values: []interface{}{ "https://", Ref{"BOSHEIP"}, ":25555", }, }, }, }, } } <file_sep>/bosh/azs_generator_test.go package bosh_test import ( "github.com/cloudfoundry/bosh-bootloader/bosh" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("AZs Generator", func() { Describe("Generate", func() { It("returns cloud config AZs", func() { azsGenerator := bosh.NewAZsGenerator("us-east-1a", "us-east-1b", "us-east-1c") azs := azsGenerator.Generate() Expect(azs).To(ConsistOf( bosh.AZ{ Name: "z1", CloudProperties: bosh.AZCloudProperties{ AvailabilityZone: "us-east-1a", }, }, bosh.AZ{ Name: "z2", CloudProperties: bosh.AZCloudProperties{ AvailabilityZone: "us-east-1b", }, }, bosh.AZ{ Name: "z3", CloudProperties: bosh.AZCloudProperties{ AvailabilityZone: "us-east-1c", }, })) }) }) }) <file_sep>/commands/commands_usage_test.go package commands_test import ( "github.com/cloudfoundry/bosh-bootloader/commands" . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/extensions/table" . "github.com/onsi/gomega" ) var _ = Describe("Commands Usage", func() { Describe("Up", func() { Describe("Usage", func() { It("returns string describing usage", func() { upCmd := commands.Up{} usageText := upCmd.Usage() Expect(usageText).To(Equal(`Deploys BOSH director on AWS --aws-access-key-id AWS Access Key ID to use (Defaults to environment variable BBL_AWS_ACCESS_KEY_ID) --aws-secret-access-key AWS Secret Access Key to use (Defaults to environment variable BBL_AWS_SECRET_ACCESS_KEY) --aws-region AWS region to use (Defaults to environment variable BBL_AWS_REGION)`)) }) }) }) Describe("Create LBs", func() { Describe("Usage", func() { It("returns string describing usage", func() { command := commands.CreateLBs{} usageText := command.Usage() Expect(usageText).To(Equal(`Attaches load balancer(s) with a certificate, key, and optional chain --type Load balancer(s) type. Valid options: "concourse" or "cf" --cert Path to SSL certificate --key Path to SSL certificate key [--chain] Path to SSL certificate chain (optional) [--skip-if-exists] Skips creating load balancer(s) if it is already attached (optional)`)) }) }) }) Describe("Update LBs", func() { Describe("Usage", func() { It("returns string describing usage", func() { command := commands.UpdateLBs{} usageText := command.Usage() Expect(usageText).To(Equal(`Updates load balancer(s) with the supplied certificate, key, and optional chain --cert Path to SSL certificate --key Path to SSL certificate key [--chain] Path to SSL certificate chain (optional) [--skip-if-missing] Skips updating load balancer(s) if it is not attached (optional)`)) }) }) }) Describe("Delete LBs", func() { Describe("Usage", func() { It("returns string describing usage", func() { command := commands.DeleteLBs{} usageText := command.Usage() Expect(usageText).To(Equal(`Deletes load balancer(s) [--skip-if-missing] Skips deleting load balancer(s) if it is not attached (optional)`)) }) }) }) Describe("Destroy", func() { Describe("Usage", func() { It("returns string describing usage", func() { command := commands.Destroy{} usageText := command.Usage() Expect(usageText).To(Equal(`Tears down BOSH director infrastructure [--no-confirm] Do not ask for confirmation (optional) [--skip-if-missing] Gracefully exit if there is no state file (optional)`)) }) }) }) Describe("Usage", func() { Describe("Usage", func() { It("returns string describing usage", func() { command := commands.Usage{} usageText := command.Usage() Expect(usageText).To(Equal(`Prints helpful message for the given command`)) }) }) }) DescribeTable("command description", func(command commands.Command, expectedDescription string) { usageText := command.Usage() Expect(usageText).To(Equal(expectedDescription)) }, Entry("LBs", commands.LBs{}, "Prints attached load balancer(s)"), Entry("director-address", newStateQuery("director address"), "Prints BOSH director address"), Entry("director-password", newStateQuery("director password"), "Prints BOSH director password"), Entry("director-username", newStateQuery("director username"), "Prints BOSH director username"), Entry("director-ca-cert", newStateQuery("director ca cert"), "Prints BOSH director CA certificate"), Entry("bosh-ca-cert", newStateQuery("bosh ca cert"), "Prints BOSH director CA certificate"), Entry("env-id", newStateQuery("environment id"), "Prints environment ID"), Entry("ssh-key", newStateQuery("ssh key"), "Prints SSH private key"), Entry("version", commands.Version{}, "Prints version"), ) }) func newStateQuery(propertyName string) commands.StateQuery { return commands.NewStateQuery(nil, nil, propertyName, nil) } <file_sep>/boshinit/manifests/manifest_builder_test.go package manifests_test import ( "errors" "fmt" "io/ioutil" "gopkg.in/yaml.v2" "github.com/cloudfoundry/bosh-bootloader/boshinit/manifests" "github.com/cloudfoundry/bosh-bootloader/fakes" "github.com/cloudfoundry/bosh-bootloader/ssl" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/pivotal-cf-experimental/gomegamatchers" ) var _ = Describe("ManifestBuilder", func() { var ( logger *fakes.Logger sslKeyPairGenerator *fakes.SSLKeyPairGenerator stringGenerator *fakes.StringGenerator manifestBuilder manifests.ManifestBuilder manifestProperties manifests.ManifestProperties cloudProviderManifestBuilder manifests.CloudProviderManifestBuilder jobsManifestBuilder manifests.JobsManifestBuilder input manifests.ManifestBuilderInput ) BeforeEach(func() { logger = &fakes.Logger{} sslKeyPairGenerator = &fakes.SSLKeyPairGenerator{} stringGenerator = &fakes.StringGenerator{} cloudProviderManifestBuilder = manifests.NewCloudProviderManifestBuilder(stringGenerator) jobsManifestBuilder = manifests.NewJobsManifestBuilder(stringGenerator) input = manifests.ManifestBuilderInput{ BOSHURL: "some-bosh-url", BOSHSHA1: "some-bosh-sha1", BOSHAWSCPIURL: "some-bosh-aws-cpi-url", BOSHAWSCPISHA1: "some-bosh-aws-cpi-sha1", StemcellURL: "some-stemcell-url", StemcellSHA1: "some-stemcell-sha1", } manifestBuilder = manifests.NewManifestBuilder(input, logger, sslKeyPairGenerator, stringGenerator, cloudProviderManifestBuilder, jobsManifestBuilder) manifestProperties = manifests.ManifestProperties{ DirectorName: "bosh-name", DirectorUsername: "bosh-username", DirectorPassword: "<PASSWORD>", SubnetID: "subnet-12345", AvailabilityZone: "some-az", CACommonName: "BOSH Bootloader", ElasticIP: "192.168.3.11", AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", DefaultKeyName: "some-key-name", Region: "some-region", SecurityGroup: "some-security-group", } stringGenerator.GenerateCall.Stub = func(prefix string, length int) (string, error) { return fmt.Sprintf("%s%s", prefix, "some-random-string"), nil } }) Describe("Build", func() { It("builds the bosh-init manifest and updates the manifest properties", func() { sslKeyPairGenerator.GenerateCall.Returns.KeyPair = ssl.KeyPair{ CA: []byte(ca), Certificate: []byte(certificate), PrivateKey: []byte(privateKey), } manifest, manifestProperties, err := manifestBuilder.Build(manifestProperties) Expect(err).NotTo(HaveOccurred()) expectedAWSProperties := manifests.AWSProperties{ AccessKeyId: "some-access-key-id", SecretAccessKey: "some-secret-access-key", DefaultKeyName: "some-key-name", DefaultSecurityGroups: []string{"some-security-group"}, Region: "some-region", } Expect(manifest.Name).To(Equal("bosh")) Expect(manifest.Releases[0].Name).To(Equal("bosh")) Expect(manifest.ResourcePools[0].CloudProperties.AvailabilityZone).To(Equal("some-az")) Expect(manifest.DiskPools[0].Name).To(Equal("disks")) Expect(manifest.Networks[0].Subnets[0].CloudProperties.Subnet).To(Equal("subnet-12345")) Expect(manifest.Jobs[0].Networks[1].StaticIPs[0]).To(Equal("192.168.3.11")) Expect(manifest.Jobs[0].Properties.AWS).To(Equal(expectedAWSProperties)) Expect(manifest.Jobs[0].Properties.Director.Name).To(Equal("bosh-name")) Expect(manifest.Jobs[0].Properties.Director.SSL).To(Equal(manifests.SSLProperties{ Cert: certificate, Key: privateKey, })) Expect(manifest.CloudProvider.Properties.AWS).To(Equal(expectedAWSProperties)) Expect(manifest.CloudProvider.SSHTunnel.Host).To(Equal("192.168.3.11")) Expect(manifest.CloudProvider.MBus).To(Equal("https://mbus-user-some-random-string:mbus-some-random-string@192.168.3.11:6868")) Expect(sslKeyPairGenerator.GenerateCall.Receives.CACommonName).To(Equal("BOSH Bootloader")) Expect(sslKeyPairGenerator.GenerateCall.Receives.CertCommonName).To(Equal("192.168.3.11")) Expect(sslKeyPairGenerator.GenerateCall.CallCount).To(Equal(1)) Expect(manifestProperties).To(Equal( manifests.ManifestProperties{ DirectorName: "bosh-name", DirectorUsername: "bosh-username", DirectorPassword: "<PASSWORD>", SubnetID: "subnet-12345", AvailabilityZone: "some-az", CACommonName: "BOSH Bootloader", ElasticIP: "192.168.3.11", AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", DefaultKeyName: "some-key-name", Region: "some-region", SecurityGroup: "some-security-group", SSLKeyPair: ssl.KeyPair{ CA: []byte(ca), Certificate: []byte(certificate), PrivateKey: []byte(privateKey), }, Credentials: manifests.InternalCredentials{ MBusUsername: "mbus-user-some-random-string", NatsUsername: "nats-user-some-random-string", PostgresUsername: "postgres-user-some-random-string", RegistryUsername: "registry-user-some-random-string", BlobstoreDirectorUsername: "blobstore-director-user-some-random-string", BlobstoreAgentUsername: "blobstore-agent-user-some-random-string", HMUsername: "hm-user-some-random-string", MBusPassword: "<PASSWORD>", NatsPassword: "<PASSWORD>", PostgresPassword: "<PASSWORD>", RegistryPassword: "<PASSWORD>", BlobstoreDirectorPassword: "<PASSWORD>", BlobstoreAgentPassword: "<PASSWORD>", HMPassword: "<PASSWORD>", }, }, )) }) It("does not generate an ssl keypair if it exists", func() { manifestProperties.SSLKeyPair = ssl.KeyPair{ CA: []byte(ca), Certificate: []byte(certificate), PrivateKey: []byte(privateKey), } _, _, err := manifestBuilder.Build(manifestProperties) Expect(err).NotTo(HaveOccurred()) Expect(sslKeyPairGenerator.GenerateCall.CallCount).To(Equal(0)) }) It("logs that the bosh-init manifest is being generated", func() { _, _, err := manifestBuilder.Build(manifestProperties) Expect(err).NotTo(HaveOccurred()) Expect(logger.StepCall.Receives.Message).To(Equal("generating bosh-init manifest")) }) It("stores the randomly generated passwords into manifest properties", func() { _, manifestProperties, err := manifestBuilder.Build(manifestProperties) Expect(err).NotTo(HaveOccurred()) Expect(stringGenerator.GenerateCall.CallCount).To(Equal(14)) Expect(manifestProperties.Credentials).To(Equal(manifests.InternalCredentials{ MBusUsername: "mbus-user-some-random-string", NatsUsername: "nats-user-some-random-string", PostgresUsername: "postgres-user-some-random-string", RegistryUsername: "registry-user-some-random-string", BlobstoreDirectorUsername: "blobstore-director-user-some-random-string", BlobstoreAgentUsername: "blobstore-agent-user-some-random-string", HMUsername: "hm-user-some-random-string", MBusPassword: "<PASSWORD>", NatsPassword: "<PASSWORD>", PostgresPassword: "<PASSWORD>", RegistryPassword: "<PASSWORD>", BlobstoreDirectorPassword: "<PASSWORD>", BlobstoreAgentPassword: "<PASSWORD>", HMPassword: "<PASSWORD>", })) }) It("does not regenerate new random passwords if they already exist", func() { manifestProperties.Credentials = manifests.InternalCredentials{ MBusUsername: "mbus-user-some-persisted-string", NatsUsername: "nats-user-some-persisted-string", PostgresUsername: "postgres-user-some-persisted-string", RegistryUsername: "registry-user-some-persisted-string", BlobstoreDirectorUsername: "blobstore-director-user-some-persisted-string", BlobstoreAgentUsername: "blobstore-agent-user-some-persisted-string", HMUsername: "hm-user-some-persisted-string", MBusPassword: "<PASSWORD>", NatsPassword: "<PASSWORD>", PostgresPassword: "<PASSWORD>", RegistryPassword: "registry-some-persisted-string", BlobstoreDirectorPassword: "<PASSWORD>", BlobstoreAgentPassword: "<PASSWORD>", HMPassword: "<PASSWORD>", } _, manifestProperties, err := manifestBuilder.Build(manifestProperties) Expect(err).NotTo(HaveOccurred()) Expect(stringGenerator.GenerateCall.CallCount).To(Equal(0)) Expect(manifestProperties.Credentials).To(Equal(manifests.InternalCredentials{ MBusUsername: "mbus-user-some-persisted-string", NatsUsername: "nats-user-some-persisted-string", PostgresUsername: "postgres-user-some-persisted-string", RegistryUsername: "registry-user-some-persisted-string", BlobstoreDirectorUsername: "blobstore-director-user-some-persisted-string", BlobstoreAgentUsername: "blobstore-agent-user-some-persisted-string", HMUsername: "hm-user-some-persisted-string", MBusPassword: "<PASSWORD>", NatsPassword: "<PASSWORD>", PostgresPassword: "<PASSWORD>", RegistryPassword: "<PASSWORD>", BlobstoreDirectorPassword: "<PASSWORD>", BlobstoreAgentPassword: "<PASSWORD>", HMPassword: "<PASSWORD>", })) }) Context("failure cases", func() { It("returns an error when the ssl key pair cannot be generated", func() { sslKeyPairGenerator.GenerateCall.Returns.Error = errors.New("failed to generate key pair") _, _, err := manifestBuilder.Build(manifestProperties) Expect(err).To(MatchError("failed to generate key pair")) }) Context("failing cloud provider manifest builder", func() { BeforeEach(func() { fakeCloudProviderManifestBuilder := &fakes.CloudProviderManifestBuilder{} fakeCloudProviderManifestBuilder.BuildCall.Returns.Error = fmt.Errorf("something bad happened") manifestBuilder = manifests.NewManifestBuilder(input, logger, sslKeyPairGenerator, stringGenerator, fakeCloudProviderManifestBuilder, jobsManifestBuilder) manifestProperties = manifests.ManifestProperties{ DirectorUsername: "bosh-username", DirectorPassword: "<PASSWORD>", SubnetID: "subnet-12345", AvailabilityZone: "some-az", CACommonName: "BOSH Bootloader", ElasticIP: "192.168.3.11", AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", DefaultKeyName: "some-key-name", Region: "some-region", SecurityGroup: "some-security-group", } }) It("returns an error when it cannot build the cloud provider manifest", func() { _, _, err := manifestBuilder.Build(manifestProperties) Expect(err).To(HaveOccurred()) }) }) Context("failing jobs manifest builder", func() { BeforeEach(func() { fakeJobsManifestBuilder := &fakes.JobsManifestBuilder{} fakeJobsManifestBuilder.BuildCall.Returns.Error = fmt.Errorf("something bad happened") manifestBuilder = manifests.NewManifestBuilder(input, logger, sslKeyPairGenerator, stringGenerator, cloudProviderManifestBuilder, fakeJobsManifestBuilder) manifestProperties = manifests.ManifestProperties{ DirectorUsername: "bosh-username", DirectorPassword: "<PASSWORD>", SubnetID: "subnet-12345", AvailabilityZone: "some-az", CACommonName: "BOSH Bootloader", ElasticIP: "192.168.3.11", AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", DefaultKeyName: "some-key-name", Region: "some-region", SecurityGroup: "some-security-group", } }) It("returns an error when it cannot build the job manifest", func() { _, _, err := manifestBuilder.Build(manifestProperties) Expect(err).To(HaveOccurred()) }) }) }) }) Describe("template marshaling", func() { It("can be marshaled to YML", func() { sslKeyPairGenerator.GenerateCall.Returns.KeyPair = ssl.KeyPair{ CA: []byte(ca), Certificate: []byte(certificate), PrivateKey: []byte(privateKey), } manifest, _, err := manifestBuilder.Build(manifestProperties) Expect(err).NotTo(HaveOccurred()) buf, err := ioutil.ReadFile("fixtures/manifest.yml") Expect(err).NotTo(HaveOccurred()) output, err := yaml.Marshal(manifest) Expect(err).NotTo(HaveOccurred()) Expect(output).To(MatchYAML(string(buf))) }) }) }) <file_sep>/fakes/string_generator.go package fakes type StringGenerator struct { GenerateCall struct { Receives struct { Prefixes []string Lengths []int } Returns struct { String string Error error } Stub func(string, int) (string, error) CallCount int } } func (s *StringGenerator) Generate(prefix string, length int) (string, error) { defer func() { s.GenerateCall.CallCount++ }() s.GenerateCall.Receives.Lengths = append(s.GenerateCall.Receives.Lengths, length) s.GenerateCall.Receives.Prefixes = append(s.GenerateCall.Receives.Prefixes, prefix) if s.GenerateCall.Stub != nil { return s.GenerateCall.Stub(prefix, length) } return s.GenerateCall.Returns.String, s.GenerateCall.Returns.Error } <file_sep>/integration-test/concourse/manifest_manipulation_test.go package integration_test import "gopkg.in/yaml.v2" type concourseManifestInputs struct { boshDirectorUUID string webExternalURL string stemcellVersion string concourseReleaseVersion string gardenReleaseVersion string } type concourseManifest struct { Name string `yaml:"name"` DirectorUUID string `yaml:"director_uuid"` Releases []map[string]string `yaml:"releases"` Stemcells []map[string]string `yaml:"stemcells"` InstanceGroups []instanceGroup `yaml:"instance_groups"` Update map[string]interface{} `yaml:"update"` } type instanceGroup struct { Name string `yaml:"name"` Instances int `yaml:"instances"` VMType string `yaml:"vm_type"` VMExtensions []string `yaml:"vm_extensions,omitempty"` Stemcell string `yaml:"stemcell"` AZs []string `yaml:"azs"` Networks []map[string]string `yaml:"networks"` Jobs []job `yaml:"jobs"` PersistentDiskType string `yaml:"persistent_disk_type,omitempty"` } type properties struct { ExternalURL string `yaml:"external_url,omitempty"` BasicAuthUsername string `yaml:"basic_auth_username,omitempty"` BasicAuthPassword string `yaml:"basic_auth_password,omitempty"` PostgreSQLDatabase interface{} `yaml:"postgresql_database,omitempty"` Databases []*propertiesDatabase `yaml:"databases,omitempty"` Garden map[string]string `yaml:"garden,omitempty"` } type propertiesDatabase struct { Name string `yaml:"name"` Role string `yaml:"role"` Password string `yaml:"<PASSWORD>"` } type job struct { Name string `yaml:"name"` Release string `yaml:"release"` Properties properties `yaml:"properties"` } func populateManifest(baseManifest string, concourseManifestInputs concourseManifestInputs) (string, error) { var concourseManifest concourseManifest err := yaml.Unmarshal([]byte(baseManifest), &concourseManifest) if err != nil { return "", err } concourseManifest.DirectorUUID = concourseManifestInputs.boshDirectorUUID concourseManifest.Stemcells[0]["version"] = concourseManifestInputs.stemcellVersion for releaseIdx, release := range concourseManifest.Releases { switch release["name"] { case "concourse": concourseManifest.Releases[releaseIdx]["version"] = concourseManifestInputs.concourseReleaseVersion case "garden-runc": concourseManifest.Releases[releaseIdx]["version"] = concourseManifestInputs.gardenReleaseVersion } } for i, _ := range concourseManifest.InstanceGroups { concourseManifest.InstanceGroups[i].VMType = "m3.medium" switch concourseManifest.InstanceGroups[i].Name { case "web": concourseManifest.InstanceGroups[i].VMExtensions = []string{"lb"} concourseManifest.InstanceGroups[i].Jobs[0].Properties.BasicAuthUsername = "admin" concourseManifest.InstanceGroups[i].Jobs[0].Properties.BasicAuthPassword = "<PASSWORD>" concourseManifest.InstanceGroups[i].Jobs[0].Properties.ExternalURL = concourseManifestInputs.webExternalURL case "worker": concourseManifest.InstanceGroups[i].VMExtensions = []string{"50GB_ephemeral_disk"} case "db": concourseManifest.InstanceGroups[i].PersistentDiskType = "1GB" concourseManifest.InstanceGroups[i].Jobs[0].Properties.Databases[0].Role = "admin" concourseManifest.InstanceGroups[i].Jobs[0].Properties.Databases[0].Password = "<PASSWORD>" } } finalConcourseManifestYAML, err := yaml.Marshal(concourseManifest) if err != nil { return "", err } return string(finalConcourseManifestYAML), nil } <file_sep>/aws/cloudformation/templates/ssh_keypair_template_builder_test.go package templates_test import ( "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("SSHKeyPairTemplateBuilder", func() { var builder templates.SSHKeyPairTemplateBuilder BeforeEach(func() { builder = templates.NewSSHKeyPairTemplateBuilder() }) Describe("SSHKeyPairName", func() { It("returns a template containing the ssh keypair name", func() { ssh_keypair_name := builder.SSHKeyPairName("some-key-pair-name") Expect(ssh_keypair_name.Parameters).To(HaveLen(1)) Expect(ssh_keypair_name.Parameters).To(HaveKeyWithValue("SSHKeyPairName", templates.Parameter{ Type: "AWS::EC2::KeyPair::KeyName", Default: "some-key-pair-name", Description: "SSH KeyPair to use for instances", })) }) }) }) <file_sep>/aws/ec2/keypair_synchronizer.go package ec2 type keyPairManager interface { Sync(keypair KeyPair) (KeyPair, error) } type KeyPairSynchronizer struct { keyPairManager keyPairManager } func NewKeyPairSynchronizer(keyPairManager keyPairManager) KeyPairSynchronizer { return KeyPairSynchronizer{ keyPairManager: keyPairManager, } } func (s KeyPairSynchronizer) Sync(keyPair KeyPair) (KeyPair, error) { ec2KeyPair, err := s.keyPairManager.Sync(KeyPair{ Name: keyPair.Name, PrivateKey: keyPair.PrivateKey, PublicKey: keyPair.PublicKey, }) if err != nil { return KeyPair{}, err } return KeyPair{ Name: ec2KeyPair.Name, PrivateKey: string(ec2KeyPair.PrivateKey), PublicKey: string(ec2KeyPair.PublicKey), }, nil } <file_sep>/commands/delete_lbs_test.go package commands_test import ( "errors" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation" "github.com/cloudfoundry/bosh-bootloader/bosh" "github.com/cloudfoundry/bosh-bootloader/commands" "github.com/cloudfoundry/bosh-bootloader/fakes" "github.com/cloudfoundry/bosh-bootloader/storage" . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/extensions/table" . "github.com/onsi/gomega" ) var _ = Describe("Delete LBs", func() { var ( command commands.DeleteLBs awsCredentialValidator *fakes.AWSCredentialValidator availabilityZoneRetriever *fakes.AvailabilityZoneRetriever certificateManager *fakes.CertificateManager infrastructureManager *fakes.InfrastructureManager logger *fakes.Logger cloudConfigurator *fakes.BoshCloudConfigurator cloudConfigManager *fakes.CloudConfigManager boshClient *fakes.BOSHClient boshClientProvider *fakes.BOSHClientProvider stateStore *fakes.StateStore stateValidator *fakes.StateValidator incomingState storage.State ) BeforeEach(func() { awsCredentialValidator = &fakes.AWSCredentialValidator{} availabilityZoneRetriever = &fakes.AvailabilityZoneRetriever{} certificateManager = &fakes.CertificateManager{} infrastructureManager = &fakes.InfrastructureManager{} cloudConfigurator = &fakes.BoshCloudConfigurator{} cloudConfigManager = &fakes.CloudConfigManager{} boshClient = &fakes.BOSHClient{} boshClientProvider = &fakes.BOSHClientProvider{} stateStore = &fakes.StateStore{} stateValidator = &fakes.StateValidator{} boshClientProvider.ClientCall.Returns.Client = boshClient logger = &fakes.Logger{} incomingState = storage.State{ Stack: storage.Stack{ LBType: "concourse", CertificateName: "some-certificate", Name: "some-stack-name", }, BOSH: storage.BOSH{ DirectorAddress: "some-director-address", DirectorUsername: "some-director-username", DirectorPassword: "<PASSWORD>", }, AWS: storage.AWS{ Region: "some-region", }, KeyPair: storage.KeyPair{ Name: "some-keypair", }, EnvID: "some-env-id", } infrastructureManager.ExistsCall.Returns.Exists = true command = commands.NewDeleteLBs(awsCredentialValidator, availabilityZoneRetriever, certificateManager, infrastructureManager, logger, cloudConfigurator, cloudConfigManager, boshClientProvider, stateStore, stateValidator) }) Describe("Execute", func() { It("updates cloud config", func() { availabilityZoneRetriever.RetrieveCall.Returns.AZs = []string{"some-az"} infrastructureManager.DescribeCall.Returns.Stack = cloudformation.Stack{ Name: "some-stack-name", } cloudConfigurator.ConfigureCall.Returns.CloudConfigInput = bosh.CloudConfigInput{ AZs: []string{"some-az"}, LBs: []bosh.LoadBalancerExtension{ { Name: "some-lb", }, }, } err := command.Execute([]string{}, incomingState) Expect(err).NotTo(HaveOccurred()) Expect(boshClientProvider.ClientCall.Receives.DirectorAddress).To(Equal("some-director-address")) Expect(boshClientProvider.ClientCall.Receives.DirectorUsername).To(Equal("some-director-username")) Expect(boshClientProvider.ClientCall.Receives.DirectorPassword).To(Equal("<PASSWORD>")) Expect(infrastructureManager.DescribeCall.Receives.StackName).To(Equal("some-stack-name")) Expect(cloudConfigurator.ConfigureCall.Receives.Stack).To(Equal(cloudformation.Stack{ Name: "some-stack-name", })) Expect(cloudConfigManager.UpdateCall.Receives.CloudConfigInput).To(Equal(bosh.CloudConfigInput{ AZs: []string{"some-az"}, })) Expect(cloudConfigManager.UpdateCall.Receives.BOSHClient).To(Equal(boshClient)) }) It("delete lbs from cloudformation and deletes certificate", func() { availabilityZoneRetriever.RetrieveCall.Returns.AZs = []string{"a", "b", "c"} err := command.Execute([]string{}, incomingState) Expect(err).NotTo(HaveOccurred()) Expect(awsCredentialValidator.ValidateCall.CallCount).To(Equal(1)) Expect(availabilityZoneRetriever.RetrieveCall.Receives.Region).To(Equal("some-region")) Expect(infrastructureManager.UpdateCall.Receives.KeyPairName).To(Equal("some-keypair")) Expect(infrastructureManager.UpdateCall.Receives.NumberOfAvailabilityZones).To(Equal(3)) Expect(infrastructureManager.UpdateCall.Receives.StackName).To(Equal("some-stack-name")) Expect(infrastructureManager.UpdateCall.Receives.LBType).To(Equal("")) Expect(infrastructureManager.UpdateCall.Receives.LBCertificateARN).To(Equal("")) Expect(infrastructureManager.UpdateCall.Receives.EnvID).To(Equal("some-env-id")) Expect(certificateManager.DeleteCall.Receives.CertificateName).To(Equal("some-certificate")) Expect(logger.StepCall.Messages).To(ContainElement("deleting certificate")) }) It("checks if the bosh director exists", func() { err := command.Execute([]string{}, incomingState) Expect(err).NotTo(HaveOccurred()) Expect(boshClientProvider.ClientCall.Receives.DirectorAddress).To(Equal("some-director-address")) Expect(boshClientProvider.ClientCall.Receives.DirectorUsername).To(Equal("some-director-username")) Expect(boshClientProvider.ClientCall.Receives.DirectorPassword).To(Equal("<PASSWORD>")) Expect(boshClient.InfoCall.CallCount).To(Equal(1)) }) Context("if the user hasn't bbl'd up yet", func() { It("returns an error if the stack does not exist", func() { infrastructureManager.ExistsCall.Returns.Exists = false err := command.Execute([]string{}, storage.State{}) Expect(err).To(MatchError(commands.BBLNotFound)) }) It("returns an error if the bosh director does not exist", func() { boshClient.InfoCall.Returns.Error = errors.New("director not found") err := command.Execute([]string{}, incomingState) Expect(err).To(MatchError(commands.BBLNotFound)) }) }) It("returns an error if there is no lb", func() { err := command.Execute([]string{}, storage.State{ Stack: storage.Stack{ LBType: "none", }, }) Expect(err).To(MatchError(commands.LBNotFound)) }) Context("state management", func() { It("saves state with no lb type nor certificate", func() { err := command.Execute([]string{}, storage.State{ Stack: storage.Stack{ Name: "some-stack", LBType: "cf", CertificateName: "some-certificate", }, }) Expect(err).NotTo(HaveOccurred()) Expect(stateStore.SetCall.CallCount).To(Equal(1)) Expect(stateStore.SetCall.Receives.State).To(Equal(storage.State{ Stack: storage.Stack{ Name: "some-stack", LBType: "none", CertificateName: "", }, })) }) }) Context("when --skip-if-missing is provided", func() { It("no-ops when lb does not exist", func() { err := command.Execute([]string{ "--skip-if-missing", }, storage.State{}) Expect(err).NotTo(HaveOccurred()) Expect(infrastructureManager.UpdateCall.CallCount).To(Equal(0)) Expect(certificateManager.DeleteCall.CallCount).To(Equal(0)) Expect(logger.PrintlnCall.Receives.Message).To(Equal(`no lb type exists, skipping...`)) }) DescribeTable("deletes the lb if the lb exists", func(currentLBType string) { incomingState.Stack.LBType = currentLBType err := command.Execute([]string{ "--skip-if-missing", }, incomingState) Expect(err).NotTo(HaveOccurred()) Expect(infrastructureManager.UpdateCall.CallCount).To(Equal(1)) Expect(certificateManager.DeleteCall.CallCount).To(Equal(1)) }, Entry("when the current lb-type is 'cf'", "cf"), Entry("when the current lb-type is 'concourse'", "concourse"), ) }) Context("failure cases", func() { It("returns an error when an unknown flag is provided", func() { err := command.Execute([]string{"--unknown-flag"}, incomingState) Expect(err).To(MatchError("flag provided but not defined: -unknown-flag")) Expect(awsCredentialValidator.ValidateCall.CallCount).To(Equal(0)) }) It("returns an error when aws credential validator fails to validate", func() { awsCredentialValidator.ValidateCall.Returns.Error = errors.New("validate failed") err := command.Execute([]string{}, incomingState) Expect(err).To(MatchError("validate failed")) }) It("return an error when availability zone retriever fails to retrieve", func() { availabilityZoneRetriever.RetrieveCall.Returns.Error = errors.New("retrieve failed") err := command.Execute([]string{}, incomingState) Expect(err).To(MatchError("retrieve failed")) }) It("return an error when infrastructure manager fails to describe", func() { infrastructureManager.DescribeCall.Returns.Error = errors.New("describe failed") err := command.Execute([]string{}, incomingState) Expect(err).To(MatchError("describe failed")) }) It("return an error when cloud config manager fails to update", func() { cloudConfigManager.UpdateCall.Returns.Error = errors.New("update failed") err := command.Execute([]string{}, incomingState) Expect(err).To(MatchError("update failed")) }) It("return an error when infrastructure manager fails to update", func() { infrastructureManager.UpdateCall.Returns.Error = errors.New("update failed") err := command.Execute([]string{}, incomingState) Expect(err).To(MatchError("update failed")) }) It("return an error when certificate manager fails to delete", func() { certificateManager.DeleteCall.Returns.Error = errors.New("delete failed") err := command.Execute([]string{}, incomingState) Expect(err).To(MatchError("delete failed")) }) It("returns an error when the state fails to be saved", func() { stateStore.SetCall.Returns = []fakes.SetCallReturn{{errors.New("failed to save state")}} err := command.Execute([]string{}, incomingState) Expect(err).To(MatchError("failed to save state")) }) It("returns an error when state validator fails", func() { stateValidator.ValidateCall.Returns.Error = errors.New("state validator failed") err := command.Execute([]string{}, storage.State{}) Expect(stateValidator.ValidateCall.CallCount).To(Equal(1)) Expect(err).To(MatchError("state validator failed")) }) }) }) }) <file_sep>/fakes/state_store.go package fakes import "github.com/cloudfoundry/bosh-bootloader/storage" type StateStore struct { SetCall struct { CallCount int Receives struct { State storage.State } Returns []SetCallReturn } GetCall struct { CallCount int Receives struct { Dir string } Returns struct { State storage.State Error error } } } type SetCallReturn struct { Error error } func (s *StateStore) Set(state storage.State) error { s.SetCall.CallCount++ s.SetCall.Receives.State = state if len(s.SetCall.Returns) < s.SetCall.CallCount { s.SetCall.Returns = append(s.SetCall.Returns, SetCallReturn{}) } return s.SetCall.Returns[s.SetCall.CallCount-1].Error } <file_sep>/fakes/template_builder.go package fakes import "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" type TemplateBuilder struct { BuildCall struct { Receives struct { KeyPairName string NumberOfAZs int LBType string LBCertificateARN string IAMUserName string EnvID string } Returns struct { Template templates.Template } } } func (b *TemplateBuilder) Build(keyPairName string, numberOfAvailabilityZones int, lbType string, lbCertificateARN string, iamUserName string, envID string) templates.Template { b.BuildCall.Receives.KeyPairName = keyPairName b.BuildCall.Receives.NumberOfAZs = numberOfAvailabilityZones b.BuildCall.Receives.LBType = lbType b.BuildCall.Receives.LBCertificateARN = lbCertificateARN b.BuildCall.Receives.IAMUserName = iamUserName b.BuildCall.Receives.EnvID = envID return b.BuildCall.Returns.Template } <file_sep>/application/aws_credential_validator_test.go package application_test import ( "github.com/cloudfoundry/bosh-bootloader/application" "github.com/cloudfoundry/bosh-bootloader/storage" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("AWSCredentialValidator", func() { var awsCredentialValidator application.AWSCredentialValidator Describe("ValidateCredentials", func() { It("validates that the credentials have been set", func() { awsCredentialValidator = application.NewAWSCredentialValidator(application.Configuration{ State: storage.State{ AWS: storage.AWS{ AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", Region: "some-region", }, }, }) err := awsCredentialValidator.Validate() Expect(err).NotTo(HaveOccurred()) }) Context("failure cases", func() { It("returns an error when the access key id is missing", func() { awsCredentialValidator = application.NewAWSCredentialValidator(application.Configuration{ State: storage.State{ AWS: storage.AWS{ SecretAccessKey: "some-secret-access-key", Region: "some-region", }, }, }) Expect(awsCredentialValidator.Validate()).To(MatchError("AWS access key ID must be provided")) }) It("returns an error when the secret access key is missing", func() { awsCredentialValidator = application.NewAWSCredentialValidator(application.Configuration{ State: storage.State{ AWS: storage.AWS{ AccessKeyID: "some-access-key-id", Region: "some-region", }, }, }) Expect(awsCredentialValidator.Validate()).To(MatchError("AWS secret access key must be provided")) }) It("returns an error when the region is missing", func() { awsCredentialValidator = application.NewAWSCredentialValidator(application.Configuration{ State: storage.State{ AWS: storage.AWS{ AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", }, }, }) Expect(awsCredentialValidator.Validate()).To(MatchError("AWS region must be provided")) }) }) }) }) <file_sep>/aws/ec2/availability_zone_retriever.go package ec2 import ( "errors" goaws "github.com/aws/aws-sdk-go/aws" awsec2 "github.com/aws/aws-sdk-go/service/ec2" ) type AvailabilityZoneRetriever struct { ec2ClientProvider ec2ClientProvider } func NewAvailabilityZoneRetriever(ec2ClientProvider ec2ClientProvider) AvailabilityZoneRetriever { return AvailabilityZoneRetriever{ ec2ClientProvider: ec2ClientProvider, } } func (r AvailabilityZoneRetriever) Retrieve(region string) ([]string, error) { output, err := r.ec2ClientProvider.GetEC2Client().DescribeAvailabilityZones(&awsec2.DescribeAvailabilityZonesInput{ Filters: []*awsec2.Filter{{ Name: goaws.String("region-name"), Values: []*string{goaws.String(region)}, }}, }) if err != nil { return []string{}, err } azList := []string{} for _, az := range output.AvailabilityZones { if az == nil { return []string{}, errors.New("aws returned nil availability zone") } if az.ZoneName == nil { return []string{}, errors.New("aws returned availability zone with nil zone name") } azList = append(azList, *az.ZoneName) } return azList, nil } <file_sep>/bbl/init_test.go package main_test import ( "encoding/json" "io/ioutil" "os" "os/exec" "path/filepath" "strings" "time" "github.com/cloudfoundry/bosh-bootloader/storage" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/onsi/gomega/gexec" "testing" ) func TestBbl(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "bbl") } var ( pathToBBL string pathToBOSHInit string pathToFakeBOSHInit string ) var _ = BeforeSuite(func() { var err error pathToBBL, err = gexec.Build("github.com/cloudfoundry/bosh-bootloader/bbl") Expect(err).NotTo(HaveOccurred()) pathToFakeBOSHInit, err = gexec.Build("github.com/cloudfoundry/bosh-bootloader/bbl/fakeboshinit") Expect(err).NotTo(HaveOccurred()) pathToBOSHInit = filepath.Join(filepath.Dir(pathToFakeBOSHInit), "bosh-init") err = os.Rename(pathToFakeBOSHInit, pathToBOSHInit) Expect(err).NotTo(HaveOccurred()) os.Setenv("PATH", strings.Join([]string{filepath.Dir(pathToBOSHInit), os.Getenv("PATH")}, ":")) }) var _ = AfterSuite(func() { gexec.CleanupBuildArtifacts() }) func executeCommand(args []string, exitCode int) *gexec.Session { cmd := exec.Command(pathToBBL, args...) session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session, 10*time.Second).Should(gexec.Exit(exitCode)) return session } func writeStateJson(state storage.State, tempDirectory string) { buf, err := json.Marshal(state) Expect(err).NotTo(HaveOccurred()) ioutil.WriteFile(filepath.Join(tempDirectory, storage.StateFileName), buf, os.ModePerm) } func readStateJson(tempDirectory string) storage.State { buf, err := ioutil.ReadFile(filepath.Join(tempDirectory, storage.StateFileName)) Expect(err).NotTo(HaveOccurred()) var state storage.State err = json.Unmarshal(buf, &state) Expect(err).NotTo(HaveOccurred()) return state } <file_sep>/aws/iam/certificate_uploader_test.go package iam_test import ( "errors" "io/ioutil" "os" "github.com/aws/aws-sdk-go/aws" awsiam "github.com/aws/aws-sdk-go/service/iam" "github.com/cloudfoundry/bosh-bootloader/aws/iam" "github.com/cloudfoundry/bosh-bootloader/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("CertificateUploader", func() { var ( iamClient *fakes.IAMClient iamClientProvider *fakes.ClientProvider uploader iam.CertificateUploader certificateFile *os.File privateKeyFile *os.File chainFile *os.File ) BeforeEach(func() { var err error iamClient = &fakes.IAMClient{} iamClientProvider = &fakes.ClientProvider{} iamClientProvider.GetIAMClientCall.Returns.IAMClient = iamClient uploader = iam.NewCertificateUploader(iamClientProvider) certificateFile, err = ioutil.TempFile("", "") Expect(err).NotTo(HaveOccurred()) privateKeyFile, err = ioutil.TempFile("", "") Expect(err).NotTo(HaveOccurred()) chainFile, err = ioutil.TempFile("", "") Expect(err).NotTo(HaveOccurred()) }) Describe("Upload", func() { BeforeEach(func() { err := ioutil.WriteFile(certificateFile.Name(), []byte("some-certificate-body"), os.ModePerm) Expect(err).NotTo(HaveOccurred()) err = ioutil.WriteFile(privateKeyFile.Name(), []byte("some-private-key-body"), os.ModePerm) Expect(err).NotTo(HaveOccurred()) }) It("uploads a certificate and private key with the given name", func() { iamClient.UploadServerCertificateCall.Returns.Output = &awsiam.UploadServerCertificateOutput{ ServerCertificateMetadata: &awsiam.ServerCertificateMetadata{ Arn: aws.String("arn:aws:iam::some-arn:server-certificate/some-certificate"), Path: aws.String("/"), ServerCertificateId: aws.String("some-certificate-id"), ServerCertificateName: aws.String("test-certificate"), }, } err := uploader.Upload(certificateFile.Name(), privateKeyFile.Name(), "", "test-certificate") Expect(err).NotTo(HaveOccurred()) Expect(iamClient.UploadServerCertificateCall.Receives.Input).To(Equal( &awsiam.UploadServerCertificateInput{ CertificateBody: aws.String("some-certificate-body"), PrivateKey: aws.String("some-private-key-body"), ServerCertificateName: aws.String("test-certificate"), }, )) }) It("uploads a certificate with an optional chain", func() { err := ioutil.WriteFile(chainFile.Name(), []byte("some-chain-body"), os.ModePerm) Expect(err).NotTo(HaveOccurred()) iamClient.UploadServerCertificateCall.Returns.Output = &awsiam.UploadServerCertificateOutput{ ServerCertificateMetadata: &awsiam.ServerCertificateMetadata{ Arn: aws.String("arn:aws:iam::some-arn:server-certificate/some-certificate"), Path: aws.String("/"), ServerCertificateId: aws.String("some-certificate-id"), ServerCertificateName: aws.String("bbl-cert-abcd"), }, } err = uploader.Upload(certificateFile.Name(), privateKeyFile.Name(), chainFile.Name(), "bbl-cert-abcd") Expect(err).NotTo(HaveOccurred()) Expect(iamClient.UploadServerCertificateCall.Receives.Input).To(Equal( &awsiam.UploadServerCertificateInput{ CertificateBody: aws.String("some-certificate-body"), PrivateKey: aws.String("some-private-key-body"), CertificateChain: aws.String("some-chain-body"), ServerCertificateName: aws.String("bbl-cert-abcd"), }, )) }) It("logs uploading certificate", func() { err := uploader.Upload(certificateFile.Name(), privateKeyFile.Name(), chainFile.Name(), "") Expect(err).NotTo(HaveOccurred()) }) Context("failure cases", func() { It("returns an error when the certificate name contains invalid characters", func() { err := uploader.Upload(certificateFile.Name(), privateKeyFile.Name(), "", "some:invalid:name") Expect(err).To(MatchError(`"some:invalid:name" is an invalid certificate name, it must not contain ":"`)) }) It("returns an error when the certificate path does not exist", func() { err := uploader.Upload("/some/fake/path", privateKeyFile.Name(), "", "") Expect(err).To(MatchError(ContainSubstring("no such file or directory"))) }) It("returns an error when the private key path does not exist", func() { err := uploader.Upload(certificateFile.Name(), "/some/fake/path", "", "") Expect(err).To(MatchError(ContainSubstring("no such file or directory"))) }) It("returns an error when the chain path does not exist and was specified", func() { err := uploader.Upload(certificateFile.Name(), privateKeyFile.Name(), "/some/fake/chain/path", "") Expect(err).To(MatchError(ContainSubstring("no such file or directory"))) }) It("returns an error when the certificate fails to upload", func() { iamClient.UploadServerCertificateCall.Returns.Error = errors.New("failed to upload certificate") err := uploader.Upload(certificateFile.Name(), privateKeyFile.Name(), "", "") Expect(err).To(MatchError("failed to upload certificate")) }) }) }) }) <file_sep>/commands/command.go package commands import ( "fmt" "strings" "github.com/cloudfoundry/bosh-bootloader/bosh" "github.com/cloudfoundry/bosh-bootloader/storage" ) type Command interface { Execute(subcommandFlags []string, state storage.State) error Usage() string } func bblExists(stackName string, infrastructureManager infrastructureManager, boshClient bosh.Client) error { if stackExists, err := infrastructureManager.Exists(stackName); err != nil { return err } else if !stackExists { return BBLNotFound } if _, err := boshClient.Info(); err != nil { return BBLNotFound } return nil } func checkBBLAndLB(state storage.State, boshClientProvider boshClientProvider, infrastructureManager infrastructureManager) error { boshClient := boshClientProvider.Client(state.BOSH.DirectorAddress, state.BOSH.DirectorUsername, state.BOSH.DirectorPassword) if err := bblExists(state.Stack.Name, infrastructureManager, boshClient); err != nil { return err } if !lbExists(state.Stack.LBType) { return LBNotFound } return nil } func lbExists(lbType string) bool { return lbType == "concourse" || lbType == "cf" } func certificateNameFor(lbType string, generator guidGenerator, envid string) (string, error) { guid, err := generator.Generate() if err != nil { return "", err } var certificateName string if envid == "" { certificateName = fmt.Sprintf("%s-elb-cert-%s", lbType, guid) } else { certificateName = fmt.Sprintf("%s-elb-cert-%s-%s", lbType, guid, envid) } return strings.Replace(certificateName, ":", "-", -1), nil } <file_sep>/commands/destroy_test.go package commands_test import ( "bytes" "errors" "fmt" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation" "github.com/cloudfoundry/bosh-bootloader/boshinit" "github.com/cloudfoundry/bosh-bootloader/commands" "github.com/cloudfoundry/bosh-bootloader/fakes" "github.com/cloudfoundry/bosh-bootloader/storage" . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/extensions/table" . "github.com/onsi/gomega" ) var _ = Describe("Destroy", func() { var ( destroy commands.Destroy boshDeleter *fakes.BOSHDeleter stackManager *fakes.StackManager infrastructureManager *fakes.InfrastructureManager vpcStatusChecker *fakes.VPCStatusChecker stringGenerator *fakes.StringGenerator logger *fakes.Logger keyPairDeleter *fakes.KeyPairDeleter certificateDeleter *fakes.CertificateDeleter awsCredentialValidator *fakes.AWSCredentialValidator stateStore *fakes.StateStore stateValidator *fakes.StateValidator stdin *bytes.Buffer ) BeforeEach(func() { stdin = bytes.NewBuffer([]byte{}) logger = &fakes.Logger{} vpcStatusChecker = &fakes.VPCStatusChecker{} stackManager = &fakes.StackManager{} infrastructureManager = &fakes.InfrastructureManager{} boshDeleter = &fakes.BOSHDeleter{} keyPairDeleter = &fakes.KeyPairDeleter{} certificateDeleter = &fakes.CertificateDeleter{} stringGenerator = &fakes.StringGenerator{} awsCredentialValidator = &fakes.AWSCredentialValidator{} stateStore = &fakes.StateStore{} stateValidator = &fakes.StateValidator{} destroy = commands.NewDestroy(awsCredentialValidator, logger, stdin, boshDeleter, vpcStatusChecker, stackManager, stringGenerator, infrastructureManager, keyPairDeleter, certificateDeleter, stateStore, stateValidator) }) Describe("Execute", func() { It("returns when there is no state and --skip-if-missing flag is provided", func() { err := destroy.Execute([]string{"--skip-if-missing"}, storage.State{}) Expect(err).NotTo(HaveOccurred()) Expect(logger.StepCall.Receives.Message).To(Equal("state file not found, and —skip-if-missing flag provided, exiting")) }) It("returns an error when state validator fails", func() { stateValidator.ValidateCall.Returns.Error = errors.New("state validator failed") err := destroy.Execute([]string{}, storage.State{}) Expect(stateValidator.ValidateCall.CallCount).To(Equal(1)) Expect(err).To(MatchError("state validator failed")) }) It("returns an error when aws credential validator fails", func() { awsCredentialValidator.ValidateCall.Returns.Error = errors.New("aws credentials validator failed") err := destroy.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("aws credentials validator failed")) }) DescribeTable("prompting the user for confirmation", func(response string, proceed bool) { fmt.Fprintf(stdin, "%s\n", response) err := destroy.Execute([]string{}, storage.State{ BOSH: storage.BOSH{ DirectorName: "some-director", }, EnvID: "some-lake", }) Expect(err).NotTo(HaveOccurred()) Expect(logger.PromptCall.Receives.Message).To(Equal(`Are you sure you want to delete infrastructure for "some-lake"? This operation cannot be undone!`)) if proceed { Expect(logger.StepCall.Messages).To(ContainElement("destroying AWS stack")) Expect(boshDeleter.DeleteCall.CallCount).To(Equal(1)) } else { Expect(logger.StepCall.Receives.Message).To(Equal("exiting")) Expect(boshDeleter.DeleteCall.CallCount).To(Equal(0)) } }, Entry("responding with 'yes'", "yes", true), Entry("responding with 'y'", "y", true), Entry("responding with 'Yes'", "Yes", true), Entry("responding with 'Y'", "Y", true), Entry("responding with 'no'", "no", false), Entry("responding with 'n'", "n", false), Entry("responding with 'No'", "No", false), Entry("responding with 'N'", "N", false), ) Context("when the --no-confirm flag is supplied", func() { DescribeTable("destroys without prompting the user for confirmation", func(flag string) { err := destroy.Execute([]string{flag}, storage.State{ BOSH: storage.BOSH{ DirectorName: "some-director", }, }) Expect(err).NotTo(HaveOccurred()) Expect(logger.PromptCall.CallCount).To(Equal(0)) Expect(boshDeleter.DeleteCall.CallCount).To(Equal(1)) }, Entry("--no-confirm", "--no-confirm"), Entry("-n", "-n"), ) }) Describe("destroying the infrastructure", func() { var ( state storage.State ) BeforeEach(func() { stdin.Write([]byte("yes\n")) state = storage.State{ AWS: storage.AWS{ AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", Region: "some-aws-region", }, KeyPair: storage.KeyPair{ Name: "some-ec2-key-pair-name", PrivateKey: "some-private-key", PublicKey: "some-public-key", }, BOSH: storage.BOSH{ DirectorUsername: "some-director-username", DirectorPassword: "<PASSWORD>", State: map[string]interface{}{ "key": "value", }, Credentials: map[string]string{ "some-username": "some-<PASSWORD>", }, DirectorSSLCertificate: "some-certificate", DirectorSSLPrivateKey: "some-private-key", Manifest: "bosh-init-manifest", }, Stack: storage.Stack{ Name: "some-stack-name", LBType: "some-lb-type", CertificateName: "some-certificate-name", }, } }) It("fails fast if BOSH deployed VMs still exist in the VPC", func() { stackManager.DescribeCall.Returns.Stack = cloudformation.Stack{ Name: "some-stack-name", Status: "some-stack-status", Outputs: map[string]string{ "VPCID": "some-vpc-id", }, } vpcStatusChecker.ValidateSafeToDeleteCall.Returns.Error = errors.New("vpc some-vpc-id is not safe to delete") err := destroy.Execute([]string{}, state) Expect(err).To(MatchError("vpc some-vpc-id is not safe to delete")) Expect(vpcStatusChecker.ValidateSafeToDeleteCall.Receives.VPCID).To(Equal("some-vpc-id")) }) It("invokes bosh-init delete", func() { stackManager.DescribeCall.Returns.Stack = cloudformation.Stack{ Name: "some-stack-name", Status: "some-stack-status", Outputs: map[string]string{ "BOSHSubnet": "some-subnet-id", "BOSHSubnetAZ": "some-availability-zone", "BOSHEIP": "some-elastic-ip", "BOSHUserAccessKey": "some-access-key-id", "BOSHUserSecretAccessKey": "some-secret-access-key", "BOSHSecurityGroup": "some-security-group", }, } err := destroy.Execute([]string{}, state) Expect(err).NotTo(HaveOccurred()) Expect(stackManager.DescribeCall.Receives.StackName).To(Equal("some-stack-name")) Expect(boshDeleter.DeleteCall.Receives.BOSHInitManifest).To(Equal("bosh-init-manifest")) Expect(boshDeleter.DeleteCall.Receives.BOSHInitState).To(Equal(boshinit.State{"key": "value"})) Expect(boshDeleter.DeleteCall.Receives.EC2PrivateKey).To(Equal("some-private-key")) }) It("deletes the stack", func() { err := destroy.Execute([]string{}, state) Expect(err).NotTo(HaveOccurred()) Expect(infrastructureManager.DeleteCall.Receives.StackName).To(Equal("some-stack-name")) }) It("deletes the certificate", func() { err := destroy.Execute([]string{}, state) Expect(err).NotTo(HaveOccurred()) Expect(certificateDeleter.DeleteCall.Receives.CertificateName).To(Equal("some-certificate-name")) Expect(logger.StepCall.Messages).To(ContainElement("deleting certificate")) }) It("doesn't call delete certificate if there is no certificate to delete", func() { state.Stack.CertificateName = "" err := destroy.Execute([]string{}, state) Expect(err).NotTo(HaveOccurred()) Expect(certificateDeleter.DeleteCall.CallCount).To(Equal(0)) }) It("deletes the keypair", func() { err := destroy.Execute([]string{}, state) Expect(err).NotTo(HaveOccurred()) Expect(keyPairDeleter.DeleteCall.Receives.Name).To(Equal("some-ec2-key-pair-name")) }) It("clears the state", func() { err := destroy.Execute([]string{}, state) Expect(err).NotTo(HaveOccurred()) Expect(stateStore.SetCall.CallCount).To(Equal(4)) Expect(stateStore.SetCall.Receives.State).To(Equal(storage.State{})) }) Context("reentrance", func() { Context("when the stack fails to delete", func() { It("removes the bosh properties from state and returns an error", func() { infrastructureManager.DeleteCall.Returns.Error = errors.New("failed to delete stack") err := destroy.Execute([]string{}, state) Expect(err).To(MatchError("failed to delete stack")) Expect(stateStore.SetCall.CallCount).To(Equal(1)) Expect(stateStore.SetCall.Receives.State).To(Equal(storage.State{ AWS: storage.AWS{ AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", Region: "some-aws-region", }, KeyPair: storage.KeyPair{ Name: "some-ec2-key-pair-name", PrivateKey: "some-private-key", PublicKey: "some-public-key", }, BOSH: storage.BOSH{}, Stack: storage.Stack{ Name: "some-stack-name", LBType: "some-lb-type", CertificateName: "some-certificate-name", }, })) }) }) Context("when there is no bosh to delete", func() { It("does not attempt to delete the bosh", func() { state.BOSH = storage.BOSH{} err := destroy.Execute([]string{}, state) Expect(err).NotTo(HaveOccurred()) Expect(logger.PrintlnCall.Receives.Message).To(Equal("no BOSH director, skipping...")) Expect(boshDeleter.DeleteCall.CallCount).To(Equal(0)) }) }) Context("when the certificate fails to delete", func() { It("removes the stack from the state and returns an error", func() { certificateDeleter.DeleteCall.Returns.Error = errors.New("failed to delete certificate") err := destroy.Execute([]string{}, state) Expect(err).To(MatchError("failed to delete certificate")) Expect(stateStore.SetCall.CallCount).To(Equal(2)) Expect(stateStore.SetCall.Receives.State).To(Equal(storage.State{ AWS: storage.AWS{ AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", Region: "some-aws-region", }, KeyPair: storage.KeyPair{ Name: "some-ec2-key-pair-name", PrivateKey: "some-private-key", PublicKey: "some-public-key", }, BOSH: storage.BOSH{}, Stack: storage.Stack{ Name: "", LBType: "", CertificateName: "some-certificate-name", }, })) }) }) Context("when the keypair fails to delete", func() { It("removes the certificate from the state and returns an error", func() { keyPairDeleter.DeleteCall.Returns.Error = errors.New("failed to delete keypair") err := destroy.Execute([]string{}, state) Expect(err).To(MatchError("failed to delete keypair")) Expect(stateStore.SetCall.CallCount).To(Equal(3)) Expect(stateStore.SetCall.Receives.State).To(Equal(storage.State{ AWS: storage.AWS{ AccessKeyID: "some-access-key-id", SecretAccessKey: "some-secret-access-key", Region: "some-aws-region", }, KeyPair: storage.KeyPair{ Name: "some-ec2-key-pair-name", PrivateKey: "some-private-key", PublicKey: "some-public-key", }, BOSH: storage.BOSH{}, Stack: storage.Stack{ Name: "", LBType: "", CertificateName: "", }, })) }) }) Context("when there is no stack to delete", func() { BeforeEach(func() { stackManager.DescribeCall.Returns.Error = cloudformation.StackNotFound }) It("does not validate the vpc", func() { state.Stack = storage.Stack{} err := destroy.Execute([]string{}, state) Expect(err).NotTo(HaveOccurred()) Expect(vpcStatusChecker.ValidateSafeToDeleteCall.CallCount).To(Equal(0)) }) It("does not attempt to delete the stack", func() { state.Stack = storage.Stack{} err := destroy.Execute([]string{}, state) Expect(err).NotTo(HaveOccurred()) Expect(logger.PrintlnCall.Receives.Message).To(Equal("no AWS stack, skipping...")) Expect(infrastructureManager.DeleteCall.CallCount).To(Equal(0)) }) }) }) }) Context("failure cases", func() { BeforeEach(func() { stdin.Write([]byte("yes\n")) }) Context("when an invalid command line flag is supplied", func() { It("returns an error", func() { err := destroy.Execute([]string{"--invalid-flag"}, storage.State{}) Expect(err).To(MatchError("flag provided but not defined: -invalid-flag")) Expect(awsCredentialValidator.ValidateCall.CallCount).To(Equal(0)) }) }) Context("when the bosh delete fails", func() { It("returns an error", func() { boshDeleter.DeleteCall.Returns.Error = errors.New("BOSH Delete Failed") err := destroy.Execute([]string{}, storage.State{ BOSH: storage.BOSH{ DirectorName: "some-director", }, }) Expect(err).To(MatchError("BOSH Delete Failed")) }) }) Context("when the stack manager cannot describe the stack", func() { It("returns an error", func() { stackManager.DescribeCall.Returns.Error = errors.New("cannot describe stack") err := destroy.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("cannot describe stack")) }) }) Context("when failing to delete the stack", func() { It("returns an error", func() { infrastructureManager.DeleteCall.Returns.Error = errors.New("failed to delete stack") err := destroy.Execute([]string{}, storage.State{ Stack: storage.Stack{ Name: "some-stack-name", }, }) Expect(err).To(MatchError("failed to delete stack")) }) }) Context("when the keypair cannot be deleted", func() { It("returns an error", func() { keyPairDeleter.DeleteCall.Returns.Error = errors.New("failed to delete keypair") err := destroy.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("failed to delete keypair")) }) }) Context("when the certificate cannot be deleted", func() { It("returns an error", func() { certificateDeleter.DeleteCall.Returns.Error = errors.New("failed to delete certificate") err := destroy.Execute([]string{}, storage.State{ Stack: storage.Stack{ CertificateName: "some-certificate", }}) Expect(err).To(MatchError("failed to delete certificate")) }) }) Context("when state store fails to set the state before destroying infrastructure", func() { It("returns an error", func() { stateStore.SetCall.Returns = []fakes.SetCallReturn{{errors.New("failed to set state")}} err := destroy.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("failed to set state")) }) }) Context("when state store fails to set the state before destroying certificate", func() { It("returns an error", func() { stateStore.SetCall.Returns = []fakes.SetCallReturn{{}, {errors.New("failed to set state")}} err := destroy.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("failed to set state")) }) }) Context("when state store fails to set the state before destroying keypair", func() { It("returns an error", func() { stateStore.SetCall.Returns = []fakes.SetCallReturn{{}, {}, {errors.New("failed to set state")}} err := destroy.Execute([]string{}, storage.State{ Stack: storage.Stack{ CertificateName: "some-certificate-name", }, }) Expect(err).To(MatchError("failed to set state")) }) }) Context("when the state fails to be set", func() { It("return an error", func() { stateStore.SetCall.Returns = []fakes.SetCallReturn{{}, {}, {errors.New("failed to set state")}} err := destroy.Execute([]string{}, storage.State{}) Expect(err).To(MatchError("failed to set state")) }) }) }) }) }) <file_sep>/storage/state.go package storage import ( "encoding/json" "errors" "io" "os" "path/filepath" "reflect" ) const ( OS_READ_WRITE_MODE = os.FileMode(0644) StateFileName = "bbl-state.json" ) type logger interface { Println(message string) } var ( encode func(io.Writer, interface{}) error = encodeFile rename func(string, string) error = os.Rename ) type AWS struct { AccessKeyID string `json:"accessKeyId"` SecretAccessKey string `json:"secretAccessKey"` Region string `json:"region"` } type Stack struct { Name string `json:"name"` LBType string `json:"lbType"` CertificateName string `json:"certificateName"` } type State struct { Version int `json:"version"` AWS AWS `json:"aws"` KeyPair KeyPair `json:"keyPair,omitempty"` BOSH BOSH `json:"bosh,omitempty"` Stack Stack `json:"stack"` EnvID string `json:"envID"` } type Store struct { version int stateFile string } func NewStore(dir string) Store { return Store{ version: 1, stateFile: filepath.Join(dir, StateFileName), } } func (s Store) Set(state State) error { _, err := os.Stat(filepath.Dir(s.stateFile)) if err != nil { return err } if reflect.DeepEqual(state, State{}) { err := os.Remove(s.stateFile) if err != nil && !os.IsNotExist(err) { return err } return nil } file, err := os.OpenFile(s.stateFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, OS_READ_WRITE_MODE) if err != nil { return err } state.Version = s.version err = encode(file, state) if err != nil { return err } return nil } var GetStateLogger logger func GetState(dir string) (State, error) { state := State{} _, err := os.Stat(dir) if err != nil { return state, err } bothExist, err := stateAndBBLStateExist(dir) if err != nil { return state, err } if bothExist { return state, errors.New("Cannot proceed with state.json and bbl-state.json present. Please delete one of the files.") } err = renameStateToBBLState(dir) if err != nil { return state, err } file, err := os.Open(filepath.Join(dir, StateFileName)) if err != nil { if os.IsNotExist(err) { return state, nil } return state, err } err = json.NewDecoder(file).Decode(&state) if err != nil { return state, err } return state, nil } func renameStateToBBLState(dir string) error { stateFile := filepath.Join(dir, "state.json") _, err := os.Stat(stateFile) switch { case os.IsNotExist(err): return nil case err == nil: GetStateLogger.Println("renaming state.json to bbl-state.json") err := rename(stateFile, filepath.Join(dir, StateFileName)) if err != nil { return err } return nil default: return err } } func stateAndBBLStateExist(dir string) (bool, error) { stateFile := filepath.Join(dir, "state.json") _, err := os.Stat(stateFile) switch { case os.IsNotExist(err): return false, nil case err != nil: return false, err } bblStateFile := filepath.Join(dir, StateFileName) _, err = os.Stat(bblStateFile) switch { case os.IsNotExist(err): return false, nil case err != nil: return false, err } return true, nil } func encodeFile(w io.Writer, v interface{}) error { return json.NewEncoder(w).Encode(v) } <file_sep>/bosh/vm_types_generator_test.go package bosh_test import ( "github.com/cloudfoundry/bosh-bootloader/bosh" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("VMTypes Generator", func() { Describe("Generate", func() { It("returns cloud config VM Types", func() { vmTypesGenerator := bosh.NewVMTypesGenerator() vmTypes := vmTypesGenerator.Generate() ExpectToContainVMType(vmTypes, "m3.medium") ExpectToContainVMType(vmTypes, "m3.large") ExpectToContainVMType(vmTypes, "m3.xlarge") ExpectToContainVMType(vmTypes, "m3.2xlarge") ExpectToContainVMType(vmTypes, "m4.large") ExpectToContainVMType(vmTypes, "m4.xlarge") ExpectToContainVMType(vmTypes, "m4.2xlarge") ExpectToContainVMType(vmTypes, "m4.4xlarge") ExpectToContainVMType(vmTypes, "m4.10xlarge") ExpectToContainVMType(vmTypes, "c3.large") ExpectToContainVMType(vmTypes, "c3.xlarge") ExpectToContainVMType(vmTypes, "c3.2xlarge") ExpectToContainVMType(vmTypes, "c3.4xlarge") ExpectToContainVMType(vmTypes, "c3.8xlarge") ExpectToContainVMType(vmTypes, "c4.large") ExpectToContainVMType(vmTypes, "c4.xlarge") ExpectToContainVMType(vmTypes, "c4.2xlarge") ExpectToContainVMType(vmTypes, "c4.4xlarge") ExpectToContainVMType(vmTypes, "c4.8xlarge") ExpectToContainVMType(vmTypes, "r3.large") ExpectToContainVMType(vmTypes, "r3.xlarge") ExpectToContainVMType(vmTypes, "r3.2xlarge") ExpectToContainVMType(vmTypes, "r3.4xlarge") ExpectToContainVMType(vmTypes, "r3.8xlarge") ExpectToContainVMType(vmTypes, "t2.nano") ExpectToContainVMType(vmTypes, "t2.micro") ExpectToContainVMType(vmTypes, "t2.small") ExpectToContainVMType(vmTypes, "t2.medium") ExpectToContainVMType(vmTypes, "t2.large") }) }) }) func ExpectToContainVMType(vmTypes []bosh.VMType, vmType string) { Expect(vmTypes).To(ContainElement( bosh.VMType{ Name: vmType, CloudProperties: &bosh.VMTypeCloudProperties{ InstanceType: vmType, EphemeralDisk: &bosh.EphemeralDisk{ Size: 1024, Type: "gp2", }, }, })) } <file_sep>/bbl/awsbackend/keypairs.go package awsbackend import ( "sync" "github.com/rosenhouse/awsfaker" ) type KeyPair struct { Name string PrivateKey string } type KeyPairs struct { mutex sync.Mutex store map[string]KeyPair createKeyPair struct { returns struct { err *awsfaker.ErrorResponse } } deleteKeyPair struct { returns struct { err *awsfaker.ErrorResponse } } } func NewKeyPairs() *KeyPairs { return &KeyPairs{ store: make(map[string]KeyPair), } } func (k *KeyPairs) Set(keyPair KeyPair) { k.mutex.Lock() defer k.mutex.Unlock() k.store[keyPair.Name] = keyPair } func (k *KeyPairs) Get(name string) (KeyPair, bool) { k.mutex.Lock() defer k.mutex.Unlock() keyPair, ok := k.store[name] return keyPair, ok } func (k *KeyPairs) Delete(name string) { k.mutex.Lock() defer k.mutex.Unlock() delete(k.store, name) } func (k *KeyPairs) All() []KeyPair { var keyPairs []KeyPair for _, keyPair := range k.store { keyPairs = append(keyPairs, keyPair) } return keyPairs } func (k *KeyPairs) SetCreateKeyPairReturnError(err *awsfaker.ErrorResponse) { k.mutex.Lock() defer k.mutex.Unlock() k.createKeyPair.returns.err = err } func (k *KeyPairs) CreateKeyPairReturnError() *awsfaker.ErrorResponse { return k.createKeyPair.returns.err } func (k *KeyPairs) SetDeleteKeyPairReturnError(err *awsfaker.ErrorResponse) { k.mutex.Lock() defer k.mutex.Unlock() k.deleteKeyPair.returns.err = err } func (k *KeyPairs) DeleteKeyPairReturnError() *awsfaker.ErrorResponse { return k.deleteKeyPair.returns.err } <file_sep>/boshinit/command_runner_test.go package boshinit_test import ( "errors" "io/ioutil" "os" "path/filepath" "github.com/cloudfoundry/bosh-bootloader/boshinit" "github.com/cloudfoundry/bosh-bootloader/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("CommandRunner", func() { Describe("Execute", func() { var ( tempDir string executable *fakes.Executable runner boshinit.CommandRunner ) BeforeEach(func() { var err error tempDir, err = ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) executable = &fakes.Executable{} executable.RunCall.Stub = func() error { return ioutil.WriteFile(filepath.Join(tempDir, "bosh-state.json"), []byte(`{"key": "value"}`), os.ModePerm) } runner = boshinit.NewCommandRunner(tempDir, executable) }) It("writes out the bosh.yml file to a temporary directory", func() { _, err := runner.Execute([]byte("some-manifest-yaml"), "some-private-key", boshinit.State{}) Expect(err).NotTo(HaveOccurred()) manifest, err := ioutil.ReadFile(filepath.Join(tempDir, "bosh.yml")) Expect(err).NotTo(HaveOccurred()) Expect(manifest).To(ContainSubstring("some-manifest-yaml")) fileInfo, err := os.Stat(filepath.Join(tempDir, "bosh.yml")) Expect(err).NotTo(HaveOccurred()) Expect(fileInfo.Mode()).To(Equal(os.FileMode(0644))) }) It("writes out the private key", func() { _, err := runner.Execute([]byte("some-manifest-yaml"), "some-private-key", boshinit.State{}) Expect(err).NotTo(HaveOccurred()) manifest, err := ioutil.ReadFile(filepath.Join(tempDir, "bosh.pem")) Expect(err).NotTo(HaveOccurred()) Expect(manifest).To(ContainSubstring("some-private-key")) fileInfo, err := os.Stat(filepath.Join(tempDir, "bosh.pem")) Expect(err).NotTo(HaveOccurred()) Expect(fileInfo.Mode()).To(Equal(os.FileMode(0644))) }) It("runs the executable", func() { _, err := runner.Execute([]byte("some-manifest-yaml"), "some-private-key", boshinit.State{}) Expect(err).NotTo(HaveOccurred()) Expect(executable.RunCall.CallCount).To(Equal(1)) }) Context("when the bosh-state.json file exists", func() { It("returns a bosh state object", func() { state, err := runner.Execute([]byte("some-manifest-yaml"), "some-private-key", boshinit.State{}) Expect(err).NotTo(HaveOccurred()) Expect(state).To(Equal(boshinit.State{ "key": "value", })) }) }) Context("when the bosh-state.json file does not exist", func() { It("returns an empty bosh state object", func() { executable.RunCall.Stub = func() error { return os.Remove(filepath.Join(tempDir, "bosh-state.json")) } state, err := runner.Execute([]byte("some-manifest-yaml"), "some-private-key", boshinit.State{}) Expect(err).NotTo(HaveOccurred()) Expect(state).To(Equal(boshinit.State{})) }) }) It("receives a bosh state object and writes the bosh-state.json file", func() { executable.RunCall.Stub = nil _, err := runner.Execute([]byte("some-manifest-yaml"), "some-private-key", boshinit.State{ "original_key": "original_value", }) Expect(err).NotTo(HaveOccurred()) file, err := ioutil.ReadFile(filepath.Join(tempDir, "bosh-state.json")) Expect(err).NotTo(HaveOccurred()) Expect(file).To(MatchJSON(`{ "original_key": "original_value" }`)) fileInfo, err := os.Stat(filepath.Join(tempDir, "bosh-state.json")) Expect(err).NotTo(HaveOccurred()) Expect(fileInfo.Mode()).To(Equal(os.FileMode(0644))) }) Context("failure cases", func() { Context("when the bosh-init state cannot be marshaled", func() { It("returns an error", func() { _, err := runner.Execute([]byte("some-manifest-yaml"), "some-private-key", boshinit.State{ "key": func() {}, }) Expect(err).To(MatchError(ContainSubstring("unsupported type: func()"))) }) }) Context("when the bosh-state.json file cannot be written", func() { It("returns an error", func() { err := ioutil.WriteFile(filepath.Join(tempDir, "bosh-state.json"), []byte(""), os.ModePerm) Expect(err).NotTo(HaveOccurred()) err = os.Chmod(filepath.Join(tempDir, "bosh-state.json"), os.FileMode(0000)) Expect(err).NotTo(HaveOccurred()) _, err = runner.Execute([]byte("some-manifest-yaml"), "some-private-key", boshinit.State{}) Expect(err).To(MatchError(ContainSubstring("permission denied"))) }) }) Context("when the bosh.yml file write fails", func() { It("returns an error", func() { err := ioutil.WriteFile(filepath.Join(tempDir, "bosh.yml"), []byte(""), os.ModePerm) Expect(err).NotTo(HaveOccurred()) err = os.Chmod(filepath.Join(tempDir, "bosh.yml"), os.FileMode(0000)) Expect(err).NotTo(HaveOccurred()) _, err = runner.Execute([]byte("some-manifest-yaml"), "some-private-key", boshinit.State{}) Expect(err).To(MatchError(ContainSubstring("permission denied"))) }) }) Context("when the bosh.pem file write fails", func() { It("returns an error", func() { err := ioutil.WriteFile(filepath.Join(tempDir, "bosh.pem"), []byte(""), os.ModePerm) Expect(err).NotTo(HaveOccurred()) err = os.Chmod(filepath.Join(tempDir, "bosh.pem"), os.FileMode(0000)) Expect(err).NotTo(HaveOccurred()) _, err = runner.Execute([]byte("some-manifest-yaml"), "some-private-key", boshinit.State{}) Expect(err).To(MatchError(ContainSubstring("permission denied"))) }) }) Context("when the command fails to run", func() { It("returns an error", func() { executable.RunCall.Stub = nil executable.RunCall.Returns.Error = errors.New("failed to run") _, err := runner.Execute([]byte("some-manifest-yaml"), "some-private-key", boshinit.State{}) Expect(err).To(MatchError("failed to run")) }) }) Context("when bosh-state.json cannot be read", func() { It("returns an error", func() { executable.RunCall.Stub = func() error { err := ioutil.WriteFile(filepath.Join(tempDir, "bosh-state.json"), []byte(`{"key": "value"}`), os.ModePerm) if err != nil { return err } return os.Chmod(filepath.Join(tempDir, "bosh-state.json"), 0000) } _, err := runner.Execute([]byte("some-manifest-yaml"), "some-private-key", boshinit.State{}) Expect(err).To(MatchError(ContainSubstring("permission denied"))) }) }) Context("when bosh-state.json cannot be unmarshalled", func() { It("returns an error", func() { executable.RunCall.Stub = func() error { return ioutil.WriteFile(filepath.Join(tempDir, "bosh-state.json"), []byte("%%%%%"), os.ModePerm) } _, err := runner.Execute([]byte("some-manifest-yaml"), "some-private-key", boshinit.State{}) Expect(err).To(MatchError(ContainSubstring("invalid character"))) }) }) }) }) }) <file_sep>/aws/cloudformation/stack_manager.go package cloudformation import ( "encoding/json" "errors" "fmt" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/cloudformation" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation/templates" ) var StackNotFound error = errors.New("stack not found") type logger interface { Step(message string, a ...interface{}) Dot() } type cloudFormationClientProvider interface { GetCloudFormationClient() Client } type StackManager struct { cloudFormationClientProvider cloudFormationClientProvider logger logger } func NewStackManager(cloudFormationClientProvider cloudFormationClientProvider, logger logger) StackManager { return StackManager{ cloudFormationClientProvider: cloudFormationClientProvider, logger: logger, } } func (s StackManager) CreateOrUpdate(name string, template templates.Template, tags Tags) error { s.logger.Step("checking if cloudformation stack %q exists", name) _, err := s.Describe(name) switch err { case StackNotFound: return s.create(name, template, tags) case nil: return s.Update(name, template, tags) default: return err } } func (s StackManager) cloudFormationClient() Client { return s.cloudFormationClientProvider.GetCloudFormationClient() } func (s StackManager) Describe(name string) (Stack, error) { if name == "" { return Stack{}, StackNotFound } output, err := s.cloudFormationClient().DescribeStacks(&cloudformation.DescribeStacksInput{ StackName: aws.String(name), }) if err != nil { switch err.(type) { case awserr.RequestFailure: requestFailure := err.(awserr.RequestFailure) if requestFailure.StatusCode() == 400 && requestFailure.Code() == "ValidationError" && requestFailure.Message() == fmt.Sprintf("Stack with id %s does not exist", name) { return Stack{}, StackNotFound } return Stack{}, err default: return Stack{}, err } } for _, s := range output.Stacks { if s.StackName != nil && *s.StackName == name { status := "UNKNOWN" if s.StackStatus != nil { status = *s.StackStatus } stack := Stack{ Name: *s.StackName, Status: status, Outputs: map[string]string{}, } for _, output := range s.Outputs { if output.OutputKey == nil { return Stack{}, errors.New("failed to parse outputs") } value := "" if output.OutputValue != nil { value = *output.OutputValue } stack.Outputs[*output.OutputKey] = value } return stack, nil } } return Stack{}, StackNotFound } func (s StackManager) WaitForCompletion(name string, sleepInterval time.Duration, action string) error { stack, err := s.Describe(name) if err != nil { if err == StackNotFound { s.logger.Step(fmt.Sprintf("finished %s", action)) return nil } return err } switch stack.Status { case cloudformation.StackStatusCreateComplete, cloudformation.StackStatusUpdateComplete, cloudformation.StackStatusDeleteComplete: s.logger.Step(fmt.Sprintf("finished %s", action)) return nil case cloudformation.StackStatusCreateFailed, cloudformation.StackStatusRollbackComplete, cloudformation.StackStatusRollbackFailed, cloudformation.StackStatusUpdateRollbackComplete, cloudformation.StackStatusUpdateRollbackFailed, cloudformation.StackStatusDeleteFailed: return fmt.Errorf(`CloudFormation failure on stack '%s'. Check the AWS console for error events related to this stack, and/or open a GitHub issue at https://github.com/cloudfoundry/bosh-bootloader/issues.`, name) default: s.logger.Dot() time.Sleep(sleepInterval) return s.WaitForCompletion(name, sleepInterval, action) } return nil } func (s StackManager) Delete(name string) error { s.logger.Step("deleting cloudformation stack") _, err := s.cloudFormationClient().DeleteStack(&cloudformation.DeleteStackInput{ StackName: &name, }) if err != nil { return err } return nil } func (s StackManager) create(name string, template templates.Template, tags Tags) error { s.logger.Step("creating cloudformation stack") templateJson, err := json.Marshal(&template) if err != nil { return err } awsTags := tags.toAWSTags() params := &cloudformation.CreateStackInput{ StackName: aws.String(name), Capabilities: []*string{aws.String("CAPABILITY_IAM"), aws.String("CAPABILITY_NAMED_IAM")}, TemplateBody: aws.String(string(templateJson)), Tags: awsTags, } _, err = s.cloudFormationClient().CreateStack(params) if err != nil { return err } return nil } func (s StackManager) Update(name string, template templates.Template, tags Tags) error { s.logger.Step("updating cloudformation stack") templateJson, err := json.Marshal(&template) if err != nil { return err } awsTags := tags.toAWSTags() params := &cloudformation.UpdateStackInput{ StackName: aws.String(name), Capabilities: []*string{aws.String("CAPABILITY_IAM"), aws.String("CAPABILITY_NAMED_IAM")}, TemplateBody: aws.String(string(templateJson)), Tags: awsTags, } _, err = s.cloudFormationClient().UpdateStack(params) if err != nil { switch err.(type) { case awserr.RequestFailure: requestFailure := err.(awserr.RequestFailure) if requestFailure.StatusCode() == 400 && requestFailure.Code() == "ValidationError" { switch requestFailure.Message() { case "No updates are to be performed.": return nil case fmt.Sprintf("Stack [%s] does not exist", name): return StackNotFound default: } } return err default: return err } } return nil } func (s StackManager) GetPhysicalIDForResource(stackName string, logicalResourceID string) (string, error) { describeStackResourceOutput, err := s.cloudFormationClient().DescribeStackResource(&cloudformation.DescribeStackResourceInput{ StackName: aws.String(stackName), LogicalResourceId: aws.String(logicalResourceID), }) if err != nil { return "", err } return aws.StringValue(describeStackResourceOutput.StackResourceDetail.PhysicalResourceId), nil } <file_sep>/aws/cloudformation/templates/vpc_template_builder.go package templates import "fmt" type VPCTemplateBuilder struct{} func NewVPCTemplateBuilder() VPCTemplateBuilder { return VPCTemplateBuilder{} } func (t VPCTemplateBuilder) VPC(envID string) Template { return Template{ Parameters: map[string]Parameter{ "VPCCIDR": Parameter{ Description: "CIDR block for the VPC.", Type: "String", Default: "10.0.0.0/16", }, }, Resources: map[string]Resource{ "VPC": Resource{ Type: "AWS::EC2::VPC", Properties: VPC{ CidrBlock: Ref{"VPCCIDR"}, Tags: []Tag{ { Value: fmt.Sprintf("vpc-%s", envID), Key: "Name", }, }, }, }, "VPCGatewayInternetGateway": Resource{ Type: "AWS::EC2::InternetGateway", }, "VPCGatewayAttachment": Resource{ Type: "AWS::EC2::VPCGatewayAttachment", Properties: VPCGatewayAttachment{ VpcId: Ref{"VPC"}, InternetGatewayId: Ref{"VPCGatewayInternetGateway"}, }, }, }, Outputs: map[string]Output{ "VPCID": Output{ Value: Ref{ Ref: "VPC", }, }, }, } } <file_sep>/bosh/compilation_generator_test.go package bosh_test import ( "github.com/cloudfoundry/bosh-bootloader/bosh" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("CompilationGenerator", func() { Describe("Generate", func() { It("returns a slice of disk types for cloud config", func() { generator := bosh.NewCompilationGenerator() compilation := generator.Generate() Expect(compilation).To(Equal( &bosh.Compilation{ Workers: 6, Network: "private", AZ: "z1", ReuseCompilationVMs: true, VMType: "c3.large", VMExtensions: []string{ "100GB_ephemeral_disk", }, }, )) }) }) }) <file_sep>/boshinit/manifests/manifest_builder.go package manifests import "github.com/cloudfoundry/bosh-bootloader/ssl" type logger interface { Step(message string, a ...interface{}) Println(string) } type sslKeyPairGenerator interface { Generate(caCommonName, commonName string) (ssl.KeyPair, error) } type stringGenerator interface { Generate(string, int) (string, error) } type cloudProviderManifestBuilder interface { Build(ManifestProperties) (CloudProvider, ManifestProperties, error) } type jobsManifestBuilder interface { Build(ManifestProperties) ([]Job, ManifestProperties, error) } type ManifestProperties struct { DirectorName string DirectorUsername string DirectorPassword string SubnetID string AvailabilityZone string CACommonName string ElasticIP string AccessKeyID string SecretAccessKey string DefaultKeyName string Region string SecurityGroup string SSLKeyPair ssl.KeyPair Credentials InternalCredentials } type ManifestBuilder struct { input ManifestBuilderInput logger logger sslKeyPairGenerator sslKeyPairGenerator stringGenerator stringGenerator cloudProviderManifestBuilder cloudProviderManifestBuilder jobsManifestBuilder jobsManifestBuilder } type ManifestBuilderInput struct { BOSHURL string BOSHSHA1 string BOSHAWSCPIURL string BOSHAWSCPISHA1 string StemcellURL string StemcellSHA1 string } func NewManifestBuilder(input ManifestBuilderInput, logger logger, sslKeyPairGenerator sslKeyPairGenerator, stringGenerator stringGenerator, cloudProviderManifestBuilder cloudProviderManifestBuilder, jobsManifestBuilder jobsManifestBuilder) ManifestBuilder { return ManifestBuilder{ input: input, logger: logger, sslKeyPairGenerator: sslKeyPairGenerator, stringGenerator: stringGenerator, cloudProviderManifestBuilder: cloudProviderManifestBuilder, jobsManifestBuilder: jobsManifestBuilder, } } func (m ManifestBuilder) Build(manifestProperties ManifestProperties) (Manifest, ManifestProperties, error) { m.logger.Step("generating bosh-init manifest") releaseManifestBuilder := NewReleaseManifestBuilder() resourcePoolsManifestBuilder := NewResourcePoolsManifestBuilder() diskPoolsManifestBuilder := NewDiskPoolsManifestBuilder() networksManifestBuilder := NewNetworksManifestBuilder() if !manifestProperties.SSLKeyPair.IsValidForIP(manifestProperties.ElasticIP) { keyPair, err := m.sslKeyPairGenerator.Generate(manifestProperties.CACommonName, manifestProperties.ElasticIP) if err != nil { return Manifest{}, ManifestProperties{}, err } manifestProperties.SSLKeyPair = keyPair } cloudProvider, manifestProperties, err := m.cloudProviderManifestBuilder.Build(manifestProperties) if err != nil { return Manifest{}, ManifestProperties{}, err } jobs, manifestProperties, err := m.jobsManifestBuilder.Build(manifestProperties) if err != nil { return Manifest{}, ManifestProperties{}, err } return Manifest{ Name: "bosh", Releases: releaseManifestBuilder.Build(m.input.BOSHURL, m.input.BOSHSHA1, m.input.BOSHAWSCPIURL, m.input.BOSHAWSCPISHA1), ResourcePools: resourcePoolsManifestBuilder.Build(manifestProperties, m.input.StemcellURL, m.input.StemcellSHA1), DiskPools: diskPoolsManifestBuilder.Build(), Networks: networksManifestBuilder.Build(manifestProperties), Jobs: jobs, CloudProvider: cloudProvider, }, manifestProperties, nil } <file_sep>/fakes/certificate_manager.go package fakes import "github.com/cloudfoundry/bosh-bootloader/aws/iam" type CertificateManager struct { CreateCall struct { CallCount int Receives struct { Certificate string PrivateKey string Chain string CertificateName string } Returns struct { Error error } } DeleteCall struct { CallCount int Receives struct { CertificateName string } Returns struct { Error error } } DescribeCall struct { CallCount int Stub func(string) (iam.Certificate, error) Receives struct { CertificateName string } Returns struct { Certificate iam.Certificate Error error } } } func (c *CertificateManager) Create(certificate, privatekey, chain, certificateName string) error { c.CreateCall.CallCount++ c.CreateCall.Receives.Certificate = certificate c.CreateCall.Receives.PrivateKey = privatekey c.CreateCall.Receives.Chain = chain c.CreateCall.Receives.CertificateName = certificateName return c.CreateCall.Returns.Error } func (c *CertificateManager) Delete(certificateName string) error { c.DeleteCall.CallCount++ c.DeleteCall.Receives.CertificateName = certificateName return c.DeleteCall.Returns.Error } func (c *CertificateManager) Describe(certificateName string) (iam.Certificate, error) { c.DescribeCall.CallCount++ c.DescribeCall.Receives.CertificateName = certificateName if c.DescribeCall.Stub != nil { return c.DescribeCall.Stub(certificateName) } return c.DescribeCall.Returns.Certificate, c.DescribeCall.Returns.Error } <file_sep>/integration-test/config_test.go package integration_test import ( "errors" "io/ioutil" "os" "path/filepath" "github.com/cloudfoundry/bosh-bootloader/integration-test" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("config", func() { var tempDir string BeforeEach(func() { var err error tempDir, err = ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) integration.ResetTempDir() }) Describe("LoadConfig", func() { var configPath string BeforeEach(func() { configPath = os.Getenv("BIT_CONFIG") }) AfterEach(func() { os.Setenv("BIT_CONFIG", configPath) }) var writeConfigurationFile = func(json string) string { configurationFilePath := filepath.Join(tempDir, "config.json") err := ioutil.WriteFile(configurationFilePath, []byte(json), os.ModePerm) Expect(err).NotTo(HaveOccurred()) return configurationFilePath } It("returns a valid config from a path", func() { configurationFilePath := writeConfigurationFile(`{ "AWSAccessKeyID": "some-aws-access-key-id", "AWSSecretAccessKey": "some-aws-secret-access-key", "AWSRegion": "some-region", "StateFileDir": "/some/path" }`) os.Setenv("BIT_CONFIG", configurationFilePath) config, err := integration.LoadConfig() Expect(err).NotTo(HaveOccurred()) Expect(config).To(Equal(integration.Config{ AWSAccessKeyID: "some-aws-access-key-id", AWSSecretAccessKey: "some-aws-secret-access-key", AWSRegion: "some-region", StateFileDir: "/some/path", })) }) It("returns a random path if no StateFileDir is specified", func() { integration.SetTempDir(func(string, string) (string, error) { return "/some/temp/dir", nil }) configurationFilePath := writeConfigurationFile(`{ "AWSAccessKeyID": "some-aws-access-key-id", "AWSSecretAccessKey": "some-aws-secret-access-key", "AWSRegion": "some-region" }`) os.Setenv("BIT_CONFIG", configurationFilePath) config, err := integration.LoadConfig() Expect(err).NotTo(HaveOccurred()) Expect(config).To(Equal(integration.Config{ AWSAccessKeyID: "some-aws-access-key-id", AWSSecretAccessKey: "some-aws-secret-access-key", AWSRegion: "some-region", StateFileDir: "/some/temp/dir", })) }) Context("failure cases", func() { It("returns an error if the temp dir cannot be created", func() { integration.SetTempDir(func(string, string) (string, error) { return "", errors.New("temp dir creation failed") }) configurationFilePath := writeConfigurationFile(`{ "AWSAccessKeyID": "some-aws-access-key-id", "AWSSecretAccessKey": "some-aws-secret-access-key", "AWSRegion": "some-region" }`) os.Setenv("BIT_CONFIG", configurationFilePath) _, err := integration.LoadConfig() Expect(err).To(MatchError("temp dir creation failed")) }) It("returns an error if aws access key id is missing", func() { configurationFilePath := writeConfigurationFile(`{ "AWSSecretAccessKey": "some-aws-secret-access-key", "AWSRegion": "some-region" }`) os.Setenv("BIT_CONFIG", configurationFilePath) _, err := integration.LoadConfig() Expect(err).To(MatchError("aws access key id is missing")) }) It("returns an error if aws access key id is missing", func() { configurationFilePath := writeConfigurationFile(`{ "AWSAccessKeyID": "some-aws-access-key-id", "AWSRegion": "some-region" }`) os.Setenv("BIT_CONFIG", configurationFilePath) _, err := integration.LoadConfig() Expect(err).To(MatchError("aws secret access key is missing")) }) It("returns an error if aws access key id is missing", func() { configurationFilePath := writeConfigurationFile(`{ "AWSAccessKeyID": "some-aws-access-key-id", "AWSSecretAccessKey": "some-aws-secret-access-key" }`) os.Setenv("BIT_CONFIG", configurationFilePath) _, err := integration.LoadConfig() Expect(err).To(MatchError("aws region is missing")) }) It("returns an error if it cannot open the config file", func() { os.Setenv("BIT_CONFIG", "/nonexistent-file") _, err := integration.LoadConfig() Expect(err).To(MatchError("open /nonexistent-file: no such file or directory")) }) It("returns an error if it cannot parse json in config file", func() { configurationFilePath := writeConfigurationFile(`%%%%`) os.Setenv("BIT_CONFIG", configurationFilePath) _, err := integration.LoadConfig() Expect(err).To(MatchError("invalid character '%' looking for beginning of value")) }) It("returns an error when the path is not set", func() { os.Setenv("BIT_CONFIG", "") _, err := integration.LoadConfig() Expect(err).To(MatchError(`$BIT_CONFIG "" does not specify an absolute path to test config file`)) }) It("returns an error when the path is not absolute", func() { os.Setenv("BIT_CONFIG", "some/path.json") _, err := integration.LoadConfig() Expect(err).To(MatchError(`$BIT_CONFIG "some/path.json" does not specify an absolute path to test config file`)) }) }) }) }) <file_sep>/boshinit/manifests/internal_credentials_test.go package manifests_test import ( "github.com/cloudfoundry/bosh-bootloader/boshinit/manifests" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("InternalCredentials", func() { var ( inputCredentials map[string]string ) BeforeEach(func() { inputCredentials = map[string]string{ "mbusUsername": "some-mbus-username", "natsUsername": "some-nats-username", "postgresUsername": "some-postgres-username", "registryUsername": "some-registry-username", "blobstoreDirectorUsername": "some-blobstore-director-username", "blobstoreAgentUsername": "some-blobstore-agent-username", "hmUsername": "some-hm-username", "mbusPassword": "<PASSWORD>", "natsPassword": "<PASSWORD>", "postgresPassword": "<PASSWORD>", "registryPassword": "<PASSWORD>", "blobstoreDirectorPassword": "<PASSWORD>", "blobstoreAgentPassword": "<PASSWORD>", "hmPassword": "<PASSWORD>", } }) Describe("NewInternalCredentials", func() { It("creates a new InternalCredentials from a map[string]string", func() { outputCredentials := manifests.NewInternalCredentials(inputCredentials) Expect(outputCredentials).To(Equal(manifests.InternalCredentials{ MBusUsername: "some-mbus-username", NatsUsername: "some-nats-username", PostgresUsername: "some-postgres-username", RegistryUsername: "some-registry-username", BlobstoreDirectorUsername: "some-blobstore-director-username", BlobstoreAgentUsername: "some-blobstore-agent-username", HMUsername: "some-hm-username", MBusPassword: "<PASSWORD>", NatsPassword: "<PASSWORD>", PostgresPassword: "<PASSWORD>", RegistryPassword: "<PASSWORD>", BlobstoreDirectorPassword: "<PASSWORD>", BlobstoreAgentPassword: "<PASSWORD>", HMPassword: "<PASSWORD>", })) }) }) Describe("ToMap", func() { It("returns a map representation of the credentials", func() { outputCredentials := manifests.NewInternalCredentials(inputCredentials) Expect(outputCredentials.ToMap()).To(Equal(inputCredentials)) }) }) }) <file_sep>/fakes/private_key_generator.go package fakes import ( "crypto/rsa" "io" ) type PrivateKeyGenerator struct { GenerateKeyCall struct { Stub func() (*rsa.PrivateKey, error) CallCount int Receives []GenerateKeyCallReceives Returns struct { PrivateKey *rsa.PrivateKey Error error } } } type GenerateKeyCallReceives struct { Random io.Reader Bits int } func (k *PrivateKeyGenerator) GenerateKey(random io.Reader, bits int) (*rsa.PrivateKey, error) { defer func() { k.GenerateKeyCall.CallCount++ }() k.GenerateKeyCall.Receives = append(k.GenerateKeyCall.Receives, GenerateKeyCallReceives{ Random: random, Bits: bits, }) if k.GenerateKeyCall.Stub != nil { return k.GenerateKeyCall.Stub() } return k.GenerateKeyCall.Returns.PrivateKey, k.GenerateKeyCall.Returns.Error } <file_sep>/aws/cloudformation/templates/load_balancer_template_builder.go package templates import "fmt" type LoadBalancerTemplateBuilder struct{} func NewLoadBalancerTemplateBuilder() LoadBalancerTemplateBuilder { return LoadBalancerTemplateBuilder{} } func (l LoadBalancerTemplateBuilder) CFSSHProxyLoadBalancer(numberOfAvailabilityZones int) Template { return Template{ Outputs: l.outputsFor("CFSSHProxyLoadBalancer"), Resources: map[string]Resource{ "CFSSHProxyLoadBalancer": { Type: "AWS::ElasticLoadBalancing::LoadBalancer", DependsOn: "VPCGatewayAttachment", Properties: ElasticLoadBalancingLoadBalancer{ CrossZone: true, Subnets: l.loadBalancerSubnets(numberOfAvailabilityZones), SecurityGroups: []interface{}{Ref{"CFSSHProxySecurityGroup"}}, HealthCheck: HealthCheck{ HealthyThreshold: "5", Interval: "6", Target: "tcp:2222", Timeout: "2", UnhealthyThreshold: "2", }, Listeners: []Listener{ { Protocol: "tcp", LoadBalancerPort: "2222", InstanceProtocol: "tcp", InstancePort: "2222", }, }, }, }, }, } } func (l LoadBalancerTemplateBuilder) CFRouterLoadBalancer(numberOfAvailabilityZones int, sslCertificateID string) Template { return Template{ Outputs: l.outputsFor("CFRouterLoadBalancer"), Resources: map[string]Resource{ "CFRouterLoadBalancer": { Type: "AWS::ElasticLoadBalancing::LoadBalancer", DependsOn: "VPCGatewayAttachment", Properties: ElasticLoadBalancingLoadBalancer{ CrossZone: true, Subnets: l.loadBalancerSubnets(numberOfAvailabilityZones), SecurityGroups: []interface{}{Ref{"CFRouterSecurityGroup"}}, HealthCheck: HealthCheck{ HealthyThreshold: "5", Interval: "12", Target: "tcp:80", Timeout: "2", UnhealthyThreshold: "2", }, Listeners: []Listener{ { Protocol: "http", LoadBalancerPort: "80", InstanceProtocol: "http", InstancePort: "80", }, { Protocol: "https", LoadBalancerPort: "443", InstanceProtocol: "http", InstancePort: "80", SSLCertificateID: sslCertificateID, }, { Protocol: "ssl", LoadBalancerPort: "4443", InstanceProtocol: "tcp", InstancePort: "80", SSLCertificateID: sslCertificateID, }, }, }, }, }, } } func (l LoadBalancerTemplateBuilder) ConcourseLoadBalancer(numberOfAvailabilityZones int, sslCertificateID string) Template { return Template{ Outputs: l.outputsFor("ConcourseLoadBalancer"), Resources: map[string]Resource{ "ConcourseLoadBalancer": { DependsOn: "VPCGatewayAttachment", Type: "AWS::ElasticLoadBalancing::LoadBalancer", Properties: ElasticLoadBalancingLoadBalancer{ Subnets: l.loadBalancerSubnets(numberOfAvailabilityZones), SecurityGroups: []interface{}{Ref{"ConcourseSecurityGroup"}}, HealthCheck: HealthCheck{ HealthyThreshold: "2", Interval: "30", Target: "tcp:8080", Timeout: "5", UnhealthyThreshold: "10", }, Listeners: []Listener{ { Protocol: "tcp", LoadBalancerPort: "80", InstanceProtocol: "tcp", InstancePort: "8080", }, { Protocol: "tcp", LoadBalancerPort: "2222", InstanceProtocol: "tcp", InstancePort: "2222", }, { Protocol: "ssl", LoadBalancerPort: "443", InstanceProtocol: "tcp", InstancePort: "8080", SSLCertificateID: sslCertificateID, }, }, }, }, }, } } func (LoadBalancerTemplateBuilder) outputsFor(loadBalancerName string) map[string]Output { return map[string]Output{ loadBalancerName: {Value: Ref{loadBalancerName}}, loadBalancerName + "URL": { Value: FnGetAtt{ []string{ loadBalancerName, "DNSName", }, }, }, } } func (LoadBalancerTemplateBuilder) loadBalancerSubnets(numberOfAvailabilityZones int) []interface{} { subnets := []interface{}{} for i := 1; i <= numberOfAvailabilityZones; i++ { subnets = append(subnets, Ref{fmt.Sprintf("LoadBalancerSubnet%d", i)}) } return subnets } <file_sep>/aws/ec2/keypair_checker.go package ec2 import ( "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" ) type KeyPairChecker struct { ec2ClientProvider ec2ClientProvider } func NewKeyPairChecker(ec2ClientProvider ec2ClientProvider) KeyPairChecker { return KeyPairChecker{ ec2ClientProvider: ec2ClientProvider, } } type KeyPairInfo struct { Name string Fingerprint string } func (k KeyPairChecker) HasKeyPair(name string) (bool, error) { if name == "" { return false, nil } params := &ec2.DescribeKeyPairsInput{ KeyNames: []*string{ aws.String(name), }, } _, err := k.ec2ClientProvider.GetEC2Client().DescribeKeyPairs(params) if err != nil { if strings.Contains(err.Error(), "InvalidKeyPair.NotFound") { return false, nil } return false, err } return true, nil } <file_sep>/integration-test/actors/aws.go package actors import ( "os" "github.com/cloudfoundry/bosh-bootloader/application" "github.com/cloudfoundry/bosh-bootloader/aws" "github.com/cloudfoundry/bosh-bootloader/aws/clientmanager" "github.com/cloudfoundry/bosh-bootloader/aws/cloudformation" "github.com/cloudfoundry/bosh-bootloader/aws/ec2" "github.com/cloudfoundry/bosh-bootloader/aws/iam" "github.com/cloudfoundry/bosh-bootloader/integration-test" . "github.com/onsi/gomega" awslib "github.com/aws/aws-sdk-go/aws" awsec2 "github.com/aws/aws-sdk-go/service/ec2" ) type AWS struct { stackManager cloudformation.StackManager certificateDescriber iam.CertificateDescriber ec2Client ec2.Client cloudFormationClient cloudformation.Client } func NewAWS(configuration integration.Config) AWS { awsConfig := aws.Config{ AccessKeyID: configuration.AWSAccessKeyID, SecretAccessKey: configuration.AWSSecretAccessKey, Region: configuration.AWSRegion, } clientProvider := &clientmanager.ClientProvider{} clientProvider.SetConfig(awsConfig) stackManager := cloudformation.NewStackManager(clientProvider, application.NewLogger(os.Stdout)) certificateDescriber := iam.NewCertificateDescriber(clientProvider) return AWS{ stackManager: stackManager, certificateDescriber: certificateDescriber, ec2Client: clientProvider.GetEC2Client(), cloudFormationClient: clientProvider.GetCloudFormationClient(), } } func (a AWS) StackExists(stackName string) bool { _, err := a.stackManager.Describe(stackName) if err == cloudformation.StackNotFound { return false } Expect(err).NotTo(HaveOccurred()) return true } func (a AWS) GetPhysicalID(stackName, logicalID string) string { physicalID, err := a.stackManager.GetPhysicalIDForResource(stackName, logicalID) Expect(err).NotTo(HaveOccurred()) return physicalID } func (a AWS) LoadBalancers(stackName string) map[string]string { stack, err := a.stackManager.Describe(stackName) Expect(err).NotTo(HaveOccurred()) loadBalancers := map[string]string{} for _, loadBalancer := range []string{"CFRouterLoadBalancer", "CFSSHProxyLoadBalancer", "ConcourseLoadBalancer", "ConcourseLoadBalancerURL"} { if stack.Outputs[loadBalancer] != "" { loadBalancers[loadBalancer] = stack.Outputs[loadBalancer] } } return loadBalancers } func (a AWS) DescribeCertificate(certificateName string) iam.Certificate { certificate, err := a.certificateDescriber.Describe(certificateName) if err != nil && err != iam.CertificateNotFound { Expect(err).NotTo(HaveOccurred()) } return certificate } func (a AWS) GetEC2InstanceTags(instanceID string) map[string]string { describeInstanceInput := &awsec2.DescribeInstancesInput{ DryRun: awslib.Bool(false), Filters: []*awsec2.Filter{ { Name: awslib.String("instance-id"), Values: []*string{ awslib.String(instanceID), }, }, }, InstanceIds: []*string{ awslib.String(instanceID), }, } describeInstancesOutput, err := a.ec2Client.DescribeInstances(describeInstanceInput) Expect(err).NotTo(HaveOccurred()) Expect(describeInstancesOutput.Reservations).To(HaveLen(1)) Expect(describeInstancesOutput.Reservations[0].Instances).To(HaveLen(1)) instance := describeInstancesOutput.Reservations[0].Instances[0] tags := make(map[string]string) for _, tag := range instance.Tags { tags[awslib.StringValue(tag.Key)] = awslib.StringValue(tag.Value) } return tags } func (a AWS) DescribeKeyPairs(keypairName string) []*awsec2.KeyPairInfo { params := &awsec2.DescribeKeyPairsInput{ Filters: []*awsec2.Filter{{}}, KeyNames: []*string{ awslib.String(keypairName), }, } keypairOutput, err := a.ec2Client.DescribeKeyPairs(params) Expect(err).NotTo(HaveOccurred()) return keypairOutput.KeyPairs } <file_sep>/aws/ec2/keypair_deleter_test.go package ec2_test import ( "errors" "github.com/aws/aws-sdk-go/aws" awsec2 "github.com/aws/aws-sdk-go/service/ec2" "github.com/cloudfoundry/bosh-bootloader/aws/ec2" "github.com/cloudfoundry/bosh-bootloader/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("KeyPairDeleter", func() { var ( deleter ec2.KeyPairDeleter client *fakes.EC2Client ec2ClientProvider *fakes.ClientProvider logger *fakes.Logger ) BeforeEach(func() { ec2ClientProvider = &fakes.ClientProvider{} client = &fakes.EC2Client{} logger = &fakes.Logger{} ec2ClientProvider.GetEC2ClientCall.Returns.EC2Client = client deleter = ec2.NewKeyPairDeleter(ec2ClientProvider, logger) }) It("deletes the ec2 keypair", func() { err := deleter.Delete("some-key-pair-name") Expect(err).NotTo(HaveOccurred()) Expect(client.DeleteKeyPairCall.Receives.Input).To(Equal(&awsec2.DeleteKeyPairInput{ KeyName: aws.String("some-key-pair-name"), })) Expect(logger.StepCall.Receives.Message).To(Equal("deleting keypair")) }) Context("failure cases", func() { Context("when the keypair cannot be deleted", func() { It("returns an error", func() { client.DeleteKeyPairCall.Returns.Error = errors.New("failed to delete keypair") err := deleter.Delete("some-key-pair-name") Expect(err).To(MatchError("failed to delete keypair")) }) }) }) }) <file_sep>/bosh/client_provider.go package bosh type ClientProvider struct{} func NewClientProvider() ClientProvider { return ClientProvider{} } func (ClientProvider) Client(directorAddress, directorUsername, directorPassword string) Client { return NewClient(directorAddress, directorUsername, directorPassword) } <file_sep>/fakes/certificate_describer.go package fakes import ( "github.com/cloudfoundry/bosh-bootloader/aws/iam" ) type CertificateDescriber struct { DescribeCall struct { CallCount int Receives struct { CertificateName string } Returns struct { Certificate iam.Certificate Error error } } } func (c *CertificateDescriber) Describe(certificateName string) (iam.Certificate, error) { c.DescribeCall.CallCount++ c.DescribeCall.Receives.CertificateName = certificateName return c.DescribeCall.Returns.Certificate, c.DescribeCall.Returns.Error } <file_sep>/application/aws_credential_validator.go package application import "errors" type AWSCredentialValidator struct { configuration Configuration } func NewAWSCredentialValidator(configuration Configuration) AWSCredentialValidator { return AWSCredentialValidator{ configuration: configuration, } } func (a AWSCredentialValidator) Validate() error { if a.configuration.State.AWS.AccessKeyID == "" { return errors.New("AWS access key ID must be provided") } if a.configuration.State.AWS.SecretAccessKey == "" { return errors.New("AWS secret access key must be provided") } if a.configuration.State.AWS.Region == "" { return errors.New("AWS region must be provided") } return nil } <file_sep>/fakes/bosh_deleter.go package fakes import "github.com/cloudfoundry/bosh-bootloader/boshinit" type BOSHDeleter struct { DeleteCall struct { CallCount int Receives struct { BOSHInitManifest string BOSHInitState boshinit.State EC2PrivateKey string } Returns struct { Error error } } } func (d *BOSHDeleter) Delete(boshInitManifest string, boshInitState boshinit.State, ec2PrivateKey string) error { d.DeleteCall.CallCount++ d.DeleteCall.Receives.BOSHInitManifest = boshInitManifest d.DeleteCall.Receives.BOSHInitState = boshInitState d.DeleteCall.Receives.EC2PrivateKey = ec2PrivateKey return d.DeleteCall.Returns.Error } <file_sep>/ssl/keypair_test.go package ssl_test import ( "github.com/cloudfoundry/bosh-bootloader/ssl" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("KeyPair", func() { Describe("IsEmpty", func() { It("returns true if the keypair is empty", func() { keyPair := ssl.KeyPair{} Expect(keyPair.IsEmpty()).To(BeTrue()) }) It("returns false if the keypair is not empty", func() { keyPair := ssl.KeyPair{ Certificate: []byte("some-cert"), PrivateKey: []byte("some-key"), } Expect(keyPair.IsEmpty()).To(BeFalse()) }) }) Describe("IsValidForIP", func() { It("returns false if the keypair is empty", func() { keyPair := ssl.KeyPair{} Expect(keyPair.IsValidForIP("127.0.0.1")).To(BeFalse()) }) It("returns false if the keypair is not empty", func() { keyPair := ssl.KeyPair{ Certificate: []byte(certificatePEM), PrivateKey: []byte(privateKeyPEM), } Expect(keyPair.IsValidForIP("127.0.0.1")).To(BeFalse()) Expect(keyPair.IsValidForIP("172.16.17.32")).To(BeTrue()) }) Context("failure cases", func() { Context("when the cert cannot be decoded", func() { It("returns false", func() { keyPair := ssl.KeyPair{ Certificate: []byte(privateKeyPEM), PrivateKey: []byte(certificatePEM), } Expect(keyPair.IsValidForIP("172.16.17.32")).To(BeFalse()) }) }) Context("when the cert is not PEM encoded", func() { It("returns false", func() { keyPair := ssl.KeyPair{ Certificate: []byte("something"), PrivateKey: []byte("something"), } Expect(keyPair.IsValidForIP("172.16.17.32")).To(BeFalse()) }) }) }) }) }) <file_sep>/bosh/client_test.go package bosh_test import ( "io/ioutil" "net/http" "net/http/httptest" "net/url" "github.com/cloudfoundry/bosh-bootloader/bosh" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Client", func() { Describe("Info", func() { It("returns the director info", func() { fakeBOSH := httptest.NewTLSServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) { responseWriter.Write([]byte(`{ "name": "some-bosh-director", "uuid": "some-uuid", "version": "some-version" }`)) })) client := bosh.NewClient(fakeBOSH.URL, "some-username", "some-password") info, err := client.Info() Expect(err).NotTo(HaveOccurred()) Expect(info).To(Equal(bosh.Info{ Name: "some-bosh-director", UUID: "some-uuid", Version: "some-version", })) }) Context("failure cases", func() { It("returns an error when the response is not StatusOK", func() { fakeBOSH := httptest.NewTLSServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) { responseWriter.WriteHeader(http.StatusNotFound) })) client := bosh.NewClient(fakeBOSH.URL, "some-username", "some-password") _, err := client.Info() Expect(err).To(MatchError("unexpected http response 404 Not Found")) }) It("returns an error when the url cannot be parsed", func() { client := bosh.NewClient("%%%", "some-username", "some-password") _, err := client.Info() Expect(err.(*url.Error).Op).To(Equal("parse")) }) It("returns an error when the request fails", func() { client := bosh.NewClient("fake://some-url", "some-username", "some-password") _, err := client.Info() Expect(err).To(MatchError(ContainSubstring("unsupported protocol scheme"))) }) It("returns an error when it cannot parse info json", func() { fakeBOSH := httptest.NewTLSServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) { responseWriter.Write([]byte(`%%%`)) })) client := bosh.NewClient(fakeBOSH.URL, "some-username", "some-password") _, err := client.Info() Expect(err).To(MatchError(ContainSubstring("invalid character"))) }) }) }) Describe("UpdateCloudConfig", func() { It("uploads the given cloud config", func() { var ( cloudConfig []byte contentType string username string password string ) fakeBOSH := httptest.NewTLSServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) { var ( err error ) username, password, _ = request.BasicAuth() contentType = request.Header.Get("Content-Type") cloudConfig, err = ioutil.ReadAll(request.Body) Expect(err).NotTo(HaveOccurred()) responseWriter.WriteHeader(http.StatusCreated) })) client := bosh.NewClient(fakeBOSH.URL, "some-username", "some-password") err := client.UpdateCloudConfig([]byte("cloud: config")) Expect(err).NotTo(HaveOccurred()) Expect(cloudConfig).To(Equal([]byte("cloud: config"))) Expect(contentType).To(Equal("text/yaml")) Expect(username).To(Equal("some-username")) Expect(password).To(Equal("<PASSWORD>")) }) Context("failure cases", func() { It("returns an error when the status code is not StatusCreated", func() { fakeBOSH := httptest.NewTLSServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) { responseWriter.WriteHeader(http.StatusInternalServerError) })) client := bosh.NewClient(fakeBOSH.URL, "", "") err := client.UpdateCloudConfig([]byte("cloud: config")) Expect(err).To(MatchError("unexpected http response 500 Internal Server Error")) }) It("returns an error when the director address is malformed", func() { client := bosh.NewClient("%%%%%%%%%%%%%%%", "", "") err := client.UpdateCloudConfig([]byte("cloud: config")) Expect(err.(*url.Error).Op).To(Equal("parse")) }) It("returns an error when the director address is malformed", func() { fakeBOSH := httptest.NewTLSServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) { responseWriter.WriteHeader(http.StatusInternalServerError) })) client := bosh.NewClient(fakeBOSH.URL, "", "") fakeBOSH.Close() err := client.UpdateCloudConfig([]byte("cloud: config")) Expect(err).To(MatchError(ContainSubstring("connection refused"))) }) }) }) }) <file_sep>/fakes/command_line_parser.go package fakes import "github.com/cloudfoundry/bosh-bootloader/application" type CommandLineParser struct { ParseCall struct { Receives struct { Arguments []string } Returns struct { CommandLineConfiguration application.CommandLineConfiguration Error error } } } func (p *CommandLineParser) Parse(arguments []string) (application.CommandLineConfiguration, error) { p.ParseCall.Receives.Arguments = arguments return p.ParseCall.Returns.CommandLineConfiguration, p.ParseCall.Returns.Error } <file_sep>/fakes/keypair_creator.go package fakes import "github.com/cloudfoundry/bosh-bootloader/aws/ec2" type KeyPairCreator struct { CreateCall struct { Returns struct { KeyPair ec2.KeyPair Error error } Receives struct { KeyPairName string } } } func (k *KeyPairCreator) Create(keyPairName string) (ec2.KeyPair, error) { k.CreateCall.Receives.KeyPairName = keyPairName return k.CreateCall.Returns.KeyPair, k.CreateCall.Returns.Error } <file_sep>/ssl/keypair.go package ssl import ( "crypto/x509" "encoding/pem" ) type KeyPair struct { CA []byte Certificate []byte PrivateKey []byte } func (k KeyPair) IsEmpty() bool { return len(k.Certificate) == 0 || len(k.PrivateKey) == 0 } func (k KeyPair) IsValidForIP(ip string) bool { if k.IsEmpty() { return false } block, _ := pem.Decode(k.Certificate) if block == nil { return false } certificate, err := x509.ParseCertificate(block.Bytes) if err != nil { return false } err = certificate.VerifyHostname(ip) return err == nil } <file_sep>/boshinit/manifests/job_properties.go package manifests type JobProperties struct { NATS NATSJobProperties `yaml:"nats"` Postgres PostgresProperties `yaml:"postgres"` Registry RegistryJobProperties `yaml:"registry"` Blobstore BlobstoreJobProperties `yaml:"blobstore"` Director DirectorJobProperties `yaml:"director"` HM HMJobProperties `yaml:"hm"` AWS AWSProperties `yaml:"aws"` Agent AgentProperties `yaml:"agent"` } type NATSJobProperties struct { Address string `yaml:"address"` User string `yaml:"user"` Password string `yaml:"password"` } type RegistryJobProperties struct { Host string `yaml:"host"` Address string `yaml:"address"` Username string `yaml:"username"` Password string `yaml:"<PASSWORD>"` DB RegistryPostgresProperties `yaml:"db"` HTTP HTTPProperties `yaml:"http"` } type BlobstoreJobProperties struct { Address string `yaml:"address"` Director Credentials `yaml:"director"` Agent Credentials `yaml:"agent"` } type DefaultSSHOptions struct { GatewayHost string `yaml:"gateway_host"` } type DirectorJobProperties struct { Address string `yaml:"address"` Name string `yaml:"name"` CPIJob string `yaml:"cpi_job"` Workers int `yaml:"workers"` EnableDedicatedStatusWorker bool `yaml:"enable_dedicated_status_worker"` EnablePostDeploy bool `yaml:"enable_post_deploy"` DB PostgresProperties `yaml:"db"` UserManagement UserManagementProperties `yaml:"user_management"` SSL SSLProperties `yaml:"ssl"` DefaultSSHOptions DefaultSSHOptions `yaml:"default_ssh_options"` } type HMJobProperties struct { DirectorAccount Credentials `yaml:"director_account"` ResurrectorEnabled bool `yaml:"resurrector_enabled"` } type LocalProperties struct { Users []UserProperties `yaml:"users"` } type UserProperties struct { Name string `yaml:"name"` Password string `yaml:"password"` } type UserManagementProperties struct { Local LocalProperties `yaml:"local"` } type SSLProperties struct { Cert string `yaml:"cert"` Key string `yaml:"key"` } type HTTPProperties struct { User string `yaml:"user"` Password string `yaml:"<PASSWORD>"` } type Credentials struct { User string `yaml:"user"` Password string `yaml:"<PASSWORD>"` } <file_sep>/aws/ec2/vpc_status_checker_test.go package ec2_test import ( "errors" "github.com/aws/aws-sdk-go/aws" awsec2 "github.com/aws/aws-sdk-go/service/ec2" "github.com/cloudfoundry/bosh-bootloader/aws/ec2" "github.com/cloudfoundry/bosh-bootloader/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("VPCStatusChecker", func() { var ( vpcStatusChecker ec2.VPCStatusChecker ec2Client *fakes.EC2Client clientProvider *fakes.ClientProvider ) BeforeEach(func() { clientProvider = &fakes.ClientProvider{} ec2Client = &fakes.EC2Client{} clientProvider.GetEC2ClientCall.Returns.EC2Client = ec2Client vpcStatusChecker = ec2.NewVPCStatusChecker(clientProvider) }) Describe("ValidateSafeToDelete", func() { var reservationContainingInstance = func(tag string) *awsec2.Reservation { return &awsec2.Reservation{ Instances: []*awsec2.Instance{{ Tags: []*awsec2.Tag{{ Key: aws.String("Name"), Value: aws.String(tag), }}, }}, } } It("returns nil when the only EC2 instances are bosh and nat", func() { ec2Client.DescribeInstancesCall.Returns.Output = &awsec2.DescribeInstancesOutput{ Reservations: []*awsec2.Reservation{ reservationContainingInstance("NAT"), reservationContainingInstance("bosh/0"), }, } err := vpcStatusChecker.ValidateSafeToDelete("some-vpc-id") Expect(err).NotTo(HaveOccurred()) Expect(ec2Client.DescribeInstancesCall.Receives.Input).To(Equal(&awsec2.DescribeInstancesInput{ Filters: []*awsec2.Filter{{ Name: aws.String("vpc-id"), Values: []*string{aws.String("some-vpc-id")}, }}, })) }) It("returns nil when there are no instances at all", func() { ec2Client.DescribeInstancesCall.Returns.Output = &awsec2.DescribeInstancesOutput{ Reservations: []*awsec2.Reservation{}, } err := vpcStatusChecker.ValidateSafeToDelete("some-vpc-id") Expect(err).NotTo(HaveOccurred()) }) It("returns an error when there are bosh-deployed VMs in the VPC", func() { ec2Client.DescribeInstancesCall.Returns.Output = &awsec2.DescribeInstancesOutput{ Reservations: []*awsec2.Reservation{ reservationContainingInstance("NAT"), reservationContainingInstance("bosh/0"), reservationContainingInstance("first-bosh-deployed-vm"), reservationContainingInstance("second-bosh-deployed-vm"), }, } err := vpcStatusChecker.ValidateSafeToDelete("some-vpc-id") Expect(err).To(MatchError("vpc some-vpc-id is not safe to delete; vms still exist: [first-bosh-deployed-vm, second-bosh-deployed-vm]")) }) It("returns an error even when there are two VMs in the VPC, but they are not NAT and BOSH", func() { ec2Client.DescribeInstancesCall.Returns.Output = &awsec2.DescribeInstancesOutput{ Reservations: []*awsec2.Reservation{ reservationContainingInstance("not-bosh"), reservationContainingInstance("not-nat"), }, } err := vpcStatusChecker.ValidateSafeToDelete("some-vpc-id") Expect(err).To(MatchError("vpc some-vpc-id is not safe to delete; vms still exist: [not-bosh, not-nat]")) }) It("returns an error even if the vpc contains other instances tagged NAT and bosh/0", func() { ec2Client.DescribeInstancesCall.Returns.Output = &awsec2.DescribeInstancesOutput{ Reservations: []*awsec2.Reservation{ reservationContainingInstance("NAT"), reservationContainingInstance("NAT"), reservationContainingInstance("bosh/0"), reservationContainingInstance("bosh/0"), reservationContainingInstance("bosh/0"), }, } err := vpcStatusChecker.ValidateSafeToDelete("some-vpc-id") Expect(err).To(MatchError("vpc some-vpc-id is not safe to delete; vms still exist: [NAT, bosh/0, bosh/0]")) }) It("returns an error even if the vpc contains untagged vms", func() { ec2Client.DescribeInstancesCall.Returns.Output = &awsec2.DescribeInstancesOutput{ Reservations: []*awsec2.Reservation{ &awsec2.Reservation{ Instances: []*awsec2.Instance{{ Tags: []*awsec2.Tag{{ Key: aws.String("Name"), Value: aws.String(""), }}, }, {}, {}}, }, }, } err := vpcStatusChecker.ValidateSafeToDelete("some-vpc-id") Expect(err).To(MatchError("vpc some-vpc-id is not safe to delete; vms still exist: [unnamed, unnamed, unnamed]")) }) Describe("failure cases", func() { It("returns an error when the describe instances call fails", func() { ec2Client.DescribeInstancesCall.Returns.Error = errors.New("failed to describe instances") err := vpcStatusChecker.ValidateSafeToDelete("some-vpc-id") Expect(err).To(MatchError("failed to describe instances")) }) }) }) }) <file_sep>/boshinit/command_builder.go package boshinit import ( "io" "os/exec" "path/filepath" ) type CommandBuilder struct { Path string Directory string Stdout io.Writer Stderr io.Writer } func NewCommandBuilder(path string, dir string, stdout io.Writer, stderr io.Writer) CommandBuilder { return CommandBuilder{ Path: path, Directory: dir, Stdout: stdout, Stderr: stderr, } } func (b CommandBuilder) DeployCommand() *exec.Cmd { return &exec.Cmd{ Path: b.Path, Args: []string{ filepath.Base(b.Path), "deploy", "bosh.yml", }, Dir: b.Directory, Stdout: b.Stdout, Stderr: b.Stderr, } } func (b CommandBuilder) DeleteCommand() *exec.Cmd { return &exec.Cmd{ Path: b.Path, Args: []string{ filepath.Base(b.Path), "delete", "bosh.yml", }, Dir: b.Directory, Stdout: b.Stdout, Stderr: b.Stderr, } } <file_sep>/boshinit/manifests/disk_pools_manifest_builder.go package manifests type DiskPoolsManifestBuilder struct{} func NewDiskPoolsManifestBuilder() DiskPoolsManifestBuilder { return DiskPoolsManifestBuilder{} } func (r DiskPoolsManifestBuilder) Build() []DiskPool { return []DiskPool{ { Name: "disks", DiskSize: 80 * 1024, CloudProperties: DiskPoolsCloudProperties{ Type: "gp2", Encrypted: true, }, }, } } <file_sep>/commands/usage.go package commands import ( "fmt" "io" "strings" "github.com/cloudfoundry/bosh-bootloader/storage" ) const ( HelpCommand = "help" UsageHeader = ` Usage: bbl [GLOBAL OPTIONS] %s [OPTIONS] Global Options: --help [-h] Print usage --state-dir Directory containing bbl-state.json %s ` CommandUsage = ` [%s command options] %s` ) const GlobalUsage = ` Commands: bosh-ca-cert Prints BOSH director CA certificate create-lbs Attaches load balancer(s) delete-lbs Deletes attached load balancer(s) destroy Tears down BOSH director infrastructure director-address Prints BOSH director address director-username Prints BOSH director username director-password Prints BOSH <PASSWORD> password director-ca-cert Prints BOSH director CA certificate env-id Prints environment ID help Prints usage lbs Prints attached load balancer(s) ssh-key Prints SSH private key up Deploys BOSH director on AWS update-lbs Updates load balancer(s) version Prints version Use "bbl [command] --help" for more information about a command.` type Usage struct { stdout io.Writer } func NewUsage(stdout io.Writer) Usage { return Usage{stdout} } func (u Usage) Execute(subcommandFlags []string, state storage.State) error { u.Print() return nil } func (u Usage) Print() { content := fmt.Sprintf(UsageHeader, "COMMAND", GlobalUsage) fmt.Fprint(u.stdout, strings.TrimLeft(content, "\n")) } func (u Usage) PrintCommandUsage(command, message string) { commandUsage := fmt.Sprintf(CommandUsage, command, message) content := fmt.Sprintf(UsageHeader, command, commandUsage) fmt.Fprint(u.stdout, strings.TrimLeft(content, "\n")) } <file_sep>/fakes/jobs_manifest_builder.go package fakes import "github.com/cloudfoundry/bosh-bootloader/boshinit/manifests" type JobsManifestBuilder struct { BuildCall struct { Returns struct { Error error } } } func (j JobsManifestBuilder) Build(manifestProperties manifests.ManifestProperties) ([]manifests.Job, manifests.ManifestProperties, error) { return nil, manifestProperties, j.BuildCall.Returns.Error } <file_sep>/bosh/client.go package bosh import ( "bytes" "crypto/tls" "encoding/json" "fmt" "net/http" "strings" ) type Client interface { UpdateCloudConfig(yaml []byte) error Info() (Info, error) } type Info struct { Name string `json:"name"` UUID string `json:"uuid"` Version string `json:"version"` } type client struct { directorAddress string username string password string httpClient *http.Client } func NewClient(directorAddress, username, password string) Client { httpClient := &http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, }, }, } return client{ directorAddress: directorAddress, username: username, password: <PASSWORD>, httpClient: httpClient, } } func (c client) Info() (Info, error) { request, err := http.NewRequest("GET", fmt.Sprintf("%s/info", c.directorAddress), strings.NewReader("")) if err != nil { return Info{}, err } response, err := c.httpClient.Do(request) if err != nil { return Info{}, err } if response.StatusCode != http.StatusOK { return Info{}, fmt.Errorf("unexpected http response %d %s", response.StatusCode, http.StatusText(response.StatusCode)) } var info Info if err := json.NewDecoder(response.Body).Decode(&info); err != nil { return Info{}, err } return info, nil } func (c client) UpdateCloudConfig(yaml []byte) error { request, err := http.NewRequest("POST", fmt.Sprintf("%s/cloud_configs", c.directorAddress), bytes.NewBuffer(yaml)) if err != nil { return err } request.Header.Set("Content-Type", "text/yaml") request.SetBasicAuth(c.username, c.password) response, err := c.httpClient.Do(request) if err != nil { return err } if response.StatusCode != http.StatusCreated { return fmt.Errorf("unexpected http response %d %s", response.StatusCode, http.StatusText(response.StatusCode)) } return nil } <file_sep>/aws/cloudformation/client.go package cloudformation import ( "github.com/aws/aws-sdk-go/aws/session" "github.com/cloudfoundry/bosh-bootloader/aws" awscloudformation "github.com/aws/aws-sdk-go/service/cloudformation" ) type Client interface { CreateStack(input *awscloudformation.CreateStackInput) (*awscloudformation.CreateStackOutput, error) UpdateStack(input *awscloudformation.UpdateStackInput) (*awscloudformation.UpdateStackOutput, error) DescribeStacks(input *awscloudformation.DescribeStacksInput) (*awscloudformation.DescribeStacksOutput, error) DeleteStack(input *awscloudformation.DeleteStackInput) (*awscloudformation.DeleteStackOutput, error) DescribeStackResource(input *awscloudformation.DescribeStackResourceInput) (*awscloudformation.DescribeStackResourceOutput, error) } func NewClient(config aws.Config) Client { return awscloudformation.New(session.New(config.ClientConfig())) } <file_sep>/bosh/vm_extensions_generator_test.go package bosh_test import ( "github.com/cloudfoundry/bosh-bootloader/bosh" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("VMExtensionsGenerator", func() { Describe("Generate", func() { It("returns cloud config vm extensions", func() { input := []bosh.LoadBalancerExtension{ { Name: "lb", ELBName: "some-lb", }, { Name: "another-lb", ELBName: "some-other-lb", SecurityGroups: []string{ "some-security-group", "some-other-security-group", }, }, } vmExtensions := bosh.NewVMExtensionsGenerator(input).Generate() Expect(vmExtensions).To(HaveLen(8)) Expect(vmExtensions).To(Equal([]bosh.VMExtension{ { Name: "5GB_ephemeral_disk", CloudProperties: bosh.VMExtensionCloudProperties{ EphemeralDisk: &bosh.VMExtensionEphemeralDisk{ Size: 5120, Type: "gp2", }, }, }, { Name: "10GB_ephemeral_disk", CloudProperties: bosh.VMExtensionCloudProperties{ EphemeralDisk: &bosh.VMExtensionEphemeralDisk{ Size: 10240, Type: "gp2", }, }, }, { Name: "50GB_ephemeral_disk", CloudProperties: bosh.VMExtensionCloudProperties{ EphemeralDisk: &bosh.VMExtensionEphemeralDisk{ Size: 51200, Type: "gp2", }, }, }, { Name: "100GB_ephemeral_disk", CloudProperties: bosh.VMExtensionCloudProperties{ EphemeralDisk: &bosh.VMExtensionEphemeralDisk{ Size: 102400, Type: "gp2", }, }, }, { Name: "500GB_ephemeral_disk", CloudProperties: bosh.VMExtensionCloudProperties{ EphemeralDisk: &bosh.VMExtensionEphemeralDisk{ Size: 512000, Type: "gp2", }, }, }, { Name: "1TB_ephemeral_disk", CloudProperties: bosh.VMExtensionCloudProperties{ EphemeralDisk: &bosh.VMExtensionEphemeralDisk{ Size: 1048576, Type: "gp2", }, }, }, { Name: "lb", CloudProperties: bosh.VMExtensionCloudProperties{ ELBS: []string{"some-lb"}, }, }, { Name: "another-lb", CloudProperties: bosh.VMExtensionCloudProperties{ ELBS: []string{"some-other-lb"}, SecurityGroups: []string{"some-security-group", "some-other-security-group"}, }, }, })) }) }) }) <file_sep>/aws/ec2/availability_zone_retriever_test.go package ec2_test import ( "errors" goaws "github.com/aws/aws-sdk-go/aws" awsec2 "github.com/aws/aws-sdk-go/service/ec2" "github.com/cloudfoundry/bosh-bootloader/aws/ec2" "github.com/cloudfoundry/bosh-bootloader/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("AvailabilityZoneRetriever", func() { var ( availabilityZoneRetriever ec2.AvailabilityZoneRetriever ec2Client *fakes.EC2Client ec2ClientProvider *fakes.ClientProvider ) BeforeEach(func() { ec2Client = &fakes.EC2Client{} ec2ClientProvider = &fakes.ClientProvider{} ec2ClientProvider.GetEC2ClientCall.Returns.EC2Client = ec2Client availabilityZoneRetriever = ec2.NewAvailabilityZoneRetriever(ec2ClientProvider) }) It("fetches availability zones for a given region", func() { ec2Client.DescribeAvailabilityZonesCall.Returns.Output = &awsec2.DescribeAvailabilityZonesOutput{ AvailabilityZones: []*awsec2.AvailabilityZone{ {ZoneName: goaws.String("us-east-1a")}, {ZoneName: goaws.String("us-east-1b")}, {ZoneName: goaws.String("us-east-1c")}, {ZoneName: goaws.String("us-east-1e")}, }, } azs, err := availabilityZoneRetriever.Retrieve("us-east-1") Expect(err).NotTo(HaveOccurred()) Expect(azs).To(ConsistOf("us-east-1a", "us-east-1b", "us-east-1c", "us-east-1e")) Expect(ec2Client.DescribeAvailabilityZonesCall.Receives.Input).To(Equal(&awsec2.DescribeAvailabilityZonesInput{ Filters: []*awsec2.Filter{{ Name: goaws.String("region-name"), Values: []*string{goaws.String("us-east-1")}, }}, })) }) Describe("failure cases", func() { It("returns an error when AWS returns a nil availability zone", func() { ec2Client.DescribeAvailabilityZonesCall.Returns.Output = &awsec2.DescribeAvailabilityZonesOutput{ AvailabilityZones: []*awsec2.AvailabilityZone{nil}, } _, err := availabilityZoneRetriever.Retrieve("us-east-1") Expect(err).To(MatchError("aws returned nil availability zone")) }) It("returns an error when an availability zone with a nil ZoneName", func() { ec2Client.DescribeAvailabilityZonesCall.Returns.Output = &awsec2.DescribeAvailabilityZonesOutput{ AvailabilityZones: []*awsec2.AvailabilityZone{{ZoneName: nil}}, } _, err := availabilityZoneRetriever.Retrieve("us-east-1") Expect(err).To(MatchError("aws returned availability zone with nil zone name")) }) It("returns an error when describe availability zones fails", func() { ec2Client.DescribeAvailabilityZonesCall.Returns.Error = errors.New("describe availability zones failed") _, err := availabilityZoneRetriever.Retrieve("us-east-1") Expect(err).To(MatchError("describe availability zones failed")) }) }) }) <file_sep>/aws/ec2/keypair_creator_test.go package ec2_test import ( "errors" goaws "github.com/aws/aws-sdk-go/aws" awsec2 "github.com/aws/aws-sdk-go/service/ec2" "github.com/cloudfoundry/bosh-bootloader/aws/ec2" "github.com/cloudfoundry/bosh-bootloader/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("KeyPairCreator", func() { var ( keyPairCreator ec2.KeyPairCreator ec2Client *fakes.EC2Client clientProvider *fakes.ClientProvider ) BeforeEach(func() { clientProvider = &fakes.ClientProvider{} ec2Client = &fakes.EC2Client{} clientProvider.GetEC2ClientCall.Returns.EC2Client = ec2Client keyPairCreator = ec2.NewKeyPairCreator(clientProvider) }) Describe("Create", func() { It("creates a new keypair on ec2", func() { ec2Client.CreateKeyPairCall.Returns.Output = &awsec2.CreateKeyPairOutput{ KeyFingerprint: goaws.String("some-fingerprint"), KeyMaterial: goaws.String("some-private-key"), KeyName: goaws.String("keypair-guid"), } keyPair, err := keyPairCreator.Create("keypair-some-env-id") Expect(err).NotTo(HaveOccurred()) Expect(keyPair.Name).To(Equal("keypair-some-env-id")) Expect(keyPair.PrivateKey).To(Equal("some-private-key")) Expect(ec2Client.CreateKeyPairCall.Receives.Input).To(Equal(&awsec2.CreateKeyPairInput{ KeyName: goaws.String("keypair-some-env-id"), })) }) Context("failure cases", func() { Context("when the create keypair request fails", func() { It("returns an error", func() { ec2Client.CreateKeyPairCall.Returns.Error = errors.New("failed to create keypair") _, err := keyPairCreator.Create("") Expect(err).To(MatchError("failed to create keypair")) }) }) }) }) }) <file_sep>/commands/delete_lbs.go package commands import ( "github.com/cloudfoundry/bosh-bootloader/bosh" "github.com/cloudfoundry/bosh-bootloader/flags" "github.com/cloudfoundry/bosh-bootloader/storage" ) const ( DeleteLBsCommand = "delete-lbs" ) type DeleteLBs struct { awsCredentialValidator awsCredentialValidator availabilityZoneRetriever availabilityZoneRetriever certificateManager certificateManager infrastructureManager infrastructureManager logger logger boshCloudConfigurator boshCloudConfigurator cloudConfigManager cloudConfigManager boshClientProvider boshClientProvider stateStore stateStore stateValidator stateValidator } type cloudConfigManager interface { Update(cloudConfigInput bosh.CloudConfigInput, boshClient bosh.Client) error } type deleteLBsConfig struct { skipIfMissing bool } func NewDeleteLBs(awsCredentialValidator awsCredentialValidator, availabilityZoneRetriever availabilityZoneRetriever, certificateManager certificateManager, infrastructureManager infrastructureManager, logger logger, boshCloudConfigurator boshCloudConfigurator, cloudConfigManager cloudConfigManager, boshClientProvider boshClientProvider, stateStore stateStore, stateValidator stateValidator, ) DeleteLBs { return DeleteLBs{ awsCredentialValidator: awsCredentialValidator, availabilityZoneRetriever: availabilityZoneRetriever, certificateManager: certificateManager, infrastructureManager: infrastructureManager, logger: logger, boshCloudConfigurator: boshCloudConfigurator, cloudConfigManager: cloudConfigManager, boshClientProvider: boshClientProvider, stateStore: stateStore, stateValidator: stateValidator, } } func (c DeleteLBs) Execute(subcommandFlags []string, state storage.State) error { config, err := c.parseFlags(subcommandFlags) if err != nil { return err } if config.skipIfMissing && !lbExists(state.Stack.LBType) { c.logger.Println("no lb type exists, skipping...") return nil } err = c.stateValidator.Validate() if err != nil { return err } err = c.awsCredentialValidator.Validate() if err != nil { return err } if err := checkBBLAndLB(state, c.boshClientProvider, c.infrastructureManager); err != nil { return err } azs, err := c.availabilityZoneRetriever.Retrieve(state.AWS.Region) if err != nil { return err } stack, err := c.infrastructureManager.Describe(state.Stack.Name) if err != nil { return err } cloudConfigInput := c.boshCloudConfigurator.Configure(stack, azs) cloudConfigInput.LBs = nil boshClient := c.boshClientProvider.Client(state.BOSH.DirectorAddress, state.BOSH.DirectorUsername, state.BOSH.DirectorPassword) err = c.cloudConfigManager.Update(cloudConfigInput, boshClient) if err != nil { return err } _, err = c.infrastructureManager.Update(state.KeyPair.Name, len(azs), state.Stack.Name, "", "", state.EnvID) if err != nil { return err } c.logger.Step("deleting certificate") err = c.certificateManager.Delete(state.Stack.CertificateName) if err != nil { return err } state.Stack.LBType = "none" state.Stack.CertificateName = "" err = c.stateStore.Set(state) if err != nil { return err } return nil } func (DeleteLBs) parseFlags(subcommandFlags []string) (deleteLBsConfig, error) { lbFlags := flags.New("delete-lbs") config := deleteLBsConfig{} lbFlags.Bool(&config.skipIfMissing, "skip-if-missing", "", false) err := lbFlags.Parse(subcommandFlags) if err != nil { return config, err } return config, nil } <file_sep>/boshinit/manifests/networks_manifest_builder.go package manifests type NetworksManifestBuilder struct{} func NewNetworksManifestBuilder() NetworksManifestBuilder { return NetworksManifestBuilder{} } func (r NetworksManifestBuilder) Build(manifestProperties ManifestProperties) []Network { return []Network{ { Name: "private", Type: "manual", Subnets: []Subnet{ { Range: "10.0.0.0/24", Gateway: "10.0.0.1", DNS: []string{"10.0.0.2"}, CloudProperties: NetworksCloudProperties{ Subnet: manifestProperties.SubnetID, }, }, }, }, { Name: "public", Type: "vip", }, } } <file_sep>/application/configuration_parser_test.go package application_test import ( "errors" "github.com/cloudfoundry/bosh-bootloader/application" "github.com/cloudfoundry/bosh-bootloader/fakes" "github.com/cloudfoundry/bosh-bootloader/storage" . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/extensions/table" . "github.com/onsi/gomega" ) var _ = Describe("ConfigurationParser", func() { var ( commandLineParser *fakes.CommandLineParser configurationParser application.ConfigurationParser ) BeforeEach(func() { commandLineParser = &fakes.CommandLineParser{} configurationParser = application.NewConfigurationParser(commandLineParser) application.SetGetState(func(dir string) (storage.State, error) { return storage.State{Version: 1}, nil }) }) AfterEach(func() { application.ResetGetState() }) Describe("Parse", func() { It("returns a configuration based on arguments provided", func() { commandLineParser.ParseCall.Returns.CommandLineConfiguration = application.CommandLineConfiguration{ Command: "up", SubcommandFlags: []string{"--some-flag", "some-value"}, StateDir: "some/state/dir", EndpointOverride: "some-endpoint-override", } configuration, err := configurationParser.Parse([]string{"up"}) Expect(err).NotTo(HaveOccurred()) Expect(configuration.Command).To(Equal("up")) Expect(configuration.SubcommandFlags).To(Equal(application.StringSlice{"--some-flag", "some-value"})) Expect(configuration.Global).To(Equal(application.GlobalConfiguration{ EndpointOverride: "some-endpoint-override", StateDir: "some/state/dir", })) Expect(commandLineParser.ParseCall.Receives.Arguments).To(Equal([]string{"up"})) }) Describe("state management", func() { It("returns a configuration with the state from the state store", func() { commandLineParser.ParseCall.Returns.CommandLineConfiguration = application.CommandLineConfiguration{ StateDir: "some/state/dir", Command: "up", } configuration, err := configurationParser.Parse([]string{}) Expect(err).NotTo(HaveOccurred()) Expect(configuration.State).To(Equal(storage.State{ Version: 1, })) }) DescribeTable("help, version, help flags does not try parse state", func(command string, subcommandFlags []string) { commandLineParser.ParseCall.Returns.CommandLineConfiguration = application.CommandLineConfiguration{ Command: command, SubcommandFlags: application.StringSlice(subcommandFlags), } application.SetGetState(func(dir string) (storage.State, error) { return storage.State{}, errors.New("State Error") }) _, err := configurationParser.Parse([]string{}) Expect(err).NotTo(HaveOccurred()) }, Entry("help", "help", []string{}), Entry("--help", "some-command", []string{"--help"}), Entry("-h", "some-command", []string{"-h"}), Entry("version", "version", []string{}), Entry("--version", "some-command", []string{"--version"}), Entry("-v", "some-command", []string{"-v"}), ) }) Context("failure cases", func() { It("returns an error when the command line cannot be parsed", func() { commandLineParser.ParseCall.Returns.Error = errors.New("failed to parse command line") _, err := configurationParser.Parse([]string{"some-command"}) Expect(err).To(MatchError("failed to parse command line")) }) It("returns an error when the state cannot be read", func() { application.SetGetState(func(dir string) (storage.State, error) { return storage.State{}, errors.New("failed to read state") }) _, err := configurationParser.Parse([]string{"some-command"}) Expect(err).To(MatchError("failed to read state")) }) }) }) })
ea483791b84f099e03327d95b9c33f472e7719ef
[ "Markdown", "Go", "Shell" ]
235
Go
ekcasey/bosh-bootloader
8f334c4fc2740e4114cef30e9b3320b61c36a25d
5426c8fb53d047455f058f8c046ce9be5fb9eb43
refs/heads/master
<repo_name>Inoeng85/pawoon_test<file_sep>/rest_client/application/views/template.php <div id="container"> <h1>REST Client Tests</h1> <h3>Accessing the REST Server Using the Curl Library</h3> <br/> <div id="body"> <h4><a href="<?php echo site_url('curl-test/get_users'); ?>">Testing a GET all user request</a></h4> <h4><a href="<?php echo site_url('curl-test/get_users/037a8f749f990fd51edd27f9bae8d36c:d3'); ?>">Testing a GET users/$1 request</a></h4> <h4><a href="<?php echo site_url('post-test'); ?>">Testing a POST request</a></h4> </div> <br/> </div> <div class="row"> <div class="col-md-9"> <div class="table-responsive"> <p> <button type="button" class="btn btn-primary btn-sm">Refresh</button> <a class="btn btn-default btn-sm" href="<?php echo site_url('rest_client/form_registrasi');?>" role="button">Form Registrasi</a> </p> <table class="table table-bordered table-striped"> <colgroup> <col class="col-md-3" /> <col class="col-md-3" /> <col class="col-md-3" /> </colgroup> <thead> <tr> <th>ID Customer</th> <th>Nama</th> <th>Alamat</th> </tr> </thead> <tbody> <?php foreach($response as $key=>$value){ ?> <tr> <th scope="row"> <?php echo $value['uuid'];?> </th> <td><?php echo $value['nama'];?></td> <td><?php echo $value['alamat'];?></td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds. <?php echo (ENVIRONMENT === 'development') ? 'CodeIgniter Version <strong>' . CI_VERSION . '</strong>' : '' ?></p> <file_sep>/rest_client/application/controllers/Post_test.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Post_test extends CI_Controller { public function index() { $this->load->helper('url'); $this->load->library('curl'); $rest_url = config_item('rest_server') . 'api/example/users/'; $this->render($rest_url); } public function render($rest_url) { // Optional, delete this line if your API is open. $username = 'admin'; $password = '<PASSWORD>'; $headers = array('Accept' => 'application/json'); $options = array('auth' => array('admin', '1234')); $data = array('nama' => 'John', 'alamat' => 'slipi'); $this->curl->create($rest_url); $this->curl->http_login($username, $password); $response = json_decode($this->curl->post($data)->execute(), TRUE); $data['response'] = $response; //var_dump($data);exit; $this->load->view('header'); $this->load->view('post_test', $data); $this->load->view('footer'); } } <file_sep>/rest_client/application/controllers/Curl_test.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Curl_test extends CI_Controller { public function index() { $this->load->helper('url'); $this->load->library('curl'); $rest_url = config_item('rest_server') . 'api/example/users/format/json'; $this->render($rest_url); } public function get_users($user_id = NULL) { $this->load->helper('url'); $this->load->library('curl'); if($user_id){ $rest_url = config_item('rest_server') . 'api/example/users/id/' . $user_id . '/format/json'; }else{ $rest_url = config_item('rest_server') . 'api/example/users/format/json'; } //var_dump($response);exit; $this->render($rest_url); } public function render($rest_url) { // Optional, delete this line if your API is open. $username = 'admin'; $password = '<PASSWORD>'; $this->curl->create($rest_url); $this->curl->http_login($username, $password); $response = json_decode($this->curl->get()->execute(), TRUE); $data['response'] = $response; //var_dump($data);exit; $this->load->view('header'); $this->load->view('curl_test', $data); $this->load->view('footer'); } } <file_sep>/rest_client/application/controllers/Rest_client.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Rest_client extends CI_Controller { public function index() { //echo "here";exit; $this->load->helper('url'); $this->load->library('curl'); $rest_url = config_item('rest_server') . 'api/example/users/format/json'; $this->render($rest_url); } public function render($rest_url) { // Optional, delete this line if your API is open. $username = 'admin'; $password = '<PASSWORD>'; $this->curl->create($rest_url); $this->curl->http_login($username, $password); $response = json_decode($this->curl->get()->execute(), TRUE); $data['response'] = $response; //var_dump($data);exit; $this->load->view('header'); $this->load->view('template', $data); $this->load->view('footer'); } public function form_registrasi() { //echo "here";exit; $this->load->helper('url'); $this->load->library('curl'); $data = null; //$data['count_user'] = 4; $this->load->view('header'); $this->load->view('form_registrasi', $data); $this->load->view('footer'); } public function simpan_form() { //echo "here";exit; $uid = $this->input->get_post('hash'); $nama = $this->input->get_post('nama'); $alamat = $this->input->get_post('alamat'); var_dump($uid);exit; $this->index(); } } <file_sep>/README.md # Pawoon : PHP Test App The test consist of creating an application to demonstrate knowledge of PHP & AJAX ## Requirements 1. PHP 5.4 or greater 2. CodeIgniter 3.0+ Scope 1: Backend Create a User Model with the following specifications: uuid: unique random Hash generated in scope 2: Front-End nama: unique, text alamat: text Create a RESTful service with JSON to interface with scope 2: Front-End Explanation: http://localhost/codeigniter/pawoon/rest_server/ this is an application for Web REST backend API Scope 2: Front-end Use JQuery & CSS framework (Bootstrap or Foundation or …) System Interface: All requests to be made with AJAX ID is a unique Hash auto generated (non-editable) Display alert to the user if the name is already used Single Page Form + content as follow: Explanation: http://localhost/codeigniter/pawoon/rest_client/ this is an application for Web REST client API as UI request Database dump: folder : schema/mysql/pawoon_test.sql (PDO ext) A fully RESTful server implementation for CodeIgniter using one library, one config file and one controller. ## Requirements 1. PHP 5.4 or greater 2. CodeIgniter 3.0+ <file_sep>/rest_client/application/views/curl_test.php <div id="container"> <h1>Accessing the REST Server Using the Curl Library</h1> <div id="body"> <h2><a href="<?php echo site_url(); ?>">Home</a></h2> <h3> Result: </h3> <code><pre><?php var_dump($response); ?></pre></code> <?php /* <h3> Debug Information: </h3> <?php $this->curl->debug(); ?> */ ?> </div> <p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds. <?php echo (ENVIRONMENT === 'development') ? 'CodeIgniter Version <strong>' . CI_VERSION . '</strong>' : '' ?></p> </div><file_sep>/rest_client/application/views/post_test.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <div id="container"> <h1>Testing a POST request</h1> <div id="body"> <h2><a href="<?php echo site_url(); ?>">Home</a></h2> <h2><a href="<?php echo site_url('rest-server'); ?>">Tests Home</a></h2> <h3> Result: </h3> <code><pre><?php var_dump($response); ?></pre></code> <h3> Status Code: </h3> <code><pre><?php echo html_escape($status_code); ?></pre></code> <h3> Content Type: </h3> <code><pre><?php echo html_escape($content_type); ?></pre></code> </div> <p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds. <?php echo (ENVIRONMENT === 'development') ? 'CodeIgniter Version <strong>' . CI_VERSION . '</strong>' : '' ?></p> </div> <file_sep>/schema/mysql/pawoon_test.sql /* Navicat MySQL Data Transfer Source Server : Local Source Server Version : 50624 Source Host : 127.0.0.1:3306 Source Database : pawoon_test Target Server Type : MYSQL Target Server Version : 50624 File Encoding : 65001 Date: 2016-05-31 04:28:11 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for tbl_users -- ---------------------------- DROP TABLE IF EXISTS `tbl_users`; CREATE TABLE `tbl_users` ( `uuid` varchar(255) NOT NULL, `nama` text NOT NULL, `alamat` text, PRIMARY KEY (`uuid`) ) ENGINE=MyISAM AUTO_INCREMENT=43 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of tbl_users -- ---------------------------- INSERT INTO `tbl_users` VALUES ('037a8f749f990fd51edd27f9bae8d36c:df', 'ibnu', 'jl.ultraviolet jakarta kelapa gading'); INSERT INTO `tbl_users` VALUES ('037a8f749f990fd51edd27f9bae8d36c:d3', 'hajar', 'kelapa gading timur, jakarta'); INSERT INTO `tbl_users` VALUES ('037a8f749f990fd51edd27f9bae8d36c:dd', 'inoeng', 'tanbora,jakarta selatan'); <file_sep>/rest_server/application/models/Users_model.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Users_Model extends CI_Model { /** * Constructor * * @access public * @return void */ public function __construct() { parent::__construct(); } /** * Get the manufacturers * * @access public * @return array */ public function get_users() { /* $result = $this->db ->select('uuid, nama, alamat') ->from('tbl_users') ->order_by('nama') ->get(); */ $result = $this->db->get('tbl_users'); if ($result->num_rows() > 0) { return $result->result_array(); } return NULL; } } /* End of file rest_model.php */ /* Location: ./system/models/rest_model.php */<file_sep>/rest_client/application/views/form_registrasi.php <div id="container"> <h1>Form Registrasi</h1> <div class="row"> <div class="col-md-6"> <form class="form-horizontal" action="<?php echo site_url('rest_client/simpan_form');?>" method="POST"> <div class="form-group"> <label for="txt_id" class="col-sm-2 control-label">ID</label> <div class="col-sm-10"> <input type="text" readonly class="form-control" id="txt_id" name="hash" value="<?php echo hash('md5', rand());?>"> </div> </div> <div class="form-group"> <label for="txt_nama" class="col-sm-2 control-label">Nama</label> <div class="col-sm-10"> <input type="text" class="form-control" id="txt_nama" name="nama" placeholder="Nama"> </div> </div> <div class="form-group"> <label for="txt_alamat" class="col-sm-2 control-label">Alamat</label> <div class="col-sm-10"> <input type="text" class="form-control" id="txt_alamat" placeholder="Alamat"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Simpan</button> </div> </div> </form> </div> </div> </div> <p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds. <?php echo (ENVIRONMENT === 'development') ? 'CodeIgniter Version <strong>' . CI_VERSION . '</strong>' : '' ?></p>
bef8721dd61c0d779bfadea645e9d7d2b2a31b69
[ "Markdown", "SQL", "PHP" ]
10
PHP
Inoeng85/pawoon_test
eca805ce787ae4a2a7450f10ba79569e4fcef849
52c79a86f7c5969e5901b82903611224709ba69a
refs/heads/master
<repo_name>mdunleavy0/Labyrinthine-Caves<file_sep>/Assets/Scripts/PosRot.cs using UnityEngine; public class PosRot { public Vector3 pos; public Quaternion rot; public PosRot(Vector3 pos, Quaternion rot) { this.pos = pos; this.rot = rot; } public static void DrawPosRot(PosRot pr) { Color save = Gizmos.color; Gizmos.color = Color.blue; Gizmos.DrawRay(pr.pos, pr.rot * Vector3.forward * 0.5f); Gizmos.color = Color.red; Gizmos.DrawRay(pr.pos, pr.rot * Vector3.right * 0.333f); Gizmos.color = Color.green; Gizmos.DrawRay(pr.pos, pr.rot * Vector3.up * 0.333f); Gizmos.color = save; } } <file_sep>/Assets/Scripts/Tunnel.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Tunnel : MonoBehaviour { public Vector3 start, end; public float ribDensity = 1; public float radius = 1; public int ribVertexC = 10; void Start() { GenMesh(); } public void GenMesh() { Mesh mesh = GetComponent<MeshFilter>().mesh; mesh.Clear(); PosRot[] vertebrae = GenVertebrae(); Vector3[][] ribs = GenRibs(vertebrae); mesh.vertices = GenVertices(ribs); mesh.triangles = GenTriangles(ribs); mesh.RecalculateNormals(); } PosRot[] GenVertebrae() { Quaternion rot = Quaternion.LookRotation(end - start, Vector3.up); float len = Vector3.Distance(start, end); int segmentC = Mathf.CeilToInt(len * ribDensity); int vertebraC = segmentC + 1; PosRot[] vertebrae = new PosRot[vertebraC]; for (int i = 0; i < vertebraC; i++) vertebrae[i] = new PosRot( Vector3.Lerp(start, end, (float) i / segmentC), rot); return vertebrae; } Vector3[][] GenRibs(PosRot[] vertebrae) { Vector3[][] ribs = new Vector3[vertebrae.Length][]; for (int i = 0; i < vertebrae.Length; i++) { ribs[i] = new Vector3[ribVertexC]; for (int j = 0; j < ribVertexC; j++) { float theta = 360f * j / ribVertexC; Quaternion rot = vertebrae[i].rot * Quaternion.Euler(0, 0, theta); ribs[i][j] = vertebrae[i].pos + rot * Vector3.right * radius; } } return ribs; } Vector3[] GenVertices(Vector3[][] ribs) { Vector3[] vertices = new Vector3[ribs.Length * ribVertexC]; for (int i = 0; i < ribs.Length; i++) ribs[i].CopyTo(vertices, i * ribVertexC); return vertices; } int[] GenTriangles(Vector3[][] ribs) { int ribC = ribs.Length; int quadC = (ribC - 1) * ribVertexC; int triangleC = 2 * quadC; int[] triangles = new int[3 * triangleC]; int Index(int ribIdx, int ribVertexIdx) { return ribIdx * ribVertexC + ribVertexIdx % ribVertexC; } for (int i = 0, t = 0; i < ribC - 1; i++) { for (int j = 0; j < ribVertexC; j++) { triangles[t++] = Index(i, j); triangles[t++] = Index(i + 1, j); triangles[t++] = Index(i + 1, j + 1); triangles[t++] = Index(i, j); triangles[t++] = Index(i + 1, j + 1); triangles[t++] = Index(i, j + 1); } } return triangles; } } <file_sep>/README.md # Labyrinthine-Caves Procedural generation of labyrinthine caves (TU Dublin Game Engines 1 CA) ## Description The aim is to create a maze in the from of an organic cave-system in the [Unity3D](https://unity.com/) game engine. By organic I mean, lacking 90º angles and other man-made geometric traits. ## Background Mark et al. (TODO:CITE:mark15procedural) set out a methodology for cave generation in 3 steps: 1. Generate a structural skeleton using a [L-system](https://en.wikipedia.org/wiki/L-system). 2. Build tunnels around the skeleton using [voxels](https://en.wikipedia.org/wiki/Voxel). 3. Generate a mesh from the voxels. L-systems won't produce maze like structures (which the authors do somewhat address). However steps 2 & 3 remain pertinent should I provide an alternatively sourced skeleton. ![Mark et al.'s L-system derived cave structures.](Figures/mark15procedural-fig3b.png) ***Fig. 1** Mark et al.'s L-system derived cave structures. Suitably organic but lacking a maze structure.* The alternative skeletal structure I have in mind is that of a graph-based maze. The advantage of graph-based maze is its organic form compared to conventional rectangular mazes. Fotlin (TODO:CITE:foltin11automated) provides an overview of maze generation techniques with a preference for graph-based approaches. ![Animation of graph-based maze generation (Source: Wikipedia)](Figures/graph-maze.gif) ***Fig. 2** Animation of graph-based maze generation. (Source: Wikipedia)* The official [Unity tutorials](https://learn.unity.com/tutorials) host a series on cave generation (TODO:CITE:lague15procedural) using [cellular automata](https://en.wikipedia.org/wiki/Cellular_automaton). This is seemingly based on of a paper by <NAME> al. (TODO:CITE:johnson10cellular). This approach generates a cavernous layout on a grid and applies the [marching squares](https://en.wikipedia.org/wiki/Marching_squares) algorithm to generate contours for a mesh. Whilst the tutorial simply extrudes the 2D layout outward to create a 3D space; it should be possible to generate a 3D voxel grid and apply the marching cubes algorithm. Pech et al. (TODO:CITE:pech15evolving) build upon the work of Johnson et al. to produce "layouts with desired maze-like properties". ## Approach My approach will be to: 1. Generate a graph. Edges will represent tunnels, vertices will be intersections. The graph will need to meet certain criteria such as [planarity](https://en.wikipedia.org/wiki/Planar_graph) and a minimum spacing between vertices. 2. Generate a maze from the graph. This will likely be in the form of a spanning tree of the graph. 3. Generate tunnel outlines in voxels around the graph edges. 4. Generate a mesh from the voxel data. One additional avenue to explore is that of verticality. A 3-dimensional graph and maze could be generated. However, for the purposes of a game, the maze should be traversable by a gravity-bound player avatar. The maze would need to be culled of any tunnels that are too steep for a player to realistically climb. The emphasis of this proposal is on the generation of the cave structure rather than the presentation of caves themselves. ## Bibliography (TODO: bibliography) Just look in the biblatex file [ca.bib](ca.bib), until I get around to marking this up. <file_sep>/Assets/Scripts/GridGraph.cs using System; using UnityEngine; using Random = System.Random; public class GridGraph : Graph { public GridGraph(int rowC, int colC, float gap, Vector3 pos, float randomness, Random rng) { Vector3 corner = pos; corner.x -= 0.5f * colC * gap; corner.z -= 0.5f * rowC * gap; // add vertices var grid = new Vertex[rowC, colC]; for (int r = 0; r < rowC; r++) { float z = corner.z + r * gap; for (int c = 0; c < colC; c++) { float x = corner.x + c * gap; var vx = new Vertex(x, corner.y, z); vx.x += randomness * ((float) rng.NextDouble() - 0.5f); vx.y += randomness * ((float) rng.NextDouble() - 0.5f); vx.z += randomness * ((float) rng.NextDouble() - 0.5f); Debug.Log($"Adding {vx}"); grid[r, c] = vx; Add(vx); } } // add edges for (int r = 0; r < rowC; r++) for (int c = 0; c < colC; c++) { if (r < rowC - 1) Add(new Edge(grid[r, c], grid[r+1, c])); if (c < colC - 1) Add(new Edge(grid[r, c], grid[r, c+1])); } } } <file_sep>/Assets/Scripts/Labyrinth.cs using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using Random = System.Random; public class Labyrinth : MonoBehaviour { public string seed = "Knossos"; public int rowC = 8; public int colC = 10; public float gap = 10; public float randomness = 2; public GameObject tunnelPrefab; Random rng; Graph graph; void Start() { rng = new Random(seed.GetHashCode()); graph = new GridGraph(rowC, colC, gap, transform.position, randomness, rng); GameObject tunnelDir = new GameObject("Tunnels"); tunnelDir.transform.parent = transform; foreach (Graph.Edge edge in graph.edges) { GameObject tunnel = Instantiate(tunnelPrefab, tunnelDir.transform); Tunnel tunnelMB = tunnel.GetComponent<Tunnel>(); tunnelMB.start = edge.a.ToVector3(); tunnelMB.end = edge.b.ToVector3(); tunnelMB.GenMesh(); } } void OnDrawGizmos() { if (graph != null) { foreach (var vx in graph.vertices) Gizmos.DrawWireSphere(vx.ToVector3(), 0.5f); foreach (var ed in graph.edges) Gizmos.DrawLine(ed.a.ToVector3(), ed.b.ToVector3()); } } } <file_sep>/Assets/Scripts/Graph.cs using System; using System.Collections.Generic; using UnityEngine; public class Graph { public HashSet<Vertex> vertices = new HashSet<Vertex>(); public HashSet<Edge> edges = new HashSet<Edge>(); public void Add(Vertex v) { if (vertices.Contains(v)) throw new ArgumentException( $"Vertex {v} already in graph."); vertices.Add(v); } public void Add(Edge e) { if (!vertices.Contains(e.a)) throw new ArgumentException( $"Vertex {e.a} not in graph."); else if (!vertices.Contains(e.b)) throw new ArgumentException( $"Vertex {e.b} not in graph."); edges.Add(e); } public class Vertex { public float x, y, z; public Vertex(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } public Vertex(Vector3 vec) { x = vec.x; y = vec.y; z = vec.z; } override public bool Equals(object obj) { if (obj == null || ! GetType().Equals(obj.GetType())) return false; else { var that = (Vertex) obj; return x == that.x && y == that.y && z == that.z; } } public Vector3 ToVector3() { return new Vector3(x, y, z); } override public string ToString() { return $"({x}, {y}, {z})"; } } public class Edge { public Vertex a, b; public Edge(Vertex a, Vertex b) { this.a = a; this.b = b; } public Edge(Vector3 a, Vector3 b) { this.a = new Vertex(a); this.b = new Vertex(b); } override public bool Equals(object obj) { if (obj == null || ! GetType().Equals(obj.GetType())) return false; else { var that = (Edge) obj; return (a.Equals(that.a) && b.Equals(that.b)) || (a.Equals(that.b) && b.Equals(that.a)); } } override public string ToString() { return $"({a}, {b})"; } } }
4330b85d1c2b322cc25d4e1b571811624a3cc8c6
[ "Markdown", "C#" ]
6
C#
mdunleavy0/Labyrinthine-Caves
c54e6c4bf52fae6161cd6223721200b67dab6652
7794bef686582e477e47bbbc7f7bf9e60a4c36ca
refs/heads/master
<file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System.Collections.Generic; using System; using System.Linq; namespace KazooQuestCS { public class World { public Tile[,] Tiles; private List<WeakReference<Tile>> nonFloorTiles; const int playerMoveDistance = Main.tileSize / 10; public bool Active { get; set; } public World() { Tiles = new Tile[Main.totalMapSize, Main.totalMapSize]; nonFloorTiles = new List<WeakReference<Tile>>(); } public void Initialize() { for (int x = 0; x < Main.totalMapSize; ++x) { for (int y = 0; y < Main.totalMapSize; ++y) { switch (Main.random.Next(15)) { case 1: Tiles[x, y] = new Tile(new Vector2(x, y), "Tiles/Rock1"); Tiles[x, y].IsPassable = false; nonFloorTiles.Add(new WeakReference<Tile>(Tiles[x, y])); break; case 14: Tiles[x, y] = new Tile(new Vector2(x, y), "Tiles/Grass1"); Tiles[x, y].Enemy = new Enemy(); break; default: Tiles[x, y] = new Tile(new Vector2(x, y), "Tiles/Grass1"); break; } } } } public void Update(GameTime gameTime) { if (!Active) return; foreach (WeakReference<Tile> tileRef in nonFloorTiles) { Tile tile; tileRef.TryGetTarget(out tile); if(tile != null) if(tile.CollisionBox.Intersects(Main.player.CollisionBox)) { Rectangle collision = Rectangle.Intersect(tile.CollisionBox, Main.player.CollisionBox); if (collision.Width == collision.Height) { // TODO: Detect player movement direction and offset negative if(Main.KeyDown(Keys.D) || Main.KeyDown(Keys.W)) Main.player.CollisionBox.Offset(playerMoveDistance, -playerMoveDistance); if (Main.KeyDown(Keys.A) || Main.KeyDown(Keys.S)) Main.player.CollisionBox.Offset(-playerMoveDistance, playerMoveDistance); } if (collision.Width <= collision.Height) { int colX = collision.Center.X - tile.CollisionBox.Center.X; if (colX <= 0) Main.player.CollisionBox.X -= collision.Width; else Main.player.CollisionBox.X += collision.Width; } else { int colY = collision.Center.Y - tile.CollisionBox.Center.Y; if (colY <= 0) Main.player.CollisionBox.Y -= collision.Height; else Main.player.CollisionBox.Y += collision.Height; } } } } public void Draw(SpriteBatch spriteBatch) { if (!Active) return; int xPos = Main.player.CollisionBox.X / Main.tileSize; int yPos = Main.player.CollisionBox.Y / Main.tileSize; for (int x = xPos - Main.maxVisibleTiles / 2; x < xPos + Main.maxVisibleTiles; ++x) { if (x < 0 || x > Main.totalMapSize - 1) continue; for (int y = yPos - Main.maxVisibleTiles / 2; y < yPos + Main.maxVisibleTiles; ++y) { if (y < 0 || y > Main.totalMapSize - 1) continue; Tiles[x, y].Draw(spriteBatch); } } /* * This was a really bad method for drawing, as it drew stuff that wasn't even visible foreach (Tile tile in Tiles) tile.Draw(spriteBatch);*/ } } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System.Collections.Generic; using System; using KazooQuestCS; namespace KazooQuestCS.GUI { public class HUD { public bool Active { get; set; } public HUD(bool active = true) { Active = active; } public void Update(GameTime gameTime) { } public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(Main.TextureStore["Pixel"], new Rectangle(0, 0, spriteBatch.GraphicsDevice.Viewport.Width, spriteBatch.GraphicsDevice.Viewport.Height / 10), Color.Black); /*spriteBatch.Draw(Main.TextureStore["Pixel"], new Rectangle(0, 0, spriteBatch.GraphicsDevice.Viewport.Width / 20, spriteBatch.GraphicsDevice.Viewport.Height), Color.Black); spriteBatch.Draw(Main.TextureStore["Pixel"], new Rectangle((spriteBatch.GraphicsDevice.Viewport.Width / 20) * 19, 0, spriteBatch.GraphicsDevice.Viewport.Width / 20, spriteBatch.GraphicsDevice.Viewport.Height), Color.Black); spriteBatch.Draw(Main.TextureStore["Pixel"], new Rectangle(0, (spriteBatch.GraphicsDevice.Viewport.Height / 20) * 19, spriteBatch.GraphicsDevice.Viewport.Width, spriteBatch.GraphicsDevice.Viewport.Height / 20), Color.Black);*/ } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Graphics; namespace KazooQuestCS.GUI { class MainMenu : Menu { public MainMenu() { Add("Start Game", Start); Add("Exit", Main.self.Exit); Active = true; } private void Start() { Active = false; Main.player.Active = true; Main.world.Active = true; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace KazooQuestCS { public class Stats { private int level = -1; private int hp; private int maxHP; private int mp; private int maxMP; private int stamina; private int maxStamina; private int str; private int def; private int res; private int spd; private bool statsSet = false; public string name; public Stats() { } public void Set(int _level, int _maxHP, int _maxMP, int _maxStamina, int _str, int _def, int _res) { if (statsSet) return; level = _level; maxHP = _maxHP; maxMP = _maxMP; maxStamina = _maxStamina; str = _str; def = _def; res = _res; statsSet = true; } public void FromXml(XmlNode node) { for(int x=0; x < node.ChildNodes.Count; ++x) { switch(node.ChildNodes[x].Name) { case "name": name = node.ChildNodes[x].InnerText; break; case "level": level = int.Parse(node.ChildNodes[x].InnerText); break; case "hp": maxHP = int.Parse(node.ChildNodes[x].InnerText); hp = maxHP; break; case "mana": maxMP = int.Parse(node.ChildNodes[x].InnerText); mp = maxMP; break; case "stamina": maxStamina = int.Parse(node.ChildNodes[x].InnerText); stamina = MaxStamina; break; case "str": str = int.Parse(node.ChildNodes[x].InnerText); break; case "def": def = int.Parse(node.ChildNodes[x].InnerText); break; case "res": res = int.Parse(node.ChildNodes[x].InnerText); break; case "spd": spd = int.Parse(node.ChildNodes[x].InnerText); break; } } } public int Level { get { return level; } } public int HP { get { return hp; } set { hp = value; } } public int MaxHP { get { return maxHP; } } public int MP { get { return mp; } set { mp = value; } } public int MaxMP { get { return maxMP; } } public int Stamina { get { return stamina; } set { stamina = value; } } public int MaxStamina { get { return maxStamina; } } public int Str { get { return str; } set { str = value; } } public int Def { get { return def; } set { def = value; } } public int Res { get { return res; } set { res = value; } } public int Spd { get { return spd; } set { spd = value; } } } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System.Collections.Generic; using System; namespace KazooQuestCS { public class Player { private Stats stats; public Stats Stats { get { return stats; } } public Texture2D Texture { get { return Main.TextureStore[Main.Textures["player"]]; } } public Rectangle CollisionBox; public Rectangle OldCollisionBox; public Vector2 TilePosition { get; } public string Name { get; } public int Height { get { return Texture.Height; }} public int Width { get {return Texture.Width; }} public bool Active { get; set; } public Player() { TilePosition = new Vector2(0, 0); CollisionBox = new Rectangle((Main.windowSize - Main.tileSize) / 2, (Main.windowSize - Main.tileSize) / 2, Main.tileSize, Main.tileSize); OldCollisionBox = CollisionBox; } public void Create(string name, int _class) { stats = new Stats(); stats.Set(1, 100, 10, 10, 1, 0, 0); } public void Update(GameTime gameTime) { if (!Active) return; CollisionBox.X = MathHelper.Clamp(CollisionBox.X, 0, (Main.totalMapSize - 1) * Main.tileSize); CollisionBox.Y = MathHelper.Clamp(CollisionBox.Y, 0, (Main.totalMapSize - 1) * Main.tileSize); } public void Draw(SpriteBatch spriteBatch) { if (!Active) return; spriteBatch.Draw(Texture, CollisionBox, Color.White); } private void CheckValidTile() { } } } <file_sep>using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KazooQuestCS { public class AnimationManager { private List<Animation> animations; public AnimationManager() { animations = new List<Animation>(); } public void AddAnimation(Animation anim) { animations.Add(anim); } public void Update(GameTime gameTime) { foreach(Animation anim in animations) { anim.Update(gameTime); } } } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System.Collections.Generic; using System; using KazooQuestCS.GUI; namespace KazooQuestCS { public class Menu : IDisposable { public string Title; Texture2D Background; SpriteFont Font; Rectangle Position; public bool Active { get; set; } public short Selected = 0; private Vector2 _base; private Vector2 _pos; public List<Button> Items = new List<Button>() {}; public void Dispose() { Active = false; Items.Clear(); if(Background != null) Background.Dispose(); } public Menu() { _base.X = Main.windowSize / 5; _base.Y = Main.windowSize / 5; Background = new Texture2D(Main.graphicsDevice, (Main.windowSize / 5) * 4, (Main.windowSize / 5) * 4); } public void Add(string name, Action action, int type = 0, string text = "") { Button b = new Button(name, type, text); if (text == "") text = name; b.Initialize(action); b.Position.X = _base.X; b.Position.Y = _base.Y + ((Background.Height / 10) * Items.Count); Items.Add(b); } public void Update(GameTime gameTime) { if (!Active) return; Selected = (short)MathHelper.Clamp(Selected, 0, Items.Count - 1); } public void Draw(SpriteBatch spriteBatch) { if (!Active) return; spriteBatch.Draw(Background, Position, Color.White); _pos = _base; for (int i = 0; i < Items.Count; i++) { Items[i].Draw(spriteBatch, Font); } _pos.X -= Main.graphicsDevice.Viewport.Width / 8; _pos.Y += ((Background.Height / 10) * Selected); spriteBatch.DrawString(Main.Fonts["Arial"], ">>", _pos, Color.DarkGreen); } } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System.Collections.Generic; using System; using KazooQuestCS.GUI; namespace KazooQuestCS.GUI { class PauseMenu : Menu { public PauseMenu() { Title = "PauseMenu"; Active = false; Add("Resume", Resume); Add("Exit", Main.self.Exit); Main.Pause = Pause; } public void Pause() { Main.player.Active = false; Main.world.Active = false; Active = true; } private void Resume() { Active = false; // TODO: check to see if this is abusable Main.player.Active = true; Main.world.Active = true; } } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace KazooQuestCS { public class Animation { private int Frame; private int Frames = -1; private string Name; private Regex reg; private int Delay; private int delayLoop = 0; public string TextureName { get { return string.Format("{0}{1}", Name, Frame); } } public Animation( string name, int delay = 0, int frameCount = -1) { reg = new Regex(name + @"\d{1,}"); if (frameCount == -1) { foreach (KeyValuePair<string, Texture2D> entry in Main.TextureStore) { if (reg.Match(entry.Key).Success) { Frames++; } } } else { Frames = frameCount - 1; } Name = name; Delay = delay; } public void Update(GameTime gameTime) { if (Delay == 0) { Frame++; if (Frame > Frames) Frame = 0; UpdateTexture(); return; } delayLoop++; if (delayLoop >= Delay) { delayLoop = 0; Frame++; if (Frame >= Frames) Frame = 0; UpdateTexture(); } } public void UpdateTexture() { Main.Textures[Name] = TextureName; } } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System.Collections.Generic; using System; namespace KazooQuestCS { public class Tile { public Texture2D Texture = new Texture2D(Main.graphicsDevice, Main.tileSize, Main.tileSize); public Vector2 Offset; public Rectangle Position; public Color Color; Enemy Enemy; public bool Passable = true; public Tile(Vector2 offset, Color color) { Offset = offset; Position = new Rectangle((int)offset.X * Main.tileSize, (int)offset.Y * Main.tileSize, Main.tileSize, Main.tileSize); Color = color; SetColor(); } private void SetColor() { Color[] data = new Color[Texture.Width * Texture.Height]; Texture.GetData(data); for (int x = 0; x < data.Length; ++x) { data[x] = Color; } Texture.SetData(data); } public void SetEnemy(Enemy enemy) { Enemy = enemy; } public void Update(GameTime gameTime) { if (Enemy != null) { Random rnd = new Random(Guid.NewGuid().GetHashCode()); int move = rnd.Next(1, 4); int offX = (int)Offset.X; int offY = (int)Offset.Y; switch (move) { case 1: if (Offset.X > 0) offX--; else offX++; break; case 2: if (Offset.X < Main.totalMapSize - 1) offX++; else offX--; break; case 3: if (Offset.Y > 0) offY--; else offY++; break; case 4: if (Offset.Y < Main.totalMapSize - 1) offY++; else offY--; break; } Tile tile = Main.world.GetTileByOffset(offX, offY); if (tile.Enemy == null && tile.Passable) { tile.SetEnemy(Enemy); Enemy = null; } } } public void Draw(SpriteBatch spriteBatch, bool aaa = false) { Vector2 pos = new Vector2((Main.world.CameraPosition.X + Offset.X) * Main.tileSize, (Main.world.CameraPosition.Y + Offset.Y) * Main.tileSize); spriteBatch.Draw(Texture, pos, Color); /*if (Enemy != null) { pos.X += (Main.tileSize / 4); pos.Y += (Main.tileSize / 4); spriteBatch.DrawString(Main.font, string.Format("!"), pos, Color.Red); }*/ //if(Main.font != null) // spriteBatch.DrawString(Main.font, string.Format("{0},{1}", Offset.X, Offset.Y), pos, Color.White); } } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KazooQuestCS { class Room { Vector2 Position; public Texture2D Texture = new Texture2D(Main.graphicsDevice, Main.tileSize, Main.tileSize); public bool Visible = true; Tile[,] Tiles; public Enemy Enemy; private int _xtiles; private int _ytiles; public Room(Vector2 position) { Random rnd = new Random(GetHashCode()); if(rnd.Next(5) == 1) Enemy = new Enemy(); Position = position; _xtiles = Main.graphicsDevice.Viewport.Width / Main.tileSize; _ytiles = Main.graphicsDevice.Viewport.Height / Main.tileSize; Tiles = new Tile[_xtiles, _ytiles]; Color[] data = new Color[Texture.Width * Texture.Height]; Texture.GetData(data); // This is ungodly ugly for (int x = 0; x < data.Length; ++x) { if (Enemy != null) data[x] = Color.Red; else data[x] = Color.Black; } Texture.SetData(data); } public void Draw(SpriteBatch spriteBatch) { if (!Visible) return; spriteBatch.Draw(Texture, Position, Color.White); } } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System.Collections.Generic; using System; namespace KazooQuestCS.GUI { enum ButtonType { basic = 0, // Calls a function toggle = 1, // Changes a setting thing submenu = 2, // Opens another menu back = 3 // Goes back from a submenu } public class Button { public Vector2 Position; public string Name; public string Text; public int Type { get; } protected Action _Call = null; public Button(string name, int type, string text = "") { Name = name; Type = type; if (text == "") Text = name; else Text = text; } public void Initialize(Action call) { _Call = call; } public void Call() { _Call(); } public void Update() { } public void Draw(SpriteBatch spriteBatch, SpriteFont font) { if(Main.Fonts != null) spriteBatch.DrawString(Main.Fonts["Arial"], Text, Position, Color.Black); } } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System.Collections.Generic; using System; using System.Xml; namespace KazooQuestCS { public class Enemy { Texture2D Texture; Vector2 Position; Stats Stats = new Stats(); public Enemy() { int level = 1; if (Main.player.Stats != null) { level = Main.player.Stats.Level; } XmlNodeList enemies = Main.Enemies.SelectNodes(string.Format("/Enemies/Enemy[level > {0} and level < {1}]", level - 3, level + 3)); Random rnd = new Random(GetHashCode()); int _index = rnd.Next(enemies.Count); Stats.FromXml(enemies[_index]); if (Stats.name != "Wolf") { Texture = new Texture2D(Main.graphicsDevice, Main.tileSize / 2, Main.tileSize / 2); Color[] data = new Color[Texture.Width * Texture.Height]; Texture.GetData(data); for (int x = 0; x < data.Length; ++x) { int r = rnd.Next(256); int g = rnd.Next(256); int b = rnd.Next(256); data[x] = new Color(r, g, b); } Texture.SetData(data); } else { Texture = Main.TextureStore["wolf1"]; } } public void StartFight() { Main.world.Active = false; } public void Update() { } public void Draw(SpriteBatch spriteBatch) { } } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KazooQuestCS { public class Tile { public bool IsPassable { get; set; } public Rectangle CollisionBox; public Vector2 TilePosition; public Enemy Enemy; private string Texture; private WeakReference<Tile> tileUp = null; private WeakReference<Tile> tileDown = null; private WeakReference<Tile> tileLeft = null; private WeakReference<Tile> tileRight = null; public Tile(Vector2 tilePosition, string textureName) { TilePosition = tilePosition; Texture = textureName; CollisionBox = new Rectangle((int)TilePosition.X * Main.tileSize, (int)TilePosition.Y * Main.tileSize, Main.tileSize, Main.tileSize); int x = (int)tilePosition.X; int y = (int)tilePosition.Y; if (tilePosition.X > 0) tileLeft = new WeakReference<Tile>(Main.world.Tiles[x - 1, y]); if (tilePosition.X < Main.totalMapSize - 1) tileRight = new WeakReference<Tile>(Main.world.Tiles[x + 1, y]); if (tilePosition.Y > 0) tileUp = new WeakReference<Tile>(Main.world.Tiles[x, y - 1]); if (tilePosition.Y < Main.totalMapSize - 1) tileDown = new WeakReference<Tile>(Main.world.Tiles[x, y + 1]); } public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(Main.TextureStore[Texture], CollisionBox, Color.Gray); if(Enemy != null) { Enemy.Draw(spriteBatch); } } } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KazooQuestCS { public class InputManager { const int playerMoveDistance = Main.tileSize / 10; public void Update(GameTime gameTime) { MenuInput(); PlayerInput(); } private void MenuInput() { foreach (Menu menu in Main.menus) { if (menu.Title == "PauseMenu" && Main.KeyPush(Keys.Escape)) Main.Pause(); if (!menu.Active) continue; if (Main.KeyPush(Keys.W)) menu.Selected -= 1; if (Main.KeyPush(Keys.S)) menu.Selected += 1; if (Main.KeyPush(Keys.Enter)) { menu.Items[menu.Selected].Call(); if (menu.Items[menu.Selected].Type != 1) menu.Active = false; } } } private void PlayerInput() { if (!Main.player.Active) return; if (Main.currKeyboard.GetPressedKeys().Length > 0) Main.player.OldCollisionBox = Main.player.CollisionBox; else return; if (Main.KeyDown(Keys.A)) Main.player.CollisionBox.X -= playerMoveDistance; if (Main.KeyDown(Keys.D)) Main.player.CollisionBox.X += playerMoveDistance; if (Main.KeyDown(Keys.W)) Main.player.CollisionBox.Y -= playerMoveDistance; if (Main.KeyDown(Keys.S)) Main.player.CollisionBox.Y += playerMoveDistance; } } } <file_sep>using KazooQuestCS.GUI; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; using System; using System.Collections.Generic; using System.IO; using System.Xml; namespace KazooQuestCS { /// <summary> /// This is the main type for your game. /// </summary> public class Main : Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; InputManager inputManager; Camera camera; public const int tileSize = 32; public const int windowSize = 480; public const int maxVisibleTiles = windowSize / tileSize; public const int totalMapSize = maxVisibleTiles * 15; public static Dictionary<string, SpriteFont> Fonts; public static List<Menu> menus; public static Player player; public static World world; public static HUD hud; public static GraphicsDevice graphicsDevice; public static XmlDocument Enemies; public static Dictionary<string, Texture2D> TextureStore; public static Dictionary<string, string> Textures; public static AnimationManager AManager; // Because workarounds public static Action Pause; public static Random random = new Random(Guid.NewGuid().GetHashCode()); public static KeyboardState currKeyboard; public static KeyboardState prevKeyboard; public static bool KeyPush(Keys key) { if( currKeyboard.IsKeyDown(key) && !prevKeyboard.IsKeyDown(key)) { return true; } else { return false; } } public static bool KeyDown(Keys key) { return currKeyboard.IsKeyDown(key); } // Praise the Stack https://stackoverflow.com/a/29089475 public static Main self; public Main() { self = this; graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = windowSize; graphics.PreferredBackBufferHeight = windowSize; graphics.ApplyChanges(); Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { graphicsDevice = GraphicsDevice; Fonts = new Dictionary<string, SpriteFont>(); Enemies = new XmlDocument(); menus = new List<Menu>(); TextureStore = new Dictionary<string, Texture2D>(); Textures = new Dictionary<string, string>(); AManager = new AnimationManager(); Rectangle menuRect = new Rectangle(100, 100, windowSize - 100, windowSize - 100); menus.Add(new MainMenu()); menus.Add(new PauseMenu()); inputManager = new InputManager(); camera = new Camera(graphicsDevice.Viewport); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); Enemies.Load("Data/Enemies.xml"); List<string> graphicsFiles = new List<string>() { "player0", "player1", "player2", "player3", "player4", "player5", "Tiles/Grass1", "Tiles/Rock1", "wolf1" }; foreach (string file in graphicsFiles) { Texture2D texture = Content.Load<Texture2D>(string.Format("Graphics/{0}", file)); TextureStore.Add(file, texture); } Texture2D pixel = new Texture2D(graphicsDevice, 1, 1); pixel.SetData(new[] { Color.White }); TextureStore.Add("Pixel", pixel); Textures.Add("player", "player0"); player = new Player(); Animation playerAnim = new Animation("player", 10); AManager.AddAnimation(playerAnim); world = new World(); world.Initialize(); hud = new HUD(); SpriteFont font = Content.Load<SpriteFont>("Graphics/Arial"); Fonts.Add("Arial", font); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// game-specific content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here Content.Unload(); } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { prevKeyboard = currKeyboard; currKeyboard = Keyboard.GetState(); inputManager.Update(gameTime); AManager.Update(gameTime); foreach (Menu menu in menus) { menu.Update(gameTime); } player.Update(gameTime); world.Update(gameTime); base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.White); // Relative elements spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, camera.TransformMatrix); world.Draw(spriteBatch); player.Draw(spriteBatch); spriteBatch.End(); // Absolute elements spriteBatch.Begin(); foreach (Menu menu in menus) { menu.Draw(spriteBatch); } hud.Draw(spriteBatch); spriteBatch.End(); base.Draw(gameTime); } } }
91acf3f2b36c2226545ab12da28e44912796250a
[ "C#" ]
16
C#
Awoonar/KazooSharp
bd3deffe5298872344b1903356733017dbdbce33
f96351d2e2e16faee1cac2fe5adc5e061a9b1a04
refs/heads/master
<file_sep>var work = { "jobs":[ { "employer": "Frontier", "title": "sys admin", "location": "Gresham, OR", "dates": "Apr 2016 - Present", "description": "troubleshoot and extend application" }, { "employer": "Verizon", "title": "contract admin", "location": "Thousand Oaks, CA", "dates": "Dec 2004 - Apr 2016", "description": "inform employees on proper use of contractor resources" } ] }; var projects = { "projects": [ { "title": "cat-a-log", "dates": "Oct 2012", "description": "database of items with categories and images", "images": [ "http://www.gettyimages.com/detail/978043334" ] } ] }; var bio = { "name": "<NAME>", "role": "developer", "welcomeMessage": "Hello, World", "biopic": "Looking for a coding job", "contacts": { "mobile": "555-555-1234", "email": "<EMAIL>", "github": "gitUser", "location": "Portland, OR" }, "skills": [ "HTML", "JavaScript", "JSON" ] }; var education = { "schools": [ { "name": "ucla", "location": "Los Angeles, CA", "degree": "BS", "dates": "2000 - 2004", "url": "ucla.edu", "majors": [ "cs" ] } ], "onlineCourses": [ { "title": "software as a service", "school": "edx", "dates": "2012", "url": "edx.com" }, { "title": "fullstack nanodegree", "school": "udacity", "dates": "2016", "url": "udacity.com" } ] }; $('#header').append(HTMLheaderName.replace('%data%', bio.name)); if(bio.skills.length > 0) { $('#header').append(HTMLskillsStart); bio.skills.forEach(function(skill) { $('#skills').append(HTMLskills.replace('%data%', skill)); }); }
f4980244f8ed88138431ca2274b0fa17c1a06c56
[ "JavaScript" ]
1
JavaScript
victorjz/frontend-nanodegree-resume
e20455e0b8632eece44e2081ac84ba066f28eabb
86f364e11510d91a5f035805a24a65904debc7ec
refs/heads/master
<repo_name>mixereqv1/cars_without_sort<file_sep>/add__user.php <?php session_start(); include_once('connect.php'); include_once('functions.php'); // if(checkPrivileges($mysqli,4) == true) { $user_name = $_POST['user__name']; $user_password = $_POST['user__password']; $user_role = $_POST['user__role']; $sql_user = "INSERT INTO users VALUES(null,'$user_name','$user_password',$user_role)"; mysqli_query($mysqli,$sql_user); header('location:login.php'); // } else { // header('location:login.php?action=no_permission'); // } ?><file_sep>/add__car.php <?php session_start(); include_once('connect.php'); include_once('functions.php'); // if(checkPrivileges($mysqli,1)) { $photo = basename($_FILES['car__photo']['name']); $description = $_POST['car__description']; $price = $_POST['car__price']; $promo = $_POST['car__promo']; //UPLOADING PHOTO $target_dir = "img/"; $target_file = $target_dir . basename($_FILES['car__photo']['name']); // $upload_ok = 1; move_uploaded_file($_FILES['car__photo']['tmp_name'], $target_file); // if(move_uploaded_file($_FILES['car__photo']['tmp_name'], $target_file)) { // echo "The file has been uploaded correctly."; // } else { // echo "Problem with uploading photo to server."; // } $sql = "INSERT INTO cars VALUES(null,'$photo','$description',$price,$promo)"; $mysqli -> query($sql); header('location:login.php'); // } else { // header('location:login.php?action=no_permission'); // } ?><file_sep>/amount.php <?php function getAmount() { $amount = $_POST['amount']; return $amount; } header('location:index.php'); ?><file_sep>/db/cars_db_backup.sql -- phpMyAdmin SQL Dump -- version 4.9.0.1 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Sep 13, 2019 at 04:22 PM -- Server version: 10.4.6-MariaDB -- PHP Version: 7.3.9 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: `cars` -- -- -------------------------------------------------------- -- -- Table structure for table `cars` -- CREATE TABLE `cars` ( `id` int(11) NOT NULL, `name` varchar(255) COLLATE utf8_polish_ci NOT NULL, `description` varchar(255) COLLATE utf8_polish_ci NOT NULL, `price` varchar(9) COLLATE utf8_polish_ci NOT NULL, `promo` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci; -- -- Dumping data for table `cars` -- INSERT INTO `cars` (`id`, `name`, `description`, `price`, `promo`) VALUES (1, 'nissan', 'Nissan Skyline R34 2.5 200HP AWD', '150 000', 10), (2, 'm6', 'BMW M6 Coupe 4.4 560HP RWD', '560 000', 5), (3, 'rs6', 'Audi RS6 4.2 480HP AWD', '380 000', 8), (4, 'golf', 'VW Golf 7 2.0 300HP AWD', '120 000', 15), (5, 'bugatti', 'Bugatti Chiron 8.0 1500HP AWD', '12 000 00', 5), (6, 'passat', 'VW Passat 1.9 110HP FWD', '1 000 000', 10), (7, 'lambo', 'Lamborghini Huracan 5.2 640HP AWD', '1 200 000', 5), (8, 'ferrari', 'Ferrari 488 GTB 3.9 661HP', '600 000', 15), (9, 'mustang', 'Ford Mustang 5.0 460HP RWD', '300 000', 9); -- -- Indexes for dumped tables -- -- -- Indexes for table `cars` -- ALTER TABLE `cars` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `cars` -- ALTER TABLE `cars` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10; 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>/db/cars_db_backup-23_09.sql -- phpMyAdmin SQL Dump -- version 4.9.0.1 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Sep 23, 2019 at 11:47 PM -- Server version: 10.4.6-MariaDB -- PHP Version: 7.3.9 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: `cars` -- -- -------------------------------------------------------- -- -- Table structure for table `cars` -- CREATE TABLE `cars` ( `id` int(11) NOT NULL, `photo` varchar(255) COLLATE utf8_polish_ci NOT NULL, `description` varchar(255) COLLATE utf8_polish_ci NOT NULL, `price` int(11) NOT NULL, `promo` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci; -- -- Dumping data for table `cars` -- INSERT INTO `cars` (`id`, `photo`, `description`, `price`, `promo`) VALUES (1, 'nissan.png', 'Nissan Skyline R34 2.5 200HP AWD', 150000, 10), (2, 'm6.jpg', 'BMW M6 Coupe 4.4 560HP RWD', 560000, 5), (3, 'rs6.jpg', 'Audi RS6 4.2 480HP AWD', 380000, 8), (4, 'golf.jpg', 'VW Golf 7 2.0 300HP AWD', 120000, 15), (5, 'bugatti.jpeg', 'Bugatti Chiron 8.0 1500HP AWD', 1200000, 5), (6, 'passat.jpg', 'VW Passat 1.9 110HP FWD', 1000000, 10), (7, 'lambo.jpg', 'Lamborghini Huracan 5.2 640HP AWD', 1200000, 5), (8, 'ferrari.jpg', 'Ferrari 488 GTB 3.9 661HP', 600000, 15), (9, 'mustang.jpg', 'Ford Mustang 5.0 460HP RWD', 300000, 9), (10, 'unknown.jpg', 'Dodge Challenger 4.0 350HP RWD', 350000, 4); -- -------------------------------------------------------- -- -- Table structure for table `privileges` -- CREATE TABLE `privileges` ( `id` int(11) NOT NULL, `user_name` varchar(255) COLLATE utf8_polish_ci NOT NULL, `add_car` int(11) NOT NULL, `modify` int(11) NOT NULL, `delete` int(11) NOT NULL, `add_user` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci; -- -- Dumping data for table `privileges` -- INSERT INTO `privileges` (`id`, `user_name`, `add_car`, `modify`, `delete`, `add_user`) VALUES (1, 'admin', 1, 1, 1, 1), (2, 'editor', 0, 1, 0, 0), (3, 'delete', 0, 0, 1, 0); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL, `login` varchar(255) COLLATE utf8_polish_ci NOT NULL, `password` varchar(255) COLLATE utf8_polish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `login`, `password`) VALUES (1, 'admin', '<PASSWORD>'), (2, 'editor', '<PASSWORD>'), (3, 'delete', '<PASSWORD>'); -- -- Indexes for dumped tables -- -- -- Indexes for table `cars` -- ALTER TABLE `cars` ADD PRIMARY KEY (`id`); -- -- Indexes for table `privileges` -- ALTER TABLE `privileges` ADD PRIMARY KEY (`id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `cars` -- ALTER TABLE `cars` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11; -- -- AUTO_INCREMENT for table `privileges` -- ALTER TABLE `privileges` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; 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>/index.php <?php session_start(); // $_SESSION['logged_in'] = 'false'; // $_SESSION['wrong_data'] = 'false'; include_once('card.php'); include_once('connect.php'); include('functions.php'); $sql = "SELECT id FROM cars ORDER BY id DESC LIMIT 1"; $result = $mysqli -> query($sql); $amount_of_cars = $result -> fetch_assoc()['id']; // if(isset($_GET['action']) && $_GET['action'] == 'logout') { // $_SESSION['logged_in'] == 'false'; // unset($_SESSION['login']); // unset($_SESSION['password']); // } // if(isset($_POST['sign_in'])) { // if($_POST['login'] == 'admin' && $_POST['password'] == '<PASSWORD>') { // $_SESSION['logged_in'] = 'true'; // $_SESSION['wrong_data'] = 'false'; // } else { // $_SESSION['logged_in'] = 'false'; // $_SESSION['wrong_data'] = 'true'; // } // } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Grid template</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" media="screen" href="main.min.css" /> <link href="https://fonts.googleapis.com/css?family=Livvic|Rubik:700&display=swap" rel="stylesheet"> </head> <body> <div class="container"> <header class="header"> <h1><NAME></h1> <a class="login__link" href="login.php">Sign in</a> </header> <div class="sidebar"> <?php // if($_SESSION['logged_in'] == 'true') { ?> <!-- <form class="add__car" action="add__car.php" method="POST"> <input type="file" name="car__photo" required> <input type="text" name="car__description" placeholder="Opis" required> <input type="number" name="car__price" placeholder="Cena" required> <input type="number" name="car__promo" placeholder="Promocja w %" required> <input type="submit" value="Dodaj"> </form> --> <?php //} ?> </div> <main class="main"> <?php for($i=0; $i<$amount_of_cars; $i++) { createTab($i,$photo,$description,$price,$promo,$car__id,$mysqli); } ?> </main> <footer class="footer"> <?php // if(isset($_GET['action']) && $_GET['action'] == 'logout') { // echo('<span class="logged__out">Logged out correctly</span>'); // } // if($_SESSION['wrong_data'] == 'true') { // echo('<span class="wrong__data">Incorrect login/password</span>'); // } // if($_SESSION['logged_in'] == 'false') { ?> <!-- <form action="index.php" method="POST"> <label for="login">Login:</label> <input type="text" name="login" id="login" required> <label for="password">Password:</label> <input type="password" name="password" id="password" required> <input type="submit" value="Sign in" name="sign_in"> </form> --> <?php //} else { ?> <!-- <a class="logout__button" href="index.php?action=logout">Logout</a> --> <?php //} ?> </footer> </div> </body> </html><file_sep>/upload.php <?php $target_dir = "img/"; $target_file = $target_dir ?><file_sep>/functions.php <?php function checkPrivileges($mysqli,$number) { $login = $_SESSION['user']; $user_sql = "SELECT id_role FROM users WHERE username = '$login'"; $user_result = mysqli_query($mysqli,$user_sql); $user_row = mysqli_fetch_assoc($user_result); $id_role = $user_row['id_role']; $role_sql = "SELECT role FROM roles WHERE id_role = $id_role"; $role_result = mysqli_query($mysqli,$role_sql); $role_row = mysqli_fetch_assoc($role_result); $privilege_sql = "SELECT privilege FROM privileges WHERE id_privilege = $number"; $privilege_result = mysqli_query($mysqli,$privilege_sql); $privilege_row = mysqli_fetch_assoc($privilege_result); $GLOBAL_SQL = "SELECT roles.role,privileges.privilege FROM users,roles,privileges,roles_privileges WHERE users.id_role = roles.id_role AND roles.id_role = roles_privileges.id_role AND privileges.id_privilege = roles_privileges.id_privilege AND roles.id_role = $id_role AND roles_privileges.id_privilege = $number"; $global = mysqli_query($mysqli,$GLOBAL_SQL); $global_row = mysqli_fetch_assoc($global); $privilege = false; if($role_row['role'] == $global_row['role'] && $privilege_row['privilege'] == $global_row['privilege']) { $privilege = true; } return $privilege; } function createTab($i,$photo,$description,$price,$promo,$car__id,$mysqli) { echo(' <div class="item card" id='.$car__id[$i].'> <div class="image"> <img src="img/'.$photo[$i].'" alt="'.$photo[$i].'" class="image__img"> </div> <div class="description"> <span class="description__content">'.$description[$i].'</span> '); // if(isset($_SESSION['user']) && $_SESSION['user'] == 'admin' && $_SESSION['logged_in'] == 'true') { // echo '<input type="submit" value="Update title" class="edit__title">'; // } if(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == true) { echo '<input type="submit" value="Update title" class="edit__title">'; } echo(' <div class="colors"> <ul class="colors__list"> Dostępne kolory: <li>Biały</li> <li>Niebieski</li> <li>Czerwony</li> </ul> </div> <div class="price"> <span class="price__value">Cena: <span>'.$price[$i].'zł</span></span> <span class="price__promo">Promocja <span>-'.$promo[$i].'%</span></span> </div> <div class="buy"> <a class="buy__link" href="#">Kup teraz!</a> </div> <div class="more"> <a class="more__link" href="#">Zobacz więcej!</a> </div> '); // if(isset($_SESSION['user']) && $_SESSION['user'] == 'admin' && $_SESSION['logged_in'] == 'true') { // echo(' // <form action="del__car.php" method="POST"> // <input type="hidden" name="car__id" value='.$car__id[$i].'> // <input class="delete__link" type="submit" value="Delete"> // </form>' // ); // } if(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == true) { echo(' <form action="del__car.php" method="POST"> <input type="hidden" name="car__id" value='.$car__id[$i].'> <input class="delete__link" type="submit" value="Delete"> </form>' ); } echo(' </div> </div> '); } ?><file_sep>/del__car.php <?php session_start(); include_once('connect.php'); include_once('functions.php'); if(checkPrivileges($mysqli,3) == true) { $car_id = $_POST['car__id']; $sql = "DELETE FROM cars WHERE id = $car_id"; mysqli_query($mysqli,$sql); header('location:login.php'); } else { header('location:login.php?action=no_permission'); } ?><file_sep>/login.php <?php // $GLOBAL_SQL = "SELECT roles.role,privileges.privilege FROM users,roles,privileges,roles_privileges WHERE users.id_role = roles.id_role AND roles.id_role = roles_privileges.id_role AND privileges.id_privilege = roles_privileges.id_privilege"; session_start(); include_once('card.php'); include_once('connect.php'); include_once('functions.php'); $sql = "SELECT id FROM cars ORDER BY id DESC LIMIT 1"; $result = $mysqli -> query($sql); $amount_of_cars = $result -> fetch_assoc()['id']; if(isset($_GET['action']) && $_GET['action'] == 'logout') { $_SESSION['logged_in'] = false; unset($_SESSION['login']); unset($_SESSION['password']); unset($_SESSION['user']); unset($_GET['action']); } if(isset($_POST['sign_in'])) { if($_POST['login'] != '' && $_POST['password'] != '') { $login = $_POST['login']; $query = "SELECT username,password FROM users WHERE username = '$login'"; $result = $mysqli -> query($query); $row = $result -> fetch_assoc(); if($row['username'] == $login) { $password = $_POST['password']; if($row['password'] == $password) { $_SESSION['user'] = $login; $_SESSION['logged_in'] = true; $_SESSION['wrong_data'] = false; $_SESSION['no_data'] = false; } else { $_SESSION['wrong_data'] = true; } } else { $_SESSION['wrong_data'] = true; } } else { $_SESSION['no_data'] = true; } } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Grid template</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" media="screen" href="main.min.css" /> <link href="https://fonts.googleapis.com/css?family=Livvic|Rubik:700&display=swap" rel="stylesheet"> <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).ready(a => { $('.description__content').dblclick(function() { $old_text = $(this).text(); $(this).html('<input placeholder="'+$old_text+'" type="text"><input type="submit" value="Update">'); }) }) </script> --> </head> <body> <?php if(isset($_GET['action']) && $_GET['action'] == 'no_permission') { unset($_GET['action']); ?> <script> alert('Nie masz wystarczających permisji.'); </script> <?php } ?> <div class="container"> <header class="header"> <h1><NAME></h1> <a href="index.php" class="home__page">Home page</a> </header> <div class="sidebar"> <?php if(isset($_GET['action']) && $_GET['action'] == 'logout') { echo('<span class="logged__out">Logged out correctly</span>'); } if(isset($_SESSION['wrong_data']) && $_SESSION['wrong_data'] == true) { echo('<span class="wrong__data">Incorrect login/password</span>'); } if(isset($_SESSION['no_data']) && $_SESSION['no_data'] == true) { echo('<span class="wrong__data">Login/password cannot be empty</span>'); } if(!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] == false) { ?> <form action="login.php" method="POST"> <label for="login">Login:</label> <input type="text" name="login" id="login"> <label for="password">Password:</label> <input type="<PASSWORD>" name="password" id="password"> <input type="submit" value="Sign in" name="sign_in"> </form> <?php } else { ?> <a class="logout__button" href="login.php?action=logout">Logout</a> <span class="logged__user">You are logged in as: <?php echo '<b>'. $_SESSION['user'] .'</b>' ?></span> <?php if(checkPrivileges($mysqli,1) == true) { ?> <form class="add__car" action="add__car.php" method="POST" enctype="multipart/form-data"> <input type="file" id="car__photo" name="car__photo" accept="image/*" required> <input type="text" name="car__description" placeholder="Opis" required> <input type="number" name="car__price" placeholder="Cena" required> <input type="number" name="car__promo" placeholder="Promocja w %" required> <input type="submit" value="Dodaj"> </form> <?php } if(checkPrivileges($mysqli,4) == true) { ?> <form class="add__user" action="add__user.php" method="POST"> <h3>Add user</h3> <input type="text" name="user__name" placeholder="Nazwa" required> <input type="password" name="user__password" placeholder="<PASSWORD>" required> <input type="number" name="user__role" placeholder="Rola" required> <!-- <div class="add__user__privileges"> <input type="checkbox" name="add_car" id="add_car"> <label for="add">Add cars</label> </div> <div class="add__user__privileges"> <input type="checkbox" name="modify" id="modify"> <label for="add">Modify cars</label> </div> <div class="add__user__privileges"> <input type="checkbox" name="delete" id="delete"> <label for="add">Delete cars</label> </div> <div class="add__user__privileges"> <input type="checkbox" name="add_user" id="add_user"> <label for="add">Add users</label> </div> --> <input type="submit" value="Dodaj użytkownika"> </form> <?php } } ?> </div> <main class="main"> <?php for($i=0; $i<$amount_of_cars; $i++) { createTab($i,$photo,$description,$price,$promo,$car__id,$mysqli); } ?> </main> <footer class="footer"> </footer> </div> <script src="script.js"></script> </body> </html><file_sep>/connect.php <?php $mysqli = new mysqli('localhost','root','','cars'); if($mysqli -> connect_errno) { printf('Connect failed: %s\n', $mysqli -> connect_error); exit(); } ?><file_sep>/db/db_backup_06_10.sql -- phpMyAdmin SQL Dump -- version 4.9.0.1 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Oct 06, 2019 at 08:29 PM -- Server version: 10.4.6-MariaDB -- PHP Version: 7.3.9 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: `cars` -- -- -------------------------------------------------------- -- -- Table structure for table `cars` -- CREATE TABLE `cars` ( `id` int(11) NOT NULL, `photo` varchar(255) COLLATE utf8_polish_ci NOT NULL, `description` varchar(255) COLLATE utf8_polish_ci NOT NULL, `price` int(11) NOT NULL, `promo` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci; -- -- Dumping data for table `cars` -- INSERT INTO `cars` (`id`, `photo`, `description`, `price`, `promo`) VALUES (1, 'nissan.png', 'Nissan Skyline R34 2.5 200HP AWD', 150000, 10), (2, 'm6.jpg', 'BMW M6 Coupe 4.4 560HP RWD', 560000, 5), (3, 'rs6.jpg', 'Audi RS6 4.2 480HP AWD', 380000, 8), (4, 'golf.jpg', 'VW Golf 7 2.0 300HP AWD', 120000, 15), (5, 'bugatti.jpeg', 'Bugatti Chiron 8.0 1500HP AWD', 1200000, 5), (6, 'passat.jpg', 'VW Passat 1.9 110HP FWD', 1000000, 10), (7, 'lambo.jpg', 'Lamborghini Huracan 5.2 640HP AWD', 1200000, 5), (8, 'ferrari.jpg', 'Ferrari 488 GTB 3.9 661HP', 600000, 15), (9, 'mustang.jpg', 'Ford Mustang 5.0 460HP RWD', 300000, 9), (10, 'unknown.jpg', 'Dodge Challenger 4.0 350HP RWD', 350000, 4); -- -------------------------------------------------------- -- -- Table structure for table `privileges` -- CREATE TABLE `privileges` ( `id_privilege` int(11) NOT NULL, `privilege` varchar(255) COLLATE utf8_polish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci; -- -- Dumping data for table `privileges` -- INSERT INTO `privileges` (`id_privilege`, `privilege`) VALUES (1, 'add_car'), (2, 'edit_car'), (3, 'del_car'), (4, 'add_user'); -- -------------------------------------------------------- -- -- Table structure for table `roles` -- CREATE TABLE `roles` ( `id_role` int(11) NOT NULL, `role` varchar(255) COLLATE utf8_polish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci; -- -- Dumping data for table `roles` -- INSERT INTO `roles` (`id_role`, `role`) VALUES (1, 'admin'), (2, 'editor'); -- -------------------------------------------------------- -- -- Table structure for table `roles_privileges` -- CREATE TABLE `roles_privileges` ( `id` int(11) NOT NULL, `id_role` int(11) NOT NULL, `id_privilege` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci; -- -- Dumping data for table `roles_privileges` -- INSERT INTO `roles_privileges` (`id`, `id_role`, `id_privilege`) VALUES (1, 1, 1), (2, 1, 2), (3, 1, 3), (4, 1, 4), (5, 2, 2); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL, `username` varchar(255) COLLATE utf8_polish_ci NOT NULL, `password` varchar(255) COLLATE utf8_polish_ci NOT NULL, `id_role` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `username`, `password`, `id_role`) VALUES (1, 'admin', '<PASSWORD>', 1), (2, 'editor', '<PASSWORD>', 2); -- -- Indexes for dumped tables -- -- -- Indexes for table `cars` -- ALTER TABLE `cars` ADD PRIMARY KEY (`id`); -- -- Indexes for table `privileges` -- ALTER TABLE `privileges` ADD PRIMARY KEY (`id_privilege`); -- -- Indexes for table `roles` -- ALTER TABLE `roles` ADD PRIMARY KEY (`id_role`); -- -- Indexes for table `roles_privileges` -- ALTER TABLE `roles_privileges` ADD PRIMARY KEY (`id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `cars` -- ALTER TABLE `cars` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11; -- -- AUTO_INCREMENT for table `privileges` -- ALTER TABLE `privileges` MODIFY `id_privilege` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `roles` -- ALTER TABLE `roles` MODIFY `id_role` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `roles_privileges` -- ALTER TABLE `roles_privileges` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; 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>/card.php <?php include_once('connect.php'); $sql = "SELECT * FROM cars"; //DEFINING ARRAYS $car__id = array(); $photo = array(); $description = array(); $price = array(); $promo = array(); //FETCHING DATA FROM DB TO ARRAYS if($result = $mysqli -> query($sql)) { while($row = $result -> fetch_assoc()) { array_push($car__id,$row['id']); array_push($photo,$row['photo']); array_push($description,$row['description']); array_push($price,$row['price']); array_push($promo,$row['promo']); } } ?><file_sep>/update.php <?php session_start(); include_once('connect.php'); include_once('functions.php'); if(checkPrivileges($mysqli,2) == true) { $car_id_to_edit = $_POST['car_id_to_edit']; $new_description = $_POST['new_description']; $sql = "UPDATE cars SET description = '$new_description' WHERE id = $car_id_to_edit" ; mysqli_query($mysqli,$sql); header('location:login.php'); } else { header('location:login.php?action=no_permission'); } ?>
d0154eabaea079327a71a7041516f5f928aa4334
[ "SQL", "PHP" ]
14
PHP
mixereqv1/cars_without_sort
606841916d169db157ed01841beb31a9807cc6fe
2bc36a9f29547ba5c8bcb48580f7822fa8187c9f
refs/heads/master
<repo_name>LahariReddyMuthyala/StudentManagement<file_sep>/classproject/onlineapp/admin.py from django.contrib import admin # Register your models here. from .models import College, Student admin.site.register(College) admin.site.register(Student) from rest_framework.authtoken.admin import TokenAdmin TokenAdmin.raw_id_fields = ('user',)<file_sep>/classproject/onlineapp/views/college.py from django.views import View from onlineapp.models import * from onlineapp.forms import * from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.mixins import LoginRequiredMixin import logging class CollegeView(LoginRequiredMixin, View): login_url = '/login/' def get(self, request, *args, **kwargs): if kwargs: college = get_object_or_404(College, id=kwargs.get('college_id')) studentDetails = Student.objects.values('id', 'name', 'email', 'mocktest1__total').filter(college__id=kwargs.get('college_id')).order_by("-mocktest1__total") user_permissions = request.user.get_all_permissions() return render( request, template_name='college_details.html', context={ 'college': college, 'studentDetails': studentDetails, 'title': 'Students of {} | class project'.format(college.name), 'user_permissions': user_permissions, 'logged_in': request.user.is_authenticated } ) colleges=College.objects.all() user_permissions = request.user.get_all_permissions() logging.error('Error') return render( request, template_name="colleges.html", context={ 'colleges': colleges, 'title': 'All colleges | Class Project', 'user_permissions': user_permissions, 'logged_in': request.user.is_authenticated } ) class AddCollegeView(LoginRequiredMixin, View): login_url = '/login/' def get(self, request, *args, **kwargs): form = AddCollege() if kwargs: college = College.objects.get(id=kwargs.get('id')) form = AddCollege(instance=college) return render(request, 'add_college.html', {'form': form, 'title': 'Add college', 'logged_in': request.user.is_authenticated}) def post(self, request, *args, **kwargs): form = AddCollege(request.POST) if kwargs: college = College.objects.get(id=kwargs.get('id')) form = AddCollege(request.POST, instance=college) if form.is_valid(): form.save() return redirect('colleges_html') form = AddCollege(request.POST) if form.is_valid(): form.save() return redirect('colleges_html') class DeleteCollegeView(LoginRequiredMixin, View): login_url = '/login/' def get(self, request, *args, **kwargs): if kwargs: college = get_object_or_404(College, id=kwargs.get('college_id')) college.delete() return redirect('colleges_html') <file_sep>/classproject/onlineapp/urls.py from django.contrib import admin from django.urls import path from onlineapp.views import * urlpatterns = [ path('test/', testview.test, name="test"), path('login/', LoginController.as_view(), name="login"), path('signup/', SignUpController.as_view(), name="signup"), path('logout/', logout_user, name="logout"), path('api/v1/colleges/', college_list, name="rest_colleges"), path('api/v1/colleges/<int:cpk>/', college_list, name="rest_colleges"), path('api/v1/colleges/<int:cpk>/students/', student_details.as_view(), name="rest_students"), path('api/v1/colleges/<int:cpk>/students/<int:spk>/', student_details.as_view(), name="rest_students"), path('api-token-auth/', CustomAuthToken.as_view()), path('colleges/', CollegeView.as_view(), name="colleges_html"), path('colleges/<int:college_id>/', CollegeView.as_view(), name="college_details"), path('colleges/add', AddCollegeView.as_view(), name="add_college"), path('colleges/<int:id>/edit', AddCollegeView.as_view(), name="edit_college"), path('colleges/<int:id>/delete', DeleteCollegeView.as_view(), name="delete_college"), path('colleges/<int:college_id>/addstudent', AddStudentView.as_view(), name="add_student"), path('colleges/<int:college_id>/editstudent/<int:student_id>', AddStudentView.as_view(), name="edit_student"), path('colleges/<int:college_id>/deletestudent/<int:student_id>', DeleteStudentView.as_view(), name="delete_student"), ] <file_sep>/classproject/onlineapp/forms/student.py from onlineapp.models import * from django import forms class AddStudent(forms.ModelForm): class Meta: model = Student exclude = ['id', 'dob', 'college'] widgets = { 'name': forms.TextInput(attrs={"class": "input", "placeholder": "Enter student name"}), 'email': forms.TextInput(attrs={"class": "input", "placeholder": "Enter email ID"}), 'db_folder': forms.TextInput(attrs={"class": "input", "placeholder": "Folder name"}), 'dropped_out': forms.CheckboxInput(attrs={"class": "input"}), } <file_sep>/classproject/onlineapp/forms/mocktest1.py from onlineapp.models import * from django import forms class AddMockTest1(forms.ModelForm): class Meta: model = MockTest1 exclude = ['id', 'student', 'total'] widgets = { 'problem1': forms.TextInput(attrs={"class": "input", "placeholder": "Score of problem1"}), 'problem2': forms.TextInput(attrs={"class": "input", "placeholder": "Score of problem2"}), 'problem3': forms.TextInput(attrs={"class": "input", "placeholder": "Score of problem3"}), 'problem4': forms.TextInput(attrs={"class": "input", "placeholder": "Score of problem4"}), } <file_sep>/classproject/onlineapp/views/rest_students.py from django.views import View from onlineapp.models import * from onlineapp.forms import * from onlineapp.serializers import * from rest_framework.response import Response from rest_framework import status from rest_framework.decorators import APIView from django.shortcuts import get_object_or_404 from rest_framework.authentication import SessionAuthentication, BasicAuthentication, TokenAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView class student_details(APIView): authentication_classes = (SessionAuthentication, BasicAuthentication, TokenAuthentication) permission_classes = (IsAuthenticated,) def get(self, request, *args, **kwargs): if kwargs.get('spk'): college = get_object_or_404(College,pk=kwargs.get('cpk')) student = get_object_or_404(Student, pk=kwargs.get('spk'), college_id=college) serializer = StudentDetailsSerializer(student, many=False) return Response(serializer.data) college = get_object_or_404(College,pk=kwargs.get('cpk')) student = Student.objects.filter(college_id=college) serializer = StudentDetailsSerializer(student, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = StudentDetailsSerializer(data=request.data, context={'cpk': kwargs['cpk']}) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def put(self, request, *args, **kwargs): if kwargs.get('spk'): college = get_object_or_404(College,pk=kwargs.get('cpk')) student = get_object_or_404(Student, pk=kwargs.get('spk'), college_id=college) serializer = StudentDetailsSerializer(student, data=request.data, many=False, context={'cpk': kwargs['cpk'], 'spk': kwargs['spk']}) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, *args, **kwargs): if kwargs.get('spk'): college = get_object_or_404(College, pk=kwargs.get('cpk')) student = get_object_or_404(Student, pk=kwargs.get('spk'), college_id=college) serializer = StudentDetailsSerializer(student, many=False) student.delete() return Response(serializer.data) <file_sep>/classproject/onlineapp/views/rest_colleges.py from django.views import View from onlineapp.models import * from onlineapp.forms import * from onlineapp.serializers import * from rest_framework.response import Response from rest_framework import status from rest_framework.decorators import api_view, authentication_classes, permission_classes from django.shortcuts import get_object_or_404 from rest_framework.authentication import SessionAuthentication, BasicAuthentication, TokenAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView @api_view(['GET', 'POST', 'PUT', 'DELETE']) @authentication_classes((SessionAuthentication, BasicAuthentication, TokenAuthentication)) @permission_classes((IsAuthenticated,)) def college_list(request, *args, **kwargs): if request.method == 'GET': if kwargs: college = get_object_or_404(College, pk = kwargs.get('cpk')) serializer = CollegeSerializer(college) return Response(serializer.data) colleges = College.objects.all() serializer = CollegeSerializer(colleges, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = CollegeSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'PUT': college = get_object_or_404(College, pk=kwargs.get('cpk')) serializer = CollegeSerializer(college, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': college = get_object_or_404(College, pk=kwargs.get('cpk')) college.delete() return Response(status=status.HTTP_204_NO_CONTENT) <file_sep>/classproject/onlineapp/serializers.py from onlineapp.models import * from rest_framework import serializers class CollegeSerializer(serializers.ModelSerializer): class Meta: model = College fields = ('id', 'name', 'location', 'acronym', 'contact') class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ('name', 'dob', 'email', 'db_folder', 'dropped_out', 'college') def create(self, validated_data): student = Student.objects.create(**validated_data) student.save() return student def update(self,instance, validated_data): self.instance.name = validated_data.get('name', self.instance.name) self.instance.email = validated_data.get('email', self.instance.email) self.instance.db_folder = validated_data.get('db_folder', self.instance.db_folder) self.instance.dropped_out = validated_data.get('dropped_out', self.instance.dropped_out) self.instance.save() return self.instance class MockTest1Serializer(serializers.ModelSerializer): class Meta: model = MockTest1 fields = ('problem1', 'problem2', 'problem3', 'problem4', 'total') def create(self, validated_data): mocktest1 = MockTest1.objects.create(**validated_data) mocktest1.total = sum(validated_data.values()) mocktest1.save() return mocktest1 def update(self,instance, validated_data): instance.problem1 = validated_data.get('problem1', instance.problem1) instance.problem2 = validated_data.get('problem2', instance.problem2) instance.problem3 = validated_data.get('problem3', instance.problem3) instance.problem4 = validated_data.get('problem4', instance.problem4) validated_data.pop('total') instance.total = validated_data.get('total', sum(validated_data.values())) instance.save() return instance class StudentDetailsSerializer(serializers.ModelSerializer): mocktest1 = MockTest1Serializer(many=False, read_only=False) class Meta: model = Student fields = ('id', 'name', 'email', 'db_folder', 'dropped_out', "mocktest1") def create(self, validated_data): mock = validated_data.pop('mocktest1') validated_data['college'] = College.objects.get(id=self.context['cpk']) student = Student.objects.create(**validated_data) MockTest1.objects.create(student=student, **mock) return student def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.email = validated_data.get('email', instance.email) instance.dropped_out = validated_data.get('dropped_out', instance.dropped_out) instance.db_folder = validated_data.get('db_folder', instance.db_folder) mocktest1 = MockTest1Serializer(instance.mocktest1, data=dict( self._validated_data.get('mocktest1') )) if mocktest1.is_valid(): mocktest1.save() instance.save() return instance <file_sep>/classproject/threads.py import time import threading counter = 0 def watcher(): global counter for i in range(50): print("counter = ",i, counter) time.sleep(0.1) def update(): name = threading.current_thread().ident global counter for i in range(5): counter += 1 time.sleep(0.1) def main(): thread1 = threading.Thread(target=update) thread2 = threading.Thread(target=update) thread3 = threading.Thread(target=watcher) thread1.start() thread2.start() thread3.start() thread1.join() thread2.join() thread3.join() if __name__ == '__main__': main() <file_sep>/classproject/onlineapp/forms/__init__.py from .colleges import * from .mocktest1 import * from .student import * from .login_form import * from .signup_form import *<file_sep>/classproject/onlineapp/migrations/0005_auto_20190606_1542.py # Generated by Django 2.2.1 on 2019-06-06 10:12 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('onlineapp', '0004_auto_20190606_1541'), ] operations = [ migrations.AlterField( model_name='mocktest1', name='student', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='onlineapp.Student'), ), migrations.AlterField( model_name='student', name='college', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='onlineapp.College'), ), migrations.AlterField( model_name='teacher', name='college', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='onlineapp.College'), ), ] <file_sep>/classproject/onlineapp/views/__init__.py from .college import * from .student import * from .authentication import * from .rest_colleges import * from .rest_students import * from .testview import * from .rest_authentication import * <file_sep>/classproject/onlineclass.py import click import openpyxl import MySQLdb import os import sys from bs4 import BeautifulSoup import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'classproject.settings') django.setup() from onlineapp.models import * @click.group() @click.pass_context def cli(ctx): pass def connectDB(db_name): con = MySQLdb.connect("localhost", "root", "04111998",db_name) return con pass def dropdb(ctx,db_name): con=connectDB(db_name) cur = con.cursor() cur.execute("DROP DATABASE IF EXISTS onlineclass") con.commit() pass @cli.command() @click.argument('source_excel1', nargs=1) @click.argument('source_html', nargs=1) @click.pass_context def importdata(ctx,source_excel1, source_html): wb1=openpyxl.load_workbook(source_excel1) sheet = wb1.get_sheet_by_name('Colleges') rows = sheet.max_row columns = sheet.max_column for r in range(2, rows + 1): val = [] for c in range(1, columns + 1): e = sheet.cell(row=r, column=c) val.append(e.value) valt = tuple(val) print(valt) c = College(name=valt[0], acronym=valt[1], location=valt[2], contact=valt[3]) c.save() sheet=wb1.get_sheet_by_name('Current') rows=sheet.max_row columns=sheet.max_column for r in range(2,rows+1): val=[] for c in range(1,columns+1): e=sheet.cell(row=r,column=c) val.append(e.value) valt=tuple(val) print(valt) s = Student(name = valt[0], college = College.objects.get(acronym = valt[1]), email = valt[2], db_folder = valt[3]) s.save() soup = BeautifulSoup(open(source_html).read(), 'html.parser') headings = soup.find_all('th') data = soup.find_all('tr') for row in range(2, len(data) + 1): rowTemp = data[row - 1].find_all('td') tds = [rowTemp[i].text for i in range(len(rowTemp))] name = tds[1].split('_') if(name[2]!="skc"): m = MockTest1(student = Student.objects.get(db_folder = name[2]), problem1 = tds[2], problem2 = tds[3], problem3 = tds[4], problem4 = tds[5], total = tds[6] ) m.save() if __name__ == '__main__': cli(obj={})<file_sep>/classproject/onlineapp/views/student.py from django.views import View from onlineapp.models import * from onlineapp.forms import * from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.mixins import LoginRequiredMixin class AddStudentView(LoginRequiredMixin, View): login_url = '/login/' def get(self, request, *args, **kwargs): form1 = AddStudent() form2 = AddMockTest1() if kwargs.get('student_id'): student = Student.objects.get(id=kwargs.get('student_id')) mocktest1 = MockTest1.objects.get(student_id=kwargs.get('student_id')) form1 = AddStudent(instance=student) form2 = AddMockTest1(instance=mocktest1) return render( request, 'add_student.html', {'form1': form1, 'form2': form2, 'title': "Add student", 'logged_in': request.user.is_authenticated}) def post(self, request, *args, **kwargs): form1 = AddStudent(request.POST) form2 = AddMockTest1(request.POST) if kwargs.get('student_id'): student = Student.objects.get(id=kwargs.get('student_id')) mocktest1 = MockTest1.objects.get(student_id=kwargs.get('student_id')) form1 = AddStudent(request.POST, instance=student) form2 = AddMockTest1(request.POST, instance=mocktest1) college = get_object_or_404(College, id=kwargs.get('college_id')) else: form1 = AddStudent(request.POST) form2 = AddMockTest1(request.POST) college = get_object_or_404(College, id=kwargs.get('college_id')) if form1.is_valid() and form2.is_valid(): student = form1.save(commit=False) student.college = college student.save() mocktest1 = form2.save(commit=False) mocktest1.student = student mocktest1.total = str(mocktest1.problem1+mocktest1.problem2+mocktest1.problem3+mocktest1.problem4) mocktest1.save() return redirect('colleges_html') class DeleteStudentView(LoginRequiredMixin, View): login_url = '/login/' def get(self, request, *args, **kwargs): if kwargs.get('student_id'): mocktest1 = get_object_or_404(MockTest1, student_id=kwargs.get('student_id')) mocktest1.delete() student = get_object_or_404(Student, id=kwargs.get('student_id')) student.delete() return redirect('colleges_html')
514fefbe4a5ba8302df6443bcfd70283be0a5bc5
[ "Python" ]
14
Python
LahariReddyMuthyala/StudentManagement
0eb21d90336292a554657d35ef42ac11f2b7f212
6a002c710a211056800b785e53dbb137357d87a2
refs/heads/master
<file_sep>#!/bin/sh # # # Quick and dirty way to run picard metrics on entire set of files # # Created by <NAME> on 6/23/14. # usage() { echo "WGS_analyze.sh -r Reference_genome.fa -1 Read1.gz -2 Read2.gz" } parse_arguments() { #Grab Read1 and Read2 echo "blah" } #Trim adaptors and write trimmed reads trim_adapters() { #Currently assuming Illumina TruSeq adapters #Do I want -g??? #Trim same adapter from both ends, filter paired reads to have q score > 10 and minimum length of 20 cutadapt -q 10 -a AGATCGGAAGAGC --minimum-length 20 --paired-output tmp.2.fastq -o tmp.1.fastq $1 $2 cutadapt -q 10 -a AGATCGGAAGAGC --minimum-length 20 --paired-output $1.trimmed.fastq -o $2.trimmed.fastq tmp.2.fastq tmp.1.fastq rm tmp.1.fastq tmp.2.fastq } #Bowtie2 mapping and prep of the BAM map_reads() { #Removed .fa from bowtie index bowtie2 --no-mixed --no-discordant -X 1000 -x$1 -1 $2 -2 $3 -S $2.paired.sam samtools view -bS $2.paired.sam > $2.paired.bam rm $2.paired.sam samtools sort $2.paired.bam $2.sorted rm $2.paired.bam } picard_analysis() { java -Xmx2g -jar /Users/briankudlow/analysis-master/FastqToSam.jar FASTQ=$1_L001_R1_001.fastq.gz FASTQ2=$1_L001_R2_001.fastq.gz SAMPLE_NAME=$1 OUTPUT=$1.bam java -Xmx2g -jar /Users/briankudlow/analysis-master/EstimateLibraryComplexity.jar INPUT=$1.bam OUTPUT=$1.txt MIN_IDENTICAL_BASES=30 } main() { touch complexity.summary.txt echo "LIBRARY GARBAGE UNPAIRED_READS_EXAMINED READ_PAIRS_EXAMINED UNMAPPED_READS UNPAIRED_READ_DUPLICATES READ_PAIR_DUPLICATES READ_PAIR_OPTICAL_DUPLICATES PERCENT_DUPLICATION ESTIMATED_LIBRARY_SIZE" >> complexity.summary.txt for BASE in $(ls *.fastq.gz | awk -F'_L001' '{printf $1"\n"}' | uniq) do picard_analysis $BASE paste <(echo $BASE) <(sed '8q;d' $BASE.txt) >> complexity.summary.txt rm $BASE.txt rm $BASE.bam done } main $* >> /dev/stderr <file_sep>analysis ======== NGS analysis scratch space <file_sep>#!/bin/sh # Garbage script to quickly throw together a bunch of files in a datadump directory # Missing a tab at the beggining of the filenames # # Created by <NAME> on 4/25/14. # make_summary_file() { FILE=*.trimmed.deduped.summary.txt i=true o=data.deduped.summary.txt tempfile=temp.deduped.summary.txt for f in $FILE do if [ "$i" = true ] then awk '{print $1}' $f > $o i=false fi #Horrible, awful solution paste <(cat $o) <(awk '{print $2}' $f) > $tempfile mv $tempfile $o done #Add column headers NEED TO ADD TAB BEFORE FILE NAMES ls $FILE | tr '\n' '\t' | awk '{print "Row_Name\t",$0'\n} > $tempfile cat $o >> $tempfile mv $tempfile $o } main() { make_summary_file } main $* >> /dev/stdout
687a47a1760c1bdd3682f1ca714a8adac8f0a5af
[ "Markdown", "Shell" ]
3
Shell
bkudlow/analysis
cfb83f2a370d56cb046a5d81f44000c857d019ab
3ad022eeccff4bf9c5e8468b7ad1b4a827ac9883
refs/heads/master
<file_sep>$(document).ready(() => { $("#submit").click(function(){ let a=$("#idTextBox").val(); let b=$("#titleTextBox").val(); let c=$("#yearTextBox").val(); $("#cardContainer").html(""); if((a==="")&&(b==="")) alert("Please enter atleast Id or Title"); else{ getAllData(a,b,c); } }); $("#resetButton").click(function(){ $("#idTextBox").val(""); $("#titleTextBox").val(""); $("#yearTextBox").val(""); }); }); // end of document.ready() let getAllData = (a,b,c) => { let d=""; let urlLink=""; d=b.split(" ").join("+"); if(a!="") { urlLink="https://www.omdbapi.com/?i="+a+"&apikey=thewdb"; console.log(urlLink); } else{ if(c!="") urlLink="https://www.omdbapi.com/?s="+d+"&y="+c+"&apikey=thewdb"; else urlLink="https://www.omdbapi.com/?s="+d+"&apikey=thewdb"; console.log(urlLink); } console.log("making request") $.ajax({ type: 'GET', // request type GET, POST, PUT dataType: 'json', // requesting datatype // url: 'http://www.omdbapi.com/?i=tt3896198&apikey=thewdb', // URL of getting data url:urlLink, success: (data) => { // in case of success response console.log(data); if(data.Response==="False") { alert(data.Error); } else{ if(data["Search"]===undefined) { let image=(data.Poster==="N/A")?"sources/optional.jpg":data.Poster; let card= `<div class="card col-8 col-sm-8 col-lg-4"> <img class="card-img-top image1" src="${image}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">${data.Title}</h5> <p class="card-text">Type is ${data.Type} and Year is ${data.Year}</p> </div> </div> ` $("#cardContainer").append(card); } else{ let searchReult=data["Search"]; for(movie of searchReult){ let image=(movie.Poster==="N/A")?"sources/optional.jpg":movie.Poster; let card= `<div class="card col-8 col-sm-8 col-lg-4"> <img class="card-img-top image1" src="${image}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">${movie.Title}</h5> <p class="card-text">Type: ${movie.Type}<br>Year: ${movie.Year}<br>ImdbId: ${movie.imdbID}</p> </div> </div> ` $("#cardContainer").append(card); } } } }, error: (data) => { // in case of error response alert("some error occured") }, // beforeSend: () => { // while request is processing. // // you can use loader here. // alert("request is being made. please wait") // }, // complete: () => { // // what you want to do while request is completed // alert("data fetched success") // }, timeout:5000 // this is in milli seconds }); // end of AJAX request } // end of getAllData
1ad89cea93a7821ed2c49dd9c52db6f2b9ba815b
[ "JavaScript" ]
1
JavaScript
Ayush-jaiswal/MovieApi
55a1e0d0b315ed5c1b83a017ae2c0304224e95a7
278342fa4d88964fe7a960966fb63c253d3883b4
refs/heads/master
<file_sep><?php /** * The template for displaying Projects on index view * * @package wpportfolio */ // get Jetpack portfolio taxonomy terms for portfolio filtering $terms = get_the_terms( $post->ID, 'jetpack-portfolio-type' ); if ( $terms && ! is_wp_error( $terms ) ) : $filtering_links = array(); foreach ( $terms as $term ) { $filtering_links[] = $term->slug; } $filtering = join( " ", $filtering_links ); ?> <div class="item <?php echo $filtering; ?> type-jetpack-portfolio"> <?php if ( '' != get_the_post_thumbnail() ) : ?> <?php the_post_thumbnail( 'portfolio-img' ); ?> <?php endif; ?> <a href="<?php the_permalink(); ?>" rel="bookmark" class="portfolio-link" tabindex="-1"></a> <div class="portfolio-info"> <div class="portfolio-content"> <div class="portfolio-entry"> <?php the_title( '<h2 class="entry-title">', '</h2>' ); ?> </div> </div> </div> </div><!-- #post-## --> <?php endif;
eee918a4fc5a8208f46717c6cbac97f76d7a9dea
[ "PHP" ]
1
PHP
diversethemes/portfolio
f91784e33bd41a1e733e469b39f2b9d200522fbd
8e6241d1d1c63801774b6a698cc13a09fe3613fe
refs/heads/master
<file_sep>var lastStopTime = new Date() var lastStop = [0,0,0,0] var lastStopDuration = 0 function printTime(time) { return time.getDate() + "/" + (time.getMonth()+1) + "/" + time.getFullYear() + " @ " + ('0' + time.getHours()).substr(-2) + ":" + ('0' + time.getMinutes()).substr(-2); } function printStopDuration(duration) { var ms = duration % 1000; duration = (duration - ms) / 1000; var secs = duration % 60; duration = (duration - secs) / 60; var mins = duration % 60; var hrs = (duration - mins) / 60; return ('0' + hrs).substr(-2) + ':' + ('0' + mins).substr(-2) + ':' + ('0' + secs).substr(-2); } function calculateLastStop(payload) { var accelX = parseFloat(payload["accelX"]) var accelY = parseFloat(payload["accelY"]) var accelZ = parseFloat(payload["accelZ"]) if (accelX != lastStop[0] || accelY != lastStop[1] || accelZ != lastStop[2]) { if (lastStop[3] == 0) { lastStop[3] = 1 } lastStop[0] = accelX lastStop[1] = accelY lastStop[2] = accelZ } else { if (lastStop[3] == 1) { lastStopTime = new Date() lastStop[3] = 0 } else { lastStopDuration = Math.abs(new Date() - lastStopTime.getTime()); } } } var wsbroker = "iot.eclipse.org"; //mqtt websocket enabled broker var wsport = 443 // port for above var client = new Paho.MQTT.Client(wsbroker, wsport, "myclientid_" + parseInt(Math.random() * 100, 10)); client.onConnectionLost = function (responseObject) { console.log("connection lost: " + responseObject.errorMessage); }; client.onMessageArrived = function (message) { var payload = JSON.parse(message.payloadString)["messages"][0] calculateLastStop(payload) $("#deviceID").text("ID: " + payload["sensor"]) $("#ambientTemp").text("Temperature: " + parseFloat(payload["ambientTemp"]).toFixed(2) + "°C") $("#pressure").text("Pressure: " + parseFloat(payload["pressure"]).toFixed(2) + " mbar") $("#altitude").text("Altitude: " + parseFloat(payload["altitude"]).toFixed(2) + " meter") $("#light").text("Light: " + parseFloat(payload["light"]).toFixed(2) + " lux") $("#lastStop").text("Last stop: " + printTime(lastStopTime)) $("#lastStopDuration").text("Duration: " + printStopDuration(lastStopDuration)) console.log(message.destinationName, ' -- ', message.payloadString); }; var options = { timeout: 3, useSSL: true, onSuccess: function () { console.log("mqtt connected"); // Connection succeeded; subscribe to our topic, you can add multile lines of these client.subscribe('iot/data/iotmmsp2000234487trial/v1/f56fe2b5-88cc-44d6-bf35-80eb15fe4a13', {qos: 1}); }, onFailure: function (message) { console.log("Connection failed: " + message.errorMessage); } }; client.connect(options);
18135ca6df74ccd22bdb2a9684fe24ba6fa1a5d5
[ "JavaScript" ]
1
JavaScript
JoaquinFernandez/SAPDemo
5376c0051f0182a0228ff1ce63ddf61ba70e92ae
d146ef1f7a14f502ba9431211e1e5ea7311263c9
refs/heads/master
<repo_name>kritikaumashankar/rails_postit<file_sep>/app/controllers/post_its_controller.rb class PostItsController < ApplicationController def index @post_its = PostIt.order(created_at: :asc) end def show @post_it = PostIt.find(params[:id]) end def new @post_it = PostIt.new end def create @post_it = PostIt.new(post_its_params) if @post_it.save redirect_to post_its_path else render :new end end def edit @post_it = PostIt.find(params[:id]) end def update @post_it = PostIt.find(params[:id]) if @post_it.update(post_its_params) redirect_to post_its_path else render :edit end end def destroy PostIt.find(params[:id]).destroy redirect_to post_its_path end private def post_its_params params.require(:post_it).permit(:title, :body, :completed) end end
e6009254d88085815d321dd3de36c61dc4b23ca9
[ "Ruby" ]
1
Ruby
kritikaumashankar/rails_postit
4205a154652df22a495fae16a7d9742c385d8d39
0d2da69dba4e711be77bc48993d6e68d6001f788
refs/heads/master
<repo_name>shibiana/myWebserver<file_sep>/webserver.h #ifndef WEBSERVER_H_ #define WEBSERVER_H_ //定义webserver类 #include <sys/socket.h> //socket #include <netinet/in.h> //socketaddr_in htons等 #include <arpa/inet.h> //inet_pton等 #include <stdio.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <cassert> #include <sys/epoll.h> #include <string> #include <iostream> using namespace std; //一些宏定义 const int MAX_FD = 65536; //最大文件描述符 const int MAX_EVENT_NUMBER = 10000; //最大事件数 const int TIMESLOT = 5; //最小超时单位 class WebServer { public: WebServer(); ~WebServer(); //初始化函数 void init(int port, string user, string passWord, string databaseName,int long_write,int opt_linger, int trigmode, int sql_num, int tread_num, int close_log, int actor_model); //线程池函数 void thread_pool(); //数据库连接池 void sql_pool(); //写日志 void log_write(); //trig_mode void trig_mode(); void eventlisten(); void eventloop(); //定时器 void timer(int connfd, struct sockaddr_in client_address); void adjust_timer(util_timer* timer); bool dealclientdata(); bool dealwithsignal(bool& timeout, bool& stop_server); void dealwithwrite(int sockfd); void dealwithwrite(int sockfd); public: int m_port; char* m_root; int m_log_write; int m_close_log; int m_actormodel; int m_pipefd[2]; int m_epollfd; http_conn* users; //数据库相关 connection_pool* m_connPool; //登录数据库的用户 string m_user; //登录数据库的密码 string m_passWord; //所使用的数据库的名字 string m_databaseName; //连接的数量 int m_sql_num; //线程池相关 threadpool<http_conn>* m_pool; //连接的数量 int m_thread_num; //event_loop相关 epoll_event events[MAX_EVENT_NUMBER]; int m_listenfd; int m_OPT_LINGER; int m_TRIGMode; int m_LISTENTrigmode; int m_CONNTrigmode; //定时器相关 client_data *users_timer; Utils utils; }; #endif
83d87868647f9946722c599bc5913a023fc2528b
[ "C++" ]
1
C++
shibiana/myWebserver
1530c07b6fb3bbcff50db684ef67dc12104977cf
4d8713d5b8e00057d49e11ba651c521cb7a0c5ff
refs/heads/main
<repo_name>pravinkumarsp/CS50-C-Programming<file_sep>/new.c // Online C compiler to run C program online #include<cs50.h> #include<stdio.h> int main(void) { int n; do { n = get_int("Height: "); }while (n <1 || n>50); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { printf("#"); // printf("%d %d ,", i, j); } printf("\n"); } } <file_sep>/negint.c #include<stdio.h> #include<cs50.h> int get_negative_int(void); int main(void) { int i = get_negative_int(); printf("i\n, i"); } int get_negative_int(void) { int n; do { n = get_int("negative integer: "); } while (n < 0); return n; }<file_sep>/new2.c // Online C compiler to run C program online #include<cs50.h> #include<stdio.h> int main(void) { int n; do { n = get_int("Height: "); }while (n <1 || n>); for(int i = 0; i < n ; i++) { for(int j = 0; j < n ; j++) { if (i + j < n - 1) printf(" "); else printf("#"); } printf("\n"); } } <file_sep>/README.md # CS50-C-Programming<file_sep>/print no.c #include<stdio.h> #include<cs50.h> int main(void) { int n = get_int("print anumbers from 1 to 10"); for(int i = 1; i<11; i++) { printf("%d,",i); } } <file_sep>/newmario.c #include<cs50.h> #include<stdio.h> int main(void) { int n; d0 { int = get_int("Height: "); ne }while (n<1 || n>8); for (int i = 0; i < n; i++) { for (int j = o; int j < n; j++) { if (i + j < n - 1) printf(" "); else printf("#"); } printf("\n"); } } <file_sep>/mario1.c #include<stdio.h> #include<cs50.h> int main(void) { int n; do { n = get_int("enter a height: "); }while ( n<1 || n>8); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i+j<n-1) printf(" "); else printf("*"); } printf("\n"); } }
ff786b6ff02a95a4990c00055d81445ff7571aa0
[ "Markdown", "C" ]
7
C
pravinkumarsp/CS50-C-Programming
30e896d09ce9795fb69c4d09915a517ec50fdd69
ea18cafecad22085ce477afbfdaedc931767ca85
refs/heads/master
<file_sep>/* A fork of CanonicalArduinoRead by <NAME> www.chrisheydrick.com */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <stdint.h> #include <fcntl.h> #include <termios.h> #include <errno.h> #include <sys/ioctl.h> #define DEBUG 1 int setup(int * pfd, char * tty_dev, int baud){ struct termios toptions; /* open serial port */ *pfd = open(tty_dev, O_RDWR | O_NOCTTY); printf("%s opened as %i\n", tty_dev, *pfd); /* wait for the Arduino to reboot */ usleep(3500000); /* Choose the right baud rate identifier */ speed_t br; switch (baud) { case 9600: br = B9600; break; case 19200: br = B19200; break; case 38400: br = B38400; break; case 57600: br = B57600; break; case 115200: br = B115200; break; default: printf("Unknown baud rate\n"); printf("Using default of 9600\n"); br = B9600; break; } printf("Baud rate %d\n", baud); /* get current serial port settings */ tcgetattr(*pfd, &toptions); /* set baud rate both ways */ cfsetispeed(&toptions, br); cfsetospeed(&toptions, br); /* 8 bits, no parity, no stop bits */ toptions.c_cflag &= ~PARENB; toptions.c_cflag &= ~CSTOPB; toptions.c_cflag &= ~CSIZE; toptions.c_cflag |= CS8; /* Canonical mode */ /* i.e. line buffering - chars will not come through until a \n is sent */ // toptions.c_lflag |= ICANON; /* Non-canonical mode */ toptions.c_lflag &= ~ICANON; /* commit the serial port settings */ tcsetattr(*pfd, TCSANOW, &toptions); } int available(const int fd){ int n = 0; ioctl(fd, FIONREAD, &n); return n; } int main(int argc, char *argv[]){ int fd, n, i; char buf[64] = "temp text"; if(argc < 3){ printf("Usage: %s <tty> <baudrate>\n", argv[0]); return 0; } setup(&fd, argv[1], atoi(argv[2])); //Send initial character to begin back-and-forth write(fd, "Z", 1); //The arduino will respond with the next character //of the alphabet (wrapped) while(1){ if(available(fd)){ n = read(fd, buf, 63); //read up to 63 chars buf[n] = 0; //set null terminator printf("%d bytes: %s\n", n, buf); write(fd, buf, 1); } } return 0; }
0c8d597f1fca2b9249d90632fef1f32387766650
[ "C" ]
1
C
mattlkf/Canonical-Arduino-Read
e5b7485c2be1492a7af47bbdd451610ffdbca2d1
cd2fc5dfa38a5d984ac68e028af2a59a396133c8
refs/heads/main
<file_sep>import React from 'react' import HeaderLine from '../../common/components/HeaderLine' const User = () => { return (<div> User </div>) } export default User<file_sep>import styled from 'styled-components' const HomeWrapper = styled.div` box-sizing: border-box; height:100%; ` export { HomeWrapper }<file_sep>import React from 'react' import { VideoWrapper, VideoHeader, VideoBody } from './style' import Back from '../../common/components/Back' const Video = ({ history }) => { const handleBack = () => { history.goBack() } return ( <VideoWrapper> <VideoHeader> <Back onBack={handleBack}>返回</Back> </VideoHeader> <VideoBody></VideoBody> </VideoWrapper> ) } export default Video<file_sep>//获取轮播图 const GET_BANNERLIST = 'GET_BANNERLIST' //设置轮播图 const SET_BANNERLIST = 'SET_BANNERLIST' export { GET_BANNERLIST, SET_BANNERLIST }<file_sep>import styled from 'styled-components' const SongWrapper = styled.div` position: absolute; width: 100%; height: 100%; z-index: 3; color: #fff; background-color: #000000; ` const SongHeader = styled.div` margin: 10px 5px; ` const SongBody = styled.div` ` export { SongWrapper, SongHeader, SongBody }<file_sep>import React from 'react' import { Route, Redirect } from 'react-router-dom' import GlobalStyle from '../common/global-style' import { routes, tabItems } from './config' import TabItem from './TabItem' import { HRouter, ViewWrapper, TabWrapper } from './style' const Router = () => { return ( <HRouter> <GlobalStyle /> {/* 定义路由视图 */} <ViewWrapper> {routes.map((route, index) => { if (route.path === '/') return <Route path="/" exact render={() => (<Redirect to="/home" />)} key={index}/> return <Route path={route.path} component={route.component} key={index} /> })} </ViewWrapper> {/* 定义路由导航 */} <TabWrapper> { tabItems.map((tabItem, index) => (<TabItem to={tabItem.to} icon={tabItem.icon} title={tabItem.title} key={index} />)) } </TabWrapper> </HRouter> ) } export default Router<file_sep>import React from 'react' import PropTypes from 'prop-types' import './iconfont.css' import { ListItemWrapper, Icon, Title, Arrow,TitleWrapper } from './style' const ListItem = (props) => { const { icon, title, onClick } = props return ( <ListItemWrapper onClick={onClick}> <TitleWrapper> <Icon className={`iconfont icon-${icon}`}></Icon> <Title>{title}</Title> </TitleWrapper> <Arrow className="iconfont icon-youjiantou"></Arrow> </ListItemWrapper> ) } //定义ListItem的参数检查 ListItem.propTypes = { icon: PropTypes.string, title: PropTypes.string, onClick: PropTypes.func } //定义ListItem的默认参数 ListItem.defaultProps = { icon: 'gedan', title: '歌单列表', onClick: e => e } export default ListItem<file_sep>const HOME_URL = { BANNER: '/banner', //轮播图 MUSICLIST: '/playlist/catlist' //歌单分类 } export default HOME_URL<file_sep>import React from 'react' import HeaderLine from '../../common/components/HeaderLine' const Hot = () => { return (<div> <HeaderLine title="热门" shape="circle"/> </div>) } export default Hot<file_sep>import styled from 'styled-components' const HeaderWrapper = styled.div` box-sizing: border-box; display: flex; justify-content: space-between; align-items: center; height: 100px; padding: 0 15px; ` const Title = styled.span` font-size: 40px; color: #ffffff ` export { HeaderWrapper, Title }<file_sep>import React from 'react' import { SongWrapper, SongHeader, SongBody } from './style' import Back from '../../common/components/Back' const Song = ({ history }) => { const handleBack = () => { history.goBack() } return ( <SongWrapper> <SongHeader> <Back onBack={handleBack}>返回</Back> </SongHeader> <SongBody> </SongBody> </SongWrapper> ) } export default Song<file_sep>import React from 'react' import PropTypes from 'prop-types' import SwiperCore, { Pagination, Autoplay } from 'swiper'; import { Swiper, SwiperSlide } from 'swiper/react'; // Import Swiper styles import 'swiper/swiper.scss'; import 'swiper/components/pagination/pagination.scss'; import './style.css' // install Swiper components SwiperCore.use([Pagination, Autoplay]); const Slider = (props) => { const { bannerList } = props const slides = [] for (let i = 0; i < bannerList.length; i++) { slides.push(<SwiperSlide key={`slide-${i}`} tag="li"> <img src={bannerList[i].imageUrl} alt={`Slide-${i}`} style={{width:'100%', height:'100%'}}/> </SwiperSlide>) } return ( <Swiper tag="section" wrapperTag="ul" pagination autoplay loop onSlideChange={(swiper) => { // console.log(swiper.activeIndex) }} > {slides} </Swiper> ) } //定义Slider的参数检查 Slider.propTypes = { bannerList: PropTypes.array } //定义Slider的参数默认值 Slider.defaultProps = { bannerList: [ 'https://picsum.photos/id/1/500/300', 'https://picsum.photos/id/2/500/300', 'https://picsum.photos/id/3/500/300', 'https://picsum.photos/id/4/500/300', 'https://picsum.photos/id/5/500/300', ] } export default Slider <file_sep>import { combineReducers } from 'redux' import { connectRouter } from 'connected-react-router' import HomeReducer from '../containers/Home/store/reducer' import { history } from './history' const reducer = combineReducers({ router: connectRouter(history), home: HomeReducer }) export default reducer<file_sep>import React from 'react' import HeaderLine from '../../common/components/HeaderLine' const Radio = () => { return (<div> <HeaderLine title="电台" shape="circle"/> </div>) } export default Radio<file_sep>import styled from 'styled-components' const BackWrapper = styled.div` display: flex; align-items: center; padding:5px; color: #00AC5A ` const Arrow = styled.i` color: #00AC5A ` const Title = styled.span` ` export { BackWrapper, Arrow, Title }<file_sep>import React from 'react' import ReactDOM from 'react-dom' import App from './App' import { Provider } from 'react-redux' import { store, persistor } from './store' import { ConnectedRouter } from 'connected-react-router' import { history } from './store/history' import { PersistGate } from 'redux-persist/integration/react' ReactDOM.render(<Provider store={store}> <PersistGate persistor={persistor}> <ConnectedRouter history={history}> <App /> </ConnectedRouter> </PersistGate> </Provider>, document.querySelector('#root'))<file_sep>import styled from 'styled-components' const VideoWrapper = styled.div` position: absolute; width: 100%; height: 100%; z-index: 3; color: #fff; background-color: #000000; ` const VideoHeader = styled.div` margin: 10px 5px; ` const VideoBody = styled.div` ` export { VideoWrapper, VideoHeader, VideoBody }<file_sep>import styled from 'styled-components' import { Swiper, SwiperSlide } from 'swiper/react'; const Slide = styled(SwiperSlide)` width:300px; height: 200px; ` export { Slide }<file_sep>import React from 'react' import { AlbumWrapper, AlbumHeader, AlbumBody } from './style' import Back from '../../common/components/Back' const Album = ({ history }) => { const handleBack = () => { history.goBack() } return ( <AlbumWrapper> <AlbumHeader> <Back onBack={handleBack}>返回</Back> </AlbumHeader> <AlbumBody></AlbumBody> </AlbumWrapper> ) } export default Album<file_sep>import React from 'react' import PropTypes from 'prop-types' import { ImageWrapper, Image } from './style' const Avatar = (props) => { const { shape, src } = props return ( <ImageWrapper> <Image src={src} shape={shape}/> </ImageWrapper> ) } //定义Avatar的参数类型检查 Avatar.propTypes = { shape: PropTypes.string, src: PropTypes.string } //定义Avatar的参数默认值 Avatar.defaultProps = { shape: 'square', src: 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2400268875,668657237&fm=26&gp=0.jpg' } export default Avatar <file_sep>import React from 'react' import PropTypes from 'prop-types' import { TabItemWrapper, IconWrapper, TitleWrapper } from './style' import './iconfonts.css' const TabItem = (props) => { const { to, icon, title } = props return ( <TabItemWrapper to={to} activeClassName="selected"> <IconWrapper className={`iconfont icon-${icon}`}> </IconWrapper> <TitleWrapper>{title}</TitleWrapper> </TabItemWrapper> ) } //定义接口类型检查 TabItem.propTypes = { to: PropTypes.string, icon: PropTypes.string, title: PropTypes.string } //定义接口默认值 TabItem.defaultProps = { to: '/home', icon: 'home', title: '首页' } export default TabItem<file_sep>import React from 'react' import PropTypes from 'prop-types' import Avatar from '../Avatar' import { HeaderWrapper, Title } from './style' import { NavLink } from 'react-router-dom' const HeaderLine = (props) => { const { title, src, shape, to } = props return ( <HeaderWrapper> <Title>{title}</Title> <NavLink to={to}> <Avatar src={src} shape={shape} /> </NavLink> </HeaderWrapper> ) } //定义HeaderLine的参数检查 HeaderLine.propTypes = { title: PropTypes.string, src: PropTypes.string, shape: PropTypes.string, to: PropTypes.string } //定义HeaderLine的默认值 HeaderLine.defaultProps = { title: '标题', src: 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2857175025,2520622403&fm=26&gp=0.jpg', shape: 'square', to: '/user' } export default HeaderLine<file_sep>import HOME_URL from './config' import axios from 'axios' const instance = axios.create({ baseURL: 'http://localhost:3000' }) //发送请求获取轮播图 export const get_bannerList_request = () => { return new Promise((resolve, reject) => { instance.get(HOME_URL.BANNER) .then(res => resolve(res)) .catch(err => reject(err)) }) } //获取歌单列表 export const get_musicList_request = () => { return new Promise((resolve, reject) => { instance.get(HOME_URL.MUSICLIST) .then(res => resolve(res)) .catch(err => reject(err)) }) } <file_sep>import styled from 'styled-components' import { NavLink } from 'react-router-dom' const TabItemWrapper = styled(NavLink)` display: flex; flex-direction: column; justify-content: center; align-items: center; width: 100%; height: 46px; color: #ffffff; &.selected { & div, i, span { color: #00AC5A; } } ` const IconWrapper = styled.i` width: 20px; height: 20px; font-size: 16px; margin-bottom: 5px; text-align:center; ` const TitleWrapper = styled.span` font-size: 12px; text-align: center; ` export { TabItemWrapper, IconWrapper, TitleWrapper }<file_sep>import { get_bannerList_request } from '../api' import * as types from './constants' import { push } from 'connected-react-router' export const set_bannerList = (bannerList) => { return { type: types.SET_BANNERLIST, payload: bannerList } } export const go_song = () => { return push('/song') } export const go_singer = () => { return push('/singer') } export const go_video = () => { return push('/video') } export const go_album = () => { return push('/album') } export const get_bannerList = () => { return async (dispatch) => { const { data: response } = await get_bannerList_request() if(response.code === 200) dispatch(set_bannerList(response.banners)) } }
660a56a57625e79e9b03a5129e73fe8add2075a7
[ "JavaScript" ]
25
JavaScript
publicjob/music-player
97394dc64fb3f2bebcb050bd15a0dfb6c036514d
5452d622cd775996681b004699a86fa6d710d061
refs/heads/master
<repo_name>Brando-Commando/TARS<file_sep>/TARS.py # This will be a Personal Voice Assistant following various tutorials listed below: # https://www.geeksforgeeks.org/personal-voice-assistant-in-python/ # It seems that several aspects of the tutorial are outdated, and those aspects need to be redone # What needs to be redone # -calcuating with Wolfram Alpha # -searching with firefox # Importing - import speech_recognition as sr # from google import playsound # to play saved mp3 files from gtts import gTTS # googles Text To Speech for output import os # for file functions import wolframalpha # for mathamatical calculations from strings from selenium import webdriver # for browser operations import time num = 1 def assistant_speaks(output): global num # num renames every audio file to remove ambiguity num += 1 print("TARS : ", output) toSpeak = gTTS(text = output, lang='en', slow = False) # saving the audio file given by google text to speech file = str(num)+".mp3" toSpeak.save(file) # playsound package is used to play the same file playsound.playsound(file, True) os.remove(file) def get_audio(): rObject = sr.Recognizer() audio = '' with sr.Microphone() as source: print("Speak...") # recording the audio using speech recog audio = rObject.listen(source, phrase_time_limit = 5) print("Stop.") # limits to 5 currently try: text = rObject.recognize_google(audio, language='en-US') print("You : ", text) return text except: # exception for when command could not be understood assistant_speaks("Could not understand that, please try again!") return 0 def process_text(input): try: if 'search' in input or 'play' in input: # basic web crawler using selenium search_web(input) return elif "who are you" in input or "define yourself" in input: speak = " I am Tars. A personal Assistant. I am currently in beta testing." assistant_speaks(speak) return elif "calculate" in input: # wolframalpha app_id - app_id = "" client = wolframalpha.Client(app_id) indx = input.lower().split().index('calculate') query = input.split()[indx + 1:] res = client.query(' '.join(query)) answer = next(res.results).text assistant_speaks("The answer is " + answer) return else: assistant_speaks("I can search the web for you. Do you want to continue?") ans = get_audio() if 'yes' in str(ans) or 'yeah' in str(ans): search_web(input) else: return except: assistant_speaks("I don't understand, I can search the web for you, do you want to continue?") ans = get_audio() if 'yes' in str(ans) or 'yeah' in str(ans): search_web(input) def search_web(input): driver = webdriver.Firefox() driver.implicitly_wait(1) driver.maximize_window() if 'youtube' in input.lower(): assistant_speaks("Opening in youtube") indx = input.lower().split().index('youtube') query = input.split()[indx + 1:] driver.get("http://www.youtube.com/results?search_query =" + '+'.join(query)) return elif 'wikipedia' in input.lower(): assistant_speaks("Opening Wikipedia") indx = input.lower().split().index('wikipedia') query = input.split()[indx + 1:] driver.get("https://en.wikipedia.org/wiki/" + '_'.join(query)) return # Driver Code if __name__ == "__main__": assistant_speaks("What's your name, user?") name ='user' name = get_audio() assistant_speaks("Hello, " + name + '.') while(1): assistant_speaks("What can i do for you?") text = get_audio().lower() if text == 0: continue if "exit" in str(text) or "bye" in str(text) or "sleep" in str(text): assistant_speaks("Ok bye, " + name + '.') break # calling process text to process the query process_text(text)<file_sep>/README.md # TARS TARS ( name inspired from the AI/robot companion of Interstellar ), is a standard voice assistant built in Python. Several packages are needed to run this program and they can be found in the imports, however Selenium is not yet needed. You will also need to use your own Wolfram Alpha API key, as I took mine out for privacy and security. After some painstaking debugging, the integration with the Wolfram Alpha API is complete and it is now working as intended. After the mathematical portion of the assistant has been fixed and is up and running, the next area of focus would be the Google Translate API. Personally, while I did follow a tutorial for much of the engine building, I feel like integrating the Google Translate API ( which is not a part of the tutorial ) will prove to be useful and more challenging.
75d21c42c7409aaadbb550bbf631c988ec18de76
[ "Markdown", "Python" ]
2
Python
Brando-Commando/TARS
28dff3a78b7b6082699b1f8e36c0c50ea38784af
d5c43ce50dc4bec45f8be66862df256f5bf268b1
refs/heads/master
<repo_name>jamesmehorter/honeycomb<file_sep>/php/When v3/When.php <?php /** * Name: When * Author: <NAME> <<EMAIL>> * Location: http://github.com/tplaner/When * Created: September 2010 * Description: Determines the next date of recursion given an iCalendar "rrule" like pattern. * Requirements: PHP 5.3+ - makes extensive use of the Date and Time library (http://us2.php.net/manual/en/book.datetime.php) */ class When { protected $frequency; protected $start_date; protected $try_date; protected $end_date; protected $gobymonth; protected $bymonth; protected $gobyweekno; protected $byweekno; protected $gobyyearday; protected $byyearday; protected $gobymonthday; protected $bymonthday; protected $gobyday; protected $byday; protected $gobysetpos; protected $bysetpos; protected $suggestions; protected $count; protected $counter; protected $goenddate; protected $interval; protected $wkst; protected $valid_week_days; protected $valid_frequency; /** * __construct */ public function __construct() { $this->frequency = null; $this->gobymonth = false; $this->bymonth = range(1,12); $this->gobymonthday = false; $this->bymonthday = range(1,31); $this->gobyday = false; // setup the valid week days (0 = sunday) $this->byday = range(0,6); $this->gobyyearday = false; $this->byyearday = range(0,366); $this->gobysetpos = false; $this->bysetpos = range(1,366); $this->gobyweekno = false; // setup the range for valid weeks $this->byweekno = range(0,54); $this->suggestions = array(); // this will be set if a count() is specified $this->count = 0; // how many *valid* results we returned $this->counter = 0; // max date we'll return $this->end_date = new DateTime('9999-12-31'); // the interval to increase the pattern by $this->interval = 1; // what day does the week start on? (0 = sunday) $this->wkst = 0; $this->valid_week_days = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'); $this->valid_frequency = array('SECONDLY', 'MINUTELY', 'HOURLY', 'DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY'); } /** * @param DateTime|string $start_date of the recursion - also is the first return value. * @param string $frequency of the recrusion, valid frequencies: secondly, minutely, hourly, daily, weekly, monthly, yearly */ public function recur($start_date, $frequency = "daily") { try { if(is_object($start_date)) { $this->start_date = clone $start_date; } else { // timestamps within the RFC have a 'Z' at the end of them, remove this. $start_date = trim($start_date, 'Z'); $this->start_date = new DateTime($start_date); } $this->try_date = clone $this->start_date; } catch(Exception $e) { throw new InvalidArgumentException('Invalid start date DateTime: ' . $e); } $this->freq($frequency); return $this; } public function freq($frequency) { if(in_array(strtoupper($frequency), $this->valid_frequency)) { $this->frequency = strtoupper($frequency); } else { throw new InvalidArgumentException('Invalid frequency type.'); } return $this; } // accepts an rrule directly public function rrule($rrule) { // strip off a trailing semi-colon $rrule = trim($rrule, ";"); $parts = explode(";", $rrule); foreach($parts as $part) { list($rule, $param) = explode("=", $part); $rule = strtoupper($rule); $param = strtoupper($param); switch($rule) { case "FREQ": $this->frequency = $param; break; case "UNTIL": $this->until($param); break; case "COUNT": $this->count($param); break; case "INTERVAL": $this->interval($param); break; case "BYDAY": $params = explode(",", $param); $this->byday($params); break; case "BYMONTHDAY": $params = explode(",", $param); $this->bymonthday($params); break; case "BYYEARDAY": $params = explode(",", $param); $this->byyearday($params); break; case "BYWEEKNO": $params = explode(",", $param); $this->byweekno($params); break; case "BYMONTH": $params = explode(",", $param); $this->bymonth($params); break; case "BYSETPOS": $params = explode(",", $param); $this->bysetpos($params); break; case "WKST": $this->wkst($param); break; } } return $this; } //max number of items to return based on the pattern public function count($count) { $this->count = (int)$count; return $this; } // how often the recurrence rule repeats public function interval($interval) { $this->interval = (int)$interval; return $this; } // starting day of the week public function wkst($day) { switch($day) { case 'SU': $this->wkst = 0; break; case 'MO': $this->wkst = 1; break; case 'TU': $this->wkst = 2; break; case 'WE': $this->wkst = 3; break; case 'TH': $this->wkst = 4; break; case 'FR': $this->wkst = 5; break; case 'SA': $this->wkst = 6; break; } return $this; } // max date public function until($end_date) { try { if(is_object($end_date)) { $this->end_date = clone $end_date; } else { // timestamps within the RFC have a 'Z' at the end of them, remove this. $end_date = trim($end_date, 'Z'); $this->end_date = new DateTime($end_date); } } catch(Exception $e) { throw new InvalidArgumentException('Invalid end date DateTime: ' . $e); } return $this; } public function bymonth($months) { if(is_array($months)) { $this->gobymonth = true; $this->bymonth = $months; } return $this; } public function bymonthday($days) { if(is_array($days)) { $this->gobymonthday = true; $this->bymonthday = $days; } return $this; } public function byweekno($weeks) { $this->gobyweekno = true; if(is_array($weeks)) { $this->byweekno = $weeks; } return $this; } public function bysetpos($days) { $this->gobysetpos = true; if(is_array($days)) { $this->bysetpos = $days; } return $this; } public function byday($days) { $this->gobyday = true; if(is_array($days)) { $this->byday = array(); foreach($days as $day) { $len = strlen($day); $as = '+'; // 0 mean no occurence is set $occ = 0; if($len == 3) { $occ = substr($day, 0, 1); } if($len == 4) { $as = substr($day, 0, 1); $occ = substr($day, 1, 1); } if($as == '-') { $occ = '-' . $occ; } else { $occ = '+' . $occ; } $day = substr($day, -2, 2); switch($day) { case 'SU': $this->byday[] = $occ . 'SU'; break; case 'MO': $this->byday[] = $occ . 'MO'; break; case 'TU': $this->byday[] = $occ . 'TU'; break; case 'WE': $this->byday[] = $occ . 'WE'; break; case 'TH': $this->byday[] = $occ . 'TH'; break; case 'FR': $this->byday[] = $occ . 'FR'; break; case 'SA': $this->byday[] = $occ . 'SA'; break; } } } return $this; } public function byyearday($days) { $this->gobyyearday = true; if(is_array($days)) { $this->byyearday = $days; } return $this; } // this creates a basic list of dates to "try" protected function create_suggestions() { switch($this->frequency) { case "YEARLY": $interval = 'year'; break; case "MONTHLY": $interval = 'month'; break; case "WEEKLY": $interval = 'week'; break; case "DAILY": $interval = 'day'; break; case "HOURLY": $interval = 'hour'; break; case "MINUTELY": $interval = 'minute'; break; case "SECONDLY": $interval = 'second'; break; } $month_day = $this->try_date->format('j'); $month = $this->try_date->format('n'); $year = $this->try_date->format('Y'); $timestamp = $this->try_date->format('H:i:s'); if($this->gobysetpos) { if($this->try_date == $this->start_date) { $this->suggestions[] = clone $this->try_date; } else { if($this->gobyday) { foreach($this->bysetpos as $_pos) { $tmp_array = array(); $_mdays = range(1, date('t',mktime(0,0,0,$month,1,$year))); foreach($_mdays as $_mday) { $date_time = new DateTime($year . '-' . $month . '-' . $_mday . ' ' . $timestamp); $occur = ceil($_mday / 7); $day_of_week = $date_time->format('l'); $dow_abr = strtoupper(substr($day_of_week, 0, 2)); // set the day of the month + (positive) $occur = '+' . $occur . $dow_abr; $occur_zero = '+0' . $dow_abr; // set the day of the month - (negative) $total_days = $date_time->format('t') - $date_time->format('j'); $occur_neg = '-' . ceil(($total_days + 1)/7) . $dow_abr; $day_from_end_of_month = $date_time->format('t') + 1 - $_mday; if(in_array($occur, $this->byday) || in_array($occur_zero, $this->byday) || in_array($occur_neg, $this->byday)) { $tmp_array[] = clone $date_time; } } if($_pos > 0) { $this->suggestions[] = clone $tmp_array[$_pos - 1]; } else { $this->suggestions[] = clone $tmp_array[count($tmp_array) + $_pos]; } } } } } elseif($this->gobyyearday) { foreach($this->byyearday as $_day) { if($_day >= 0) { $_day--; $_time = strtotime('+' . $_day . ' days', mktime(0, 0, 0, 1, 1, $year)); $this->suggestions[] = new Datetime(date('Y-m-d', $_time) . ' ' . $timestamp); } else { $year_day_neg = 365 + $_day; $leap_year = $this->try_date->format('L'); if($leap_year == 1) { $year_day_neg = 366 + $_day; } $_time = strtotime('+' . $year_day_neg . ' days', mktime(0, 0, 0, 1, 1, $year)); $this->suggestions[] = new Datetime(date('Y-m-d', $_time) . ' ' . $timestamp); } } } // special case because for years you need to loop through the months too elseif($this->gobyday && $interval == "year") { foreach($this->bymonth as $_month) { // this creates an array of days of the month $_mdays = range(1, date('t',mktime(0,0,0,$_month,1,$year))); foreach($_mdays as $_mday) { $date_time = new DateTime($year . '-' . $_month . '-' . $_mday . ' ' . $timestamp); // get the week of the month (1, 2, 3, 4, 5, etc) $week = $date_time->format('W'); if($date_time >= $this->start_date && in_array($week, $this->byweekno)) { $this->suggestions[] = clone $date_time; } } } } elseif($interval == "day") { $this->suggestions[] = clone $this->try_date; } elseif($interval == "week") { $this->suggestions[] = clone $this->try_date; if($this->gobyday) { $week_day = $this->try_date->format('w'); $days_in_month = $this->try_date->format('t'); $overflow_count = 1; $_day = $month_day; $run = true; while($run) { $_day++; if($_day <= $days_in_month) { $tmp_date = new DateTime($year . '-' . $month . '-' . $_day . ' ' . $timestamp); } else { $tmp_month = $month+1; $tmp_date = new DateTime($year . '-' . $tmp_month . '-' . $overflow_count . ' ' . $timestamp); $overflow_count++; } $week_day = $tmp_date->format('w'); if($this->try_date == $this->start_date) { if($week_day == $this->wkst) { $this->try_date = clone $tmp_date; $this->try_date->modify('-7 days'); $run = false; } } if($week_day != $this->wkst) { $this->suggestions[] = clone $tmp_date; } else { $run = false; } } } } elseif($this->gobyday || $interval == "month") { $_mdays = range(1, date('t',mktime(0,0,0,$month,1,$year))); foreach($_mdays as $_mday) { $date_time = new DateTime($year . '-' . $month . '-' . $_mday . ' ' . $timestamp); // get the week of the month (1, 2, 3, 4, 5, etc) $week = $date_time->format('W'); if($date_time >= $this->start_date && in_array($week, $this->byweekno)) { $this->suggestions[] = clone $date_time; } } } elseif($this->gobymonth) { foreach($this->bymonth as $_month) { $date_time = new DateTime($year . '-' . $_month . '-' . $month_day . ' ' . $timestamp); if($date_time >= $this->start_date) { $this->suggestions[] = clone $date_time; } } } else { $this->suggestions[] = clone $this->try_date; } if($interval == "month") { $this->try_date->modify('last day of ' . $this->interval . ' ' . $interval); } else { $this->try_date->modify($this->interval . ' ' . $interval); } } protected function valid_date($date) { $year = $date->format('Y'); $month = $date->format('n'); $day = $date->format('j'); $year_day = $date->format('z') + 1; $year_day_neg = -366 + $year_day; $leap_year = $date->format('L'); if($leap_year == 1) { $year_day_neg = -367 + $year_day; } // this is the nth occurence of the date $occur = ceil($day / 7); $week = $date->format('W'); $day_of_week = $date->format('l'); $dow_abr = strtoupper(substr($day_of_week, 0, 2)); // set the day of the month + (positive) $occur = '+' . $occur . $dow_abr; $occur_zero = '+0' . $dow_abr; // set the day of the month - (negative) $total_days = $date->format('t') - $date->format('j'); $occur_neg = '-' . ceil(($total_days + 1)/7) . $dow_abr; $day_from_end_of_month = $date->format('t') + 1 - $day; if(in_array($month, $this->bymonth) && (in_array($occur, $this->byday) || in_array($occur_zero, $this->byday) || in_array($occur_neg, $this->byday)) && in_array($week, $this->byweekno) && (in_array($day, $this->bymonthday) || in_array(-$day_from_end_of_month, $this->bymonthday)) && (in_array($year_day, $this->byyearday) || in_array($year_day_neg, $this->byyearday))) { return true; } else { return false; } } // return the next valid DateTime object which matches the pattern and follows the rules public function next() { // check the counter is set if($this->count !== 0) { if($this->counter >= $this->count) { return false; } } // create initial set of suggested dates if(count($this->suggestions) === 0) { $this->create_suggestions(); } // loop through the suggested dates while(count($this->suggestions) > 0) { // get the first one on the array $try_date = array_shift($this->suggestions); // make sure the date doesn't exceed the max date if($try_date > $this->end_date) { return false; } // make sure it falls within the allowed days if($this->valid_date($try_date) === true) { $this->counter++; return $try_date; } else { // we might be out of suggested days, so load some more if(count($this->suggestions) === 0) { $this->create_suggestions(); } } } } } <file_sep>/php/When v3/README.txt ##When Date/Calendar recursion library for PHP 5.2+ Author: <NAME> Contributors: <NAME>, <NAME> --- ###About After a comprehensive search I couldn't find a PHP library which could handle recursive dates. There is: [http://phpicalendar.org/][6] however it would have been extremely difficult to extract the recursion portion of the script from the application. Oddly, there are extremely good date recursion libraries for both Ruby and Python: Ruby: [http://github.com/seejohnrun/ice_cube][1] Python: [http://labix.org/python-dateutil][2] Since I couldn't find an equivalent for PHP I created [When][3]. --- ###Unit Tests Tests were written in PHPUnit ([http://www.phpunit.de/][4]) Initial set of tests were created from the examples found within RFC5545 ([http://tools.ietf.org/html/rfc5545][5]). ----------------------------------- ###Documentation Initializing the class $when = new When(); Once you have initialized the class you can create a recurring event by calling on the recur method $when->recur(<DateTime object|valid Date string>, <yearly|monthly|weekly|daily>); You can limit the number of dates to find by specifying a limit(): $when->limit(<int>); Alternatively you can specify an end date: $when->until(<DateTime object|valid Date String>); Note: the end date does not have to match the recurring pattern. Note: the script will stop returning results when either the limit or the end date is met. More documentation to come, please take a look at the unit tests for an understanding of what the class is capable of. --- ###Examples (take a look at the unit tests for more examples) The next 5 occurrences of Friday the 13th: $r = new When(); $r->recur(new DateTime(), 'monthly') ->count(5) ->byday(array('FR')) ->bymonthday(array(13)); while($result = $r->next()) { echo $result->format('c') . '<br />'; } Every four years, the first Tuesday after a Monday in November, for the next 20 years (U.S. Presidential Election day): // this is the next election date $start = new DateTime('2012-09-06'); $r = new When(); $r->recur($start, 'yearly') ->until($start->modify('+20 years')) ->interval(4) ->bymonth(array(11)) ->byday(array('TU')) ->bymonthday(array(2,3,4,5,6,7,8)); while($result = $r->next()) { echo $result->format('c') . '<br />'; } You can now pass raw RRULE's to the class: $r = new When(); $r->recur('19970922T090000')->rrule('FREQ=MONTHLY;COUNT=6;BYDAY=-2MO'); while($result = $r->next()) { echo $result->format('c') . '<br />'; } **Warnings:** * If you submit a pattern which has no results the script will loop infinitely. * If you do not specify an end date (until) or a count for your pattern you must limit the number of results within your script to avoid an infinite loop. --- ###Contributing If you would like to contribute please create a fork and upon making changes submit a pull request. Please ensure 100% pass of unit tests before submitting a pull request. There are 78 tests, 1410 assertions currently. >>>phpunit --verbose tests PHPUnit 3.4.15 by <NAME>. tests When_Core_Tests .. When_Daily_Rrule_Test ..... When_Daily_Test ..... When_Iterator_Tests .. When_Monthly_Rrule_Test .............. When_Monthly_Test .............. When_Weekly_Rrule_Test ........ When_Weekly_Test ........ When_Rrule_Test .......... When_Yearly_Test .......... Time: 2 seconds, Memory: 6.00Mb OK (78 tests, 1410 assertions) --- ###License Copyright (c) 2010 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [1]: http://github.com/seejohnrun/ice_cube [2]: http://labix.org/python-dateutil [3]: http://github.com/tplaner/When [4]: http://www.phpunit.de/ [5]: http://tools.ietf.org/html/rfc5545 [6]: http://phpicalendar.org/ <file_sep>/samples/single-hc_events.php <?php get_header(); ?> <div id="Content"> <?php if ( has_post_thumbnail(9) ) { // the current page has a feature image echo get_the_post_thumbnail(9,'post-thumbnail',''); } ?> <div class="clear"></div> <br /><br /> <div id="Sub-Content"> <div class="breadcrumbs"> <a href="<?php bloginfo('url') ?>/dance-lessons/" title="Dance Lessons">Dance Lessons</a> <!--&gt; <?php echo get_the_term_list( $post->ID, 'event_categories', '', ', ', '' ); ?>--> &gt; <?php echo $post->post_title ?> </div> <br /> <?php while (have_posts()): the_post(); ?> <div class="Blog_Post"> <h1><?php echo the_title('','',0); ?></h1> <br /> <small>Posted on <?php the_time('F jS, Y') ?></small> <br /><br /> <div class="Blog_Post_Content"> <?php the_content(__('(more...)')); ?> </div> <br /><br /> <small>Posted in:</small> <br /> <?php $terms = get_the_terms($post->ID, 'event_categories'); foreach ($terms as $term) { ?> <div class='button'> <a href="<?php echo get_bloginfo('url') . "/event-categories/" . $term->slug?>" class="Link-Fill-Container"> <?php echo $term->name ?> </a> </div> <?php } ?> </div> <?php endwhile; ?> </div> <div id="Sidebar"> <div class="button">EVENT TYPES</div> <ul> <?php wp_list_categories(array('taxonomy' => 'event_categories', 'orderby' => 'name', 'show_count' => 0, 'pad_counts' => 0, 'hierarchical' => 1,'title_li' => '')); ?> </ul> </div> </div> <?php get_footer(); ?><file_sep>/php/When v3/Tests/When_Weekly_Test.php <?php require_once 'PHPUnit/Framework.php'; require_once './When.php'; class When_Weekly_Test extends PHPUnit_Framework_TestCase { /** * Weekly for 10 occurrences: * DTSTART;TZID=America/New_York:19970902T090000 * RRULE:FREQ=WEEKLY;COUNT=10 */ function testTwentyFive() { $results[] = new DateTime('1997-09-02 09:00:00'); $results[] = new DateTime('1997-09-09 09:00:00'); $results[] = new DateTime('1997-09-16 09:00:00'); $results[] = new DateTime('1997-09-23 09:00:00'); $results[] = new DateTime('1997-09-30 09:00:00'); $results[] = new DateTime('1997-10-07 09:00:00'); $results[] = new DateTime('1997-10-14 09:00:00'); $results[] = new DateTime('1997-10-21 09:00:00'); $results[] = new DateTime('1997-10-28 09:00:00'); $results[] = new DateTime('1997-11-04 09:00:00'); $r = new When(); $r->recur('19970902T090000', 'weekly')->count(10); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Weekly until December 24, 1997: * DTSTART;TZID=America/New_York:19970902T090000 * RRULE:FREQ=WEEKLY;UNTIL=19971224T000000Z */ function testTwentySix() { $results[] = new DateTime('1997-09-02 09:00:00'); $results[] = new DateTime('1997-09-09 09:00:00'); $results[] = new DateTime('1997-09-16 09:00:00'); $results[] = new DateTime('1997-09-23 09:00:00'); $results[] = new DateTime('1997-09-30 09:00:00'); $results[] = new DateTime('1997-10-07 09:00:00'); $results[] = new DateTime('1997-10-14 09:00:00'); $results[] = new DateTime('1997-10-21 09:00:00'); $results[] = new DateTime('1997-10-28 09:00:00'); $results[] = new DateTime('1997-11-04 09:00:00'); $results[] = new DateTime('1997-11-11 09:00:00'); $results[] = new DateTime('1997-11-18 09:00:00'); $results[] = new DateTime('1997-11-25 09:00:00'); $results[] = new DateTime('1997-12-02 09:00:00'); $results[] = new DateTime('1997-12-09 09:00:00'); $results[] = new DateTime('1997-12-16 09:00:00'); $results[] = new DateTime('1997-12-23 09:00:00'); $r = new When(); $r->recur('19970902T090000', 'weekly')->until('19971224T000000'); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Every other week - forever: * DTSTART;TZID=America/New_York:19970902T090000 * RRULE:FREQ=WEEKLY;INTERVAL=2;WKST=SU */ function testTwentySeven() { $results[] = new DateTime('1997-09-02 09:00:00'); $results[] = new DateTime('1997-09-16 09:00:00'); $results[] = new DateTime('1997-09-30 09:00:00'); $results[] = new DateTime('1997-10-14 09:00:00'); $results[] = new DateTime('1997-10-28 09:00:00'); $results[] = new DateTime('1997-11-11 09:00:00'); $results[] = new DateTime('1997-11-25 09:00:00'); $results[] = new DateTime('1997-12-09 09:00:00'); $results[] = new DateTime('1997-12-23 09:00:00'); $results[] = new DateTime('1998-01-06 09:00:00'); $results[] = new DateTime('1998-01-20 09:00:00'); $results[] = new DateTime('1998-02-03 09:00:00'); $results[] = new DateTime('1998-02-17 09:00:00'); $r = new When(); $r->recur('19970902T090000', 'weekly')->count(13)->interval(2)->wkst('SU'); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Weekly on Tuesday and Thursday for five weeks: * DTSTART;TZID=America/New_York:19970902T090000 * RRULE:FREQ=WEEKLY;UNTIL=19971007T000000Z;WKST=SU;BYDAY=TU,TH * or * RRULE:FREQ=WEEKLY;COUNT=10;WKST=SU;BYDAY=TU,TH */ function testTwentyEight() { $results[] = new DateTime('1997-09-02 09:00:00'); $results[] = new DateTime('1997-09-04 09:00:00'); $results[] = new DateTime('1997-09-09 09:00:00'); $results[] = new DateTime('1997-09-11 09:00:00'); $results[] = new DateTime('1997-09-16 09:00:00'); $results[] = new DateTime('1997-09-18 09:00:00'); $results[] = new DateTime('1997-09-23 09:00:00'); $results[] = new DateTime('1997-09-25 09:00:00'); $results[] = new DateTime('1997-09-30 09:00:00'); $results[] = new DateTime('1997-10-02 09:00:00'); $r = new When(); $r->recur('19970902T090000', 'weekly')->until('19971007T000000')->wkst('SU')->byday(array('TU', 'TH')); foreach($results as $result) { $this->assertEquals($result, $r->next()); } unset($r); $r = new When(); $r->recur('19970902T090000', 'weekly')->count(10)->wkst('SU')->byday(array('TU', 'TH')); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Every other week on Monday, Wednesday, and Friday until December 24, 1997, starting on Monday, September 1, 1997: * DTSTART;TZID=America/New_York:19970901T090000 * RRULE:FREQ=WEEKLY;INTERVAL=2;UNTIL=19971224T000000Z;WKST=SU;BYDAY=MO,WE,FR */ function testTwentyNine() { $results[] = new DateTime('1997-09-01 09:00:00'); $results[] = new DateTime('1997-09-03 09:00:00'); $results[] = new DateTime('1997-09-05 09:00:00'); $results[] = new DateTime('1997-09-15 09:00:00'); $results[] = new DateTime('1997-09-17 09:00:00'); $results[] = new DateTime('1997-09-19 09:00:00'); $results[] = new DateTime('1997-09-29 09:00:00'); $results[] = new DateTime('1997-10-01 09:00:00'); $results[] = new DateTime('1997-10-03 09:00:00'); $results[] = new DateTime('1997-10-13 09:00:00'); $results[] = new DateTime('1997-10-15 09:00:00'); $results[] = new DateTime('1997-10-17 09:00:00'); $results[] = new DateTime('1997-10-27 09:00:00'); $results[] = new DateTime('1997-10-29 09:00:00'); $results[] = new DateTime('1997-10-31 09:00:00'); $results[] = new DateTime('1997-11-10 09:00:00'); $results[] = new DateTime('1997-11-12 09:00:00'); $results[] = new DateTime('1997-11-14 09:00:00'); $results[] = new DateTime('1997-11-24 09:00:00'); $results[] = new DateTime('1997-11-26 09:00:00'); $results[] = new DateTime('1997-11-28 09:00:00'); $results[] = new DateTime('1997-12-08 09:00:00'); $results[] = new DateTime('1997-12-10 09:00:00'); $results[] = new DateTime('1997-12-12 09:00:00'); $results[] = new DateTime('1997-12-22 09:00:00'); $r = new When(); $r->recur('19970901T090000', 'weekly')->until('19971224T000000')->wkst('SU')->interval(2)->byday(array('MO', 'WE', 'FR')); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Every other week on Tuesday and Thursday, for 8 occurrences: * DTSTART;TZID=America/New_York:19970902T090000 * RRULE:FREQ=WEEKLY;INTERVAL=2;COUNT=8;WKST=SU;BYDAY=TU,TH */ function testThirty() { $results[] = new DateTime('1997-09-02 09:00:00'); $results[] = new DateTime('1997-09-04 09:00:00'); $results[] = new DateTime('1997-09-16 09:00:00'); $results[] = new DateTime('1997-09-18 09:00:00'); $results[] = new DateTime('1997-09-30 09:00:00'); $results[] = new DateTime('1997-10-02 09:00:00'); $results[] = new DateTime('1997-10-14 09:00:00'); $results[] = new DateTime('1997-10-16 09:00:00'); $r = new When(); $r->recur('19970902T090000', 'weekly')->interval(2)->count(8)->wkst('SU')->byday(array('TU', 'TH')); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * An example where the days generated makes a difference because of WKST: * DTSTART;TZID=America/New_York:19970805T090000 * RRULE:FREQ=WEEKLY;INTERVAL=2;COUNT=4;BYDAY=TU,SU;WKST=MO */ function testThirtyOne() { $results[] = new DateTime('1997-08-05 09:00:00'); $results[] = new DateTime('1997-08-10 09:00:00'); $results[] = new DateTime('1997-08-19 09:00:00'); $results[] = new DateTime('1997-08-24 09:00:00'); $r = new When(); $r->recur('19970805T090000', 'weekly')->interval(2)->count(4)->byday(array('TU', 'SU'))->wkst('MO'); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * changing only WKST from MO to SU, yields different results... * DTSTART;TZID=America/New_York:19970805T090000 * RRULE:FREQ=WEEKLY;INTERVAL=2;COUNT=4;BYDAY=TU,SU;WKST=SU */ function testThirtyTwo() { $results[] = new DateTime('1997-08-05 09:00:00'); $results[] = new DateTime('1997-08-17 09:00:00'); $results[] = new DateTime('1997-08-19 09:00:00'); $results[] = new DateTime('1997-08-31 09:00:00'); $r = new When(); $r->recur('19970805T090000', 'weekly')->interval(2)->count(4)->byday(array('TU', 'SU'))->wkst('SU'); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } } <file_sep>/php/When v3/Tests/When_Core_Test.php <?php require_once 'PHPUnit/Framework.php'; require_once './When.php'; class When_Core_Tests extends PHPUnit_Framework_TestCase { // passing an invalid DateTime public function testInvalidDate() { $this->setExpectedException('InvalidArgumentException'); $r = new When(); $r->recur('NOT A VALID TIME STAMP', 'yearly'); } // passing an invalid Frequency public function testValidFrequencies() { $this->setExpectedException('InvalidArgumentException'); $r = new When(); $r->recur('2000-01-01', 'yearlyy'); } } <file_sep>/php/hc-event-functions.php <?php /* This page is contains functions called via ajax from scripts in hc-event-calendar.php */ //Reference wp-load to provide wordpress functions / globals to this external script //This should point to your wordpress root/wp-load.php file require( '../../../../wp-load.php' ); //date_default_timezone_set('America/New_York'); date_default_timezone_set('UTC'); //************* AJAX CALLS ***************// //CREATE NEW EVENT CREATION FORM if ($_REQUEST['hc_ajax_request'] == "create_event_creation_form") { create_event_creation_form(); } //CREATE NEW EVENT if ($_REQUEST['hc_ajax_request'] == "process_event_creation_form") { echo json_encode(process_new_event_form($_REQUEST['hc_event_title'], $_REQUEST['hc_event_color'], $_REQUEST['hc_event_event_categories'], $_REQUEST['hc_event_start'], $_REQUEST['hc_event_end'], $_REQUEST['hc_event_start_time'], $_REQUEST['hc_event_end_time'], $_REQUEST['hc_event_allday'], $_REQUEST['hc_event_is_repeat'], $_REQUEST['hc_event_frequency'], $_REQUEST['hc_event_interval'], $_REQUEST['hc_event_offset'])); } //EDIT EVENT FORM if ($_REQUEST['hc_ajax_request'] == "create_edit_event_form") { create_edit_event_form($_REQUEST['hc_event_id'], $_REQUEST['hc_event_recurrance']); } //EDIT EVENT FORM if ($_REQUEST['hc_ajax_request'] == "process_event_edit_form") { echo json_encode(process_event_edit_form($_REQUEST['hc_event_id'], $_REQUEST['hc_event_title'], $_REQUEST['hc_event_color'], $_REQUEST['hc_event_categories'], $_REQUEST['hc_event_start'], $_REQUEST['hc_event_end'], $_REQUEST['hc_event_start_time'], $_REQUEST['hc_event_end_time'], $_REQUEST['hc_event_allday'], $_REQUEST['hc_event_is_repeat'], $_REQUEST['hc_event_frequency'], $_REQUEST['hc_event_interval'])); } //DELETE EVENT if ($_REQUEST['hc_ajax_request'] == "delete_event") { delete_event($_REQUEST['hc_event_id']); } //Request all events in an JSON array if ($_REQUEST['hc_ajax_request'] == "request_all_JSON_events") { echo json_encode(request_calendar_events()); } //Move an event if ($_REQUEST['hc_ajax_request'] == "update_moved_event") { echo json_encode(update_moved_event($_REQUEST['hc_event_id'], $_REQUEST['hc_event_start'], $_REQUEST['hc_event_end'], $_REQUEST['hc_event_allday'])); } //Resize an event if ($_REQUEST['hc_ajax_request'] == "update_resized_event") { echo json_encode(update_resized_event($_REQUEST['hc_event_id'], $_REQUEST['hc_event_end'])); } //************* FUNCTIONS ***************// function request_calendar_events() { //Our calendar needs a slimed down array, with on specific event data. $hc_events = request_all_events(); foreach ($hc_events as $i => $hc_event) { $hc_events_out[$i]['id'] = $hc_event['ID']; $hc_events_out[$i]['title'] = $hc_event['post_title']; $hc_events_out[$i]['summary'] = $hc_event['hc_event_post_summary']; $hc_events_out[$i]['start'] = date('c', intval($hc_event['hc_event_start'])); $hc_events_out[$i]['end'] = date('c', intval($hc_event['hc_event_end'])); $hc_events_out[$i]['className'] = $hc_event['hc_event_classname']; $hc_events_out[$i]['allDay'] = $hc_event['hc_event_allday']; $hc_events_out[$i]['recurrance'] = $hc_event['hc_event_recurrance']; //var_dump($hc_event['hc_event_category_color']); if ($hc_event['hc_event_color'] == "" || $hc_event['hc_event_color'] == " ") { //echo "[" . $hc_event['hc_event_category_color'] . "]"; $hc_events_out[$i]['color'] = get_metadata('hc_event_categories', $hc_event['hc_event_category_color'], 'hc_event_category_color', true); } else { //echo "blah"; $hc_events_out[$i]['color'] = $hc_event['hc_event_color']; } $hc_events_out[$i]['url'] = $hc_event['hc_event_url']; $hc_events_out[$i]['terms'] = $hc_event['hc_event_terms']; $hc_events_out[$i]['hc_event_allow_paying'] = $hc_event['hc_event_allow_paying']; $hc_events_out[$i]['hc_event_amount'] = $hc_event['hc_event_amount']; $hc_events_out[$i]['hc_event_allow_paying_until'] = $hc_event['hc_event_allow_paying_until']; } return $hc_events_out; } //CREATE EVENT CREATION FORM function create_event_creation_form () { ?> <div class="hc_event-controller-dialog"> <form id="hc_new_event_form"> <table cellpadding="5" cellspacing="5"> <tr> <td colspan="2"><div class="hc_event_form_feedback"></div></td> </tr><tr> <td><label for="hc_event_title">When</label></td> <td> <b> <?php echo date('D, F d', $_REQUEST['hc_event_start']); //need to check start / end day, not timestamp (we dont want to count hours / minutes if (date('D, F d', $_REQUEST['hc_event_start']) != date('D, F d', $_REQUEST['hc_event_end'])) { echo ' - ' . date('D, F d', $_REQUEST['hc_event_end']); } ?></b> </td> </tr><tr> <td><label for="hc_event_title">What</label></td> <td><input type="text" size="30" name="hc_event_title" id="hc_event_title" value="<?php echo $hc_event['post_title']?>"/></td> </tr><tr> <td colspan="2" class='hc_event_new_edit_url'> </td> </tr><tr> <td> <input type="hidden" name="hc_event_start" value="<?php echo $_REQUEST['hc_event_start']; ?>" id="hc_event_start"/> <input type="hidden" name="hc_event_end" value="<?php echo $_REQUEST['hc_event_end']; ?>" id="hc_event_end"/> <input type="hidden" name="hc_event_allday" value="1" id="hc_event_allday"/> <input type="hidden" name="hc_ajax_request" value="process_event_creation_form" /> <input type="submit" value="Create" /> </td> <td> or <a class="hc_event_close" href="#">Cancel</a> </td> </tr> </table> </form> </div> <?php } //CREATE EVENT EDIT FORM function create_edit_event_form ($hc_event_id, $hc_event_recurrance) { global $wpdb; global $blog_id; //Check if this plugin is being used in a multi-site blog //If it is we want to select event posts from the current blog only if ( is_multisite() ) { $posts_table = "wp_" . $blog_id . "_posts"; } else { $posts_table = "wp_posts"; } //echo "ID: " . $hc_event_id; //print_r($hc_event_recurrance); //Select all event posts $hc_event = $wpdb->get_results("SELECT * FROM " . $posts_table . " WHERE ID = $hc_event_id AND post_status = 'publish'", ARRAY_A); //print_r($hc_event); $hc_event = $hc_event[0]; $hc_event['hc_event_start'] = get_post_meta($hc_event['ID'], 'hc_event_start', true); $hc_event['hc_event_end'] = get_post_meta($hc_event['ID'], 'hc_event_end', true); $hc_event['hc_event_allday'] = get_post_meta($hc_event['ID'], 'hc_event_allday', true); $hc_event['hc_event_color'] = get_post_meta($hc_event['ID'], 'hc_event_color', true); //$hc_event['recurrance'] = get_post_meta($hc_event['ID'], '_recurrance', true); $hc_event['hc_event_recurrance'] = $hc_event_recurrance; ?> <div class="hc_event-controller-dialog"> <form id="hc_event_edit_event_form"> <table cellpadding="5" cellspacing="5"> <tr> <td colspan="2"><div class="hc_event_form_feedback"></div></td> </tr><tr> <td><label for="hc_event_title">When</label></td> <td> <b> <?php echo date('D, F d', $hc_event['hc_event_start']); if ($hc_event['hc_event_allday'] == 0) { echo "<br /><small>" . date('ga', $hc_event['hc_event_start']); echo " - " . date('ga', $hc_event['hc_event_end']); echo "</small>"; } //need to check start / end day, not timestamp (we dont want to count hours / minutes if (date('D, F d', $hc_event['hc_event_start']) != date('D, F d', $hc_event['hc_event_end'])) { echo ' - ' . date('D, F d', $hc_event['hc_event_end']); } ?></b> </td> </tr><tr> <td><label for="hc_event_title">What</label></td> <td><input type="text" size="30" name="hc_event_title" id="hc_event_title" value="<?php echo $hc_event['post_title']?>"/></td> </tr><tr> <td colspan="2"> <a href="<?php bloginfo('url') ?>/wp-admin/post.php?post=<?php echo $hc_event_id?>&action=edit" title="Edit in full editor">Edit Event Details</a> </td> </tr><tr> <td> <input type="hidden" name="hc_event_id" value="<?php echo $hc_event['ID']; ?>" id="hc_event_id"/> <input type="hidden" name="hc_event_start" value="<?php echo $hc_event['hc_event_start']; ?>" id="hc_event_start"/> <input type="hidden" name="hc_event_end" value="<?php echo $hc_event['hc_event_end']; ?>" id="hc_event_end"/> <input type="hidden" name="hc_ajax_request" value="process_event_edit_form" /> <input type="submit" value="Update" /> </td> <td> <a href="#" class="hc_event_delete">Delete</a> or <a class="hc_event_close" href="#">Close</a> </td> </tr> </table> </form> </div> <?php } //CREATE NEW EVENT //Pre: (string event title, int start timestamp, int end timestamp, bool if the event is all day //Post: Return JSON formated string of the newly created event function process_new_event_form ($hc_event_title, $hc_event_color, $hc_event_categories, $hc_event_start, $hc_event_end, $hc_event_start_time, $hc_event_end_time, $hc_event_allday, $hc_event_is_repeat, $hc_event_frequency, $hc_event_interval) { //print_r($_REQUEST); //print_r(func_get_args()); global $wpdb; /* $hc_event_category = array(0 => $hc_event_category); if ($hc_event_is_repeat == 1) { //Generate the recurrance pattern $hc_event_recurrance = array( "hc_event_frequency" => $fhc_event_requency, "hc_event_interval" => $hc_event_interval ); $hc_event_recurrance_serialized = serialize($hc_event_recurrance); } else { $hc_event_recurrance = ""; } */ //$hc_event_start = strtotime(date('j F Y', $hc_event_start)); //$hc_event_end = strtotime(date('j F Y', $hc_event_end)); //Create a new wordpress post in the dance lessons custom post type // Create post object $hc_event_post = array( 'post_title' => $hc_event_title, 'post_type' => 'hc_events', 'post_content' => $hc_event_description, 'post_status' => 'publish', 'post_author' => 1 ); // Insert the post into the wp database $hc_event_post_id = wp_insert_post($hc_event_post); //Attach the custom taxonomy to our new post //wp_set_object_terms($hc_event_post_id, $hc_event_categories,'hc_event_categories',false); //Lets store all our meta box event settigns in an array and loop through it to store / update data $meta_data['hc_event_start'] = $hc_event_start; $meta_data['hc_event_end'] = $hc_event_end; //$meta_data['hc_event_color'] = $color; $meta_data['hc_event_allday'] = $hc_event_allday; //$meta_data['hc_event_recurrance'] = $recurrance; store_meta_data($hc_event_post_id, $meta_data); //Return an array of the event data //NEED TO DO! //we must return an array of all recurrance items if there are any in this request //then we need to process those on ajax return to create all the new events return array( 'hc_event_created' => true, 'hc_event_id' => $hc_event_post_id, 'hc_event_title' => $hc_event_title, 'hc_event_start' => $hc_event_start, 'hc_event_end' => $hc_event_end, 'hc_event_allday' => $hc_event_allday, 'hc_event_classname' => 'event-' . $hc_event_post_id/*, 'hc_event_color' => $hc_event_color*/ ); } //UPDATE EVENT function process_event_edit_form ($hc_event_id, $hc_event_title, $hc_event_color, $hc_event_hc_eventtypes, $hc_event_start, $hc_event_end, $hc_event_start_time, $hc_event_end_time, $hc_event_allday, $hc_event_is_repeat, $hc_event_frequency, $hc_event_interval) { //print_r(func_get_args()); $hc_event_updated_post = array(); $hc_event_updated_post['ID'] = $hc_event_id; $hc_event_updated_post['post_title'] = $hc_event_title; $hc_event_updated_post['post_content'] = $hc_event_content; wp_update_post($hc_event_updated_post); /* //Make sure to set allday to 0 if it has not been set during form input (inactive) if ($hc_event_allday == 1) { $hc_event_allday = 1; } else { //All day has been unchecked, so the event will have a start and end time (hours) $hc_event_allday = 0; $hc_event_start = strtotime(date('j F Y', $hc_event_start) . ' ' . $hc_event_start_time); $hc_event_end = strtotime(date('j F Y', $hc_event_end) . ' ' . $hc_event_end_time); } */ $hc_event_allday = 1; if ($hc_event_is_repeat == 1) { //Generate the recurrance pattern $hc_event_recurrance = array( "hc_event_frequency" => $hc_event_frequency, "hc_event_interval" => $hc_event_interval ); $hc_event_recurrance_serialized = serialize($hc_event_recurrance); } else { $hc_event_recurrance = ""; } //update terms $meta_data['hc_event_start'] = $hc_event_start; $meta_data['hc_event_end'] = $hc_event_end; $meta_data['hc_event_color'] = $hc_event_color; $meta_data['hc_event_allday'] = $hc_event_allday; $meta_data['hc_event_recurrance'] = $hc_event_recurrance; //update recurrance store_meta_data($hc_event_id, $meta_data); return array( 'hc_event_updated' => true, 'hc_event_id' => $hc_event_id, 'hc_event_title' => $hc_event_title, 'hc_event_start' => $hc_event_start, 'hc_event_end' => $hc_event_end, 'hc_event_allday' => $hc_event_allday, 'hc_event_className' => 'event-' . $hc_event_id, 'hc_event_color' => $hc_event_color ); } //UPDATE MOVED EVENT //Pre: int event id, int start timestamp, int end timestamp //Post: BOOL true on success, false on failure function update_moved_event ($hc_event_id, $hc_event_start, $hc_event_end, $hc_event_allday) { if ($hc_event_allday == "true") { $hc_event_allday = 1; } if ($hc_event_allday == "false") { $hc_event_allday = 0; } $hc_event_allday = abs($hc_event_allday); if ($hc_event_end == 'null' || $hc_event_end == "") { $hc_event_end = $hc_event_start; } update_post_meta($hc_event_id, 'hc_event_start', $hc_event_start); update_post_meta($hc_event_id, 'hc_event_end', $hc_event_end); update_post_meta($hc_event_id, 'hc_event_allday', $hc_event_allday); return true; } //UPDATE RESIZED EVENT function update_resized_event ($hc_event_id, $hc_event_end) { update_post_meta($hc_event_id, 'hc_event_end', $hc_event_end); return true; } //DELETE EVENT function delete_event ($hc_event_id) { wp_delete_post( $hc_event_id, $force_delete = true ); //Pass back the event id so it can be removed from the calendar echo $hc_event_id; } ?><file_sep>/readme.txt Plugin Name: Honeycomb Event Calendar Plugin URI: http://www.jamesmehorter.com Description: The Honeycomb Event Calendar plugin for WordPress 3.0+ helps you build and organize your events. Version: 0.1 Author: <NAME> Author URI: http://www.Jamesmehorter.com Copyright 2011 <NAME> (email : <EMAIL>) ABOUT The plugin uses WordPress' built-in custom post types, post meta data, and custom taxonomies - so it plays real nice with tamplate files and permalinks. There are no extra database tables created, and there is no extra data placed in the wp-options table. Events can be displayed in a category view or list view, and both are easily incorporated in your template files or page/posts with shortcodes. You can sort events by hierarchical categories, just like you would blog posts. Since events are created as posts, and categories as custom taxonomies you can easily build template files like single-events.php or taxonomy-event-types.php which will leverage WordPress' permalinks so you can immediately can go to www.mysite.com/events/my-sweet-event. This plugin creates custom posts 'Events' with a hierarchical taxonomy 'Event Types' for sorting. All event data; like start, end, allDay, and recurrance are stored as meta data on the post for each event. This way there is not extra db table for storing events. This also means we're leverging the built-in post type, taxonomy, and permalinks. So when an event is created, you can go to www.mysite.com/events/my-sweet-event. If you create a taxonomy term(category) for this post, like: 'Concerts'; you can then go to www.mysite.com/concerts/my-sweet-event. See usage info below for tips on styling the output This plugin essentially mashes several jQuery plugins together. We obviously use the core jQuery library. We then use the jQuery-UI core, widget, mouse, draggable, resizeable, and datepicker plugins. For the primary calendar view functionality we chose to use the Full Calendar jQuery plugin. http://arshaw.com/fullcalendar/ For the calendar view tooltip popups we chose to use simpletip http://craigsworks.com/projects/simpletip/. We also used the Syronex Colorpicker jQuery plugin for choosing event colors http://www.syronex.com/software/jquery-color-picker. The 'When' PHP library is also used to calculate date recurrance events https://github.com/tplaner/When. UPDATES We have not touched/hacked any of these dependant plugins, so they can *usually* be updated independently when new versions are released. Though, We will do our best to release updates for this plugin when we feel those dependant plugin updates are ready to be released. As of WordPress 3.0.4 the use of enqueue_script still does not work correctly to use the WordPress jQuery/jQuery-UI libraries, or maybe we're just being dumb - so for now they are bundled with this plugin. INSTALLATION Install the plugin as you would any other After installation: + A custom post type 'Events' and a custom taxonomy 'Event Types' will be created (You can alter these names below) + You will see a 'Events' menu in the WordPress admin to manage your new events posts + Under the 'Events' menu you will see the 'Event Types' taxonomy we created to manage your categories + Under the 'Events' menu you will also see a 'Calendar View' menu to manage your events in a drag and drop calendar view. USAGE You can create events in the 'wp-admin > Events' page, this is default custom post type page. You can also edit events here as well. Though, the real gem of this plugin lay in the 'Calendar View'. Here you can intuitively create events by clicking on days or by dragging out over several days. You can resize events by dragging on their corners. You can move events by click-dragging them around the calendar. You can drag a series of events (recurring events) as a set. And You can edit events by clicking on them. You can display a list of events with a template tag. You can also filter by a certain event type (term), and/or limit the event list items shown. Note: to filter by term you must of assigned (event type) terms to your events. You can do this while editing each event in wp-admin > Events REFERENCE & OPTIONS You can display a public version of the calendar view in a page or post with the shortcode: [events-calendar-view] OR By calling the PHP function directly <?php Display_Event_Calendar() ;?> You can display a list of events in a page or post with the shortcode: ex 1: Show all upcoming events [events-list-view] OR <?php Display_List_Of_Events('', 1) ;?> ex 2: Show 3 upcoming events [events-list-view limit=3] (The limit argument is optional) OR <?php Display_List_Of_Events('', 3) ;?> ex 3: Show 8 results with the term 'Concert' [events-list-view terms='Concert' limit=8] (The terms argument is optional) OR <?php Display_List_Of_Events('Concert', 8) ;?> ex 4: Show 12 results with any/all of the terms 'Concert, Live Music, Acoustic', note: order does not matter [events-list-view limit=12 terms='Concert, Live Music, Acoustic'] OR <?php Display_List_Of_Events('Concert, Live Music, Acoustic', 12) ;?> You can display a list of terms in the Event Types taxonomy with either a shortcode or directly calling the php function ex 1: Show a list of event type terms [event-type-list] OR Display_Event_Type_List(); By default this list will show all terms and their descriptions. I.e: " CONCERTS Our concert listings cover punk, reggae, metal, and jazz concerts in the greater Boston area... " You can specify a limit for the term description. By default this is set to 255 characters. This is helpful for seo, so your list is just an excerpt, with a link to the full content (no duplicate content). [event-type-list limit=400] OR Display_Event_Type_List(400); The term title will be a link to the term page (This is where the bundled template dile 'taxonomy-event-types.php' comes in handy. This template will be used for pages like: www.mysite.com/event-types/concerts This page is used to display a list of all events in the 'concerts' term. THEMPLATING & PERMALINKS You may want to make use of the post type / permalinks mentioned in the Notes above. To do this you will want two new files for your wordpress theme. See the samples bundled with this plugin. You can just copy the files mentioned below into your active template folder, they will immediately work. Then you can customize the markup and style of each to match your template. + single-events.php //This page can be used to output a single event as a post + taxonomy-event-types.php //This page can be used to show a specific event type 'Concerts' page You may need to reset your permalink structure if the above doesn't work right off<file_sep>/php/When v3/Tests/When_Yearly_Test.php <?php require_once 'PHPUnit/Framework.php'; require_once './When.php'; class When_Yearly_Test extends PHPUnit_Framework_TestCase { /** * DTSTART;TZID=US-Eastern:19970610T090000 * RRULE:FREQ=YEARLY;COUNT=10;BYMONTH=6,7 */ public function testOne() { $results[] = new DateTime('1997-06-10 09:00:00'); $results[] = new DateTime('1997-07-10 09:00:00'); $results[] = new DateTime('1998-06-10 09:00:00'); $results[] = new DateTime('1998-07-10 09:00:00'); $results[] = new DateTime('1999-06-10 09:00:00'); $results[] = new DateTime('1999-07-10 09:00:00'); $results[] = new DateTime('2000-06-10 09:00:00'); $results[] = new DateTime('2000-07-10 09:00:00'); $results[] = new DateTime('2001-06-10 09:00:00'); $results[] = new DateTime('2001-07-10 09:00:00'); $r = new When(); $r->recur('19970610T090000', 'yearly')->count(10)->bymonth(array(6,7)); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * DTSTART;TZID=US-Eastern:19970101T090000 * RRULE:FREQ=YEARLY;INTERVAL=3;COUNT=10;BYYEARDAY=1,100,200 */ public function testTwo() { $results[] = new DateTime('1997-01-01 09:00:00'); $results[] = new DateTime('1997-04-10 09:00:00'); $results[] = new DateTime('1997-07-19 09:00:00'); $results[] = new DateTime('2000-01-01 09:00:00'); $results[] = new DateTime('2000-04-09 09:00:00'); $results[] = new DateTime('2000-07-18 09:00:00'); $results[] = new DateTime('2003-01-01 09:00:00'); $results[] = new DateTime('2003-04-10 09:00:00'); $results[] = new DateTime('2003-07-19 09:00:00'); $results[] = new DateTime('2006-01-01 09:00:00'); $r = new When(); $r->recur('19970101T090000', 'yearly')->interval(3)->count(10)->byyearday(array(1,100,200)); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * DTSTART;TZID=US-Eastern:19970310T090000 * RRULE:FREQ=YEARLY;INTERVAL=2;COUNT=10;BYMONTH=1,2,3 */ public function testThree() { $results[] = new DateTime('1997-03-10 09:00:00'); $results[] = new DateTime('1999-01-10 09:00:00'); $results[] = new DateTime('1999-02-10 09:00:00'); $results[] = new DateTime('1999-03-10 09:00:00'); $results[] = new DateTime('2001-01-10 09:00:00'); $results[] = new DateTime('2001-02-10 09:00:00'); $results[] = new DateTime('2001-03-10 09:00:00'); $results[] = new DateTime('2003-01-10 09:00:00'); $results[] = new DateTime('2003-02-10 09:00:00'); $results[] = new DateTime('2003-03-10 09:00:00'); $r = new When(); $r->recur('19970310T090000', 'yearly')->interval(2)->count(10)->bymonth(array(1,2,3)); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * DTSTART;TZID=US-Eastern:19980101T090000 * RRULE:FREQ=YEARLY;UNTIL=20000131T090000Z;BYMONTH=1;BYDAY=SU,MO,TU,WE,TH,FR,SA */ public function testFour() { $results[] = new DateTime('1998-01-01 09:00:00'); $results[] = new DateTime('1998-01-02 09:00:00'); $results[] = new DateTime('1998-01-03 09:00:00'); $results[] = new DateTime('1998-01-04 09:00:00'); $results[] = new DateTime('1998-01-05 09:00:00'); $results[] = new DateTime('1998-01-06 09:00:00'); $results[] = new DateTime('1998-01-07 09:00:00'); $results[] = new DateTime('1998-01-08 09:00:00'); $results[] = new DateTime('1998-01-09 09:00:00'); $results[] = new DateTime('1998-01-10 09:00:00'); $results[] = new DateTime('1998-01-11 09:00:00'); $results[] = new DateTime('1998-01-12 09:00:00'); $results[] = new DateTime('1998-01-13 09:00:00'); $results[] = new DateTime('1998-01-14 09:00:00'); $results[] = new DateTime('1998-01-15 09:00:00'); $results[] = new DateTime('1998-01-16 09:00:00'); $results[] = new DateTime('1998-01-17 09:00:00'); $results[] = new DateTime('1998-01-18 09:00:00'); $results[] = new DateTime('1998-01-19 09:00:00'); $results[] = new DateTime('1998-01-20 09:00:00'); $results[] = new DateTime('1998-01-21 09:00:00'); $results[] = new DateTime('1998-01-22 09:00:00'); $results[] = new DateTime('1998-01-23 09:00:00'); $results[] = new DateTime('1998-01-24 09:00:00'); $results[] = new DateTime('1998-01-25 09:00:00'); $results[] = new DateTime('1998-01-26 09:00:00'); $results[] = new DateTime('1998-01-27 09:00:00'); $results[] = new DateTime('1998-01-28 09:00:00'); $results[] = new DateTime('1998-01-29 09:00:00'); $results[] = new DateTime('1998-01-30 09:00:00'); $results[] = new DateTime('1998-01-31 09:00:00'); $results[] = new DateTime('1999-01-01 09:00:00'); $results[] = new DateTime('1999-01-02 09:00:00'); $results[] = new DateTime('1999-01-03 09:00:00'); $results[] = new DateTime('1999-01-04 09:00:00'); $results[] = new DateTime('1999-01-05 09:00:00'); $results[] = new DateTime('1999-01-06 09:00:00'); $results[] = new DateTime('1999-01-07 09:00:00'); $results[] = new DateTime('1999-01-08 09:00:00'); $results[] = new DateTime('1999-01-09 09:00:00'); $results[] = new DateTime('1999-01-10 09:00:00'); $results[] = new DateTime('1999-01-11 09:00:00'); $results[] = new DateTime('1999-01-12 09:00:00'); $results[] = new DateTime('1999-01-13 09:00:00'); $results[] = new DateTime('1999-01-14 09:00:00'); $results[] = new DateTime('1999-01-15 09:00:00'); $results[] = new DateTime('1999-01-16 09:00:00'); $results[] = new DateTime('1999-01-17 09:00:00'); $results[] = new DateTime('1999-01-18 09:00:00'); $results[] = new DateTime('1999-01-19 09:00:00'); $results[] = new DateTime('1999-01-20 09:00:00'); $results[] = new DateTime('1999-01-21 09:00:00'); $results[] = new DateTime('1999-01-22 09:00:00'); $results[] = new DateTime('1999-01-23 09:00:00'); $results[] = new DateTime('1999-01-24 09:00:00'); $results[] = new DateTime('1999-01-25 09:00:00'); $results[] = new DateTime('1999-01-26 09:00:00'); $results[] = new DateTime('1999-01-27 09:00:00'); $results[] = new DateTime('1999-01-28 09:00:00'); $results[] = new DateTime('1999-01-29 09:00:00'); $results[] = new DateTime('1999-01-30 09:00:00'); $results[] = new DateTime('1999-01-31 09:00:00'); $results[] = new DateTime('2000-01-01 09:00:00'); $results[] = new DateTime('2000-01-02 09:00:00'); $results[] = new DateTime('2000-01-03 09:00:00'); $results[] = new DateTime('2000-01-04 09:00:00'); $results[] = new DateTime('2000-01-05 09:00:00'); $results[] = new DateTime('2000-01-06 09:00:00'); $results[] = new DateTime('2000-01-07 09:00:00'); $results[] = new DateTime('2000-01-08 09:00:00'); $results[] = new DateTime('2000-01-09 09:00:00'); $results[] = new DateTime('2000-01-10 09:00:00'); $results[] = new DateTime('2000-01-11 09:00:00'); $results[] = new DateTime('2000-01-12 09:00:00'); $results[] = new DateTime('2000-01-13 09:00:00'); $results[] = new DateTime('2000-01-14 09:00:00'); $results[] = new DateTime('2000-01-15 09:00:00'); $results[] = new DateTime('2000-01-16 09:00:00'); $results[] = new DateTime('2000-01-17 09:00:00'); $results[] = new DateTime('2000-01-18 09:00:00'); $results[] = new DateTime('2000-01-19 09:00:00'); $results[] = new DateTime('2000-01-20 09:00:00'); $results[] = new DateTime('2000-01-21 09:00:00'); $results[] = new DateTime('2000-01-22 09:00:00'); $results[] = new DateTime('2000-01-23 09:00:00'); $results[] = new DateTime('2000-01-24 09:00:00'); $results[] = new DateTime('2000-01-25 09:00:00'); $results[] = new DateTime('2000-01-26 09:00:00'); $results[] = new DateTime('2000-01-27 09:00:00'); $results[] = new DateTime('2000-01-28 09:00:00'); $results[] = new DateTime('2000-01-29 09:00:00'); $results[] = new DateTime('2000-01-30 09:00:00'); $results[] = new DateTime('2000-01-31 09:00:00'); $r = new When(); $r->recur('19980101T090000', 'yearly')->until('20000131T090000')->bymonth(array(1))->byday(array('SU','MO','TU','WE','TH','FR','SA')); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Monday of week number 20 (where the default start of the week is Monday), forever: * DTSTART;TZID=US-Eastern:19970512T090000 * RRULE:FREQ=YEARLY;BYWEEKNO=20;BYDAY=MO * Results limited to first 10 since this has no enddate or count. */ function testFive() { $results[] = new DateTime('1997-05-12 09:00:00'); $results[] = new DateTime('1998-05-11 09:00:00'); $results[] = new DateTime('1999-05-17 09:00:00'); $results[] = new DateTime('2000-05-15 09:00:00'); $results[] = new DateTime('2001-05-14 09:00:00'); $results[] = new DateTime('2002-05-13 09:00:00'); $results[] = new DateTime('2003-05-12 09:00:00'); $results[] = new DateTime('2004-05-10 09:00:00'); $results[] = new DateTime('2005-05-16 09:00:00'); $results[] = new DateTime('2006-05-15 09:00:00'); $r = new When(); $r->recur('19970512T090000', 'yearly')->count(10)->byweekno(array(20))->byday(array('MO')); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Every Thursday in March, forever: * DTSTART;TZID=US-Eastern:19970313T090000 * RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=TH */ function testSix() { $results[] = new DateTime('1997-03-13 09:00:00'); $results[] = new DateTime('1997-03-20 09:00:00'); $results[] = new DateTime('1997-03-27 09:00:00'); $results[] = new DateTime('1998-03-05 09:00:00'); $results[] = new DateTime('1998-03-12 09:00:00'); $results[] = new DateTime('1998-03-19 09:00:00'); $results[] = new DateTime('1998-03-26 09:00:00'); $results[] = new DateTime('1999-03-04 09:00:00'); $results[] = new DateTime('1999-03-11 09:00:00'); $results[] = new DateTime('1999-03-18 09:00:00'); $r = new When(); $r->recur('19970313T090000', 'yearly')->count(10)->bymonth(array(3))->byday(array('TH')); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Every Thursday, but only during June, July, and August, forever: * DTSTART;TZID=US-Eastern:19970605T090000 * RRULE:FREQ=YEARLY;BYDAY=TH;BYMONTH=6,7,8 */ function testSeven() { $results[] = new DateTime('1997-06-05 09:00:00'); $results[] = new DateTime('1997-06-12 09:00:00'); $results[] = new DateTime('1997-06-19 09:00:00'); $results[] = new DateTime('1997-06-26 09:00:00'); $results[] = new DateTime('1997-07-03 09:00:00'); $results[] = new DateTime('1997-07-10 09:00:00'); $results[] = new DateTime('1997-07-17 09:00:00'); $results[] = new DateTime('1997-07-24 09:00:00'); $results[] = new DateTime('1997-07-31 09:00:00'); $results[] = new DateTime('1997-08-07 09:00:00'); $results[] = new DateTime('1997-08-14 09:00:00'); $results[] = new DateTime('1997-08-21 09:00:00'); $results[] = new DateTime('1997-08-28 09:00:00'); $results[] = new DateTime('1998-06-04 09:00:00'); $results[] = new DateTime('1998-06-11 09:00:00'); $results[] = new DateTime('1998-06-18 09:00:00'); $results[] = new DateTime('1998-06-25 09:00:00'); $results[] = new DateTime('1998-07-02 09:00:00'); $results[] = new DateTime('1998-07-09 09:00:00'); $results[] = new DateTime('1998-07-16 09:00:00'); $results[] = new DateTime('1998-07-23 09:00:00'); $results[] = new DateTime('1998-07-30 09:00:00'); $results[] = new DateTime('1998-08-06 09:00:00'); $results[] = new DateTime('1998-08-13 09:00:00'); $results[] = new DateTime('1998-08-20 09:00:00'); $results[] = new DateTime('1998-08-27 09:00:00'); $results[] = new DateTime('1999-06-03 09:00:00'); $results[] = new DateTime('1999-06-10 09:00:00'); $results[] = new DateTime('1999-06-17 09:00:00'); $results[] = new DateTime('1999-06-24 09:00:00'); $results[] = new DateTime('1999-07-01 09:00:00'); $results[] = new DateTime('1999-07-08 09:00:00'); $results[] = new DateTime('1999-07-15 09:00:00'); $results[] = new DateTime('1999-07-22 09:00:00'); $results[] = new DateTime('1999-07-29 09:00:00'); $results[] = new DateTime('1999-08-05 09:00:00'); $results[] = new DateTime('1999-08-12 09:00:00'); $results[] = new DateTime('1999-08-19 09:00:00'); $results[] = new DateTime('1999-08-26 09:00:00'); $r = new When(); $r->recur('19970605T090000', 'yearly')->count(39)->byday(array('TH'))->bymonth(array(6,7,8)); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Every four years, the first Tuesday after a Monday in November, forever (U.S. Presidential Election day): * DTSTART;TZID=US-Eastern:19961105T090000 * RRULE:FREQ=YEARLY;INTERVAL=4;BYMONTH=11;BYDAY=TU;BYMONTHDAY=2,3,4,5,6,7,8 */ function testEight() { $results[] = new DateTime('1996-11-05 09:00:00'); $results[] = new DateTime('2000-11-07 09:00:00'); $results[] = new DateTime('2004-11-02 09:00:00'); $results[] = new DateTime('2008-11-04 09:00:00'); $results[] = new DateTime('2012-11-06 09:00:00'); $results[] = new DateTime('2016-11-08 09:00:00'); $results[] = new DateTime('2020-11-03 09:00:00'); $results[] = new DateTime('2024-11-05 09:00:00'); $results[] = new DateTime('2028-11-07 09:00:00'); $results[] = new DateTime('2032-11-02 09:00:00'); $r = new When(); $r->recur('19961105T090000', 'yearly')->count(10)->interval(4)->bymonth(array(11))->byday(array('TU'))->bymonthday(array(2,3,4,5,6,7,8)); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Every third year on the 1st, 100th, and 200th day for 10 occurrences: * DTSTART;TZID=America/New_York:19970101T090000 * RRULE:FREQ=YEARLY;INTERVAL=3;COUNT=10;BYYEARDAY=1,100,200 */ function testTwentyThree() { $results[] = new DateTime('1997-01-01 09:00:00'); $results[] = new DateTime('1997-04-10 09:00:00'); $results[] = new DateTime('1997-07-19 09:00:00'); $results[] = new DateTime('2000-01-01 09:00:00'); $results[] = new DateTime('2000-04-09 09:00:00'); $results[] = new DateTime('2000-07-18 09:00:00'); $results[] = new DateTime('2003-01-01 09:00:00'); $results[] = new DateTime('2003-04-10 09:00:00'); $results[] = new DateTime('2003-07-19 09:00:00'); $results[] = new DateTime('2006-01-01 09:00:00'); $r = new When(); $r->recur('19970101T090000', 'yearly')->interval(3)->count(10)->byyearday(array(1,100,200)); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Every year on the -1th, -100th, and -200th day for 5 occurrences (checked via google calendar import below) * BEGIN:VCALENDAR * PRODID:-//Google Inc//Google Calendar 70.9054//EN * VERSION:2.0 * CALSCALE:GREGORIAN * METHOD:PUBLISH * BEGIN:VTIMEZONE * TZID:America/New_York * X-LIC-LOCATION:America/New_York * BEGIN:DAYLIGHT * TZOFFSETFROM:-0500 * TZOFFSETTO:-0400 * TZNAME:EDT * DTSTART:19700308T020000 * RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU * END:DAYLIGHT * BEGIN:STANDARD * TZOFFSETFROM:-0400 * TZOFFSETTO:-0500 * TZNAME:EST * DTSTART:19701101T020000 * RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU * END:STANDARD * END:VTIMEZONE * BEGIN:VEVENT * DTSTART;VALUE=DATE:20101231 * RRULE:FREQ=YEARLY;COUNT=5;BYYEARDAY=-1,-100,-200 * DTSTAMP:20101231T090000 * CREATED:20101231T090000 * DESCRIPTION: * LAST-MODIFIED:20101231T090000 * LOCATION: * SEQUENCE:2 * STATUS:CONFIRMED * SUMMARY:testing yearly event * TRANSP:TRANSPARENT * END:VEVENT * END:VCALENDAR */ function testTwentyFour() { $results[] = new DateTime('2010-12-31 09:00:00'); $results[] = new DateTime('2010-09-23 09:00:00'); $results[] = new DateTime('2010-06-15 09:00:00'); $results[] = new DateTime('2011-12-31 09:00:00'); $results[] = new DateTime('2011-09-23 09:00:00'); $r = new When(); $r->recur('20101231T090000', 'yearly')->count(5)->byyearday(array(-1, -100, -200)); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } }<file_sep>/samples/taxonomy-hc_event_categories.php <?php get_header(); //Gather the current taxonomy term object being viewed $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); ?> <div id="Content"> <?php if ( has_post_thumbnail(9) ) { // the current page has a feature image echo get_the_post_thumbnail(9,'post-thumbnail',''); } ?> <div class="clear"></div> <br /><br /> <div id="Sub-Content"> <div class="breadcrumbs"> <?php if(function_exists('bcn_display')) { bcn_display();} ?> </div> <br /> <?php $loop = query_posts("post_type=hc_events&posts_per_page=10&posts_per_page=10&hc_event_categories=".$term->slug.""); if (have_posts()) { while (have_posts()): the_post(); ?> <div class="Blog_Post"> <h1> <a href="<?php the_permalink() ?>" title="<?php echo the_title('','',0); ?>"><?php echo the_title('','',0); ?></a> </h1> <br /> <small>Posted on <?php the_time('F jS, Y') ?></small> <br /><br /> <div class="Blog_Post_Content"> <?php the_excerpt(__('(more...)')); ?> </div> </div> <?php endwhile; } else { echo "There are currently no {$term->name} events. Check back soon! In the meantime take a look at events in some of these categories:<br /><br />"; wp_list_categories(array('taxonomy' => 'hc_event_categories', 'orderby' => 'name', 'show_count' => 1, 'pad_counts' => 0, 'hierarchical' => 1,'title_li' => '')); } ?> </div> <style type="text/css"> #TermList { text-align: right ; } </style> <div id="Sidebar"> <div class="button"><?php echo $term->name ?></div> <!--<div id="TermList">--> <?php //This value is populated via the wp query above echo term_description( '', get_query_var( 'taxonomy' ) ); ?> <!--</div>--> </div> </div> <?php get_footer(); ?><file_sep>/php/When v3/Tests/When_Monthly_Test.php <?php require_once 'PHPUnit/Framework.php'; require_once './When.php'; class When_Monthly_Test extends PHPUnit_Framework_TestCase { /** * Monthly on the 1st Friday for ten occurrences: * DTSTART;TZID=US-Eastern:19970905T090000 * RRULE:FREQ=MONTHLY;COUNT=10;BYDAY=1FR */ function testNine() { $results[] = new DateTime('1997-09-05 09:00:00'); $results[] = new DateTime('1997-10-03 09:00:00'); $results[] = new DateTime('1997-11-07 09:00:00'); $results[] = new DateTime('1997-12-05 09:00:00'); $results[] = new DateTime('1998-01-02 09:00:00'); $results[] = new DateTime('1998-02-06 09:00:00'); $results[] = new DateTime('1998-03-06 09:00:00'); $results[] = new DateTime('1998-04-03 09:00:00'); $results[] = new DateTime('1998-05-01 09:00:00'); $results[] = new DateTime('1998-06-05 09:00:00'); $r = new When(); $r->recur('19970905T090000', 'monthly')->count(10)->byday(array('1FR')); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Monthly on the 1st Friday until December 24, 1997: * DTSTART;TZID=US-Eastern:19970905T090000 * RRULE:FREQ=MONTHLY;UNTIL=19971224T000000Z;BYDAY=1FR */ function testTen() { $results[] = new DateTime('1997-09-05 09:00:00'); $results[] = new DateTime('1997-10-03 09:00:00'); $results[] = new DateTime('1997-11-07 09:00:00'); $results[] = new DateTime('1997-12-05 09:00:00'); $r = new When(); $r->recur('19970905T090000', 'monthly')->until('19971224T000000')->byday(array('1FR')); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Every other month on the 1st and last Sunday of the month for 10 occurrences: * DTSTART;TZID=US-Eastern:19970907T090000 * RRULE:FREQ=MONTHLY;INTERVAL=2;COUNT=10;BYDAY=1SU,-1SU */ function testEleven() { $results[] = new DateTime('1997-09-07 09:00:00'); $results[] = new DateTime('1997-09-28 09:00:00'); $results[] = new DateTime('1997-11-02 09:00:00'); $results[] = new DateTime('1997-11-30 09:00:00'); $results[] = new DateTime('1998-01-04 09:00:00'); $results[] = new DateTime('1998-01-25 09:00:00'); $results[] = new DateTime('1998-03-01 09:00:00'); $results[] = new DateTime('1998-03-29 09:00:00'); $results[] = new DateTime('1998-05-03 09:00:00'); $results[] = new DateTime('1998-05-31 09:00:00'); $r = new When(); $r->recur('19970905T090000', 'monthly')->interval(2)->count(10)->byday(array('1SU', '-1SU')); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Monthly on the second to last Monday of the month for 6 months: * DTSTART;TZID=US-Eastern:19970922T090000 * RRULE:FREQ=MONTHLY;COUNT=6;BYDAY=-2MO */ function testTwelve() { $results[] = new DateTime('1997-09-22 09:00:00'); $results[] = new DateTime('1997-10-20 09:00:00'); $results[] = new DateTime('1997-11-17 09:00:00'); $results[] = new DateTime('1997-12-22 09:00:00'); $results[] = new DateTime('1998-01-19 09:00:00'); $results[] = new DateTime('1998-02-16 09:00:00'); $r = new When(); $r->recur('19970922T090000', 'monthly')->count(6)->byday(array('-2MO')); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Monthly on the third to the last day of the month, forever: * DTSTART;TZID=US-Eastern:19970928T090000 * RRULE:FREQ=MONTHLY;BYMONTHDAY=-3 */ function testThirteen() { $results[] = new DateTime('1997-09-28 09:00:00'); $results[] = new DateTime('1997-10-29 09:00:00'); $results[] = new DateTime('1997-11-28 09:00:00'); $results[] = new DateTime('1997-12-29 09:00:00'); $results[] = new DateTime('1998-01-29 09:00:00'); $results[] = new DateTime('1998-02-26 09:00:00'); $r = new When(); $r->recur('19970902T090000', 'monthly')->count(6)->bymonthday(array(-3)); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Monthly on the 2nd and 15th of the month for 10 occurrences: * DTSTART;TZID=US-Eastern:19970902T090000 * RRULE:FREQ=MONTHLY;COUNT=10;BYMONTHDAY=2,15 */ function testFourteen() { $results[] = new DateTime('1997-09-02 09:00:00'); $results[] = new DateTime('1997-09-15 09:00:00'); $results[] = new DateTime('1997-10-02 09:00:00'); $results[] = new DateTime('1997-10-15 09:00:00'); $results[] = new DateTime('1997-11-02 09:00:00'); $results[] = new DateTime('1997-11-15 09:00:00'); $results[] = new DateTime('1997-12-02 09:00:00'); $results[] = new DateTime('1997-12-15 09:00:00'); $results[] = new DateTime('1998-01-02 09:00:00'); $results[] = new DateTime('1998-01-15 09:00:00'); $r = new When(); $r->recur('19970902T090000', 'monthly')->count(10)->bymonthday(array(2,15)); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Monthly on the first and last day of the month for 10 occurrences: * DTSTART;TZID=US-Eastern:19970930T090000 * RRULE:FREQ=MONTHLY;COUNT=10;BYMONTHDAY=1,-1 */ function testFifteen() { $results[] = new DateTime('1997-09-30 09:00:00'); $results[] = new DateTime('1997-10-01 09:00:00'); $results[] = new DateTime('1997-10-31 09:00:00'); $results[] = new DateTime('1997-11-01 09:00:00'); $results[] = new DateTime('1997-11-30 09:00:00'); $results[] = new DateTime('1997-12-01 09:00:00'); $results[] = new DateTime('1997-12-31 09:00:00'); $results[] = new DateTime('1998-01-01 09:00:00'); $results[] = new DateTime('1998-01-31 09:00:00'); $results[] = new DateTime('1998-02-01 09:00:00'); $r = new When(); $r->recur('19970930T090000', 'monthly')->count(10)->bymonthday(array(1,-1)); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Every 18 months on the 10th thru 15th of the month for 10 occurrences: * DTSTART;TZID=US-Eastern:19970910T090000 * RRULE:FREQ=MONTHLY;INTERVAL=18;COUNT=10;BYMONTHDAY=10,11,12,13,14,15 */ function testSixteen() { $results[] = new DateTime('1997-09-10 09:00:00'); $results[] = new DateTime('1997-09-11 09:00:00'); $results[] = new DateTime('1997-09-12 09:00:00'); $results[] = new DateTime('1997-09-13 09:00:00'); $results[] = new DateTime('1997-09-14 09:00:00'); $results[] = new DateTime('1997-09-15 09:00:00'); $results[] = new DateTime('1999-03-10 09:00:00'); $results[] = new DateTime('1999-03-11 09:00:00'); $results[] = new DateTime('1999-03-12 09:00:00'); $results[] = new DateTime('1999-03-13 09:00:00'); $r = new When(); $r->recur('19970910T090000', 'monthly')->interval(18)->count(10)->bymonthday(array(10,11,12,13,14,15)); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Every Tuesday, every other month: * DTSTART;TZID=US-Eastern:19970902T090000 * RRULE:FREQ=MONTHLY;INTERVAL=2;BYDAY=TU */ function testSeventeen() { $results[] = new DateTime('1997-09-02 09:00:00'); $results[] = new DateTime('1997-09-09 09:00:00'); $results[] = new DateTime('1997-09-16 09:00:00'); $results[] = new DateTime('1997-09-23 09:00:00'); $results[] = new DateTime('1997-09-30 09:00:00'); $results[] = new DateTime('1997-11-04 09:00:00'); $results[] = new DateTime('1997-11-11 09:00:00'); $results[] = new DateTime('1997-11-18 09:00:00'); $results[] = new DateTime('1997-11-25 09:00:00'); $results[] = new DateTime('1998-01-06 09:00:00'); $results[] = new DateTime('1998-01-13 09:00:00'); $results[] = new DateTime('1998-01-20 09:00:00'); $results[] = new DateTime('1998-01-27 09:00:00'); $results[] = new DateTime('1998-03-03 09:00:00'); $results[] = new DateTime('1998-03-10 09:00:00'); $results[] = new DateTime('1998-03-17 09:00:00'); $results[] = new DateTime('1998-03-24 09:00:00'); $results[] = new DateTime('1998-03-31 09:00:00'); $r = new When(); $r->recur('19970902T090000', 'monthly')->interval(2)->count(18)->byday(array('TU')); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Every Friday the 13th, forever: * DTSTART;TZID=US-Eastern:19970902T090000 * RRULE:FREQ=MONTHLY;BYDAY=FR;BYMONTHDAY=13 */ function testEighteen() { $results[] = new DateTime('1998-02-13 09:00:00'); $results[] = new DateTime('1998-03-13 09:00:00'); $results[] = new DateTime('1998-11-13 09:00:00'); $results[] = new DateTime('1999-08-13 09:00:00'); $results[] = new DateTime('2000-10-13 09:00:00'); $r = new When(); $r->recur('19970902T090000', 'monthly')->count(5)->byday(array('FR'))->bymonthday(array(13)); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * The first Saturday that follows the first Sunday of the month, forever: * DTSTART;TZID=US-Eastern:19970913T090000 * RRULE:FREQ=MONTHLY;BYDAY=SA;BYMONTHDAY=7,8,9,10,11,12,13 */ function testNineteen() { $results[] = new DateTime('1997-09-13 09:00:00'); $results[] = new DateTime('1997-10-11 09:00:00'); $results[] = new DateTime('1997-11-08 09:00:00'); $results[] = new DateTime('1997-12-13 09:00:00'); $results[] = new DateTime('1998-01-10 09:00:00'); $results[] = new DateTime('1998-02-07 09:00:00'); $results[] = new DateTime('1998-03-07 09:00:00'); $results[] = new DateTime('1998-04-11 09:00:00'); $results[] = new DateTime('1998-05-09 09:00:00'); $results[] = new DateTime('1998-06-13 09:00:00'); $r = new When(); $r->recur('19970913T090000', 'monthly')->count(10)->byday(array('SA'))->bymonthday(array(7,8,9,10,11,12,13)); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * The 3rd instance into the month of one of Tuesday, Wednesday or Thursday, for the next 3 months: * DTSTART;TZID=US-Eastern:19970904T090000 * RRULE:FREQ=MONTHLY;COUNT=3;BYDAY=TU,WE,TH;BYSETPOS=3 */ function testTwenty() { $results[] = new DateTime('1997-09-04 09:00:00'); $results[] = new DateTime('1997-10-07 09:00:00'); $results[] = new DateTime('1997-11-06 09:00:00'); $r = new When(); $r->recur('19970904T090000', 'monthly')->count(3)->byday(array('TU', 'WE', 'TH'))->bysetpos(array(3)); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * An example where an invalid date (i.e., February 30) is ignored. * DTSTART;TZID=America/New_York:20070115T090000 * RRULE:FREQ=MONTHLY;BYMONTHDAY=15,30;COUNT=5 */ function testTwentyOne() { $results[] = new DateTime('2007-01-15 09:00:00'); $results[] = new DateTime('2007-01-30 09:00:00'); $results[] = new DateTime('2007-02-15 09:00:00'); $results[] = new DateTime('2007-03-15 09:00:00'); $results[] = new DateTime('2007-03-30 09:00:00'); $r = new When(); $r->recur('20070115T090000', 'monthly')->count(5)->bymonthday(array(15,30)); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * The second-to-last weekday of the month: * DTSTART;TZID=America/New_York:19970929T090000 * RRULE:FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=-2 */ function testTwentyTwo() { $results[] = new DateTime('1997-09-29 09:00:00'); $results[] = new DateTime('1997-10-30 09:00:00'); $results[] = new DateTime('1997-11-27 09:00:00'); $results[] = new DateTime('1997-12-30 09:00:00'); $results[] = new DateTime('1998-01-29 09:00:00'); $results[] = new DateTime('1998-02-26 09:00:00'); $results[] = new DateTime('1998-03-30 09:00:00'); $r = new When(); $r->recur('19970929T090000', 'monthly')->count(7)->byday(array('MO', 'TU', 'WE', 'TH', 'FR'))->bysetpos(array(-2)); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } } <file_sep>/php/hc-event-calendar.php <!-- This page generates the actual Honeycomb Calendar. Much of the page has conditionals to determine if the calendar is being view in wp-admin or on the public website - the admin view receives several additional scripts for management purposes. The public view also runs a tooltip script for quickview of event info. --> <?php $hc_plugin_url = get_bloginfo('url') . "/wp-content/plugins/honeycomb"; ?> <link rel='stylesheet' type='text/css' href='<?php echo $hc_plugin_url; ?>/jquery-plugins/fullcalendar-1.6.4/fullcalendar/fullcalendar.css' /> <style type='text/css'> #hc_loading { position: absolute; top: 1px ; left: 1px ; } #hc_calendar { position: relative ; <?php if (is_admin()) { //The admin view feels cramped, so let's make it a little smaller echo "margin: 0px 25px 20px 0;\n"; } else { echo "margin: 20px 0 20px 0;\n"; } ?> overflow: visible ; } /* Make sure our tooltips can pop out of the calendar container */ .fcdiv, .fc-contentdiv, .fc-view { overflow: visible !important ; } .fc-event { margin-bottom: 3px !important; } <?php if (is_admin()) { ?> .hc_event-controller-dialog { position: absolute ; z-index: 999999999 ; top: 12% ; left: 28% ; padding: 20px ; background-color: rgb(255,255,255) ; -moz-border-radius: 15px; -webkit-border-radius: 15px; border-radius: 15px; -moz-box-shadow: 0px 0px 25px rgb(150,150,150) ; -webkit-box-shadow: 0px 0px 25px rgb(150,150,150) ; box-shadow: 0px 0px 25px rgb(150,150,150) ; } .hc_event-controller-dialog table td { padding: 5px ; } #hc_time_selection { display: none ; } .hc_event_form_success { background-color: #defeb7 ; padding: 5px ; font-weight: bold ; color: rgb(90,90,90) ; border: 1px solid #cff4a3 ; } <?php } //End if is_admin() else { ?> /* Tooltip Styles */ .tooltip { font-family: Georgia, "Times New Roman", Times, serif ; font-size: 12px ; color: rgb(255,255,255) !important ; font-weight: normal ; padding: 5px ; border-top: 1px solid rgb(255,255,255) ; -moz-box-shadow: 0px 0px 5px #000000; -webkit-box-shadow: 0px 0px 5px #000000; box-shadow: 0px 0px 5px #000000; } .tooltip .tooltip { position: absolute; top: 0; left: 0; z-index: 3; } .tooltip a { color: rgb(255,255,255) ; } <?php } ?> </style> <script type='text/javascript' src='<?php echo $hc_plugin_url; ?>/js/jquery-ui-1.8.6.custom.min.js'></script> <?php //echo "$hc_plugin_url/jquery-plugins/fullcalendar-1.5.1/fullcalendar/fullcalendar.min.js"; //wp_enqueue_style( 'jquery-ui-smoothness', "$hc_plugin_url/css/jquery-ui-1.8.6.custom.css"); /* add_action('wp_print_scripts', 'hc_events_load_scripts'); function hc_events_load_scripts () { global $hc_plugin_url; //if (is_page(4)) { wp_enqueue_script("fullcalendar", "$hc_plugin_url/jquery-plugins/fullcalendar-1.5.1/fullcalendar/fullcalendar.min.js", array('jquery'), '1.5.1'); //} } */ //We only need the color picker script and css for the admin page if(is_admin()) { ?> <?php } else { ?> <!--<script type="text/javascript" src="<?php echo $hc_plugin_url; ?>/js/jquery.simpletip-1.3.1.min.js"></script>--> <?php } ?> <!--<script type='text/javascript' src='<?php echo $hc_plugin_url; ?>/jquery-plugins/fullcalendar-1.5.1/fullcalendar/fullcalendar.min.js'></script>--> <script type='text/javascript'> jQuery(function($) { //$(document).ready(function() { String.prototype.ucFirst = function() { return this.charAt(0).toUpperCase() + this.substring(1); } //Initilize our calendar with a reference back to itself, e.g. var calendar var calendar = $('#hc_calendar').fullCalendar({ ignoreTimezone: true, <?php //If this page is being viewed by the admin add support for administrative controls //These controlls add functionality to move, resize, and edit events. if (is_admin()) { ?> //Add Support for adding events by either clicking a day or dragging out / selecting multiple days selectable: true, selectHelper: true, select: function(start, end, allday) { if ($(".hc_event-controller-dialog").length == 0) { create_event_creation_form(start, end, allday); } }, //Add support for dragging event positions on the calendar editable: true, eventRender: function (event) { //Add some css to our newly created event(s) to reflect the chosen color var hc_event_styles = {backgroundColor: event.color, borderColor: event.color} $('.event-' + event.id).css(hc_event_styles) $('.fc-agenda .event-' + event.id + ' .fc-event-time').css(hc_event_styles) $('.event-' + event.id + ' a').css(hc_event_styles) }, //Action to be preformed upon clicking an event by the admin eventClick: function(event, e) { //edit event e.preventDefault(); console.log(event) if ($(".hc_event-controller-dialog").length == 0) { create_event_edit_form(event.id, event.recurrance); } }, eventDrop: function(event, delta) { if (event.end == null || event.end == 'null') { hc_event_end = event.start.getTime() / 1000 } else { hc_event_end = event.end.getTime() / 1000 } var data_out = { hc_ajax_request: 'update_moved_event', hc_event_id: event.id, hc_event_start: event.start.getTime() / 1000, hc_event_end: hc_event_end, hc_event_allday: event.allDay } //console.log(data_out) $.post("<?php echo $hc_plugin_url; ?>/php/hc-event-functions.php", data_out, function(data_in) { //event moved }); }, eventResize: function(event,dayDelta,minuteDelta,revertFunc) { var data_out = { hc_ajax_request: 'update_resized_event', hc_event_id: event.id, hc_event_end: event.end.getTime() / 1000, } $.post("<?php echo $hc_plugin_url; ?>/php/hc-event-functions.php", data_out, function(data_in) { //event resized }); }, <?php } //end check for admin page, now display settings only specific to the public view else { ?> //Function used to add anything to event when they are rendered onto the calendar view eventRender: function(event, element) { //Add some css to our newly created event(s) to reflect the chosen color var event_styles = {backgroundColor: event.color, borderColor: event.color} $('.event-' + event.id).css(event_styles) $('.fc-agenda .event-' + event.id + ' .fc-event-time').css(event_styles) $('.event-' + event.id + ' a').css(event_styles) //Bind our simpletip tooltip to each event, but only if the event has a summary if (event.summary != '' && event.summary != null) { var tooltipContent = event.summary //Check if registration is still open, and display a signup link if it is var now = new Date() now = Math.round(now.getTime() / 1000) var hc_event_start = Math.round(event.start.getTime() / 1000) //only allow prepay for future events if (hc_event_start > now) { //only allow prepay if its been set if (event.hc_event_allow_paying == 'on') { //only allow prepay if an amount has been set if (event.hc_event_amount != '') { tooltipContent += "<br /><br /><a href='" + event.url + "' title='Pre-Pay for'" + event.title + "'><b>Pre-Pay Now!</b></a>" } } } element.simpletip({ content: tooltipContent, //We want our tip to remain fixed to the element which calls it fixed: true }); } }, eventClick: function (event) { //When visitors click an event on the calendar let's redirect them to the event page //This url uses the default wp permalinks, so mysite.com/events/my-cool-event window.location(event.url) }, eventMouseover: function (event) { $(this).css('z-index', '99999999'); }, eventMouseout: function (event) { $(this).css('z-index', '3'); }, <?php } ?> //Add themeing support //theme: true, header: { left: 'month,agendaWeek,agendaDay', center: 'title', right: 'prev,next today' }, //Load in our events feed via a json dataset; provided by php pulling content from mysql events: "<?php echo $hc_plugin_url; ?>/php/hc-event-functions.php?hc_ajax_request=request_all_JSON_events", //events: {"id":"163","title":"Danceathon 2010 2","summary":"Integer at nisi metus, vitae sodales massa. Phasellus placerat tempor quam id adipiscing. Nulla luctus elementum velit nec ornare. Praesent vehicula venenatis lorem in euismod. Donec tempus, eros","start":"","end":"","classname":"hc_event_event-163","allDay":0,"recurrance":"","color":"","url":"http:\/\/localhost\/Dancechatter_v2\/events\/danceathon-2010\/","terms":""}, //Display a loading dialog for heavy calendar weight loading: function(bool) { if (bool) $('#hc_loading').show(); else $('#hc_loading').hide(); } });//END CREATE FULL CALENDAR <?php //If this page is being viewed by the admin add support for administrative controls //We only wany authenticated users to has access to these function / know they even exist if (is_admin()) { ?> //List of current event colors var hc_colors = [ '#4e85ca', //Light Blue - DEFAULT COLOR '#7136e7', //Deep Blue '#6c00a4', //Purple '#9464e4', //Light Purple '#42202f', //Deep Purple '#920a2d', //Burgandy '#d06956', //Pink '#e44b00', //Dark Orange '#faa012', //Orange '#0dd703', //Green '#3b5b3c', //Dark Green '#515151', //Charcoal '#151515' //Black ]; //Create the event createtion form function create_event_creation_form (hc_event_start, hc_event_end, hc_event_allday) { //var startDateObj = new Date(hc_new_event.hc_event_start * 1000) //console.log(hc_event_start) var hc_event_start_ts = hc_event_start.getTime() / 1000 //console.log(hc_event_start_ts) var hc_event_start_ts_offset = hc_event_start.getTimezoneOffset() * 60 //console.log(hc_event_start_ts_offset) hc_event_start = hc_event_start_ts + hc_event_start_ts_offset //console.log(hc_event_start) //console.log('---------------------------'); //var endDateObj = new Date(hc_new_event.hc_event_end * 1000) var hc_event_end_ts = hc_event_end.getTime() / 1000 //console.log(hc_event_end_ts) var hc_event_end_offset = hc_event_end.getTimezoneOffset() * 60 //console.log(hc_event_start_ts_offset) hc_event_end = hc_event_end_ts + hc_event_end_offset //console.log(hc_event_end) hc_ajax_request = "create_event_creation_form"; var event_data = {hc_event_start: hc_event_start, hc_event_end: hc_event_end, hc_event_allday: hc_event_allday, hc_ajax_request: hc_ajax_request}; console.log(event_data); $.post("<?php echo $hc_plugin_url; ?>/php/hc-event-functions.php", event_data, function(create_event_form_html) { $('#hc_calendar').append(create_event_form_html); $(".hc_event-controller-dialog").fadeTo(250, 1.0); }); } //End create event creation form function create_event_edit_form (hc_event_id, hc_event_recurrance) { data_out = { hc_ajax_request: 'create_edit_event_form', hc_event_id: hc_event_id, hc_event_recurrance: hc_event_recurrance }; console.log(data_out) $.post("<?php echo $hc_plugin_url; ?>/php/hc-event-functions.php", data_out, function(edit_event_form_html) { $('#hc_calendar').append(edit_event_form_html); if($('#hc_event_allday').is(':checked')) { $('#hc_event_time_selection').hide(); } else { $('#hc_event_time_selection').css('display', 'inline'); } if ($('#hc_event_is_repeat').is(':checked')) { $('#hc_event_recurrance').css('display', 'inline'); } else { $('#hc_event_recurrance').hide(); } $(".hc_event-controller-dialog").fadeTo(250, 1.0); //Create the color picker jquery object //console.log(hc_colors) for (var i in hc_colors) { if (hc_colors[i] == $('#hc_event_color').val()) { var hc_color_index = i; } } /* $('#hc_event_colors').colorPicker({ defaultColor: parseInt(hc_color_index), // index of the default color (optional) color: hc_colors, click: function(color){ $('#hc_event_color').attr('value', color); } }); */ }); } //Proccess the create event form $('#hc_new_event_form').live('submit', function(event) { event.preventDefault(); //Send Request by converting this forms field data into a &pair=value string format $.post("<?php echo $hc_plugin_url; ?>/php/hc-event-functions.php", $(this).serialize(), function(hc_new_event) { //Process the returned data if (hc_new_event.hc_event_created == true) { $(".hc_event_form_feedback").addClass('hc_event_form_success'); $(".hc_event_form_feedback").html('Event created successfully :)'); $('.hc_event_close').html('Close'); $('.hc_event_new_edit_url').html("<a href='<?php bloginfo('url') ?>/wp-admin/post.php?post=" + hc_new_event.hc_event_id + "&action=edit' title='Edit in full editor'>Edit Event Details</a>"); calendar.fullCalendar('renderEvent', { id: hc_new_event.hc_event_id, title: hc_new_event.hc_event_title, start: hc_new_event.hc_event_start, end: hc_new_event.hc_event_end, allday: hc_new_event.hc_event_allday, className: hc_new_event.hc_event_className }, true // make the event "stick" ); calendar.fullCalendar('unselect'); //Add some css to our newly created event(s) to reflect the chosen color var hc_new_event_styles = {backgroundColor: hc_new_event.hc_event_color, borderColor: hc_new_event.hc_event_color} $('.event-' + hc_new_event.id).css(hc_new_event_styles) $('.fc-agenda .event-' + hc_new_event.id + ' .fc-event-time').css(hc_new_event_styles) $('.event-' + hc_new_event.id + ' a').css(hc_new_event_styles) //Fade and remove the create event form //$(".hc_event-controller-dialog").fadeTo(250,0.0); //$(".hc_event-controller-dialog").remove(); } else { $(".hc_event_form_feedback").addClass('hc_form_failure'); $(".hc_event_form_feedback").html('There was an error creating the event :('); } }, "json");//End Ajax Query }); //Update an event //Proccess the create event form $('#hc_event_edit_event_form').live('submit', function(event) { event.preventDefault(); //Send Request by converting this forms field data into a &pair=value string format $.post("<?php echo $hc_plugin_url; ?>/php/hc-event-functions.php", $(this).serialize(), function(hc_updated_event) { //Show success confirmation if (hc_updated_event.hc_event_updated == true) { $(".hc_event_form_feedback").addClass('hc_event_form_success'); $(".hc_event_form_feedback").html('Event updated successfully :)'); //Update the client side calendar event to reflect the update $('#hc_calendar').fullCalendar('clientEvents', function(event) { if (event.id == hc_updated_event.hc_event_id) { event.start = hc_updated_event.hc_event_start; event.end = hc_updated_event.hc_event_end; event.allday = hc_updated_event.hc_event_allday; event.title = hc_updated_event.hc_event_title; event.color = hc_updated_event.hc_event_color; $('#hc_calendar').fullCalendar('updateEvent', event); } }); //Add some css to our newly created event(s) to reflect the chosen color var hc_updated_event_styles = {backgroundColor: hc_updated_event.color, borderColor: hc_updated_event.color} $('.event-' + hc_updated_event.hc_event_id).css(hc_updated_event_styles) $('.fc-agenda .event-' + hc_updated_event.hc_event_id + ' .fc-event-time').css(hc_updated_event_styles) $('.event-' + hc_updated_event.hc_event_id + ' a').css(hc_updated_event_styles) } else { //Show any errors $(".hc_event_form_feedback").addClass('hc_form_failure'); $(".hc_event_form_feedback").html('There was an error updating the event :('); } $(".hc_event_form_feedback").show(); //Fade and remove the create event form /* $(".hc_event-controller-dialog").delay(2500).fadeTo(250,0.0).queue(function() { $(this).remove(); }); */ }, "json");//End Ajax Query }); //Functions for the create event form //Close / Cancel the create event form $(".hc_event_close").live('click', function(event) { event.preventDefault(); $(".hc_event-controller-dialog").fadeTo(250,0.0); $(".hc_event-controller-dialog").remove(); }); //Delete an event $('.hc_event_delete').live('click', function(event) { event.preventDefault(); if(confirm('Are you sure you want to delete this event?')) { var data_out = { hc_ajax_request: 'delete_event', hc_event_id: $('#hc_event_id').val() } $.post("<?php echo $hc_plugin_url;?>/php/hc-event-functions.php", data_out, function(hc_event_id) { $(".hc_event-controller-dialog").fadeTo(250,0.0); $(".hc_event-controller-dialog").remove(); calendar.fullCalendar( 'removeEvents', hc_event_id); }); } else { //If the user cancels deleting the event lets close the edit dialog $(".hc_event-controller-dialog").fadeTo(250,0.0); $(".hc_event-controller-dialog").remove(); } }); //Enable or disable the all day / timed event functions $('#hc_allday').live('change', function(event) { if($(this).is(':checked')) { $('#hc_time_selection').hide(); } else { $('#hc_time_selection').css('display', 'inline'); } }); // //----- Evemt Recurrance Form Controllers // //Enable or Disable event recurrance $('#hc_is_repeat').live('change', function(event) { if ($(this).is(':checked')) { $('#hc_recurrance').fadeTo(250, 1.0); } else { $('#hc_recurrance').hide(); } }); //Update the interval noun field for descriptive recurrance output $('#hc_frequency').live('change', function(event){ $('#hc_frequency option:selected').each(function(){ $('#hc_interval_frequency_noun').text($(this)[0].value.splice('ly').ucFirst() + '(s)') }); }); <?php } //END IS ADMIN ?> }); //End Document Ready jQuery Init </script> <?php if (is_admin()) { echo "<br /><br />\n"; } ?> <div id='hc_calendar'> <div id='hc_loading' style='display:none'>loading...</div> </div><file_sep>/php/When v3/Tests/When_Daily_Test.php <?php require_once 'PHPUnit/Framework.php'; require_once './When.php'; class When_Daily_Test extends PHPUnit_Framework_TestCase { /** * Daily for 10 occurrences: * DTSTART;TZID=America/New_York:19970902T090000 * RRULE:FREQ=DAILY;COUNT=10 */ function testThirtyThree() { $results[] = new DateTime('1997-09-02 09:00:00'); $results[] = new DateTime('1997-09-03 09:00:00'); $results[] = new DateTime('1997-09-04 09:00:00'); $results[] = new DateTime('1997-09-05 09:00:00'); $results[] = new DateTime('1997-09-06 09:00:00'); $results[] = new DateTime('1997-09-07 09:00:00'); $results[] = new DateTime('1997-09-08 09:00:00'); $results[] = new DateTime('1997-09-09 09:00:00'); $results[] = new DateTime('1997-09-10 09:00:00'); $results[] = new DateTime('1997-09-11 09:00:00'); $r = new When(); $r->recur('19970902T090000', 'daily')->count(10); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Daily until December 24, 1997: * DTSTART;TZID=America/New_York:19970902T090000 * RRULE:FREQ=DAILY;UNTIL=19971224T000000Z */ function testThirtyFour() { $results[] = new DateTime('1997-09-02 09:00:00'); $results[] = new DateTime('1997-09-03 09:00:00'); $results[] = new DateTime('1997-09-04 09:00:00'); $results[] = new DateTime('1997-09-05 09:00:00'); $results[] = new DateTime('1997-09-06 09:00:00'); $results[] = new DateTime('1997-09-07 09:00:00'); $results[] = new DateTime('1997-09-08 09:00:00'); $results[] = new DateTime('1997-09-09 09:00:00'); $results[] = new DateTime('1997-09-10 09:00:00'); $results[] = new DateTime('1997-09-11 09:00:00'); $results[] = new DateTime('1997-09-12 09:00:00'); $results[] = new DateTime('1997-09-13 09:00:00'); $results[] = new DateTime('1997-09-14 09:00:00'); $results[] = new DateTime('1997-09-15 09:00:00'); $results[] = new DateTime('1997-09-16 09:00:00'); $results[] = new DateTime('1997-09-17 09:00:00'); $results[] = new DateTime('1997-09-18 09:00:00'); $results[] = new DateTime('1997-09-19 09:00:00'); $results[] = new DateTime('1997-09-20 09:00:00'); $results[] = new DateTime('1997-09-21 09:00:00'); $results[] = new DateTime('1997-09-22 09:00:00'); $results[] = new DateTime('1997-09-23 09:00:00'); $results[] = new DateTime('1997-09-24 09:00:00'); $results[] = new DateTime('1997-09-25 09:00:00'); $results[] = new DateTime('1997-09-26 09:00:00'); $results[] = new DateTime('1997-09-27 09:00:00'); $results[] = new DateTime('1997-09-28 09:00:00'); $results[] = new DateTime('1997-09-29 09:00:00'); $results[] = new DateTime('1997-09-30 09:00:00'); $results[] = new DateTime('1997-10-01 09:00:00'); $results[] = new DateTime('1997-10-02 09:00:00'); $results[] = new DateTime('1997-10-03 09:00:00'); $results[] = new DateTime('1997-10-04 09:00:00'); $results[] = new DateTime('1997-10-05 09:00:00'); $results[] = new DateTime('1997-10-06 09:00:00'); $results[] = new DateTime('1997-10-07 09:00:00'); $results[] = new DateTime('1997-10-08 09:00:00'); $results[] = new DateTime('1997-10-09 09:00:00'); $results[] = new DateTime('1997-10-10 09:00:00'); $results[] = new DateTime('1997-10-11 09:00:00'); $results[] = new DateTime('1997-10-12 09:00:00'); $results[] = new DateTime('1997-10-13 09:00:00'); $results[] = new DateTime('1997-10-14 09:00:00'); $results[] = new DateTime('1997-10-15 09:00:00'); $results[] = new DateTime('1997-10-16 09:00:00'); $results[] = new DateTime('1997-10-17 09:00:00'); $results[] = new DateTime('1997-10-18 09:00:00'); $results[] = new DateTime('1997-10-19 09:00:00'); $results[] = new DateTime('1997-10-20 09:00:00'); $results[] = new DateTime('1997-10-21 09:00:00'); $results[] = new DateTime('1997-10-22 09:00:00'); $results[] = new DateTime('1997-10-23 09:00:00'); $results[] = new DateTime('1997-10-24 09:00:00'); $results[] = new DateTime('1997-10-25 09:00:00'); $results[] = new DateTime('1997-10-26 09:00:00'); $results[] = new DateTime('1997-10-27 09:00:00'); $results[] = new DateTime('1997-10-28 09:00:00'); $results[] = new DateTime('1997-10-29 09:00:00'); $results[] = new DateTime('1997-10-30 09:00:00'); $results[] = new DateTime('1997-10-31 09:00:00'); $results[] = new DateTime('1997-11-01 09:00:00'); $results[] = new DateTime('1997-11-02 09:00:00'); $results[] = new DateTime('1997-11-03 09:00:00'); $results[] = new DateTime('1997-11-04 09:00:00'); $results[] = new DateTime('1997-11-05 09:00:00'); $results[] = new DateTime('1997-11-06 09:00:00'); $results[] = new DateTime('1997-11-07 09:00:00'); $results[] = new DateTime('1997-11-08 09:00:00'); $results[] = new DateTime('1997-11-09 09:00:00'); $results[] = new DateTime('1997-11-10 09:00:00'); $results[] = new DateTime('1997-11-11 09:00:00'); $results[] = new DateTime('1997-11-12 09:00:00'); $results[] = new DateTime('1997-11-13 09:00:00'); $results[] = new DateTime('1997-11-14 09:00:00'); $results[] = new DateTime('1997-11-15 09:00:00'); $results[] = new DateTime('1997-11-16 09:00:00'); $results[] = new DateTime('1997-11-17 09:00:00'); $results[] = new DateTime('1997-11-18 09:00:00'); $results[] = new DateTime('1997-11-19 09:00:00'); $results[] = new DateTime('1997-11-20 09:00:00'); $results[] = new DateTime('1997-11-21 09:00:00'); $results[] = new DateTime('1997-11-22 09:00:00'); $results[] = new DateTime('1997-11-23 09:00:00'); $results[] = new DateTime('1997-11-24 09:00:00'); $results[] = new DateTime('1997-11-25 09:00:00'); $results[] = new DateTime('1997-11-26 09:00:00'); $results[] = new DateTime('1997-11-27 09:00:00'); $results[] = new DateTime('1997-11-28 09:00:00'); $results[] = new DateTime('1997-11-29 09:00:00'); $results[] = new DateTime('1997-11-30 09:00:00'); $results[] = new DateTime('1997-12-01 09:00:00'); $results[] = new DateTime('1997-12-02 09:00:00'); $results[] = new DateTime('1997-12-03 09:00:00'); $results[] = new DateTime('1997-12-04 09:00:00'); $results[] = new DateTime('1997-12-05 09:00:00'); $results[] = new DateTime('1997-12-06 09:00:00'); $results[] = new DateTime('1997-12-07 09:00:00'); $results[] = new DateTime('1997-12-08 09:00:00'); $results[] = new DateTime('1997-12-09 09:00:00'); $results[] = new DateTime('1997-12-10 09:00:00'); $results[] = new DateTime('1997-12-11 09:00:00'); $results[] = new DateTime('1997-12-12 09:00:00'); $results[] = new DateTime('1997-12-13 09:00:00'); $results[] = new DateTime('1997-12-14 09:00:00'); $results[] = new DateTime('1997-12-15 09:00:00'); $results[] = new DateTime('1997-12-16 09:00:00'); $results[] = new DateTime('1997-12-17 09:00:00'); $results[] = new DateTime('1997-12-18 09:00:00'); $results[] = new DateTime('1997-12-19 09:00:00'); $results[] = new DateTime('1997-12-20 09:00:00'); $results[] = new DateTime('1997-12-21 09:00:00'); $results[] = new DateTime('1997-12-22 09:00:00'); $results[] = new DateTime('1997-12-23 09:00:00'); $r = new When(); $r->recur('19970902T090000', 'daily')->until('19971224T000000'); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Every other day - forever: * DTSTART;TZID=America/New_York:19970902T090000 * RRULE:FREQ=DAILY;INTERVAL=2 */ function testThirtyFive() { $results[] = new DateTime('1997-09-02 09:00:00'); $results[] = new DateTime('1997-09-04 09:00:00'); $results[] = new DateTime('1997-09-06 09:00:00'); $results[] = new DateTime('1997-09-08 09:00:00'); $results[] = new DateTime('1997-09-10 09:00:00'); $results[] = new DateTime('1997-09-12 09:00:00'); $results[] = new DateTime('1997-09-14 09:00:00'); $results[] = new DateTime('1997-09-16 09:00:00'); $results[] = new DateTime('1997-09-18 09:00:00'); $results[] = new DateTime('1997-09-20 09:00:00'); $results[] = new DateTime('1997-09-22 09:00:00'); $results[] = new DateTime('1997-09-24 09:00:00'); $results[] = new DateTime('1997-09-26 09:00:00'); $results[] = new DateTime('1997-09-28 09:00:00'); $results[] = new DateTime('1997-09-30 09:00:00'); $results[] = new DateTime('1997-10-02 09:00:00'); $results[] = new DateTime('1997-10-04 09:00:00'); $results[] = new DateTime('1997-10-06 09:00:00'); $results[] = new DateTime('1997-10-08 09:00:00'); $results[] = new DateTime('1997-10-10 09:00:00'); $results[] = new DateTime('1997-10-12 09:00:00'); $results[] = new DateTime('1997-10-14 09:00:00'); $results[] = new DateTime('1997-10-16 09:00:00'); $results[] = new DateTime('1997-10-18 09:00:00'); $results[] = new DateTime('1997-10-20 09:00:00'); $results[] = new DateTime('1997-10-22 09:00:00'); $results[] = new DateTime('1997-10-24 09:00:00'); $results[] = new DateTime('1997-10-26 09:00:00'); $results[] = new DateTime('1997-10-28 09:00:00'); $results[] = new DateTime('1997-10-30 09:00:00'); $results[] = new DateTime('1997-11-01 09:00:00'); $results[] = new DateTime('1997-11-03 09:00:00'); $results[] = new DateTime('1997-11-05 09:00:00'); $results[] = new DateTime('1997-11-07 09:00:00'); $results[] = new DateTime('1997-11-09 09:00:00'); $results[] = new DateTime('1997-11-11 09:00:00'); $results[] = new DateTime('1997-11-13 09:00:00'); $results[] = new DateTime('1997-11-15 09:00:00'); $results[] = new DateTime('1997-11-17 09:00:00'); $results[] = new DateTime('1997-11-19 09:00:00'); $results[] = new DateTime('1997-11-21 09:00:00'); $results[] = new DateTime('1997-11-23 09:00:00'); $results[] = new DateTime('1997-11-25 09:00:00'); $results[] = new DateTime('1997-11-27 09:00:00'); $results[] = new DateTime('1997-11-29 09:00:00'); $results[] = new DateTime('1997-12-01 09:00:00'); $results[] = new DateTime('1997-12-03 09:00:00'); $r = new When(); $r->recur('19970902T090000', 'daily')->interval(2)->count(47); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Every 10 days, 5 occurrences: * DTSTART;TZID=America/New_York:19970902T090000 * RRULE:FREQ=DAILY;INTERVAL=10;COUNT=5 */ function testThirtySix() { $results[] = new DateTime('1997-09-02 09:00:00'); $results[] = new DateTime('1997-09-12 09:00:00'); $results[] = new DateTime('1997-09-22 09:00:00'); $results[] = new DateTime('1997-10-02 09:00:00'); $results[] = new DateTime('1997-10-12 09:00:00'); $r = new When(); $r->recur('19970902T090000', 'daily')->interval(10)->count(5); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } /** * Every day in January, for 3 years: * DTSTART;TZID=America/New_York:19980101T090000 * RRULE:FREQ=DAILY;UNTIL=20000131T140000Z;BYMONTH=1 */ function testThirtySeven() { $results[] = new DateTime('1998-01-01 09:00:00'); $results[] = new DateTime('1998-01-02 09:00:00'); $results[] = new DateTime('1998-01-03 09:00:00'); $results[] = new DateTime('1998-01-04 09:00:00'); $results[] = new DateTime('1998-01-05 09:00:00'); $results[] = new DateTime('1998-01-06 09:00:00'); $results[] = new DateTime('1998-01-07 09:00:00'); $results[] = new DateTime('1998-01-08 09:00:00'); $results[] = new DateTime('1998-01-09 09:00:00'); $results[] = new DateTime('1998-01-10 09:00:00'); $results[] = new DateTime('1998-01-11 09:00:00'); $results[] = new DateTime('1998-01-12 09:00:00'); $results[] = new DateTime('1998-01-13 09:00:00'); $results[] = new DateTime('1998-01-14 09:00:00'); $results[] = new DateTime('1998-01-15 09:00:00'); $results[] = new DateTime('1998-01-16 09:00:00'); $results[] = new DateTime('1998-01-17 09:00:00'); $results[] = new DateTime('1998-01-18 09:00:00'); $results[] = new DateTime('1998-01-19 09:00:00'); $results[] = new DateTime('1998-01-20 09:00:00'); $results[] = new DateTime('1998-01-21 09:00:00'); $results[] = new DateTime('1998-01-22 09:00:00'); $results[] = new DateTime('1998-01-23 09:00:00'); $results[] = new DateTime('1998-01-24 09:00:00'); $results[] = new DateTime('1998-01-25 09:00:00'); $results[] = new DateTime('1998-01-26 09:00:00'); $results[] = new DateTime('1998-01-27 09:00:00'); $results[] = new DateTime('1998-01-28 09:00:00'); $results[] = new DateTime('1998-01-29 09:00:00'); $results[] = new DateTime('1998-01-30 09:00:00'); $results[] = new DateTime('1998-01-31 09:00:00'); $results[] = new DateTime('1999-01-01 09:00:00'); $results[] = new DateTime('1999-01-02 09:00:00'); $results[] = new DateTime('1999-01-03 09:00:00'); $results[] = new DateTime('1999-01-04 09:00:00'); $results[] = new DateTime('1999-01-05 09:00:00'); $results[] = new DateTime('1999-01-06 09:00:00'); $results[] = new DateTime('1999-01-07 09:00:00'); $results[] = new DateTime('1999-01-08 09:00:00'); $results[] = new DateTime('1999-01-09 09:00:00'); $results[] = new DateTime('1999-01-10 09:00:00'); $results[] = new DateTime('1999-01-11 09:00:00'); $results[] = new DateTime('1999-01-12 09:00:00'); $results[] = new DateTime('1999-01-13 09:00:00'); $results[] = new DateTime('1999-01-14 09:00:00'); $results[] = new DateTime('1999-01-15 09:00:00'); $results[] = new DateTime('1999-01-16 09:00:00'); $results[] = new DateTime('1999-01-17 09:00:00'); $results[] = new DateTime('1999-01-18 09:00:00'); $results[] = new DateTime('1999-01-19 09:00:00'); $results[] = new DateTime('1999-01-20 09:00:00'); $results[] = new DateTime('1999-01-21 09:00:00'); $results[] = new DateTime('1999-01-22 09:00:00'); $results[] = new DateTime('1999-01-23 09:00:00'); $results[] = new DateTime('1999-01-24 09:00:00'); $results[] = new DateTime('1999-01-25 09:00:00'); $results[] = new DateTime('1999-01-26 09:00:00'); $results[] = new DateTime('1999-01-27 09:00:00'); $results[] = new DateTime('1999-01-28 09:00:00'); $results[] = new DateTime('1999-01-29 09:00:00'); $results[] = new DateTime('1999-01-30 09:00:00'); $results[] = new DateTime('1999-01-31 09:00:00'); $results[] = new DateTime('2000-01-01 09:00:00'); $results[] = new DateTime('2000-01-02 09:00:00'); $results[] = new DateTime('2000-01-03 09:00:00'); $results[] = new DateTime('2000-01-04 09:00:00'); $results[] = new DateTime('2000-01-05 09:00:00'); $results[] = new DateTime('2000-01-06 09:00:00'); $results[] = new DateTime('2000-01-07 09:00:00'); $results[] = new DateTime('2000-01-08 09:00:00'); $results[] = new DateTime('2000-01-09 09:00:00'); $results[] = new DateTime('2000-01-10 09:00:00'); $results[] = new DateTime('2000-01-11 09:00:00'); $results[] = new DateTime('2000-01-12 09:00:00'); $results[] = new DateTime('2000-01-13 09:00:00'); $results[] = new DateTime('2000-01-14 09:00:00'); $results[] = new DateTime('2000-01-15 09:00:00'); $results[] = new DateTime('2000-01-16 09:00:00'); $results[] = new DateTime('2000-01-17 09:00:00'); $results[] = new DateTime('2000-01-18 09:00:00'); $results[] = new DateTime('2000-01-19 09:00:00'); $results[] = new DateTime('2000-01-20 09:00:00'); $results[] = new DateTime('2000-01-21 09:00:00'); $results[] = new DateTime('2000-01-22 09:00:00'); $results[] = new DateTime('2000-01-23 09:00:00'); $results[] = new DateTime('2000-01-24 09:00:00'); $results[] = new DateTime('2000-01-25 09:00:00'); $results[] = new DateTime('2000-01-26 09:00:00'); $results[] = new DateTime('2000-01-27 09:00:00'); $results[] = new DateTime('2000-01-28 09:00:00'); $results[] = new DateTime('2000-01-29 09:00:00'); $results[] = new DateTime('2000-01-30 09:00:00'); $results[] = new DateTime('2000-01-31 09:00:00'); $r = new When(); $r->recur('19980101T090000', 'daily')->until('20000131T140000')->bymonth(array(1)); foreach($results as $result) { $this->assertEquals($result, $r->next()); } } } <file_sep>/php/When v3/Tests/When_Iterator_Test.php <?php require_once 'PHPUnit/Framework.php'; require_once './When_Iterator.php'; class When_Iterator_Tests extends PHPUnit_Framework_TestCase { function testDateWithoutCache() { $results[] = new DateTime('1997-09-29 09:00:00'); $results[] = new DateTime('1997-10-30 09:00:00'); $results[] = new DateTime('1997-11-27 09:00:00'); $results[] = new DateTime('1997-12-30 09:00:00'); $results[] = new DateTime('1998-01-29 09:00:00'); $results[] = new DateTime('1998-02-26 09:00:00'); $results[] = new DateTime('1998-03-30 09:00:00'); $r = new When_Iterator(); $r->recur('19970929T090000', 'monthly')->count(7)->byday(array('MO', 'TU', 'WE', 'TH', 'FR'))->bysetpos(array(-2)); $counter = 0; foreach($r as $result) { $this->assertEquals($result, $results[$counter]); $counter++; } // if we rewind does it still work? $r->rewind(); $counter = 0; foreach($r as $result) { $this->assertEquals($result, $results[$counter]); $counter++; } } function testDateWithCache() { $results[] = new DateTime('1997-09-29 09:00:00'); $results[] = new DateTime('1997-10-30 09:00:00'); $results[] = new DateTime('1997-11-27 09:00:00'); $results[] = new DateTime('1997-12-30 09:00:00'); $results[] = new DateTime('1998-01-29 09:00:00'); $results[] = new DateTime('1998-02-26 09:00:00'); $results[] = new DateTime('1998-03-30 09:00:00'); $r = new When_Iterator(true); $r->recur('19970929T090000', 'monthly')->count(7)->byday(array('MO', 'TU', 'WE', 'TH', 'FR'))->bysetpos(array(-2)); $counter = 0; foreach($r as $result) { $this->assertEquals($result, $results[$counter]); $counter++; } // if we rewind does it still work? $r->rewind(); $counter = 0; foreach($r as $result) { $this->assertEquals($result, $results[$counter]); $counter++; } } }<file_sep>/honeycomb-init.php <?php /* Plugin Name: Honeycomb Event Calendar Plugin URI: https://github.com/jamesmehorter/honeycomb Description: The Honeycomb Event Calendar plugin for WordPress 3.0+ helps you build and organize your events. Version: 0.1 Beta Author: <NAME> Author URI: http://www.jamesmehorter.com Copyright 2011 <NAME> (email : <EMAIL>) For detailed documentation see the README.txt file bundled with the plugin. (smysite/wp-content/honeycomb/readme.txt */ //------------------------------ Honeycomb Plugin WordPress Hooks ---------------------------// /* CREATE THE HONEYCOMB */ //Create the 'Event' custom post type and 'Event Categories' taxonomy //Also create the 'Event Categories' custom meta data database table add_action('init', 'Create_Calendar_Custom_Post_Type', 0 ); //Create the 'Calendar View' Sub-Menu Page under 'Events' add_action('admin_menu', 'Init_Honeycomb_Event_Calendar') ; //Add a custom calendar icon to the 'Events' admin menu add_action('admin_head', 'Honeycomb_Admin_Menu_Icons'); /* EXTEND EDIT EVENTS POST TYPE */ //When editing the event via the post page we need to hook into the save action to store the custom meta data for each event add_action('save_post', 'save_meta_box_event_settings', 1, 2); //These two hooks extend the 'Events' list view to include an 'Event Category' column add_filter('manage_edit-hc_events_columns', 'Manage_Events_Admin_Columns'); add_action('manage_posts_custom_column', 'Manage_Events_Admin_Column_Content'); /* EXTEND EVENT CATEGORIES TAXONOMY */ //These two hooks extend the event_categories term edit page, by adding a 'color' row add_action('hc_event_categories_edit_form_fields', 'Manage_Event_Categories_Columns', 10, 2); add_action('edited_hc_event_categories', 'Save_Event_Categories', 10, 2); //Extend the 'Event Categories' list view to include a 'Color' column add_filter('manage_edit-hc_event_categories_columns', 'Event_Categories_List_Column_Headers'); add_filter('manage_hc_event_categories_custom_column', 'Event_Categories_List_Column_Cells', 10, 3 ); /* ENQUEUE SCRIPTS AND STYLES FOR DISPLAYING EVENTS */ //Add an action to WordPress init to run our script and style register function add_action('init', 'hc_events_register_scripts'); //Add an action to WordPress footer output whichs prints our scripts and styles to wp_footer() in both admin and public page rendering add_action('wp_print_footer_scripts', 'hc_events_print_scripts'); //add_action('admin_print_scripts ', 'hc_events_print_scripts'); //We need to add some css to the admin editor add_action('admin_print_styles', 'admin_meta_css'); /* SHORTCODES TO DISPLAY EVENTS */ //Add shortcode support to embed the calendar on any page or post add_shortcode('events-calendar-view', 'Display_Event_Calendar'); //Add shortcode support to embed upcoming events on any page or post add_shortcode('events-list-view', 'Display_Events_List_Shortcode'); //Add shortcode support to embed a list of event_category terms with their descriptions add_shortcode('event-categories-list', 'Display_Event_Categories_List_Shortcode'); /* MISC HONEYCOMB INTEGRATION */ //Allow full xhtml in our taxonomy descriptions remove_filter( 'pre_term_description', 'wp_filter_kses' ); //Add the new events post type into the wordpress blog feed add_filter('request', 'Update_RSS_Feed'); //We need to make sure events are local to the user creating them //This function ensures the server running this plugin is set to Universal Coordinate Time date_default_timezone_set('UTC'); //Set a global flag that will be used to determine whether or not to display scripts and styles //This flag will be turned on when honeycomb displays events and needs to use some scripts and styles global $hc_events_add_scripts ; $hc_events_add_scripts = false ; //Set the plugin folder location for use throughout the plugin $hc_plugin_url = plugins_url() . "/honeycomb"; //------------------------------ Honeycomb Plugin Initilization Functions ---------------------------// //Create the 'Events' custom post type and 'Event Categories' Taxonomy //Also create the 'Event Categories' custom meta data database channel function Create_Calendar_Custom_Post_Type() { global $wpdb; //Create the Events post type, the Event Types taxonomy for the post type register_post_type('hc_events', array( 'labels' => array( 'name' => _x('Events', 'post type general name'), 'singular_name' => _x('Event', 'post type singular name'), 'add_new' => _x('Add New', 'Event'), 'add_new_item' => __('Add New Event'), 'edit_item' => __('Edit Event'), 'new_item' => __('New Event'), 'view_item' => __('View Event'), 'search_items' => __('Search Events'), 'not_found' => __('No Events found'), 'not_found_in_trash' => __('No Events found in Trash'), 'parent_item_colon' => '', 'menu_name' => 'Events' ), 'description' => __('Store Individual Events'), 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'capability_type' => 'post', 'hierarchical' => false, 'rewrite' => array('slug' => 'dance-lessons'), 'query_var' => true, 'register_meta_box_cb' => 'init_metaboxes_events', //Function called to build the posts custom meta boxes 'supports' => array( 'title', 'editor', 'thumbnail', 'comments', 'excerpt'), 'taxonomies' => array('event_categories') //Register the Event Types taxonomy with the new post type ) ); // Add new taxonomy 'Event Categories' for sorting events register_taxonomy('hc_event_categories', array('hc_events'), //Attach the taxonomy strictly to the events custom posts array( 'hierarchical' => true, 'labels' => array( 'name' => _x( 'Event Categories', 'taxonomy general name' ), 'singular_name' => _x( 'Event Category', 'taxonomy singular name' ), 'search_items' => __( 'Search Event Categories' ), 'all_items' => __( 'All Event Categories' ), 'parent_item' => __( 'Parent Event Category' ), 'parent_item_colon' => __( 'Parent Event Category:' ), 'edit_item' => __( 'Edit Event Category' ), 'update_item' => __( 'Update Event Category' ), 'add_new_item' => __( 'Add New Event Category' ), 'new_item_name' => __( 'New Event Category Name' ), 'menu_name' => __( 'Event Categories' ), ), 'show_ui' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'event-categories' ), ) ); //Create our event-categories taxonomy meta db table, we'll use this table to store term meta, like color. //WordPress will automatically look for {table_prefix}event_categoriesmeta since we registered teh above taxonomy as 'event_categories' $wpdb->query("CREATE TABLE IF NOT EXISTS `".$wpdb->prefix."hc_event_categoriesmeta` ( `meta_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `hc_event_categories_id` bigint(20) unsigned NOT NULL DEFAULT '0', `meta_key` varchar(255) DEFAULT NULL, `meta_value` longtext, PRIMARY KEY (`meta_id`), KEY `meta_key` (`meta_key`), KEY `hc_event_categories_id` (`hc_event_categories_id`) ) ENGINE=MyISAM DEFAULT CHARSET=".DB_CHARSET." AUTO_INCREMENT=1 ;"); //Let's go ahead and create a shortcut method of $wpdb to call upon this new table $wpdb->hc_event_categoriesmeta = $wpdb->prefix."hc_event_categoriesmeta"; } //Create the 'Calendar View' 'Events' Sub Menu Page function Init_Honeycomb_Event_Calendar () { add_submenu_page('edit.php?post_type=hc_events', 'Event Calendar', 'Calendar View', 'manage_options', 'hc-event-calendar', Display_Event_Calendar); } //Add some style to the event calendar admin drop down menu icon //Support for the default left sidebar //Support for Ohz Horizontal Admin Bar function Honeycomb_Admin_Menu_Icons() { ?> <style type="text/css" media="screen"> #menu-posts-hcevents .wp-menu-image, #oam_menu-posts-hcevents .wp-menu-image { background: url(<?php echo get_bloginfo('url') ?>/wp-content/plugins/honeycomb/images/hc-admin-calendar-icon.png) no-repeat 6px -17px !important; } #oam_menu-posts-hcevents .wp-menu-image { margin: -3px 2px 0 0 ; } #menu-posts-hcevents:hover .wp-menu-image, #menu-posts-hcevents.wp-has-current-submenu .wp-menu-image, #oam_menu-posts-hcevents:hover.wp-menu-image, #oam_menu-posts-hcevents.wp-has-current-submenu .wp-menu-image { background-position:6px 7px!important; } <?php //Force some coluymn widths when displaying the event categories page if ($_GET['taxonomy'] == 'hc_event_categories') { ?> .column-hc_event_category_color { width: 40px; } .column-description { width: 240px ; } .column-posts { width: 75px !important ; } <?php } ?> </style> <?php } //This function is called by an action hook //Add our new custom post type to the primary wp rss feed //This seems to either show the custom post or the defaults posts //Not sure why this isn't working as documents yet function Update_RSS_Feed($qv) { if (isset($qv['feed'])) $qv['post_type'] = get_post_types(); return $qv; } //This function is called by an action hook //Register scripts and styles that honeycomb will use to display events function hc_events_register_scripts () { //echo "FOOOO"; //Used to generate the admin and public views of the calendar wp_register_script('fullcalendar', plugins_url('jquery-plugins/fullcalendar-1.6.4/fullcalendar/fullcalendar.min.js', __FILE__), array('jquery'), '1.5.1', true); //Used to generate the public views of the calendar wp_register_script("simpletip", plugins_url('jquery-plugins/jquery.simpletip-1.3.1.min.js', __FILE__), array('jquery'), '1.3.1', true); //This script fails when using the newer version of datepicker. Not sure why.. so we're sticking with the stable one wp_register_script("datepicker", plugins_url('/js/jquery-ui-datepicker-1.7.3.js', __FILE__), array('jquery', 'jquery-ui-core'), '1.7.3', true); //Provide the jQuery Plugin 'miniColors' color picker scri pt to the 'Event' custom write panel for use in the CPT meta box for event settings wp_register_script("minicolors", plugins_url('jquery-plugins/jquery.miniColors-0.1/jquery.miniColors.min.js', __FILE__), array('jquery'), '0.1', true); } //This function is called by an action hook //Display scripts and styles that honeycomb will use to display events via wp_footer() //Scripts and styles are only displayed if $hc_events_add_scripts has been set to true function hc_events_print_scripts () { /* The $hc_events_add_scripts global MUST be set to try in order for these scripts to display. This flag can be set to true in and function or action. Internally we enable this flag to true when displaying the calendar or list views in both the admin and public views */ global $hc_events_add_scripts ; if ($hc_events_add_scripts) { wp_print_scripts('fullcalendar'); //Let's only load the scripts we need for the admin display of honeycomb and the public display (lists and grid form) global $post; //echo "FOOOO"; if (is_admin()) { if($post->post_type == 'hc_events') { wp_print_scripts("jquery-ui-core", array('jquery')); wp_print_scripts('datepicker'); wp_print_scripts('minicolors'); } } else { wp_print_scripts('simpletip'); } } } //This function is called by an action hook //Display the event calendar //This is used to load the admin calendar //This is also called via a shortcode to embed the calendar on public pages function Display_Event_Calendar () { global $hc_events_add_scripts ; $hc_events_add_scripts = true ; include('php/hc-event-calendar.php'); } //The following function is triggered when the admin views the list of 'Events' posts //We want to tap in and add a column for our Event Categories taxonomy function Manage_Events_Admin_Columns ($columns) { $new_columns['cb'] = '<input type="checkbox" />'; $new_columns['title'] = _x('Event Name', 'column name'); $new_columns['hc_event_categories'] = __('Event Categories'); $new_columns['hc_event_allow_paying'] = __('Paying Enabled'); $new_columns['hc_event_repeat'] = __('Repeat'); $new_columns['date'] = _x('Date', 'column name'); return $new_columns; } //This function is triggered for each colomn cell in the 'Events' list //We want to tap in and display our Event Category in the appropriate cells, with links to edit them function Manage_Events_Admin_Column_Content ($column) { global $post; switch ($column) { case 'hc_event_categories': $terms = get_the_terms( $post->ID, 'hc_event_categories'); if ($terms) { $count = 0; foreach ($terms as $term) { echo '<a href="'.get_bloginfo('url').'/wp-admin/edit-tags.php?action=edit&taxonomy=hc_event_categories&post_type=hc_events&tag_ID='.$term->term_id.'">'.$term->name.'</a>'; if ($count != (count($terms) - 1)) { echo ", "; } $count++; } } break; case 'hc_event_allow_paying': $hc_event_prepay = get_post_meta($post->ID, 'hc_event_allow_paying', true); echo $hc_event_prepay; break; case 'hc_event_repeat': $hc_event_recurrance = get_post_meta($post->ID, 'hc_event_recurrance', true); if (is_array($hc_event_recurrance)) { echo "x" . $hc_event_recurrance['hc_event_interval']; } break; } // end switch } //The following function is called in the admin when displaying event_categories edit form //The function adds a new row at the bottom of the event_category term edit form, for 'color' function Manage_Event_Categories_Columns ($tag, $taxonomy) { global $hc_plugin_url; /* //For some reason we're unable to set a global here to be called prior to page load and use the hc script engine //So we're just gonna print the colors script manually. global $hc_events_add_scripts ; $hc_events_add_scripts = true ; */ wp_print_scripts('minicolors'); //wp_enqueue_style( 'miniColors', "$hc_plugin_url/jquery-plugins/jquery.miniColors-0.1/jquery.miniColors.css"); $hc_event_category_color = get_metadata($tag->taxonomy, $tag->term_id, 'hc_event_category_color', true); ?> <tr class="form-field"> <th scope="row" valign="top"><label for="hc_event_category_color">Color</label></th> <td> <link rel="stylesheet" href="<?php echo plugins_url('jquery-plugins/jquery.miniColors-0.1/jquery.miniColors.css', __FILE__) ?>" /> <style type="text/css"> #hc_event_category_color { width: 75px ; } </style> <input type="text" name="hc_event_category_color" id="hc_event_category_color" value="<?php echo $hc_event_category_color; ?>" /> <a href="#" id="hc_event_clear_color">Clear</a> <script type="text/javascript"> jQuery(function($) { $('#hc_event_category_color').miniColors({}); $('#hc_event_clear_color').click(function(e){ e.preventDefault() $('#hc_event_category_color').val('') }) }); </script> <br /> <p class="description"><?php _e("This color will be applied to all events in this category. This color can be overridden by per-event color settings or by selecting multiple categories."); ?></p> </td> </tr> <?php } //The following function is called when saving the event_category term edit form //We tap in and update our term color meta data, we have previous created a new db table to store the meta data function Save_Event_Categories ($term_id, $tt_id) { if (!$term_id) return; if (isset($_POST['hc_event_category_color'])) { update_metadata($_POST['taxonomy'], $term_id, 'hc_event_category_color', $_POST['hc_event_category_color']); } } //Add a 'Color' column to the 'Event Categories' page function Event_Categories_List_Column_Headers ($columns) { $new_columns['cb'] = '<input type="checkbox" />'; $new_columns['name'] = 'Name'; $new_columns['description'] = 'Description'; $new_columns['posts'] = 'Events'; $new_columns['hc_event_category_color'] = "Color"; return $new_columns; } //Add a color display in the 'Event Categories' page for each category function Event_Categories_List_Column_Cells ($row_content, $column_name, $term_id) { switch ($column_name) { case 'hc_event_category_color': $color = get_metadata('hc_event_categories', $term_id, 'hc_event_category_color', true); //Returns some html to display a box with the event color return "<div style='width: 100%; height: 30px; background-color: $color; color: #ffffff; text-align: center; padding-top: 8px;'></div>"; break; } } //------------------------------ Honeycomb Functions ---------------------------// /* These are functions used for the creation and update of events. They are located here because they are needed for both the calendar view and the wp-admin custom post type edit page. Functions required by template files for event display are also located here. */ function create_form_time_options ($selected) { $times = array('12:00 am','12:30 am','1:00 am','1:30 am','2:00 am','2:30 am','3:00 am','3:30 am','4:00 am','4:30 am','5:00 am','5:30 am','6:00 am','6:30 am','7:00 am','7:30 am','8:00 am','8:30 am','9:00 am','9:30 am','10:00 am','10:30 am','11:00 am','11:30 am','12:00 pm','12:30 pm','1:00 pm','1:30 pm','2:00 pm','2:30 pm','3:00 pm','3:30 pm','4:00 pm','4:30 pm','5:00 pm','5:30 pm','6:00 pm','6:30 pm','7:00 pm','7:30 pm','8:00 pm','8:30 pm','9:00 pm','9:30 pm','10:00 pm','10:30 pm','11:00 pm','11:30 pm'); if ($selected == "") { $selected = '7:00am'; } foreach ($times as $time) { if ($time == $selected) { $html_str .= "<option value='$time' selected='selected'>$time</option>\n"; } else { $html_str .= "<option value='$time'>$time</option>\n"; } } return $html_str; } function create_form_recurrance_interval_options ($selected) { for($i = 1; $i < 31; $i++) { if ($i == $selected) { $html_str .= "<option value='$i' selected='selected'>$i</option>\n"; } else { $html_str .= "<option value='$i'>$i</option>\n"; } } return $html_str; } function store_meta_data ($post_id, $meta_data) { foreach ($meta_data as $key => $value) { //Store the start date if (get_post_meta($post_id, $key, false)) { //Update the meta value if it already exists update_post_meta($post_id, $key, $value); } else { //Store the meta data if it does not exist yet add_post_meta($post_id, $key, $value); } } //End Foreach $meta_Date } //Adding some custom event meta boxes to the edit event post type page function init_metaboxes_events () { add_meta_box('hc_event_settings', 'Event Settings', 'meta_box_event_settings', 'hc_events', 'normal', 'high'); } function admin_meta_css () { global $post; global $hc_plugin_url; if($post->post_type == 'hc_events') { wp_enqueue_style( 'jquery-ui-smoothness', "$hc_plugin_url/css/jquery-ui-1.8.6.custom.css"); wp_enqueue_style( 'miniColors', "$hc_plugin_url/jquery-plugins/jquery.miniColors-0.1/jquery.miniColors.css"); } } //Event start date meta box function meta_box_event_settings () { global $hc_events_add_scripts ; $hc_events_add_scripts = true ; global $post; global $hc_plugin_url; //Select all current / saved meta data for this post $hc_event['hc_event_start'] = abs(get_post_meta($post->ID, 'hc_event_start', true)); $hc_event['hc_event_end'] = abs(get_post_meta($post->ID, 'hc_event_end', true)); $hc_event['hc_event_color'] = get_post_meta($post->ID, 'hc_event_color', true); $hc_event['hc_event_category_color'] = get_post_meta($post->ID, 'hc_event_category_color', true); $hc_event['hc_event_allday'] = get_post_meta($post->ID, 'hc_event_allday', true); $hc_event['hc_event_recurrance'] = get_post_meta($post->ID, 'hc_event_recurrance', true); if ($hc_event['hc_event_start'] == 0) { $hc_event['hc_event_start'] = strtotime($post->post_date); $hc_event['hc_event_end'] = strtotime($post->post_date); $hc_event['hc_event_allday'] = 1; } $hc_event['hc_event_allow_paying'] = get_post_meta($post->ID, 'hc_event_allow_paying', true); $hc_event['hc_event_amount'] = get_post_meta($post->ID, 'hc_event_amount', true); $hc_event['hc_event_allow_paying_until'] = get_post_meta($post->ID, 'hc_event_allow_paying_until', true); $hc_event['hc_event_second_amount'] = get_post_meta($post->ID, 'hc_event_second_amount', true); $hc_event['hc_event_second_allow_paying_until'] = get_post_meta($post->ID, 'hc_event_second_allow_paying_until', true); $hc_event['hc_event_paper_registration'] = get_post_meta($post->ID, 'hc_event_paper_registration', true); $hc_event['hc_event_sticky'] = get_post_meta($post->ID, 'hc_event_sticky', true); if ($hc_event['hc_event_allday'] == "" || $hc_event['hc_event_allday'] == 1) { $checked = " checked='checked'"; $time_selection = "display: none;"; $allday_question = ""; } else { $checked = ""; $time_selection = ""; $allday_question = "?"; } if (is_array($hc_event['hc_event_recurrance'])) { $hc_event_is_repeat_checked = " checked='checked'"; } if ($hc_event['hc_event_allow_paying'] == "on") { $hc_event_allow_paying_checked = " checked='checked'"; } if ($hc_event['hc_event_sticky'] == "on") { $hc_event_sticky_checked = " checked='checked'"; } //Output our meta box html ?> <script type="text/javascript"> //jQuery(document).ready(function(){ jQuery(document).ready(function($) { var dates = $( "#hc_event_start_date, #hc_event_end_date" ).datepicker({ numberOfMonths: 2, onSelect: function( selectedDate ) { var option = this.id == "hc_event_start_date" ? "minDate" : "maxDate", instance = $( this ).data( "datepicker" ), date = $.datepicker.parseDate( instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings ); dates.not( this ).datepicker( "option", option, date ); } }) var hc_event_selected_start = $('#hc_event_start_date').datepicker('getDate') var hc_event_selected_end = $('#hc_event_end_date').datepicker('getDate') //var hc_event_selected_start_str = (hc_event_selected_start.getMonth() + 1) + '/' + hc_event_selected_start.getDate() + '/' + hc_event_selected_start.getFullYear() $('#hc_event_allow_paying_unitl').datepicker({ //minDate: hc_event_selected_start, //maxDate: hc_event_selected_end }); $('#hc_event_second_allow_paying_until').datepicker({ maxDate: hc_event_selected_end }); /* //List of current event colors var hc_event_colors = [ '#4e85ca', //Light Blue '#7136e7', //Deep Blue '#6c00a4', //Purple '#9464e4', //Light Purple '#42202f', //Deep Purple '#920a2d', //Burgandy '#d06956', //Pink '#e44b00', //Dark Orange '#faa012', //Orange '#0dd703', //Green '#3b5b3c', //Dark Green '#515151', //Charcoal '#151515' //Black ]; for (var i in hc_event_colors) { if (hc_event_colors[i] == '<?php echo $hc_event['hc_event_color'] ?>') { var hc_event_color_index = i; } } $('#hc_event_colors').colorPicker({ defaultColor: parseInt(hc_event_color_index), // index of the default color (optional) color: hc_event_colors, click: function(color){ jQuery('#hc_event_color').attr('value', color); } }); */ // //----- Evemt AllDay Form Controllers // //Enable or disable the all day / timed event functions if($('#hc_event_allday').is(':checked')) { /* $('#hc_event_start_time').hide() $('#hc_event_end_date').hide() $('#hc_event_end_time').hide() */ $('.hc_event_not_allday').hide() } $('#hc_event_allday').live('change', function(event) { if($(this).is(':checked')) { /* $('#hc_event_start_time').hide() $('#hc_event_end_time').hide() $('#hc_event_end_date').hide(); */ $('.hc_event_not_allday').hide() } else { $('.hc_event_not_allday').show() /* $('#hc_event_start_time').show() $('#hc_event_end_time').show() $('#hc_event_end_date').show(); */ } }); // //----- Evemt Recurrance Form Controllers // //Enable or Disable event recurrance if ($('#hc_event_is_repeat').is(':checked')) { $('#hc_event_recurrance').show(); } else { $('#hc_event_recurrance').hide(); } $('#hc_event_is_repeat').live('change', function(event) { if ($(this).is(':checked')) { $('#hc_event_recurrance').show(); } else { $('#hc_event_recurrance').hide(); } }); //Update the interval noun field for descriptive recurrance output $('#hc_event_frequency').live('change', function(event){ $('#hc_event_frequency option:selected').each(function(){ $('#hc_event_interval_frequency_noun').text($(this)[0].value.splice('ly').ucFirst() + '(s)') }); }); $('#clear-paying-until').click(function(e){ e.preventDefault() $('#hc_event_allow_paying_unitl').val('') }) if ($('#hc_event_allow_paying').is(':checked')) { $('.hc_paying_allowed').show() } else { $('.hc_paying_allowed').hide() } $('#hc_event_allow_paying').live('change', function(event) { if ($(this).is(':checked')) { $('.hc_paying_allowed').show() } else { $('.hc_paying_allowed').hide() } }) $("#hc_event_color").miniColors({ }); $('#hc_event_clear_color').click(function(e){ e.preventDefault() $('#hc_event_color').val(' ') }) }); </script> <style type="text/css"> #hc_event_meta_table { width: 100% ; } #hc_event_meta_table td { background-color: rgb(230,230,230) ; } </style> <table cellpadding="10" cellspacing="5" border="0" id="hc_event_meta_table"> <tr> <td> <table cellpadding="0" cellspacing="5" border="0"> <tr> <td> <label for="hc_event_start">Start</label> <input id="hc_event_start_date" type='text' name='hc_event_start' value='<?php echo date('n/j/Y', $hc_event['hc_event_start']) ?>' /> </td><td class='hc_event_not_allday'> <select name="hc_event_start_time" id="hc_event_start_time"> <?php echo create_form_time_options(date('g:i a', $hc_event['hc_event_start'])); ?> </select> </td><td class='hc_event_not_allday'> To </td><td class='hc_event_not_allday'> <select name="hc_event_end_time" id="hc_event_end_time"> <?php echo create_form_time_options(date('g:i a', $hc_event['hc_event_end'])); ?> </select> </td><td class='hc_event_not_allday'> <input id="hc_event_end_date" type='text' name='hc_event_end' value='<?php echo date('n/j/Y', $hc_event['hc_event_end']) ?>' class='widefat' /> </td> </tr> </table> <table cellpadding="0" cellspacing="5" border="0"> <tr> <td> <input type="checkbox" name="hc_event_allday" id="hc_event_allday" value="1" <?php echo $checked; ?>/> <label for="hc_event_allday" id="hc_event_allday_label">All Day<?php echo $allday_question;?></label> </td><td> <input type="checkbox" name="hc_event_is_repeat" id="hc_event_is_repeat" value="1" <?php echo $hc_event_is_repeat_checked; ?> /> <label for="hc_event_is_repeat">Repeats?</label> </td><td> <div id="hc_event_recurrance"> <select name="hc_event_frequency" id="hc_event_pattern"> <?php $hc_event_frequencies = array('weekly', 'monthly', 'yearly'); foreach ($hc_event_frequencies as $hc_event_frequency) { if ($hc_event_frequency == $hc_event['hc_event_recurrance']['hc_event_frequency']) { $hc_event_selected_frequency = " selected='selected'"; } echo "<option value='$hc_event_frequency'>".ucfirst($hc_event_frequency)."</option>\n"; } ?> </select> <select name="hc_event_interval" id="hc_event_interval"> <?php echo create_form_recurrance_interval_options($hc_event['hc_event_recurrance']['hc_event_interval']); ?> </select> Time(s) <br /> <?php //$hc_event_repeat_summary = ucfirst(str_replace('ly', '(s)', $frequency)); ?> <span id="hc_event_summary"><?php echo $hc_event_repeat_summary; ?></span> </div> </td> </tr> </table> </td> </tr> <tr> <td> <table cellpadding="0" border="0" cellspacing="5"> <tr> <td valign="top"> <input type="checkbox" id="hc_event_allow_paying" name="hc_event_allow_paying" <?php echo $hc_event_allow_paying_checked;?> /> <label for="hc_event_allow_paying">Allow paying?</label> &nbsp; &nbsp; </td> <td class='hc_paying_allowed'> <table> <tr> <td> <label for="hc_event_amount">for &nbsp; </label> $ <input type="text" name="hc_event_amount" id="hc_event_amount" value="<?php echo $hc_event['hc_event_amount']; ?>" size="10" /> </td> <td class='hc_paying_allowed'> <label for="hc_event_allow_paying_unitl">until</label> <input type="text" name="hc_event_allow_paying_until" id="hc_event_allow_paying_unitl" value="<?php echo $hc_event['hc_event_allow_paying_until'] ?>" /> </td> <td class='hc_paying_allowed'> &nbsp; <a href="" title="Clear Until Date" id="clear-paying-until">Clear</a> </td> </tr> <tr> <td> <label for="hc_event_second_amount">then</label> $ <input type="text" name="hc_event_second_amount" id="hc_event_second_amount" value="<?php echo $hc_event['hc_event_second_amount']; ?>" size="10" /> </td> <td> <label for="hc_event_second_allow_paying_until">until</label> <input type="text" name="hc_event_second_allow_paying_until" id="hc_event_second_allow_paying_until" value="<?php echo $hc_event['hc_event_second_allow_paying_until'] ?>" /> </td> <td> &nbsp; <a href="" title="Clear Until Date" id="clear-second-paying-until">Clear</a> </td> </tr> </table> </td> </tr> <tr> <td class="hc_paying_allowed" colspan="2"> <br /> <label for="hc_event_paper_registration">Paper Registration Form Link</label> <input type="text" name="hc_event_paper_registration" id="hc_event_paper_registration" value="<?php echo $hc_event['hc_event_paper_registration'] ?>" size="80" /> </td> </tr> </table> </td> </tr> <tr> <td> <table> <tr> <?php //Gather the event categories for this event if ($terms = get_the_terms($post->ID, 'hc_event_categories')) { //If there is more than one category give the user the option to choose which category color to inherit if (count($terms) > 1) { //Display a dropdown menu for the user to select which event category supplies the event color ?> <td> Which category color? </td><td> <select name='hc_event_category_color' id='hc_event_category_color'> <?php //hc_event_category_color stores the term id of the color category if ($hc_event['hc_event_category_color'] == "") { $hc_event['hc_event_category_color'] = $terms[0]->term_id; } foreach ($terms as $term) { if ($term->term_id == $hc_event['hc_event_category_color']) { $selected_term = "selected='selected'"; } else { $selected_term = ""; } echo "<option value='{$term->term_id}' $selected_term>{$term->name} &nbsp;</option>"; } $event_category_color = get_metadata('hc_event_categories', $hc_event['hc_event_category_color'], 'hc_event_category_color', true); ?> </select> </td><td> <div style='width: 15px; height: 15px; background-color: <?php echo $event_category_color;?>'></div> </td> <?php } else if (count($terms) > 0){ //There is only one event category, only show that one - no dropdown for the user to select from $event_category_color = get_metadata('hc_event_categories', $terms[0]->term_id, 'hc_event_category_color', true); ?> <td> Color inherited from <?php echo $terms[0]->name ?> category: </td><td> <input type="hidden" name="hc_event_category_color" value="<?php echo $terms[0]->term_id;?>" /> <div style='width: 15px; height: 15px; background-color: <?php echo $event_category_color; ?>'></div> </td> <?php } ?> <td> <!-- Display an option for the user to override the event category color or select a color if no category is chosen --> OR override the category color: <?php } else { ?> <td> Set a color for this event: <?php } ?> <input type="text" name="hc_event_color" id="hc_event_color" class="colors" size="7" value="<?php echo $hc_event['hc_event_color'] ?>" /> <a href="#" id="hc_event_clear_color">Clear</a> </td> </tr> </table> </td> </tr> <tr> <td> <table cellpadding="0" cellspacing="5" border="0"> <tr> <td> <label for="hc_event_sticky">Don't show this as an event, just a sticky post</label> <input type="checkbox" name="hc_event_sticky" <?php echo $hc_event_sticky_checked; ?> /> </td> </tr> </table> </td> </tr> </table> <?php } function save_meta_box_event_settings ($post_id, $post) { //echo "<pre>".print_r($_POST, true)."</pre>"; if ($post->post_type != 'revision') { //Lets store all our meta box event settigns in an array and loop through it to store / update data //echo $_POST['hc_event_start'] . "-" . $_POST['hc_event_end']; //01/06/1970-2/17/1970 //echo strtotime($_POST['hc_event_start']) . "-" . strtotime($_POST['hc_event_end']); //This value is given sometimes by datepicker on the first use, leaving it stuck in 1970 //432000-4060800 //Correct Values //1294272000-1294272000 //print_r($_POST); //Make sure to set allday to 0 if it has not been set during form input (inactive) if ($_POST['hc_event_allday'] == "1") { //All day has been unchecked, so the event will have a start and end time (hours) $meta_data['hc_event_allday'] = 1; $meta_data['hc_event_start'] = strtotime($_POST['hc_event_start']); $meta_data['hc_event_end'] = strtotime($_POST['hc_event_end']); } else { $meta_data['hc_event_allday'] = 0; $meta_data['hc_event_start'] = strtotime(date('j F Y', strtotime($_POST['hc_event_start'])) . ' ' . $_POST['hc_event_start_time']); $meta_data['hc_event_end'] = strtotime(date('j F Y', strtotime($_POST['hc_event_end'])) . ' ' . $_POST['hc_event_end_time']); //echo date('j F Y', strtotime($_POST['hc_event_start'])) . ' ' . $_POST['hc_event_start_time']; //echo date('j F Y', strtotime($_POST['hc_event_end'])) . ' ' . $_POST['hc_event_end_time']; } if ($_POST['hc_event_is_repeat']) { //Generate the recurrance pattern $meta_data['hc_event_recurrance'] = array( "hc_event_frequency" => $_POST['hc_event_frequency'], "hc_event_interval" => $_POST['hc_event_interval'] ); } else { $meta_data['hc_event_recurrance'] = ""; } $meta_data['hc_event_color'] = $_POST['hc_event_color']; $meta_data['hc_event_category_color'] = $_POST['hc_event_category_color']; $meta_data['hc_event_allow_paying'] = $_POST['hc_event_allow_paying']; $meta_data['hc_event_amount'] = $_POST['hc_event_amount']; $meta_data['hc_event_allow_paying_until'] = $_POST['hc_event_allow_paying_until']; $meta_data['hc_event_second_amount'] = $_POST['hc_event_second_amount']; $meta_data['hc_event_second_allow_paying_until'] = $_POST['hc_event_second_allow_paying_until']; $meta_data['hc_event_paper_registration'] = $_POST['hc_event_paper_registration']; $meta_data['hc_event_sticky'] = $_POST['hc_event_sticky']; //print_r($meta_data); foreach ($meta_data as $key => $value) { //Store the start date if (get_post_meta($post->ID, $key, false)) { //Update the meta value if it already exists update_post_meta($post->ID, $key, $value); } else { //Store the meta data if it does not exist yet add_post_meta($post->ID, $key, $value); } } //End Foreach $meta_Date } //end Revision check } function get_hc_event ($hc_event_id) { global $wpdb ; global $blog_id; //Check if this plugin is being used in a multi-site blog //If it is we want to select event posts from the current blog only if ( is_multisite() ) { $posts_table = "wp_" . $blog_id . "_posts"; } else { $posts_table = "wp_posts"; } //Select all event posts $hc_event = $wpdb->get_results("SELECT * FROM " . $posts_table . " WHERE ID = $hc_event_id AND post_type = 'hc_events' AND post_status = 'publish'", ARRAY_A); $hc_event = $hc_event[0]; $hc_event['hc_event_start'] = get_post_meta($hc_event_id, 'hc_event_start', true); $hc_event['hc_event_end'] = get_post_meta($hc_event_id, 'hc_event_end', true); $hc_event['hc_event_color'] = get_post_meta($hc_event_id, 'hc_event_color', true); //We need to make sure we're passing an int for the allday flag $hc_event['hc_event_allday'] = abs(get_post_meta($hc_event_id, 'hc_event_allday', true)); $hc_event['hc_event_recurrance'] = get_post_meta($hc_event_id, 'hc_event_recurrance', true); $hc_event['hc_event_allow_paying'] = get_post_meta($hc_event_id, 'hc_event_allow_paying', true); $hc_event['hc_event_amount'] = get_post_meta($hc_event_id, 'hc_event_amount', true); $hc_event['hc_event_allow_paying_until'] = get_post_meta($hc_event_id, 'hc_event_allow_paying_until', true); $hc_event['hc_event_second_amount'] = get_post_meta($hc_event_id, 'hc_event_second_amount', true); $hc_event['hc_event_second_allow_paying_until'] = get_post_meta($hc_event_id, 'hc_event_second_allow_paying_until', true); $hc_event['hc_event_paper_registration'] = get_post_meta($hc_event_id, 'hc_event_paper_registration', true); $hc_event['hc_event_sticky'] = get_post_meta($hc_event_id, 'hc_event_sticky', true); if ($hc_event['post_excerpt'] != "") { $hc_event['hc_event_post_summary'] = $hc_event['post_excerpt']; } else { if ($hc_event['post_content'] != "") { $hc_event['hc_event_post_summary'] = substr(str_replace("\r\n", "", strip_tags($hc_event['post_content'])), 0, 100) . ' ...'; } else { $hc_event['hc_event_post_summary'] = ""; } } //Gather the event post url $hc_event['hc_event_url'] = get_permalink($hc_event_id); //Gather the event post terms $hc_event_terms_obj = wp_get_object_terms($hc_event_id, 'hc_event_categories'); //We only want the term names $hc_event_terms = array(); foreach ($hc_event_terms_obj as $hc_event_term) { $hc_event_terms[] = $hc_event_term->name; } //Lets complie our terms into a comma delimited string for transportation and presentation $hc_event['hc_event_terms'] = implode(', ', $hc_event_terms); //We need to add the event class name $hc_event['hc_event_classname'] = "hc_event_event-" . $hc_event_id; return $hc_event; } //REQUEST ALL EVENTS //Pre: none //POST: Return a multi-dimensional php array //Our event posts are stored singuarly, so an event that repeats 4 times is only one event post //The recurrance data is stored as a array in the event post meta data //pull in all post data //loop through and call post meta to retrieve our event settings //during the loop build an array of events //if the event has been set for recurrance we build the recurrance using the 'When' library //and generate the additional events in the array function request_all_events($filterTerms="") { global $wpdb ; global $blog_id; if ($filterTerms != "") { $filterTerms = explode(', ', $filterTerms); } //Check if this plugin is being used in a multi-site blog //If it is we want to select event posts from the current blog only if ( is_multisite() ) { $posts_table = "wp_" . $blog_id . "_posts"; } else { $posts_table = "wp_posts"; } //Select all event posts //$hc_event_posts = $wpdb->get_results("SELECT * FROM " . $posts_table . " WHERE post_type = 'hc_events' AND post_status = 'publish'", ARRAY_A); $args = [ // fetch events up to a year old // and a year into the future 'meta_query' => [ [ 'key' => 'hc_event_start', 'value' => strtotime( '-1 year' ), 'compare' => '>=', ], [ 'key' => 'hc_event_start', 'value' => strtotime( '+1 year' ), 'compare' => '<=', ] ], 'post_type' => 'hc_events', 'post_status' => 'publish', 'posts_per_page' => 100, ]; $events = get_posts( $args ); //echo "\nBEGIN COUNT:" . count($events); $hc_event_recurrance_posts = array(); //Select all event post associated meta data (event settings like start, end, color, allday, and recurrance settings) foreach ($events as $key => $event) { $hc_event_posts[$key]['ID'] = $event->ID; $hc_event_posts[$key]['post_title'] = $event->post_title; $hc_event_posts[$key]['post_author'] = $event->post_author; //We will be compiling an array of all the event start dates $hc_event_posts[ $key ]['hc_event_start'] = intval( get_post_meta($event->ID, 'hc_event_start', true) ); $hc_event_posts[ $key ]['hc_event_end'] = intval( get_post_meta($event->ID, 'hc_event_end', true) ); $hc_event_posts[ $key ]['hc_event_category_color'] = get_post_meta($event->ID, 'hc_event_category_color', true); if ($hc_event_posts[ $key ]['hc_event_category_color'] == "" || !$hc_event_posts[ $key ]['hc_event_category_color']) { if ($terms = get_the_terms($event->ID, 'hc_event_categories')) { $hc_event_posts[ $key ]['hc_event_category_color'] = $terms[0]->term_id; } } $hc_event_posts[ $key ]['hc_event_color'] = get_post_meta($event->ID, 'hc_event_color', true); $hc_event_posts[ $key ]['hc_event_allday'] = get_post_meta($event->ID, 'hc_event_allday', true); $hc_event_posts[ $key ]['hc_event_recurrance'] = get_post_meta($event->ID, 'hc_event_recurrance', true); $hc_event_posts[ $key ]['hc_event_allow_paying'] = get_post_meta($event->ID, 'hc_event_allow_paying', true); $hc_event_posts[ $key ]['hc_event_amount'] = get_post_meta($event->ID, 'hc_event_amount', true); $hc_event_posts[ $key ]['hc_event_allow_paying_until'] = get_post_meta($event->ID, 'hc_event_allow_paying_until', true); $hc_event_posts[ $key ]['hc_event_second_amount'] = get_post_meta($event->ID, 'hc_event_second_amount', true); $hc_event_posts[ $key ]['hc_event_second_allow_paying_until'] = get_post_meta($event->ID, 'hc_event_second_allow_paying_until', true); $hc_event_posts[ $key ]['hc_event_paper_registration'] = get_post_meta($event->ID, 'hc_event_paper_registration', true); //We'll use this for key-matching below to sort our events array by start date $hc_event_start_dates[] = $hc_event_posts[ $key ]['hc_event_start']; if ($hc_event_posts[ $key ]['post_excerpt'] != "") { $hc_event_posts[ $key ]['hc_event_post_summary'] = $hc_event_posts[ $key ]['post_excerpt']; } else { if ($hc_event_posts[ $key ]['post_content'] != "") { $hc_event_posts[ $key ]['hc_event_post_summary'] = substr(str_replace("\r\n", "", strip_tags($hc_event_posts[ $key ]['post_content'])), 0, 100) . ' ...'; } else { $hc_event_posts[ $key ]['hc_event_post_summary'] = ""; } } //Gather the event post url $hc_event_posts[ $key ]['hc_event_url'] = get_permalink($event->ID); //Gather the event post terms $hc_event_terms_obj = wp_get_object_terms($event->ID, 'hc_event_categories'); //We only want the term names $hc_event_terms = array(); foreach ($hc_event_terms_obj as $hc_event_term) { $hc_event_terms[] = $hc_event_term->name; } //Lets complie our terms into a comma delimited string for transportation and presentation $hc_event_posts[ $key ]['hc_event_terms'] = implode(', ', $hc_event_terms); //We need to make sure we're passing an int for the allday flag $hc_event_posts[ $key ]['hc_event_allday'] = intval($hc_event_posts[ $key ]["hc_event_allday"]); //We need to add the event class name $hc_event_posts[ $key ]['hc_event_classname'] = "hc_event_event-" . $event->ID; //If the recurrance field holds a serialized array of recurrance data (interval, frequency, and offset) //This conditional will create new singular event for each recurrance date //Each recurring group will all have the same ID so the calendar can treat them as one and relocate the group is desired if (is_array($hc_event_posts[ $key ]['hc_event_recurrance'])) { //Use the 'When' library to generate our start and end recurrance dates require_once "php/When v3/When.php"; //Generate the recurring event start dates $hc_event_datetime_event_start = new DateTime(date("Y-m-d H:i:s", $hc_event_posts[ $key ]['hc_event_start'])); $hc_event_start_datetimes = new When(); $hc_event_start_datetimes->recur($hc_event_datetime_event_start, $hc_event_posts[ $key ]['hc_event_recurrance']['hc_event_frequency']); $hc_event_start_datetimes->count($hc_event_posts[ $key ]['hc_event_recurrance']['hc_event_interval'] + 1); $hc_event_start_date_timestamps = array(); while($result = $hc_event_start_datetimes->next()) { //start_date_timestamps is now an array containing our new reccurrance date start times $hc_event_start_date_timestamps[] = $result->format('U'); } //Generate the recurring event end dates $hc_event_datetime_event_end = new DateTime(date("Y-m-d H:i:s", $hc_event_posts[ $key ]['hc_event_end'])); $hc_event_end_datetimes = new When(); $hc_event_end_datetimes->recur($hc_event_datetime_event_end, $hc_event_posts[ $key ]['hc_event_recurrance']['hc_event_frequency']); $hc_event_end_datetimes->count($hc_event_posts[ $key ]['hc_event_recurrance']['hc_event_interval'] + 1); $hc_event_end_date_timestamps = array(); while($result = $hc_event_end_datetimes->next()) { //end_date_timestamps is now an array containing our new reccurrance date end times $hc_event_end_date_timestamps[] = $result->format('U'); } //Generate the new additional events to plot onto the calendar for ($i = 1; $i < $hc_event_posts[ $key ]['hc_event_recurrance']['hc_event_interval'] + 1; $i++) { //Add onto our rolling start date list with this new event $hc_event_start_dates[] = $hc_event_start_date_timestamps[$i]; //Build each new occurance of thsi event $hc_event_recurrance_posts[] = array( 'ID' => $hc_event_posts[$key]['ID'], 'post_title' => $hc_event_posts[$key]['post_title'], 'post_author' => $hc_event_posts[$key]['post_author'], 'hc_event_post_summary' => $hc_event_posts[$key]['hc_event_post_summary'], 'hc_event_color' => $hc_event_posts[$key]['hc_event_color'], 'hc_event_category_color' => $hc_event_posts[$key]['hc_event_category_color'], 'hc_event_classname' => "hc_event_event-" . $hc_event_posts[$key]['ID'], 'hc_event_start' => intval( $hc_event_start_date_timestamps[$i] ), 'hc_event_end' => intval( $hc_event_end_date_timestamps[$i] ), 'hc_event_allday' => $hc_event_posts[$key]['hc_event_allday'], 'hc_event_recurrance' => "child-" . $i, 'hc_event_url' => $hc_event_posts[$key]['hc_event_url'] ); } } }//END FOREACH EVENT POSTS //Merge our new recurring events onto the repo event bin $hc_event_posts = array_merge( $hc_event_posts, $hc_event_recurrance_posts ); /* //Filter our list of events by any terms passed into this functions if (is_array($filterTerms)) { $addedEvent = false; //Search the current terms for the filter terms foreach ($filterTerms as $hc_event_term) { //If our filtered term is in the events we'll add it to a temp arr of events //We will only add this event once by setting and checking a bool below if (is_int(array_search($hc_event_term, $hc_event_terms)) && !$addedEvent) { $e[] = $hc_event_post; $addedEvent = true; } } } //If terms were used to filter the event results, we want to convert our $hc_event_posts arr to only contain filtered results if (is_array($filterTerms)) { $hc_event_posts = $e; } */ usort( $hc_event_posts, function( $a, $b ) { return ($a['hc_event_start'] < $b['hc_event_start']) ? -1 : (($a['hc_event_start'] > $b['hc_event_start']) ? 1 : 0); } ); //Return all our individual events in a multi-dimensional array, sorted by their start dates DESC return $hc_event_posts; } // End function request_all_events //Function to display upcoming events via a shortcode in pages / posts function Display_Events_List_Shortcode($atts) { //Grab the limit field set in the shortcode and pass it to our Display_Upcoming_Events function below Display_List_Of_Events($atts['terms'], $atts['limit']); } //Generate and display a list of upcoming events //Display_List_Of_Events ( [string $term][, int $limit] ) function Display_List_Of_Events ($hc_event_terms='', $hc_event_limit=1) { global $hc_plugin_url; $hc_events = request_all_events($hc_event_terms); //Filter our events list down to only future and happening events //Add a flag for currently happening events foreach($hc_events as $i => $hc_event) { if ($hc_event['hc_event_start'] > time()) { $hc_eventsArr[$i] = $hc_event; } } $hc_events = array_values( $hc_eventsArr ); //Output our upcoming events container div ?> <link rel='stylesheet' type='text/css' href='<?php echo $hc_plugin_url; ?>/css/honeycomb.1.0.0.css' /> <div id="hc_event_list"> <?php //Check for any events if (count($hc_events) > 0) { //If a limit has been set, lets make sure we dont output more containers than there are events //I.e. request 5 events, but there are only 3 if (count($hc_events) < $hc_event_limit) { $hc_event_limit = count($hc_events); } for($i = 0; $i < $hc_event_limit; $i++) { //Trucate the description /* $hc_event_description = $hc_events[$i]['post_content']; if (strlen($hc_event_description) > 100) { $hc_event_description = substr($hc_event_description, 0, 150)."..."; } */ //print_r($hc_events); $hc_event_description = $hc_events[$i]['hc_event_post_summary']; if ($hc_events[$i]['hc_event_happening']) { $hc_event_class = " happening"; //Show the event span date, 11/06 - 11/07 $hc_event_date = date("m/d - ", $hc_events[$i]['hc_event_start']) . date("m/d - ", $hc_events[$i]['hc_event_end']); } else { $hc_event_class = ""; //Show the event star date, 11/06 $hc_event_date = date("m/d - ", $hc_events[$i]['hc_event_start']); } //Output each event item div / content ?> <div class="hc_event_item<?php echo $hc_event_class ;?>"> <span class='hc_event_item_date'><b><?php echo $hc_event_date ;?></b></span> <b><a href="<?php echo $hc_events[$i]['hc_event_url'];?>"><?php echo $hc_events[$i]['post_title'] ;?></a></b> <br /> <p><?php echo $hc_event_description ;?></p> </div> <?php }//end events for loop } else { //There are no upcoming events echo "<p class='hc_event_no_events'>Check back soon! There are no upcoming events at this time.</p>"; } ?> </div> <?php } // End function Display_Upcoming_Events //Display a list of event types(taxonomy) with links to their pages function Display_Event_Categories_List_Shortcode ($atts) { //Determine if the user set a length if ( empty( $atts['length'] ) ) { $length = 255; } else { $length = $atts['length']; } return Display_Event_Type_List($length); }// End Display_Event_Type_List function Display_Event_Type_List ($length = 255) { foreach (get_terms('hc_event_categories', 'order_by=name&hide_empty=0') as $hc_event_categories) { $html_str .= "<h2><a href='" . get_bloginfo('url') . "/event-categories/{$hc_event_categories->slug}' title='See events in {$hc_event_categories->name}'>{$hc_event_categories->name}</a> -</h2> "; $html_str .= "<p>" . substr($hc_event_categories->description, 0, $length) . " ... <a href='" . get_bloginfo('url') . "/event-categories/{$hc_event_categories->slug}' title='Read more about {$hc_event_categories->name}'>more</a></p><br /><br />"; } return $html_str; } ?>
84de0749cd45d471beb78ab1fbdb0afe46d247de
[ "Text", "PHP" ]
14
PHP
jamesmehorter/honeycomb
11c117fe412d5626e2f498da060b7700ada8cb70
2c68912810c09a55fb6b9545b42d6e014f17b769
refs/heads/master
<repo_name>magicst0ne/go-rsubl<file_sep>/README.md # rsubl ## Description Edit files on a remote server over ssh in Sublime 3 ### Binary install linux ```bash curl -LJO https://github.com/magicst0ne/go-rsubl/releases/download/lastest/rsubl-linux.tar.gz && \ sudo tar -zxf rsubl-linux.tar.gz -C /usr/local/bin ``` <file_sep>/rsubl.go package main import ( "bufio" "crypto/md5" "errors" "fmt" "github.com/urfave/cli/v2" "go-rsubl/rsub" "io" "io/ioutil" "log" "os" "os/exec" "path/filepath" "strconv" "strings" ) var ( AppVersion = "0.1.3" Verbose = false HelpTemplate = `NAME: {{.Name}} - {{.Usage}} USAGE: {{.HelpName}} {{if .VisibleFlags}}[options]{{end}}[file1 file2 ...]}{{if .Commands}} COMMANDS: {{range .Commands}}{{if not .HideHelp}} {{join .Names ", "}}{{ "\t"}}{{.Usage}}{{ "\n" }}{{end}}{{end}}{{end}}{{if .VisibleFlags}} OPTIONS: {{range .VisibleFlags}}{{.}} {{end}}{{end}}{{if .Copyright }} COPYRIGHT: {{.Copyright}} {{end}}{{if .Version}} VERSION: {{.Version}} {{end}} ` ) var hashes = make(map[string]string) func sendFile(c *rsub.Conn, path string) error { var fileSize int64 = 0 var fileExist bool = false var f *os.File fInfo, err := os.Stat(path) if err == nil { fileExist = true fileSize = fInfo.Size() if fInfo.IsDir() { return errors.New("only file can be edit") } } if !fileExist { f, err = os.Create(path) } else { //open file f, err = os.Open(path) } if err != nil { return err } defer f.Close() displayName := filepath.Base(path) hostname, err := os.Hostname() if err==nil { displayName = fmt.Sprintf("%s:%s", hostname, displayName) } realpath, _ := filepath.Abs(path) hash := fmt.Sprintf("%x", md5.Sum([]byte(realpath))) c.SendString("open\n") c.SendString(fmt.Sprintf("display-name: %v\n", displayName)) c.SendString(fmt.Sprintf("real-path: %v\n", realpath)) c.SendString("data-on-save: yes\n") c.SendString("re-activate: yes\n") c.SendString("selection: 0\n") c.SendString(fmt.Sprintf("token: %v\n", hash)) c.SendString(fmt.Sprintf("data: %v\n", fileSize)) c.SendFile(bufio.NewReader(f)) c.SendString("\n.\n") c.Flush() hashes[hash] = path return nil } func processRecv(c *rsub.Conn, line []byte) (error) { cmd := strings.TrimSpace(string(line)) switch cmd { case "close": data, err := c.Receive() if err!=nil { return cli.Exit("connection close and exit", 86) } line := string(data.([]byte)) if strings.HasPrefix(line, "token:") { token := strings.TrimSpace(line[6:]) if Verbose { log.Printf("close file %s", hashes[token]) } delete(hashes, token) } return nil case "save": var token string var size int64 for{ data, err := c.Receive() if err!=nil { return cli.Exit("connection close and exit", 86) } line := string(data.([]byte)) if strings.HasPrefix(line, "token:") { token = strings.TrimSpace(line[6:]) } else if strings.HasPrefix(line, "data:") { size, err = strconv.ParseInt(line[6:], 10, 64) if err != nil { log.Printf("read data size error") return err } if Verbose { log.Printf(" save file token:%s size:%d ", token, size) } break } } f, err := ioutil.TempFile("", "") if err != nil { return err } defer f.Close() _, err = io.CopyN(f, c.GetReader(), int64(size)) if err != nil { return err } f.Close() if file, ok := hashes[token]; ok { fi, err := os.Stat(file) if err !=nil { log.Printf("get file(%s) stat error %s ", file, err) return err } fm := fi.Mode() filePerm := fm.Perm() err = os.Rename(f.Name(), file) if err !=nil { log.Printf("save file(%s) failed %s ", file, err) return err } if Verbose { log.Printf("save file(%s) %d bytes success", file, size) } os.Chmod(file, filePerm) return nil } return errors.New("save file error token: " + token) } return nil } func main() { app := cli.NewApp() app.Name = "rsubl" app.Usage = "Edit files on a remote server over ssh in Sublime 3" app.Version = AppVersion //Override a template cli.AppHelpTemplate = HelpTemplate cli.VersionFlag = &cli.BoolFlag{Name: "version", Value: false, Usage: "print the version"} app.Flags = []cli.Flag { &cli.StringFlag{Name: "host", Value: "localhost", Usage: "Connect to host."}, &cli.IntFlag{Name: "port", Value: 52698, Usage: "Port number to use for connection."}, &cli.BoolFlag{Name: "verbose", Value: false, Usage: "verbose logging messages.", Aliases: []string{"v"}}, } app.Action = func(c *cli.Context) error { Verbose = c.Bool("verbose") n := c.NArg() if n > 0 { if !Verbose { args := []string{} args = append(args, "-v") for i:=1; i < len(os.Args); i++ { args = append(args, os.Args[i]) } cmd := exec.Command(os.Args[0], args...) cmd.Start() os.Exit(0) } //connect to host conn, err := rsub.NewConn(c.String("host"), c.Int("port")) if err != nil { return cli.Exit(fmt.Sprintf("connect %s:%d failed", c.String("host"), c.Int("port")), 86) } line, err := conn.Receive() if (err==nil&&len(line.([]byte))>0) { if c.Bool("verbose") { log.Printf("connect %s:%d success", c.String("host"), c.Int("port")) log.Printf("response: %s", string(line.([]byte))) } } //send file for i := 0; i < n; i++ { file := c.Args().Get(i) err = sendFile(conn, file) if err != nil { if c.Bool("verbose") { log.Printf("send file %s error (%v)", file, err.Error()) } } else { if c.Bool("verbose") { log.Printf("send file %s success", file) } } } //loop for{ if len(hashes)<1 { return cli.Exit("exit, no open files", 86) } line, err := conn.Receive() if err!=nil { if (err!=io.EOF) { return cli.Exit("connection close and exit", 86) } } if line !=nil { processRecv(conn, line.([]byte)) } } } else { cli.ShowAppHelp(c) } return nil } if err := app.Run(os.Args); err != nil { log.Fatal(err) } } <file_sep>/rsub/conn.go package rsub import ( "bufio" "errors" "fmt" "io" "net" "sync" "time" ) type Error string func (err Error) Error() string { return string(err) } // conn is the low-level implementation of Conn type Conn struct { // Shared mu sync.Mutex err error conn net.Conn // Read readTimeout time.Duration br *bufio.Reader // Write writeTimeout time.Duration bw *bufio.Writer } func NewConn(host string, port int) (*Conn, error){ netConn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", host, port)) if err != nil { return nil, err } c := &Conn{ conn: netConn, bw: bufio.NewWriter(netConn), br: bufio.NewReader(netConn), readTimeout: 0 * time.Second, writeTimeout: 0 * time.Second, } return c, err } func (c *Conn) Close() error { c.mu.Lock() err := c.err if c.err == nil { c.err = errors.New("conn: closed") err = c.conn.Close() } c.mu.Unlock() return err } func (c *Conn) fatal(err error) error { c.mu.Lock() if c.err == nil { c.err = err // Close connection to force errors on subsequent calls and to unblock // other reader or writer. c.conn.Close() } c.mu.Unlock() return err } func (c *Conn) Err() error { c.mu.Lock() err := c.err c.mu.Unlock() return err } func (c *Conn) writeString(s string) error { _, err := c.bw.WriteString(s) return err } func (c *Conn) writeBytes(p []byte) error { _, err := c.bw.Write(p) return err } func (c *Conn) SendString(data string) error { if c.writeTimeout != 0 { c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout)) } if err := c.writeString(data); err != nil { return c.fatal(err) } return nil } func (c *Conn) SendBytes(data []byte) error { if c.writeTimeout != 0 { c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout)) } if err := c.writeBytes(data); err != nil { return c.fatal(err) } return nil } func (c *Conn) SendFile(src *bufio.Reader) error { if c.writeTimeout != 0 { c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout)) } if _, err := io.Copy(c.bw, src); err != nil { return c.fatal(err) } return nil } func (c *Conn) Flush() error { if c.writeTimeout != 0 { c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout)) } if err := c.bw.Flush(); err != nil { return c.fatal(err) } return nil } type protocolError string func (pe protocolError) Error() string { return fmt.Sprintf("rsub: %s (possible server error or unsupported concurrent read by application)", string(pe)) } func (c *Conn) GetReader() (*bufio.Reader) { return c.br } // readLine reads a line of input func (c *Conn) readLine() ([]byte, error) { p, err := c.br.ReadSlice('\n') if err == bufio.ErrBufferFull { // The line does not fit in the bufio.Reader's buffer. Fall back to // allocating a buffer for the line. buf := append([]byte{}, p...) for err == bufio.ErrBufferFull { p, err = c.br.ReadSlice('\n') buf = append(buf, p...) } p = buf } if err != nil { return nil, err } i := len(p) - 1 if i < 0 || p[i] != '\n' { return nil, protocolError("bad response line terminator") } return p[:i], nil } func (c *Conn) readReply() ([]byte, error) { line, err := c.readLine() if err != nil { return nil, err } if len(line) == 0 { return nil, nil } return line, nil } func (c *Conn) Receive() (interface{}, error) { return c.ReceiveWithTimeout(c.readTimeout) } func (c *Conn) ReceiveWithTimeout(timeout time.Duration) (reply interface{}, err error) { var deadline time.Time if timeout != 0 { deadline = time.Now().Add(timeout) } c.conn.SetReadDeadline(deadline) if reply, err = c.readReply(); err != nil { return nil, c.fatal(err) } if err, ok := reply.(Error); ok { return nil, err } return }
6a85660456115edf32cfaf54be506f301f2d8c1d
[ "Markdown", "Go" ]
3
Markdown
magicst0ne/go-rsubl
52a73953e18b8d0f63fea83df901e1abc1614270
b6b234c375cbb720908bb995c0082f28a1fed121
refs/heads/master
<repo_name>Baton1956/HomeWork401<file_sep>/src/main/java/ru/geekbrains/main/site/at/HomeWork/DZ1/Start.java package ru.geekbrains.main.site.at.HomeWork.DZ1; public class Start { } <file_sep>/src/main/java/ru/geekbrains/main/site/at/HomeWork/DZ1/Road.java package ru.geekbrains.main.site.at.HomeWork.DZ1; public class Road { } <file_sep>/src/main/java/ru/geekbrains/main/site/at/HomeWork/DZ1/Wall.java package ru.geekbrains.main.site.at.HomeWork.DZ1; public class Wall { } <file_sep>/src/main/java/ru/geekbrains/main/site/at/HomeWork/DZ1/Actions.java package ru.geekbrains.main.site.at.HomeWork.DZ1; public interface Actions { } <file_sep>/src/main/java/ru/geekbrains/main/site/at/HomeWork/DZ1/Robot.java package ru.geekbrains.main.site.at.HomeWork.DZ1; public class Robot { } <file_sep>/src/main/java/ru/geekbrains/main/site/at/HomeWork/DZ1/Barrier.java package ru.geekbrains.main.site.at.HomeWork.DZ1; public class Barrier { }
83509f55643fdc5cc2c8558651448bdef9da6f49
[ "Java" ]
6
Java
Baton1956/HomeWork401
1466cffaddc35ed0a93cb20e4124d6ff9ea61ab7
4be9b4e96d6f94376eb5f2b7859ce03b739608e3
refs/heads/master
<repo_name>Patrick-Ren/search-form<file_sep>/src/components/App.js import React from 'react'; import SearchForm from './SearchForm'; import DataTable from './DataTable'; import ErrorBox from './ErrorBox'; import { GlobalContextProvider } from '../context/GlobalContextProvider' import '../css/App.scss'; function App() { return ( <GlobalContextProvider> <div className="app-container"> <SearchForm /> <DataTable /> <ErrorBox /> </div> </GlobalContextProvider> ) } export default App;<file_sep>/src/context/GlobalContextProvider.js import React, { useState, useEffect } from 'react' import FakeData from './FakeData'; const GlobalContext = React.createContext(); function GlobalContextProvider({ children }) { const [searchData, setSearchData] = useState({ materialNumber: [], vender: "", gsm: "" }); const [searching, setSearching] = useState(false); const [tableData, setTableData] = useState([]); const [uploadErrors, setUploadErrors] = useState([]); const [showErrorBox, setShowErrorBox] = useState(false) useEffect(() => { if (searching) { setTimeout(() => { setTableData(FakeData.table) }, 1000) } }, [searching]) useEffect(() => { setSearching(false) }, [tableData]) // function handleSearchDataChange(dataType, newValue) { // setSearchData(prev => { // return { ...prev, [dataType]: newValue } // }) // } function handleSearch(newSearchData) { setSearchData(newSearchData) setSearching(true) } function handleSearchClear() { console.log('inside handle search clear') setSearchData({ materialNumber: [], vender: "", gsm: "" }) } function handleUpload() { //show uploader, make api call setUploadErrors(FakeData.errors) setShowErrorBox(true) } return ( <GlobalContext.Provider value ={{ searchData, searching, tableData, uploadErrors, showErrorBox, setShowErrorBox, handleSearch, handleSearchClear, handleUpload }} > {children} </GlobalContext.Provider> ) } export { GlobalContext, GlobalContextProvider };<file_sep>/src/context/FakeData.js const tableData = []; for (let i = 0; i < 50; i++) { var item = { key: (i + 1).toString(), materialNumber: "MN" + (i + 1).toString().padStart(8, '0'), vender: "renzhu1", gsm: "whatever" } for (let x = 0; x < 20; x++) { item["other" + (x+1)] = "展示数据" } tableData.push(item) } const FakeData = { table: tableData, errors: [ { location: "第一行第一列", msg: "长度不符合规则" }, { location: "第二行第三列", msg: "应该是数字类型" }, { location: "第五行第二列", msg: "不可为空" }, { location: "第五行第三列", msg: "非法数据" },{ location: "第五行第三列", msg: "There are many variations of passages of Lorem Ipsum available, but the ways." },{ location: "第五行第三列", msg: "There are many variations of passages of Lorem Ipsum available, but the ways.There are many variations of passages of Lorem Ipsum available, but the ways." }, ] } export default FakeData;<file_sep>/src/components/ErrorBox.js import React, { useContext } from 'react' import { Drawer } from 'antd' import { GlobalContext } from '../context/GlobalContextProvider'; import { v4 } from 'uuid' import '../css/ErrorBox.scss'; function ErrorBox() { const { uploadErrors: errors, showErrorBox: visible, setShowErrorBox } = useContext(GlobalContext) return ( <Drawer visible={visible} title={`☹ 出现了${errors.length}条错误`} placement="right" onClose={ () => { setShowErrorBox(false) } } width={500} > { errors.map(error => ( <div className="error-card" key={v4()}> <p>位置: {error.location}</p> <p>{error.msg}</p> </div> )) } </Drawer> ) } export default ErrorBox;<file_sep>/README.md run project: npm start limitation of using context in React: only suitable for low frequency update will have performance issues for high frequency update such as key stokes<file_sep>/src/components/SearchForm.js import React, { useState, useEffect, useContext } from 'react'; import { Select, Input, Button } from 'antd'; import { GlobalContext } from '../context/GlobalContextProvider'; import '../css/SearchForm.scss'; function SearchForm() { const { searchData: { materialNumber, vender, gsm }, searching, handleSearch, handleSearchClear } = useContext(GlobalContext); //use local state and only inform global state to update when search button is clicked const [curMaterialNumber, setCurMaterialNumber] = useState(materialNumber) const [curVender, setCurVender] = useState(vender); const [curGsm, setCurGsm] = useState(gsm); //to sync local state with global state, but this code is really ugly!!! useEffect(() => { setCurMaterialNumber(materialNumber) }, [materialNumber]) useEffect(() => { setCurVender(vender) }, [vender]) useEffect(() => { setCurGsm(gsm) }, [gsm]) return ( <form className="search-form"> <div className="first-row"> <span className="label">Material Number:</span> <Select mode="tags" placeholder="请输入,然后回车;支持复制粘贴(会根据空格,逗号,分号和Tab进行分词)" dropdownStyle={{ display: "none" }} tokenSeparators={[';', ';', ',', ',', ' ', '\t']} value={curMaterialNumber} onChange={ setCurMaterialNumber } /> </div> <div className="second-row"> <div className="vender"> <span className="label">Vender:</span> <Input placeholder="Vender" value={curVender} onChange={(e) => { setCurVender(e.target.value) }} /> </div> <div className="gsm"> <span className="label">GSM:</span> <Input placeholder="GSM" value={curGsm} onChange={(e) => { setCurGsm(e.target.value) }} /> </div> <div className="btn-container"> <Button icon="search" type="primary" loading={searching} onClick={() => { handleSearch({ materialNumber: curMaterialNumber, vender: curVender, gsm: curGsm }) }} > Search </Button> <Button type='primary' onClick={handleSearchClear}> Clear </Button> </div> </div> </form> ) } export default SearchForm;
28b4918824f7c8b37e05197d786bc1a3fab2d3a3
[ "JavaScript", "Markdown" ]
6
JavaScript
Patrick-Ren/search-form
cc85a8b62dcc8f3dc72357dee050092ee632e3aa
53d2fe11749197cc9dc54fc100999381fb73d9ac
refs/heads/master
<repo_name>gutaoainibei/ShopSSHE<file_sep>/src/com/gt/model/Product.java package com.gt.model; // Generated 2015-9-22 20:01:58 by Hibernate Tools 4.0.0 import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * Product generated by hbm2java */ @Entity @Table(name = "product", catalog = "shopping") public class Product implements java.io.Serializable { private Integer id; private String name; private BigDecimal price; private String pic; private String remark; private String xremark; private Date date; private Boolean commend; private Boolean open; private Integer cid; public Product() { } public Product(Date date) { this.date = date; } public Product(String name, BigDecimal price, String pic, String remark, String xremark, Date date, Boolean commend, Boolean open, Integer cid) { this.name = name; this.price = price; this.pic = pic; this.remark = remark; this.xremark = xremark; this.date = date; this.commend = commend; this.open = open; this.cid = cid; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } @Column(name = "name", length = 20) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Column(name = "price", precision = 8) public BigDecimal getPrice() { return this.price; } public void setPrice(BigDecimal price) { this.price = price; } @Column(name = "pic", length = 200) public String getPic() { return this.pic; } public void setPic(String pic) { this.pic = pic; } @Column(name = "remark") public String getRemark() { return this.remark; } public void setRemark(String remark) { this.remark = remark; } @Column(name = "xremark") public String getXremark() { return this.xremark; } public void setXremark(String xremark) { this.xremark = xremark; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "date", nullable = false, length = 19) public Date getDate() { return this.date; } public void setDate(Date date) { this.date = date; } @Column(name = "commend") public Boolean getCommend() { return this.commend; } public void setCommend(Boolean commend) { this.commend = commend; } @Column(name = "open") public Boolean getOpen() { return this.open; } public void setOpen(Boolean open) { this.open = open; } @Column(name = "cid") public Integer getCid() { return this.cid; } public void setCid(Integer cid) { this.cid = cid; } } <file_sep>/src/main/java/com/gt/services/base/BaseServiceI.java package com.gt.services.base; import java.util.List; public interface BaseServiceI<T> { public T get(int id); public void save(T t); public List<T> query(); public void delete(int id); public void update(T t); } <file_sep>/src/main/java/com/gt/dao/base/SorderDaoI.java package com.gt.dao.base; import com.gt.model.Sorder; public interface SorderDaoI extends BaseDaoI<Sorder> { } <file_sep>/src/main/resources/public.properties filepath=G\:\\tomcat8\\webapps\\ShopSSHE\\image<file_sep>/src/main/java/com/gt/dao/Impl/UserDaoImpl.java package com.gt.dao.Impl; import org.springframework.stereotype.Repository; import com.gt.dao.base.SorderDaoI; import com.gt.dao.base.UserDaoI; import com.gt.model.Sorder; import com.gt.model.User; @Repository("userDao") public class UserDaoImpl extends BaseDaoImpl<User>implements UserDaoI { public UserDaoImpl() { super(); } @Override public User Login(User user){ String hql="from User u where u.login=:login and u.pass=:pass"; return (User)getSession().createQuery(hql) .setString("login", user.getLogin()) .setString("pass", user.getPass()) .uniqueResult(); } } <file_sep>/src/main/java/com/gt/model/User.java package com.gt.model; // Generated 2015-10-11 20:55:41 by Hibernate Tools 4.0.0 import com.alibaba.druid.pool.vendor.SybaseExceptionSorter; /** * * @ClassName: User * @Description: TODO(用户类) * @author A18ccms a18ccms_gmail_com * @date 2015年10月12日 下午2:22:07 * */ public class User implements java.io.Serializable { /** * 容器的关闭和session无关 * 当对象存储到硬盘的时候要实现序列化接口,序列化的功能就是添加了一个唯一标识的ID * 这里解释一下序列化,所谓序列化就是将内存上的类容放到硬盘上, * 反序列化就是将硬盘上的内容读到内存中,通过ID来读取 */ private static final long serialVersionUID = -4595799472692770616L; private Integer id; private String login; private String name; private String pass; private String sex; private String phone; private String email; public User() { } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getLogin() { return this.login; } public void setLogin(String login) { this.login = login; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getPass() { return this.pass; } public void setPass(String pass) { this.pass = pass; } public String getSex() { return this.sex; } public void setSex(String sex) { this.sex = sex; } public String getPhone() { return this.phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User [id=" + id + ", login=" + login + ", name=" + name + ", pass=" + <PASSWORD> + ", sex=" + sex + ", phone=" + phone + ", email=" + email + "]"; } } <file_sep>/src/main/java/com/gt/dao/Impl/CategoryDaoImpl.java package com.gt.dao.Impl; import java.util.List; import org.springframework.stereotype.Repository; import com.gt.dao.base.CategoryDaoI; import com.gt.model.Category; @Repository("categoryDao") public class CategoryDaoImpl extends BaseDaoImpl<Category>implements CategoryDaoI { public CategoryDaoImpl() { super(); } // public static void main(String[] args) { // new AccountDaoImpl(); // } @Override public List<Category> findCategoryAll(String type) { String hql = " from Category c left join fetch c.account where c.type like :type"; return getSession().createQuery(hql).setString("type", "%" + type + "%").list(); } @Override public List<Category> findCategoryAll(String type, int page, int size) { String hql = " from Category c left join fetch c.account where c.type like :type"; return getSession().createQuery(hql).setString("type", "%" + type + "%").setFirstResult((page - 1) * size) .setMaxResults(size).list(); } @Override public Long countAll(String type) { String hql = "select count(c) from Category c where c.type like :type"; return (Long)getSession().createQuery(hql).setString("type", "%" + type + "%").uniqueResult(); } @Override public List<Category> getTypeByHot(boolean hot) { String hql = "from Category c where c.hot=:hot"; return getSession().createQuery(hql).setBoolean("hot", hot).list(); } } <file_sep>/README.md # ShopSSHE 商城,后台用spring、struts2、hibernate、easyui、前台用的css、jquery、bootstrap、html5,easyui中的的demo没有删除,是用来查看的,实际项目可以删除 <file_sep>/src/main/java/com/gt/action/common/CategoryAction.java package com.gt.action.common; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.Results; import com.gt.action.base.BaseAction; import com.gt.model.Category; @ParentPackage("basePackage") @Namespace("/usershop") @Action(value = "categoryaction", results = { @Result(name = "stream", type = "stream", params = { "inputName", "inputStream" }) }) /* * namespace的命名要加上斜杠,否则会找不到路径 */ public class CategoryAction extends BaseAction<Category> { /** * request,session,application都放在baseAction中 */ private static final long serialVersionUID = 1L; public void query() { map = new HashMap<String, Object>(); Long total = categoryService.countAll(model.getType()); List<Category> list = new ArrayList<Category>(); list = categoryService.findCategoryAll(model.getType(), page, rows); map.put("total", total); map.put("rows", list); WriteJson(map); } /* * 通过stream的方式返回,这是stream的基本返回类型中的一种 * */ // public String deleteCategory(){ // categoryService.deleteCategory(ids); // inputStream = new ByteArrayInputStream("true".getBytes()); // return "stream"; // } public void saveCategory() { categoryService.save(model); map(); } public void updateCategory() { categoryService.update(model); map(); } public void deleteCategory() { categoryService.deleteCategory(ids); map(); } public void deleteCategoryArray() { categoryService.deleteCategoryArray(idArray); map(); } public void queryType() { WriteJson(categoryService.queryType()); } public void map() { map = new HashMap<String, Object>(); map.put("msg", true); WriteJson(map); } } <file_sep>/src/main/java/com/gt/services/base/UserServiceI.java package com.gt.services.base; import com.gt.model.User; public interface UserServiceI extends BaseServiceI<User> { public User Login(User user); } <file_sep>/src/main/java/com/gt/action/common/ProductAction.java package com.gt.action.common; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import com.gt.action.base.BaseAction; import com.gt.model.Product; @ParentPackage("basePackage") @Namespace("/usershop") @Action(value = "productAction", results={@Result(name="detail",location="/detail.jsp")}) /** * * @ClassName: ProductAction * @Description: TODO(用来处理商品的action) * @author gutao * @date 2015年11月10日 下午9:02:53 * */ public class ProductAction extends BaseAction<Product> { /** * */ private static final long serialVersionUID = 1L; public void query() { map = new HashMap<String, Object>(); Long total = productService.countAll(model.getName()); List<Product> list = new ArrayList<Product>(); list = productService.findProductAll(model.getName(), page, rows); for (Product product : list) { product.getCategory().setAccount(null); } map.put("total", total); map.put("rows", list); WriteJson(map); } public void updateProduct() { productService.update(model); map(); } public void deleteProduct() { productService.deleteProduct(ids); map(); } public void addproduct() throws Exception{ String pic = uploadFile.uploadFile(fileImage); model.setPic(pic); productService.save(model); System.out.println(model); map(); } public String detailProduct() { System.out.println("shoudao:"+model.getId()); request.put("productdetail", productService.get(model.getId())); return "detail"; } public void map() { map = new HashMap<String, Object>(); map.put("msg", true); WriteJson(map); } } <file_sep>/src/main/java/com/gt/action/common/AccountAction.java package com.gt.action.common; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import com.gt.action.base.BaseAction; import com.gt.model.Account; import com.opensymphony.xwork2.ActionContext; @ParentPackage("basePackage") @Namespace("/usershop") @Action(value = "accountaction",results={@Result(name="index",location="/index.jsp")}) /* * namespace的命名要加上斜杠,否则会找不到路径 * */ public class AccountAction extends BaseAction<Account>{ /** * request,session,application都放在baseAction中 */ private static final long serialVersionUID = 1L; public String query(){ // request.put("requestlist",accountService.query()); // session.put("sessionlist",accountService.query()); // application.put("applicationlist",accountService.query()); application.put("testap", "gutaoTest"); return "index"; } public void queryAccount(){ WriteJson(accountService.queryAccount()); } } <file_sep>/src/com/gt/model/Account.java package com.gt.model; // Generated 2015-9-22 20:01:58 by Hibernate Tools 4.0.0 import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.Table; /** * Account generated by hbm2java */ @Entity @Table(name = "account", catalog = "shopping") public class Account implements java.io.Serializable { private Integer id; private String login; private String name; private String pass; public Account() { } public Account(String login, String name, String pass) { this.login = login; this.name = name; this.pass = <PASSWORD>; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } @Column(name = "login", length = 20) public String getLogin() { return this.login; } public void setLogin(String login) { this.login = login; } @Column(name = "name", length = 20) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Column(name = "pass", length = 20) public String getPass() { return this.pass; } public void setPass(String pass) { this.pass = pass; } } <file_sep>/src/main/java/com/gt/dao/Impl/BusOrderDaoImpl.java package com.gt.dao.Impl; import org.springframework.stereotype.Repository; import com.gt.dao.base.BusOrderDaoI; import com.gt.model.Busorder; @Repository("busOrderDao") public class BusOrderDaoImpl extends BaseDaoImpl<Busorder>implements BusOrderDaoI { public BusOrderDaoImpl() { super(); } } <file_sep>/src/main/java/com/gt/services/Impl/CategoryServiceImpl.java package com.gt.services.Impl; import java.util.ArrayList; import java.util.List; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.gt.dao.base.CategoryDaoI; import com.gt.model.Category; import com.gt.model.Category; import com.gt.model.ComboCategory; import com.gt.model.ComboType; import com.gt.services.base.CategoryServiceI; @Service("categoryService") public class CategoryServiceImpl extends BaseServiceImpl<Category> implements CategoryServiceI{ @Autowired private CategoryDaoI categoryDao; public CategoryServiceImpl() { super(); } @Override public List<Category> findCategoryAll(String type) { return categoryDao.findCategoryAll(type); } @Override public List<Category> findCategoryAll(String type, int page, int size) { // List<Category> list = new ArrayList<Category>(); // list = categoryDao.findCategoryAll(type,page,size); // List<Category> clist = new ArrayList<Category>(); // for (Category category : list) { // Category c = new Category(); // BeanUtils.copyProperties(category, c); // c.getAccount().setPass(""); // clist.add(c); // System.out.println(c); // } // System.out.println("clist"); // for (Category category : clist) { // System.out.println("clist"); // System.out.println(category); // } return categoryDao.findCategoryAll(type,page,size); } @Override public Long countAll(String type) { Long total = categoryDao.countAll(type); return total; } @Override public void deleteCategory(String ids) { String hql = "delete Category c where c.id in ("+ids+")"; System.out.println("获得到的hql语句:"+hql); categoryDao.deleteMore(hql); } @Override public void deleteCategoryArray(List<Integer> ids) { categoryDao.deleteArray(ids); } @Override public List<ComboType> queryType() { List<Category> list = categoryDao.query(); List<ComboType> clist = new ArrayList<ComboType>(); for (Category Category : list) { ComboType type = new ComboType(); BeanUtils.copyProperties(Category, type); clist.add(type); } return clist; } @Override public List<Category> getTypeByHot(boolean hot) { List<Category> list = categoryDao.getTypeByHot(hot); return list; } } <file_sep>/src/main/java/com/gt/util/UploadFile.java package com.gt.util; import com.gt.model.FileImage; public interface UploadFile { String uploadFile(FileImage fileImage); }<file_sep>/src/main/java/com/gt/services/base/BusOrderServiceI.java package com.gt.services.base; import com.gt.model.Busorder; public interface BusOrderServiceI extends BaseServiceI<Busorder> { public double TotalCount(Busorder busorder); } <file_sep>/src/main/java/com/gt/services/base/AccountServiceI.java package com.gt.services.base; import java.util.List; import com.gt.model.Account; import com.gt.model.ComboCategory; public interface AccountServiceI extends BaseServiceI<Account> { /** * 用来类别返回combobox * @return */ public List<ComboCategory> queryAccount(); } <file_sep>/src/com/gt/model/Category.java package com.gt.model; // Generated 2015-9-22 20:01:58 by Hibernate Tools 4.0.0 import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.Table; /** * Category generated by hbm2java */ @Entity @Table(name = "category", catalog = "shopping") public class Category implements java.io.Serializable { private Integer id; private String type; private Boolean hot; private Integer aid; public Category() { } public Category(String type, Boolean hot, Integer aid) { this.type = type; this.hot = hot; this.aid = aid; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } @Column(name = "type", length = 20) public String getType() { return this.type; } public void setType(String type) { this.type = type; } @Column(name = "hot") public Boolean getHot() { return this.hot; } public void setHot(Boolean hot) { this.hot = hot; } @Column(name = "aid") public Integer getAid() { return this.aid; } public void setAid(Integer aid) { this.aid = aid; } } <file_sep>/src/main/java/com/gt/dao/base/UserDaoI.java package com.gt.dao.base; import com.gt.model.User; public interface UserDaoI extends BaseDaoI<User> { public User Login(User user); } <file_sep>/src/main/java/com/gt/services/base/SorderServiceI.java package com.gt.services.base; import com.gt.model.Busorder; import com.gt.model.Product; import com.gt.model.Sorder; public interface SorderServiceI extends BaseServiceI<Sorder> { public Sorder productToSorder(Product product); public Busorder Sorderadd(Busorder border, Product product); } <file_sep>/src/main/java/com/gt/action/common/SorderAction.java package com.gt.action.common; import java.util.HashSet; import javax.sound.midi.Synthesizer; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import com.gt.action.base.BaseAction; import com.gt.model.Busorder; import com.gt.model.Product; import com.gt.model.Sorder; @ParentPackage("basePackage") @Namespace("/usershop") @Action(value="sorderAction",results={@Result(name="shopcar",type="redirect",location="/showCar.jsp")}) public class SorderAction extends BaseAction<Sorder> { /** * */ private static final long serialVersionUID = 4010906267970601069L; public String addProduct(){ //到数据库中找到相应的商品数据 Product product = productService.get(model.getProduct().getId()); //判断session中有没有购物车 if(session.get("busOrder")==null){ System.out.println("没有购物车"); session.put("busOrder", new Busorder(new HashSet<Sorder>())); } //把商品信息转化为sorder Busorder border = (Busorder)session.get("busOrder"); Busorder busorder = sorderService.Sorderadd(border, product); //计算总价格 busorder.setTotal(busOrderService.TotalCount(busorder)); System.out.println(busorder.getSorderSet().size()); session.put("ordertotal",busorder.getSorderSet().size()); session.put("busOrder", busorder); System.out.println("添加结束"); return "shopcar"; } } <file_sep>/src/main/java/com/gt/model/Sorder.java package com.gt.model; // Generated 2015-10-11 20:55:41 by Hibernate Tools 4.0.0 /** * * @ClassName: Sorder * @Description: TODO(这里用一句话描述这个类的作用) * @author gutao * @date 2015年11月10日 下午5:08:08 * */ public class Sorder implements java.io.Serializable { /** * */ private static final long serialVersionUID = -7003708334893781345L; private Integer id; private String name; private Double price; private Integer number; private Product product; private Busorder busorder; public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Double getPrice() { return this.price; } public void setPrice(Double price) { this.price = price; } public Integer getNumber() { return this.number; } public void setNumber(Integer number) { this.number = number; } public Busorder getBusorder() { return busorder; } public void setBusorder(Busorder busorder) { this.busorder = busorder; } @Override public String toString() { return "Sorder [id=" + id + ", name=" + name + ", price=" + price + ", number=" + number + ", product=" + product + ", busorder=" + busorder + "]"; } }
6b0ee5c229d5094a37ad9a478312f8789688d061
[ "Markdown", "Java", "INI" ]
23
Java
gutaoainibei/ShopSSHE
b93b356f6ab59691da7a34e8c1ee0c4861d44434
0ead90df3d0c658d2afd9b731b4de850d0d5a41d
refs/heads/main
<file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateBooksTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('books', function (Blueprint $table) { $table->increments('book_id'); $table->string('book_name'); $table->string('book_category'); $table->string('book_writer_name')->nullable(); $table->integer('book_upload_userid'); $table->string('book_release_year')->nullable(); $table->string('book_publishers')->nullable(); $table->string('book_language'); $table->string('book_counrty')->nullable(); $table->string('book_summary')->nullable(); $table->float('book_rating')->nullable(); $table->string('book_picture')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('books'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use App\BookIHave; class Book extends Model { protected $table = 'books'; protected $primaryKey = 'book_id'; public function bookIhave() { return $this->hasMany('BookIHave', 'book_id'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; use App\UserStatus; use App\Http\Requests\RegistrationRequest; class RegistrationController extends Controller { public function index(){ return view('Registration.register'); } // user register public function register_user(RegistrationRequest $request){ $user = new User(); $user->user_name = $request->username; $user->user_password = $<PASSWORD>; $user->user_fullname = $request->user_fullname; $user->user_city = $request->city; $user->user_address = $request->address; $user->user_email = $request->email; $user->user_phone = $request->phone; $user->save(); $request->session()->flash('success_message', 'Registration Completed Successsfully'); // user available table $user = User::where('user_name', $request->username)->first(); $id = $user->user_id; $user = new UserStatus(); $user->user_id = $id; $user->user_status = 'active'; $user->save(); return redirect()->route('login'); } } <file_sep># Book Tracker Book Tracker is a laravel based web application for tracking book related activities. Technology stack: HTML, CSS, Bootstrap, PHP, Laravel, MySQL, JavaScript. <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Book; class BookIHave extends Model { public function book() { return $this->belongsTo('Book', 'book_id'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Support\Facades\DB; use Illuminate\Http\Request; use App\Book; use App\WantToReadBook; use App\AlreadyReadBook; class HomeController extends Controller { public function index(){ $userid = session('user')->user_id; $myAddedBooks = Book::where('book_upload_userid', $userid) ->orderBy('created_at', 'desc') ->get(); return view('Home.home', ['myBooks' => $myAddedBooks]); } public function addNewBook(){ return view('Home.addNewBook'); } public function showAllBook(){ $allBooks = Book::all(); return view('Book.allBooks', ['myBooks' => $allBooks]); } public function wantToReadBook(){ $userid = session('user')->user_id; $wantToReadBooks = DB::table('want_to_read_books') ->join('books', 'want_to_read_books.book_id', '=', 'books.book_id') ->where('user_id', $userid) ->get(); return view('Home.wantToRead') ->with('wantToReadBooks', $wantToReadBooks); } public function alreadyReadBook(){ $userid = session('user')->user_id; $ReadBooks = DB::table('already_read_books') ->join('books', 'already_read_books.book_id', '=', 'books.book_id') ->where('user_id', $userid) ->get(); return view('Home.readBookList') ->with('ReadBooks', $ReadBooks); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; use App\UserStatus; use App\Book; use App\Review; use Illuminate\Support\Facades\DB; use App\Http\Requests\UpdateBookRequest; class AdminController extends Controller { // show admin summary page public function showAdminHome(){ return view('Admin.index'); } // show all user public function showAllUser(){ $users = DB::table('users') ->join('user_statuses', 'user_statuses.user_id', '=', 'users.user_id') ->get(); return view('Admin.allUserList', ['users' => $users]); } // show user information public function showUserInfo($id){ $user = DB::table('users') ->join('user_statuses', 'user_statuses.user_id', '=', 'users.user_id') ->where('users.user_id', $id) ->first(); //$user = User::where('user_id', $id)->first(); return view('Admin.userInfo', ['user' => $user]); } // block user public function blockUser(Request $req){ $user = UserStatus::where('user_id', $req->user_id)->first(); //($user); if($user->user_status == 'active') { $user->user_status = 'block'; $user->save(); $req->session()->flash('success_message', 'User Blocked'); } else { $user->user_status = 'active'; $user->save(); $req->session()->flash('success_message', 'User Activated'); } return redirect()->route('showUserInfo', ['id' => $req->user_id]); } // show block user list public function blockeduserList(){ $user = DB::table('users') ->join('user_statuses', 'user_statuses.user_id', '=', 'users.user_id') ->where('user_statuses.user_status', "block") ->get(); return view('Admin.blockedUserList', ['users' => $user]); } // show all book list public function bookListAdmin(){ $book = DB::table('books') ->join('users', 'users.user_id', '=', 'books.book_upload_userid') ->get(); return view('Admin.allBooks', ['books' => $book]); } // search User public function searchUser(Request $request){ $users = DB::table('users') ->join('user_statuses', 'user_statuses.user_id', '=', 'users.user_id') ->where('user_fullname', 'LIKE' ,"%{$request->userName}%") ->get(); if(count($users) == 0) { $request->session()->flash('error_message', 'No User Found with that Name'); return redirect()->route('showUserList'); } return view('Admin.allUserList', ['users' => $users]); } // search book public function searchBookAdmin(Request $request){ $book = Book::where('book_name', 'LIKE' ,"%{$request->bookName}%") ->orWhere('book_writer_name', 'LIKE' ,"%{$request->bookName}%") ->get(); if(count($book) == 0) { $request->session()->flash('error_message', 'No Book Found with that Name'); return redirect()->route('bookListAdmin'); } return view('Admin.allBooks', ['books' => $book]); } // book details show public function showBookInfoAdmin($id){ $books = DB::table('books') ->join('users', 'books.book_upload_userid', '=', 'users.user_id') ->where('books.book_id', '=', $id) ->first(); $bookReview = DB::table('reviews') ->join('books', 'reviews.book_id', '=', 'books.book_id') ->join('users', 'reviews.user_id', '=', 'users.user_id') ->where('reviews.book_id', '=', $id) ->get(); return view('Admin.BookDetails') ->with('book', $books) ->with('bookReview', $bookReview); } public function deleteReview(Request $request){ $bookReview = Review::where('id', $request->reviewId)->first(); $bookReview->delete(); //dd($bookReview); $request->session()->flash('error_message', 'Review Deleted.'); return redirect()->route('showBookInfoAdmin', ['id' => $request->book_id]); } public function deleteBookAdmin(Request $request){ $book = Book::where('book_id', $request->book_id)->first(); $book->delete(); $request->session()->flash('success_message', 'Book Deleted Successsfully'); return redirect()->route('bookListAdmin'); } public function editBook($id){ $book = Book::where('book_id', $id)->first(); return view('Admin.AdminEditBook')->with('book', $book); } public function updateBookAdmin(UpdateBookRequest $request){ $book = Book::where('book_id', $request->book_id)->first(); // update image $image = $request->file('bookpic'); if($image) { $image = $request->file('bookpic'); $name = $book->book_id.str_slug($request->bookname).'.'.$image->getClientOriginalExtension(); $destinationPath = public_path('/UploadImage/bookImage'); $imagePath = $destinationPath. "/". $name; $image->move($destinationPath, $name); $book->book_picture = $name; //$book_updateImage->save(); } else { $book->book_picture = $book->book_picture; } $book->book_name = $request->bookname; $book->book_category = $request->category; $book->book_writer_name = $request->writername; //$book->book_upload_userid = $request->userid; $book->book_release_year = $request->releaseYear; $book->book_publishers = $request->publisher; $book->book_language = $request->language; $book->book_counrty = $request->country; $book->book_summary = $request->summary; $book->save(); $request->session()->flash('success_message', 'Book Updated Successsfully'); return redirect()->route('showBookInfoAdmin', ['id'=>$book->book_id]); } public function showSummaryPage(){ $books = Book::all(); $users = User::all(); $ActiveUser = UserStatus::where('user_status', 'active')->get(); $BlockUser = UserStatus::where('user_status', 'block')->get(); // number of book categorywise $Sciencefiction = Book::where('book_category', 'Science fiction')->get(); $Drama = Book::where('book_category', 'Drama')->get(); $ActionandAdventure = Book::where('book_category', 'Action and Adventure')->get(); $Romance = Book::where('book_category', 'Romance')->get(); $Mystery = Book::where('book_category', 'Mystery')->get(); $Horror = Book::where('book_category', 'Horror')->get(); $Guide = Book::where('book_category', 'Guide')->get(); $Health = Book::where('book_category', 'Health')->get(); $Travel = Book::where('book_category', 'Travel')->get(); $Children = Book::where('book_category', 'Children')->get(); $Religion_Spirituality_New_Age = Book::where('book_category', 'Religion, Spirituality & New Age')->get(); $Science = Book::where('book_category', 'Science')->get(); $History = Book::where('book_category', 'History')->get(); $Math = Book::where('book_category', 'Math')->get(); $Poetry = Book::where('book_category', 'Poetry')->get(); $Encyclopedias = Book::where('book_category', 'Encyclopedias')->get(); $Comics = Book::where('book_category', 'Comics')->get(); $Art = Book::where('book_category', 'Art')->get(); $Journals = Book::where('book_category', 'Journals')->get(); $Biographies = Book::where('book_category', 'Biographies')->get(); $Prayerbooks = Book::where('book_category', 'Prayer books')->get(); $Fantasy = Book::where('book_category', 'Fantasy')->get(); $totalNumberofBook = count($books); $totalNumberofUser = count($users); $numberOfActiveUser = count($ActiveUser); $numberOfBlockUser = count($BlockUser); $Sciencefiction = count($Sciencefiction); $Drama = count($Drama); $ActionandAdventure = count($ActionandAdventure); $Romance = count($Romance); $Mystery = count($Mystery); $Horror = count($Horror); $Guide = count($Guide); $Health = count($Health); $Travel = count($Travel); $Children = count($Children); $Religion_Spirituality_New_Age = count($Religion_Spirituality_New_Age); $Science = count($Science); $History = count($History); $Math = count($Math); $Poetry = count($Poetry); $Encyclopedias = count($Encyclopedias); $Comics = count($Comics); $Art = count($Art); $Journals = count($Journals); $Biographies = count($Biographies); $Prayerbooks = count($Prayerbooks); $Fantasy = count($Fantasy); $allTypeBook = array($Sciencefiction,$Drama,$ActionandAdventure,$Romance,$Mystery,$Horror,$Guide, $Health,$Travel,$Children,$Religion_Spirituality_New_Age,$Science,$History, $Math,$Poetry,$Encyclopedias,$Comics,$Art,$Journals,$Biographies,$Prayerbooks, $Fantasy); //$book = Book::where('book_id', $id)->first(); return view('Admin.summary') ->with('totalNumberofBook', $totalNumberofBook) ->with('totalNumberofUser', $totalNumberofUser) ->with('numberOfActiveUser', $numberOfActiveUser) ->with('numberOfBlockUser', $numberOfBlockUser) ->with('allBook', $allTypeBook); } // } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class WantToReadBook extends Model { // }
2f9dde7a079dabc93ad14971b1a1c63feb23f877
[ "Markdown", "PHP" ]
8
PHP
joyanbarai/book-tracker
424b2d002d95f91afb75e5745d924418da7fe5c7
5ea979fe7f1d2606dd8f09daa496a3a8a5a7b043
refs/heads/master
<repo_name>ecutler718/pingpong<file_sep>/Objects/ping_pong.cs using System; using System.Collections.Generic; namespace PingPongList { public class PingPongGenerator { private int _userInput; // private int _id; private static List<string> _items = new List<string> {}; public PingPongGenerator (int userInput) { _userInput = userInput; //put logic here for(int i = 1; i<=userInput; i++) { if (i % 15 == 0) { _items.Add("ping-pong"); } else if(i % 3 == 0) { _items.Add("ping"); } else if (i % 5 == 0) { _items.Add("pong"); } else { _items.Add(i.ToString()); } } } public int GetUserInput() { return _userInput; } public void SetUserInput(int userInput) { _userInput = userInput; } public static List<string> GetAll() { return _items; } public static void ClearAll() { _items.Clear(); } } } <file_sep>/Tests/ping_pongtest.cs using Xunit; using System; using System.Collections.Generic; using PingPongList; namespace PingPong { public class PingPongTest : IDisposable { [Fact] public void Test1ReturnAllNumbersWithPingsAndPongs() { //Arrange int number = 15; PingPongGenerator newGeneration = new PingPongGenerator(number); List<string> userList = PingPongGenerator.GetAll(); //Act List<string> testList = new List<string>{"1", "2", "ping", "4", "pong", "ping", "7", "8", "ping", "pong", "11", "ping", "13", "14", "ping-pong" }; //Assert Assert.Equal(testList, userList); } public void Dispose() { PingPongGenerator.ClearAll(); } } }
7df5e69e27ea9a173424f1944853096e4c88ff84
[ "C#" ]
2
C#
ecutler718/pingpong
73e42c11fea64b403517c9a37e6176872501118d
3971dfc90cd426bf058d8a176027eaf0d5e729b6
refs/heads/main
<file_sep>package nepu.metro.tigercard.faircalculationengine.service; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class HardCodedPeakHourServiceTest { private HardCodedPeakHourService peakHourService; static Stream<Arguments> weekdayPeakhoursboundary() { return Stream.of( Arguments.of(LocalTime.of(7, 0, 0)), Arguments.of(LocalTime.of(10, 30, 0)), Arguments.of(LocalTime.of(17, 0, 0)), Arguments.of(LocalTime.of(20, 0, 0)) ); } static Stream<Arguments> weekdayNonPeakhoursboundary() { return Stream.of( Arguments.of(LocalTime.of(0, 0, 0)), Arguments.of(LocalTime.of(6, 59, 59)), Arguments.of(LocalTime.of(10, 30, 1)), Arguments.of(LocalTime.of(16, 59, 59)), Arguments.of(LocalTime.of(20, 0, 1)), Arguments.of(LocalTime.of(23, 59, 59)) ); } static Stream<Arguments> weekenddayPeakhoursboundary() { return Stream.of( Arguments.of(LocalTime.of(9, 0, 0)), Arguments.of(LocalTime.of(11, 0, 0)), Arguments.of(LocalTime.of(18, 0, 0)), Arguments.of(LocalTime.of(22, 0, 0)) ); } static Stream<Arguments> weekenddayNonPeakhoursboundary() { return Stream.of( Arguments.of(LocalTime.of(0, 0, 0)), Arguments.of(LocalTime.of(8, 59, 59)), Arguments.of(LocalTime.of(11, 0, 1)), Arguments.of(LocalTime.of(17, 59, 59)), Arguments.of(LocalTime.of(22, 0, 1)), Arguments.of(LocalTime.of(23, 59, 59)) ); } @BeforeEach void setUp() { peakHourService = new HardCodedPeakHourService(); } @ParameterizedTest @MethodSource("weekdayPeakhoursboundary") void monday_peak_hours(LocalTime time) { LocalDateTime dateTime = LocalDateTime.of(2021, 10, 18, time.getHour(), time.getMinute(), time.getSecond()); assertTrue(peakHourService.isPeak(dateTime)); } @ParameterizedTest @MethodSource("weekdayNonPeakhoursboundary") void monday_non_peak_hours(LocalTime time) { LocalDateTime dateTime = LocalDateTime.of(2021, 10, 18, time.getHour(), time.getMinute(), time.getSecond()); assertFalse(peakHourService.isPeak(dateTime)); } @ParameterizedTest @MethodSource("weekdayPeakhoursboundary") void tuesday_peak_hours(LocalTime time) { LocalDateTime dateTime = LocalDateTime.of(2021, 10, 19, time.getHour(), time.getMinute(), time.getSecond()); assertTrue(peakHourService.isPeak(dateTime)); } @ParameterizedTest @MethodSource("weekdayNonPeakhoursboundary") void tuesday_non_peak_hours(LocalTime time) { LocalDateTime dateTime = LocalDateTime.of(2021, 10, 19, time.getHour(), time.getMinute(), time.getSecond()); assertFalse(peakHourService.isPeak(dateTime)); } @ParameterizedTest @MethodSource("weekdayPeakhoursboundary") void wednesday_peak_hours(LocalTime time) { LocalDateTime dateTime = LocalDateTime.of(2021, 10, 20, time.getHour(), time.getMinute(), time.getSecond()); assertTrue(peakHourService.isPeak(dateTime)); } @ParameterizedTest @MethodSource("weekdayNonPeakhoursboundary") void wednesday_non_peak_hours(LocalTime time) { LocalDateTime dateTime = LocalDateTime.of(2021, 10, 20, time.getHour(), time.getMinute(), time.getSecond()); assertFalse(peakHourService.isPeak(dateTime)); } @ParameterizedTest @MethodSource("weekdayPeakhoursboundary") void thursday_peak_hours(LocalTime time) { LocalDateTime dateTime = LocalDateTime.of(2021, 10, 21, time.getHour(), time.getMinute(), time.getSecond()); assertTrue(peakHourService.isPeak(dateTime)); } @ParameterizedTest @MethodSource("weekdayNonPeakhoursboundary") void thursday_non_peak_hours(LocalTime time) { LocalDateTime dateTime = LocalDateTime.of(2021, 10, 21, time.getHour(), time.getMinute(), time.getSecond()); assertFalse(peakHourService.isPeak(dateTime)); } @ParameterizedTest @MethodSource("weekdayPeakhoursboundary") void friday_peak_hours(LocalTime time) { LocalDateTime dateTime = LocalDateTime.of(2021, 10, 22, time.getHour(), time.getMinute(), time.getSecond()); assertTrue(peakHourService.isPeak(dateTime)); } @ParameterizedTest @MethodSource("weekdayNonPeakhoursboundary") void friday_non_peak_hours(LocalTime time) { LocalDateTime dateTime = LocalDateTime.of(2021, 10, 22, time.getHour(), time.getMinute(), time.getSecond()); assertFalse(peakHourService.isPeak(dateTime)); } @ParameterizedTest @MethodSource("weekenddayPeakhoursboundary") void saturday_peak_hours(LocalTime time) { LocalDateTime dateTime = LocalDateTime.of(2021, 10, 23, time.getHour(), time.getMinute(), time.getSecond()); assertTrue(peakHourService.isPeak(dateTime)); } @ParameterizedTest @MethodSource("weekenddayNonPeakhoursboundary") void saturday_non_peak_hours(LocalTime time) { LocalDateTime dateTime = LocalDateTime.of(2021, 10, 23, time.getHour(), time.getMinute(), time.getSecond()); assertFalse(peakHourService.isPeak(dateTime)); } @ParameterizedTest @MethodSource("weekenddayPeakhoursboundary") void sunday_peak_hours(LocalTime time) { LocalDateTime dateTime = LocalDateTime.of(2021, 10, 24, time.getHour(), time.getMinute(), time.getSecond()); assertTrue(peakHourService.isPeak(dateTime)); } @ParameterizedTest @MethodSource("weekenddayNonPeakhoursboundary") void sunday_non_peak_hours(LocalTime time) { LocalDateTime dateTime = LocalDateTime.of(2021, 10, 24, time.getHour(), time.getMinute(), time.getSecond()); assertFalse(peakHourService.isPeak(dateTime)); } }<file_sep>package nepu.metro.tigercard.faircalculationengine.model; import java.time.DayOfWeek; import java.time.LocalTime; public record PeakHour(DayOfWeek dayOfWeek, LocalTime startTime, LocalTime endTime) { } <file_sep>package nepu.metro.tigercard.faircalculationengine.model; public record Stations(Zone startStationZone, Zone endStationZone) { } <file_sep>package nepu.metro.tigercard.faircalculationengine; import nepu.metro.tigercard.faircalculationengine.model.Journey; import nepu.metro.tigercard.faircalculationengine.model.Stations; import nepu.metro.tigercard.faircalculationengine.model.Zone; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; public class FairCalculationEngineTest { private FairCalculationEngine engine; @BeforeEach void reset_before_each_test() { engine = new FairCalculationEngine(); } //data populators private void addJourney(List<Journey> journeys, LocalDateTime dateTime, Zone start, Zone end) { LocalDateTime day_8_AM = LocalDateTime.of(dateTime.getYear(), dateTime.getMonth(), dateTime.getDayOfMonth(), dateTime.getHour(), dateTime.getMinute(), dateTime.getSecond()); journeys.add(new Journey(day_8_AM, new Stations(start, end))); } private void addJourneySingleZone(List<Journey> journeys, LocalDateTime dateTime, Zone zone) { addJourney(journeys, dateTime, zone, zone); } private void addJourneyZone1(List<Journey> journeys, LocalDateTime dateTime) { addJourneySingleZone(journeys, dateTime, Zone.Z1()); } private void addJourneyZone2(List<Journey> journeys, LocalDateTime dateTime) { addJourneySingleZone(journeys, dateTime, Zone.Z2()); } private LocalDate getWeekDay(int offsetDay) { return LocalDate.of(2021, 10, 4 + offsetDay); } private LocalTime getDayTime(int hourOffset) { return LocalTime.of(hourOffset, 0, 0); } private void addPeakJourney_Zone1(List<Journey> journeys, int offsetHour) { LocalDate monday = getWeekDay(0); LocalTime peak = getDayTime(offsetHour); addJourneyZone1(journeys, LocalDateTime.of(monday.getYear(), monday.getMonth(), monday.getDayOfMonth(), peak.getHour(), peak.getMinute(), peak.getSecond())); } private void addPeakJourney_Zone2(List<Journey> journeys, int offsetHour) { LocalDate monday = getWeekDay(0); LocalTime peak = getDayTime(offsetHour); addJourneyZone2(journeys, LocalDateTime.of(monday.getYear(), monday.getMonth(), monday.getDayOfMonth(), peak.getHour(), peak.getMinute(), peak.getSecond())); } private void addPeakJourney_Zone1_Zone2(List<Journey> journeys, int offsetDay, int offsetHour) { LocalDate monday = getWeekDay(offsetDay); LocalTime peak = getDayTime(offsetHour); addJourney(journeys, LocalDateTime.of(monday.getYear(), monday.getMonth(), monday.getDayOfMonth(), peak.getHour(), peak.getMinute(), peak.getSecond()), Zone.Z1(), Zone.Z2()); } private void populateHourly_Zone1(List<Journey> journeys, int hoursCount) { for (int hoursInstance = 0; hoursInstance < hoursCount; hoursInstance++) { addPeakJourney_Zone1(journeys, 7 + hoursInstance); } } private void populateHourly_Zone2(List<Journey> journeys) { for (int hoursInstance = 0; hoursInstance < 4; hoursInstance++) { addPeakJourney_Zone2(journeys, 7 + hoursInstance); } } private void populateHourly(List<Journey> journeys, int offsetDay, int hoursCount) { for (int hoursInstance = 0; hoursInstance < hoursCount; hoursInstance++) { addPeakJourney_Zone1_Zone2(journeys, offsetDay, 7 + hoursInstance); } } private void populateWeeklyWithCap(List<Journey> journeys, int weeks) { for (int day = 0; day < 7 * weeks; day++) { populateHourly(journeys, day, 5); } } @Test public void no_journeys_no_fair() { List<Journey> journeys = new ArrayList<>(); BigDecimal totalfair = engine.calculate(journeys); assertEquals(BigDecimal.ZERO, totalfair); } @Test public void z1_z1_peak_30_single() { List<Journey> journeys = new ArrayList<>(); populateHourly_Zone1(journeys, 1); BigDecimal totalfair = engine.calculate(journeys); assertEquals(new BigDecimal("30"), totalfair); } @Test public void multiple_journey_without_capping() { List<Journey> journeys = new ArrayList<>(); populateHourly_Zone1(journeys, 3); BigDecimal totalfair = engine.calculate(journeys); assertEquals(new BigDecimal("90"), totalfair); } @Test public void multiple_journey_with_daily_capping_single_zone_1() { List<Journey> journeys = new ArrayList<>(); populateHourly_Zone1(journeys, 4); BigDecimal totalfair = engine.calculate(journeys); assertEquals(new BigDecimal("100"), totalfair); } @Test public void multiple_journey_with_daily_capping_single_zone_2() { List<Journey> journeys = new ArrayList<>(); populateHourly_Zone2(journeys); BigDecimal totalfair = engine.calculate(journeys); assertEquals(new BigDecimal("80"), totalfair); } @Test public void multiple_journey_with_daily_capping_multiple_zone() { List<Journey> journeys = new ArrayList<>(); populateHourly(journeys, 0, 4); BigDecimal totalfair = engine.calculate(journeys); assertEquals(new BigDecimal("120"), totalfair); } @Test public void multiple_journey_with_weekly_capping_multiple_zones() { List<Journey> journeys = new ArrayList<>(); populateWeeklyWithCap(journeys, 1); BigDecimal totalfair = engine.calculate(journeys); assertEquals(new BigDecimal("600"), totalfair); } @Test public void multiple_journey_with_weekly_capping_multiple_zone_2_multiweeks() { List<Journey> journeys = new ArrayList<>(); populateWeeklyWithCap(journeys, 2); BigDecimal totalfair = engine.calculate(journeys); assertEquals(new BigDecimal("1200"), totalfair); } @Test public void weekly_capping_multiple_zone_2_multiweeks_with_incomplete_week() { List<Journey> journeys = new ArrayList<>(); //Two weeks capped populateWeeklyWithCap(journeys, 2); // one day capped populateHourly(journeys, 21, 5); BigDecimal totalfair = engine.calculate(journeys); assertEquals(new BigDecimal("1320"), totalfair); } } <file_sep>package nepu.metro.tigercard.faircalculationengine.model; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.time.LocalDateTime; import static org.junit.jupiter.api.Assertions.assertEquals; class PeakHourTest { @Test @DisplayName("Field test for PeakHour record") public void peakhour_should_have_dayOfWeek_startTime_endTime() throws InterruptedException { LocalDateTime dateTime = LocalDateTime.now(); PeakHour peakHour = new PeakHour(dateTime.getDayOfWeek(), dateTime.toLocalTime(), dateTime.toLocalTime()); assertEquals(dateTime.getDayOfWeek(), peakHour.dayOfWeek()); assertEquals(dateTime.toLocalTime(), peakHour.startTime()); assertEquals(dateTime.toLocalTime(), peakHour.endTime()); } }<file_sep>package nepu.metro.tigercard.faircalculationengine.model; import java.time.LocalDate; import java.time.LocalDateTime; public record Journey(LocalDateTime dateTime, Stations stations) { /* Gets the date of journey, ignoring time units */ public LocalDate getDate() { return this.dateTime.toLocalDate(); } } <file_sep>package nepu.metro.tigercard.faircalculationengine.model; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; class ZonalFairTest { @Test @DisplayName("Fields test for ZonalFair") public void zonalFair_should_have_stations_and_isPeak() { Stations stations = new Stations(Zone.Z1(), Zone.Z1()); ZonalFair zonalFair = new ZonalFair(stations, false); assertEquals(stations, zonalFair.zones()); assertFalse(zonalFair.isPeak()); } }<file_sep>package nepu.metro.tigercard.faircalculationengine.service; import nepu.metro.tigercard.faircalculationengine.model.Zone; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.math.BigDecimal; import static org.junit.jupiter.api.Assertions.assertEquals; class HardCodedJourneyFairCalculatorServiceTest { private HardCodedJourneyFairCalculatorService journeyFairCalculatorService; @BeforeEach void setUp() { journeyFairCalculatorService = new HardCodedJourneyFairCalculatorService(); } @Test @DisplayName("Peak hour journey fair for z1->z1") void z1_z1_peak_30() { assertEquals(new BigDecimal("30"), journeyFairCalculatorService.getFair(Zone.Z1(), Zone.Z1(), true)); } @Test @DisplayName("Non Peak hour journey fair for z1->z1") void z1_z1_offpeak_25() { assertEquals(new BigDecimal("25"), journeyFairCalculatorService.getFair(Zone.Z1(), Zone.Z1(), false)); } @Test @DisplayName("Peak hour journey fair for z1->z2") void z1_z2_peak_35() { assertEquals(new BigDecimal("35"), journeyFairCalculatorService.getFair(Zone.Z1(), Zone.Z2(), true)); } @Test @DisplayName("Non Peak hour journey fair for z1->z2") void z1_z2_offpeak_30() { assertEquals(new BigDecimal("30"), journeyFairCalculatorService.getFair(Zone.Z1(), Zone.Z2(), false)); } @Test @DisplayName("Peak hour journey fair for z2->z1") void z2_z1_peak_35() { assertEquals(new BigDecimal("35"), journeyFairCalculatorService.getFair(Zone.Z2(), Zone.Z1(), true)); } @Test @DisplayName("Non Peak hour journey fair for z2->z1") void z2_z1_offpeak_30() { assertEquals(new BigDecimal("30"), journeyFairCalculatorService.getFair(Zone.Z2(), Zone.Z1(), false)); } @Test @DisplayName("Peak hour journey fair for z2->z2") void z2_z2_peak_25() { assertEquals(new BigDecimal("25"), journeyFairCalculatorService.getFair(Zone.Z2(), Zone.Z2(), true)); } @Test @DisplayName("NonPeak hour journey fair for z2->z2") void z2_z2_offpeak_20() { assertEquals(new BigDecimal("20"), journeyFairCalculatorService.getFair(Zone.Z2(), Zone.Z2(), false)); } }<file_sep>package nepu.metro.tigercard.faircalculationengine.model; public record Zone(String name, int normalizedDistanceFromCenter) { public static Zone Z1() { return new Zone("Zone 1", 0); } public static Zone Z2() { return new Zone("Zone 2", 1); } } <file_sep>package nepu.metro.tigercard.faircalculationengine.service; import nepu.metro.tigercard.faircalculationengine.model.Journey; import java.math.BigDecimal; import java.util.List; public interface CappingLimitService { BigDecimal getCapAmount(List<Journey> journeys, HardCodedCappingLimitService.LimitMode weekly); } <file_sep>package nepu.metro.tigercard.faircalculationengine.model; public record ZonalFair(Stations zones, boolean isPeak) { } <file_sep>package nepu.metro.tigercard.faircalculationengine.model; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class ZoneTest { @Test @DisplayName("Fields test for Zone") public void zone_should_have_name_distanceFromCenter() { Zone zone = new Zone("name", 5); assertEquals("name", zone.name()); assertEquals(5, zone.normalizedDistanceFromCenter()); } }<file_sep># TigerCard This project is being developed as Fare Calculation Engine for TigerCard. ## Technologies * Java 17- Since it is the latest LTS version at the time of development. * Maven 3.8.3 - Since it is the latest and recommended version at the time of development * Junit 5.8.1 - Since it is the latest version available at the time of development ## Methodology Test driven development, since it is more agile and helps keep the code cleaner and more organized. ## Requirements 1. The system should accept a list of journeys and return the fair applicable 1. The journey would contain the following fields 1. date-time 2. from-zone 3. to-zone 2. The zone would contain the following fields 1. name 2. normalized distance from center 2. Zones are concentric rings, with Zone 1 being at the center of the city, Zone 2 is the outer ring for Zone 1 3. Peak hour calculation will be based on Day of the week and hour slots as mentioned below 1. Monday to Friday (Both included) 1. 07:00 - 10:30 (Both included) 2. 17:00 - 20:00 (Both included) 2. Saturday - Sunday (Both included) 1. 09:00 - 11:00 (Both included) 2. 18:00 - 22:00 (Both included) 4. Any timings not included above are considered as non-peak hours 1. The fairs will be calculated as below | Start Zone | End Zone | Peak hours | Non Peak hours | |------------|----------|------------|----------------| | Z1 | Z1 | 30 | 25 | | Z1 | Z2 | 35 | 30 | | Z2 | Z1 | 35 | 30 | | Z2 | Z2 | 25 | 20 | 5. Fair Capping : There will be two types of fair capping applicable 1. Types of capping 1. Daily fair cap 2. Weekly fair cap 2. The applicable capping will be applied from the farthest journey 3. Below are the capping limits | Farthest Zones | Daily Cap | Weekly Cap | |---|---|---| | Zone 1 <-> Zone 1 | 100 | 500 | | Zone 1 <-> Zone 2 | 120 | 600 | | Zone 2 <-> Zone 2 | 80 | 400 | ## Assumptions 1. The mentioned timings for peak hours include both start and end times 2. The time for calculation is taken to nearest second 3. Start of the week is taken as the day of first journey, (and not a fixed day e.g. sunday or monday) 4. Weeks and Day's calculation is done on clock day (00:00-24:00) irrespective of start time of the first journey 5. Server LocalDate represents ## Possible improvements 1. The data should not be hardcoded 1. This includes tests as well, in production system, the service should fetch the data from external source and the tests should mock the database 2. The code could have been more flexible 3. Capping limit is done based upon highest applicable cap, instead of farthest journey. e.g. a farthest journey could be between Z2 and Z2 (due to concentricity of zones), but because of highest fairs being between zone changes, z1-z2 cap will be applied ## Test cases 1. Single Journey should return correct fair 2. Multiple journeys in a Day without being capped should return correct fair 3. Multiple journeys in a day on capped should return capped fair 4. Weekly journeys without being capped should return correct results 5. Weekly journeys after being capped should return correct results
1d2d5993af9a72a07faba2f6ec3d14e0985f2e35
[ "Markdown", "Java" ]
13
Java
mohitkanwar/sahaj-tigercard
9423f30d59d259d1cb70c6e85252331fb8c60b77
b40a484f565c13dde69b940e8e854da78d86235a
refs/heads/main
<repo_name>AnnaKhanina/fenya<file_sep>/frontend/src/components/App/App.jsx import { Route, Routes } from "react-router-dom"; import Header from "../Header/Header"; import Footer from "../Footer/Footer"; import HomeScreen from "../../screens/HomeScreen/HomeScreen"; import ProductScreen from "../../screens/ProductScreen/ProductScreen"; import SizeScreen from "../../screens/SizeScreen/SizeScreen"; import PaymentDeliveryScreen from "../../screens/PaymentDeliveryScreen/PaymentDeliveryScreen" import ContactsScreen from "../../screens/ContactsScreen/ContactsScreen"; import CartScreen from "../../screens/CartScreen/CartScreen"; import FavoriteScreen from "../../screens/FavoriteScreen/FavoriteScreen"; import ProfileScreen from "../../screens/ProfileScreen/ProfileScreen"; import NotFoundScreen from "../../screens/NotFoundScreen/NotFoundScreen"; import AboutUsScreen from "../../screens/AboutUsScreen/AboutUsScreen"; import CooperationScreen from "../../screens/CooperationScreen/CooperationScreen"; import SocialScreen from "../../screens/SocialScreen/SocialScreen"; import BlogScreen from "../../screens/BlogScreen/BlogScreen"; const App = () => { return ( <> <Header /> <Routes> <Route path="/" element={<HomeScreen />} /> <Route path="/products" element={<ProductScreen />} /> <Route path="/size" element={<SizeScreen />} /> <Route path="/payment_delivery" element={<PaymentDeliveryScreen />} /> <Route path="/contacts" element={<ContactsScreen />} /> <Route path="/favorite" element={<FavoriteScreen />} /> <Route path="/cart" element={<CartScreen />} /> <Route path="/profile" element={<ProfileScreen />} /> <Route path="/about" element={<AboutUsScreen />} /> <Route path="/сooperation" element={<CooperationScreen />} /> <Route path="/social" element={<SocialScreen />} /> <Route path="/blog" element={<BlogScreen />} /> <Route path="*" element={<NotFoundScreen />} /> </Routes> <Footer /> </> ); }; export default App; <file_sep>/backend/data/products.js const products = [{ name: "PlayStation 5", imageUrl: "https://images.unsplash.com/photo-1606813907291-d86efa9b94db?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1352&q=80", description: "PlayStation 5 (PS5) is a home video game console developed by Sony Interactive Entertainment. Announced in 2019 as the successor to the PlayStation 4, the PS5 was released on November 12, 2020 in Australia, Japan, New Zealand, North America, Singapore, and South Korea, and November 19, 2020 onwards in other major markets except China and India.", price: 499, countInStock: 15, } ]; module.exports = products;<file_sep>/frontend/src/components/Header/Header.jsx import { Link } from "react-router-dom"; import React, { useState } from "react"; import { IconContext } from "react-icons"; import * as FaIcons from "react-icons/fa"; import * as AiIcons from "react-icons/ai"; //import logo from '../../images/logoFenya.png'; import "../Header/Header.css"; import "../../components/Container/Container.css"; import { SidebarData } from "../SliderbarData/SliderbarData"; const Header = () => { const [sidebar, setSidebar] = useState(false); const showSidebar = () => setSidebar(!sidebar); return ( <header> <IconContext.Provider value={{ color: "#FFF" }}> <div className="navbar"> <div className="navbar-logo"> <Link to="/" end className="logo-links"> <h2 className="logo-title">Fenya</h2> </Link> {/* <Link to="/" end> <img src={logo} alt="Logo" /> </Link> */} </div> <ul className="navbar-list"> <li className="navbar-list-item"> <Link to="/products" className="navbar-links">Товари</Link> </li> <li className="navbar-list-item"> <Link to="/size" className="navbar-links">Розмірна сітка</Link> </li> <li className="navbar-list-item"> <Link to="/payment_delivery" className="navbar-links">Оплата і доставка</Link> </li> <li className="navbar-list-item"> <Link to="/contacts" className="navbar-links">Контакти</Link> </li> </ul> <span className="search"> <FaIcons.FaSearch /> </span> <ul className="icons-list"> <li className="icons-list-item"> <Link to="/profile" className="icons-links"><FaIcons.FaUser/></Link> </li> <li className="icons-list-item"> <Link to="/favorite" className="icons-links"><FaIcons.FaHeart /></Link> </li> <li className="icons-list-item"> {/*<Link to="/cart" className="icons-links"><FaIcons.FaCartPlus /><span className="cart-logo-badge">0</span></Link> */} <Link to="/cart" className="icons-links"><FaIcons.FaCartPlus /></Link> </li> </ul> <div className="navbar-mob"> <Link to="#" className="menu-bars"> <FaIcons.FaBars onClick={showSidebar} /> </Link> </div> <nav className={sidebar ? "nav-menu active" : "nav-menu"}> <ul className="nav-menu-items" onClick={showSidebar}> <li className="navbar-toggle"> <Link to="#" className="menu-bars"> <AiIcons.AiOutlineClose /> </Link> </li> {SidebarData.map((item, index) => { return ( <li key={index} className={item.cName}> <Link to={item.path}> {item.icon} <span>{item.title}</span> </Link> </li> ); })} </ul> </nav> </div> </IconContext.Provider> </header> ) }; export default Header;<file_sep>/frontend/src/screens/AboutUsScreen/AboutUsScreen.jsx import "../AboutUsScreen/AboutUsScreen.css"; import "../../components/Container/Container.css"; import "../MainScreen/MainScreen.css"; const AboutUsScreen = () => { return ( <main className="main-screen"> <div className="container"> <h2 className="screen-title">Про нас</h2> <p className="screen-text"> Lorem, ipsum dolor sit amet consectetur adipisicing elit. Iusto, laboriosam placeat incidunt rem illum animi nemo quibusdam quia voluptatum voluptate. </p> </div> </main> ); }; export default AboutUsScreen;<file_sep>/frontend/src/screens/CartScreen/CartScreen.jsx import "../CartScreen/CartScreen.css"; import "../../components/Container/Container.css"; import "../MainScreen/MainScreen.css"; import CartItem from "../../components/CartItem/CartItem"; import { IconContext } from "react-icons"; // import * as FaIcons from "react-icons/fa"; const CartScreen = () => { return ( <main className="main-screen"> <IconContext.Provider value={{ color: "#FFF" }}> <div className="container"> <h2 className="screen-title">Кошик</h2> <div className="cartscreen"> <ul className="cartscreen-list"> <li className="cartscreen-list-item"> <CartItem/> </li> <li className="cartscreen-list-item"> <div className="cartscreen-info"> <p className="cartscreen-name">Кількість (0)</p> <p className="cartscreen-name">259грн</p> <button className="cartscreen-button">замовити</button> </div> </li> </ul> </div> </div> </IconContext.Provider> </main> ); }; export default CartScreen;<file_sep>/frontend/src/components/Backdrop/Backdrop.jsx // import { BackdropWrapper } from "../Backdrop/Backdrop.styled"; // const Backdrop = ({show, click}) => { // return show && <BackdropWrapper onClick={click}></BackdropWrapper> // }; // export default Backdrop;<file_sep>/frontend/src/components/CartItem/CartItem.jsx import { Link } from "react-router-dom"; import { IconContext } from "react-icons"; import * as FaIcons from "react-icons/fa"; import "../CartItem/CartItem.css"; const CartItem = () => { return ( <div className="cartitem"> <IconContext.Provider value={{ color: "#fff" }}> <img className="cartitem-image img" src="https://scx1.b-cdn.net/csz/news/800a/2021/cat-1.jpg" alt ="жіноча білизна"/> <Link to={`/product/${111}`} className="cartitem-name"> <p>Трусики жіночі Anna</p> </Link> <p className="cartitem-price">259грн</p> <select className="cartitem-select"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> <button className="cartitem-deleteBtn"> <span className="cartitem-icon"><FaIcons.FaTrash /></span> </button> </IconContext.Provider> </div> ); }; export default CartItem;<file_sep>/frontend/src/components/SliderbarData/SliderbarData.js import React from "react"; import * as FaIcons from "react-icons/fa"; import * as AiIcons from "react-icons/ai"; import * as BsIcons from "react-icons/bs"; import * as TbIcons from "react-icons/tb"; export const SidebarData = [ { title: "Home", path: "/", icon: <AiIcons.AiFillHome />, cName: "nav-text" }, { title: "Profile", path: "/profile", icon: <FaIcons.FaUser />, cName: "nav-text" }, { title: "Favorite", path: "/favorite", icon: <FaIcons.FaHeart />, cName: "nav-text" }, { title: "Cart", path: "/cart", icon: <FaIcons.FaCartPlus />, cName: "nav-text" }, { title: "Products", path: "/products", icon: <FaIcons.FaRegListAlt />, cName: "nav-text" }, { title: "Size", path: "/size", icon: <BsIcons.BsFillFileEarmarkSpreadsheetFill />, cName: "nav-text" }, { title: "PaymentDelivery", path: "/payment_delivery", icon: <TbIcons.TbTruckDelivery />, cName: "nav-text" }, { title: "Contacts", path: "/contacts", icon: <AiIcons.AiOutlineContacts />, cName: "nav-text" } ];<file_sep>/frontend/src/components/SideDrawer/SideDrawer.jsx // import { SideDrawerWrapper, SideDrawerList, SideDrawerItem } from "../SideDrawer/SideDrawer.styled"; // import { Link } from "react-router-dom"; // import { HiOutlineShoppingCart } from "react-icons/hi"; // import { CartLogoBadge } from "../Header/Header.styled"; // //import { useSelector } from "react-redux"; // const SideDrawer = ({show, click}) => { // //const sideDrawerClass = ["sidedrawer"]; // const SideDrawerClass = [SideDrawerWrapper]; // // const cart = useSelector((state) => state.cart); // // const { cartItems } = cart; // // const getCartCount = () => { // // return cartItems.reduce((qty, item) => Number(item.qty) + qty, 0); // // }; // if(show) { // SideDrawerClass.push("show"); // } // return ( // <> // {SideDrawerClass.join(" ")} // <SideDrawerList onClick={click}> // <SideDrawerItem> // <Link to="/cart"> // <HiOutlineShoppingCart /><span><CartLogoBadge>0</CartLogoBadge></span> // </Link> // </SideDrawerItem> // <SideDrawerItem> // <Link to="/">Головна // </Link> // </SideDrawerItem> // </SideDrawerList> // </> // ) // }; // export default SideDrawer;<file_sep>/frontend/src/index.js import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { BrowserRouter } from "react-router-dom"; import "modern-normalize"; import App from './components/App/App'; import { Provider } from "react-redux"; import store from "./redux/store"; const rootElement = document.getElementById("root"); const root = createRoot(rootElement); root.render( <Provider store={store} > <StrictMode> <BrowserRouter> <App /> </BrowserRouter> </StrictMode> </Provider> ); // import React from "react"; // import ReactDOM from "react-dom"; // import "./index.css"; // import App from "../src/components/App/App"; // import reportWebVitals from "./reportWebVitals"; // import { Provider } from "react-redux"; // import store from "./redux/store"; // ReactDOM.render( // <Provider store={store}> // <React.StrictMode> // <App /> // </React.StrictMode> // </Provider>, // document.getElementById("root") // ); // reportWebVitals(); <file_sep>/backend/server.js // require("dotenv").config(); // const express = require("express"); // const productRoutes = require("./routes/productRoutes"); // const connectDB = require("./config/db"); // connectDB(); // const app = express(); // app.use(express.json()); // app.get("/", (req, res) => { // res.json({ message: "API running..." }); // }); // app.use("api/products", productRoutes); // const PORT = process.env.PORT || 3000; // app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); const app = require('./app'); const PORT = process.env.PORT || 3000; require('dotenv').config(); const { mongoDbConnect } = require('./config/db'); const runConnection = async () => { try { await mongoDbConnect(); app.listen(PORT, () => { console.log(`Server running. Use our API on port: ${PORT}`); }); } catch (error) { console.log(error); } }; runConnection();<file_sep>/backend/app.js const express = require("express"); const logger = require("morgan"); const cors = require("cors"); // const { errorHandler } = require("./helpers/index"); const { createProxyMiddleware } = require('http-proxy-middleware'); const productRoutes = require("./routes/productRoutes"); const app = express(); const formatsLogger = app.get("env") === "development" ? "dev" : "short"; app.use(logger(formatsLogger)); app.use(cors()); app.use(express.json()); app.get("/", function (req, res) { res.send("DataBase of FenyaDB"); }); const testProxy = createProxyMiddleware ({ target: 'http://localhost:3000/', changeOrigin: true, }); app.use('/api', testProxy); app.listen(3000); app.use("api/products", productRoutes); app.use((req, res) => { res.status(404).json({ message: "Not found" }); }); // app.use(errorHandler); module.exports = app;
2a85c34731976b228d2bc7058060bc87a06ce56d
[ "JavaScript" ]
12
JavaScript
AnnaKhanina/fenya
ab658ce391c73c218b66e0eb28973ef35e2a98dd
ed6a31d408a6ef2caaf94469adf9287d49fef4ae
refs/heads/master
<repo_name>michaelPysmenytskyi/home_work<file_sep>/home_work1.js // 1) Оголосіть три різні змінні за допомогою "let", "const", "var" let first const second var third // 2) Оголосіть одну змінну якій можна міняти значення і одну змінну якій не можна міняти значення let changable const unchgable // 3) Напишіть 1 коментар в 1 рядок і напишіть ще один коментар на 4 рядки // 1 коментар в 1 рядок /*Коментар на 4 рядки*/ // 4) Оголосіть одну змінну і прийсвойте в неї будь яке значення типу String. // * Bиведіть в консоль тип змінної виклристовуючи оператор "typeof" і функцію "console.log()" let random = 'random' console.log(typeof random) // 5) Оголосіть одну змінну і прийсвойте в неї будь яке значення типу Number. // * Bиведіть в консоль тип змінної виклристовуючи оператор "typeof" і функцію "console.log()" let random2 = 123 console.log(typeof random2) // 6) Оголосіть одну змінну і прийсвойте в неї будь яке значення типу Boolean. // * Bиведіть в консоль тип змінної виклристовуючи оператор "typeof" і функцію "console.log()" let random3 = true console.log(typeof random3) // 7) Оголосіть одну змінну і прийсвойте в неї будь яке значення типу Object яке буде містити хоча б 3 ключі. // * Bиведіть в консоль тип змінної виклристовуючи оператор "typeof" і функцію "console.log()" let random4 = { key1: false, key2: null, key3: true } console.log(typeof random4) // 8) Оголосіть одну змінну і прийсвойте в неї будь яке значення типу Array яке буде містити хоча б 3 значення. // * Bиведіть в консоль тип змінної виклристовуючи оператор "typeof" і функцію "console.log()" let random5 = [1,2,3] console.log(typeof random5) // 9) Оголосіть одну змінну і прийсвойте в неї будь яке значення типу Function. // * Bиведіть в консоль тип змінної виклристовуючи оператор "typeof" і функцію "console.log()" let random6 = () =>{} console.log(typeof random6) // 10) Оголосіть одну змінну і прийсвойте в неї будь яке значення типу Undefined. // * Bиведіть в консоль тип змінної виклристовуючи оператор "typeof" і функцію "console.log()" let random7 console.log(typeof random7) // 11) Оголосіть одну змінну і прийсвойте в неї будь яке значення типу Null. // * Bиведіть в консоль тип змінної виклристовуючи оператор "typeof" і функцію "console.log()" let random8 = null console.log(typeof random8) // 12) Оголосіть змінну user типу Object і опишіть своє: ім'я, фамілію, дату народження, // місце проживання, стать і можете добавити ще додаткові параметри використовуючи різні типи даних. let user = { firstName: 'Michael', lastName: 'Pysmenytskyi', dateOfBirth: new Date(1991, 6, 25), adress: 'Uzhorod city, Zankoveckoi st, 77/26', sex: 'male', politicalViews: undefined } <file_sep>/test_2.js // 1. Створіть обєкт та масив // * Використовуйте обєкт і масив створені в першому заданні у всіх наступних завданнях let testArr = [] let testObj = {} // 2. Додайте до обєкту ключ "birthdate" типу Date testObj.birthdate = new Date('1991-06-25') // 3. Додайте новий елемент в кінець масиву testArr.push('новий елемент') // 4. Видаліть з обєкту доданий ключ у завданні 3 delete testObj.birthdate // 5. Видаліть елемент з масиву доданий у завданні 4 testArr.pop() // 6. Додайте до обєкту метод який буде виводити ваше імя і прізвище. testObj.myName = function(){ console.log('<NAME>') } // 7. Створіть конструктор який буде відтворювати функціонал який є наявний в обєкті class MyName{ constructor() { this.birthdate = new Date('1991-06-25') } myName = function(){ console.log('<NAME>') } } let test1 = new MyName() test1.myName() // 8. Створіть новий конструктор який буде унаслідувати функціонал конструктору з попереднього звдання і буде мати додатковий метод для виводу дати народження. class Child extends MyName{ dateOfBirth = function () { console.log(this.birthdate) } } // 9. Створіть новий eлемент за допомогою конструктору з попереднього завдання і виведіть імя та прізвище або дату народження. let test2 = new Child() test2.dateOfBirth() test2.myName()<file_sep>/home_work7.js // 1. Створіть функцію за допомогою "function expression". let testObj = { arg1: 6, arg2: 3 } const getSum = function(obj, cb) { return obj.arg1 + obj.arg2; }; getSum(testObj) // 2. Створіть функцію за допомогою "new Function". const multiply = new Function('obj', 'cb', 'return obj.arg1 * obj.arg2') multiply(testObj) // 3. Створіть функцію за допомогою "arrow function". const devide = (obj, cb) => {return obj.arg1 / obj.arg2} devide(testObj) // 4. Створіть функцію яка приймає два аргументи, перший це обєкт другий це колбек. const someFunction = function(obj, cb){ return cb(obj) } someFunction(testObj, multiply) // 5. Створіть рекурсивну функцію. let tempnumber = 9 const buildPyramidWithNumber = function (arg){ let temp = '' for(let i = 0; i < arg; i++){ temp = temp.concat('*') } console.log(temp) if (arg) buildPyramidWithNumber(arg-1) } buildPyramidWithNumber(tempnumber) // 6. Створіть самовикликаючусь функцію. (function(){ console.log('I will be printed without the function being called anywhere else') })() // 7. Створіть функцію і виведіть в консоль всі аргументи які були їй передані. const printAllArguments = function(){ for(const item of arguments){ console.log(item) } } printAllArguments(1,2,3,4,5,'5','6','1234234','sdafdsfa')<file_sep>/home_work3.js // 1) Використовуючи оператор "Рівності (==)" порівняйте два значення так, щоб в першому випадку ви отримали "false" а в другому випадку "true". // * Виведіть результат порівняння в консоль за допомогою "console.log" let var1 = 0, var2 = '1', var3 = 1 console.log(var1 == var2) //false console.log(var2 == var3) //true // 2) Використовуючи оператор "Нерівності (!=)" порівняйте два значення так, щоб в першому випадку ви отримали "false" а в другому випадку "true". // * Виведіть результат порівняння в консоль за допомогою "console.log" console.log(var2 != var3) //false console.log(var1 != var2) //true // 3) Використовуючи оператор "Строгої рівності (===)" порівняйте два значення так, щоб в першому випадку ви отримали "false" а в другому випадку "true". // * Виведіть результат порівняння в консоль за допомогою "console.log" console.log(var1 === var2) // false var2-- // Now var1 = 0; var2 = 0; var3 = 1 console.log(var1 === var2) // true // 4) Використовуючи оператор "Строгої нерівності (!==)" порівняйте два значення так, щоб в першому випадку ви отримали "false" а в другому випадку "true". // * Виведіть результат порівняння в консоль за допомогою "console.log" console.log(var1 !== var2) // false console.log(var1 !== var3) // true // 5) Використовуючи оператор "Більше ніж (>)" порівняйте два значення так, щоб в першому випадку ви отримали "false" а в другому випадку "true". // * Виведіть результат порівняння в консоль за допомогою "console.log" console.log(var2 > var3) // false console.log(var3 > var2) // true // 6) Використовуючи оператор "Більше чи дорівнює (>=)" порівняйте два значення так, щоб в першому випадку ви отримали "false" а в другому випадку "true". // * Виведіть результат порівняння в консоль за допомогою "console.log" console.log(var2 >= var3) // false console.log(var3 >= var2) // true // 7) Використовуючи оператор "Менше ніж (<)" порівняйте два значення так, щоб в першому випадку ви отримали "false" а в другому випадку "true". // * Виведіть результат порівняння в консоль за допомогою "console.log" console.log(var3 < var2) // false console.log(var2 < var3) // true // 8) Використовуючи оператор "Менше чи дорівнює (<=)" порівняйте два значення так, щоб в першому випадку ви отримали "false" а в другому випадку "true". // * Виведіть результат порівняння в консоль за допомогою "console.log" console.log(var3 <= var2) // false console.log(var2 <= var3) // true // 9) Використовуючи оператор "Логічне І (&&)" порівняйте два значення так, щоб в першому випадку ви отримали "false" а в другому випадку "true". // * Виведіть результат порівняння в консоль за допомогою "console.log" console.log(Boolean(var1) && var2) //false var2++ // Now var1 = 0; var2 = 1; var3 = 1 console.log(Boolean(var3) && Boolean(var2)) //true // 10) Використовуючи оператор "Логічне АБО (||)" порівняйте два значення так, щоб в першому випадку ви отримали "false" а в другому випадку "true". // * Виведіть результат порівняння в консоль за допомогою "console.log" var2-- // Now var1 = 0; var2 = 0; var3 = 1 console.log(Boolean(var1) || Boolean(var2)) //false console.log(Boolean(var3) || Boolean(var2)) //true // 11) Використовуючи оператор "Логічне НЕ (!)" порівняйте два значення так, щоб в першому випадку ви отримали "false" а в другому випадку "true". // * Виведіть результат порівняння в консоль за допомогою "console.log" console.log(Boolean(!var3)) //false console.log(Boolean(!var2)) //true // 12) Використовуючи оператор "Рядкове додавання (+)" додайте два значення типу "string". // * Виведіть результат в консоль за допомогою "console.log" let string1 = 'Hello ' let string2 = 'world!' console.log(string1 + string2) // 13) За допомогою тернарного оператору присвойте значення у змінну "type" використовуючи змінну "color". Якщо колір дорівнює "червоний", тоді значення змінної має бути "пожежна" інакше "медична". // * Виведіть "type" в консоль за допомогою "console.log". Зробіть два варіанти в одному резyльтат в консолі має бути "пожежна" в іншому "медична" let color = 'червоний' let type = (color == 'червоний')?'пожежна':'медична' console.log(type) color = 0 type = (color == 'червоний')?'пожежна':'медична' console.log(type) // 14) Створіть об'єкт з довільними ключами і видаліть довільний ключ за допомогою оператору "delete" // * Виведіть результат в консоль за допомогою "console.log" let truba = { a: 'sideli', b: 'sideli' } delete truba.a console.log(truba) // 15) Створіть масив з довільними значеннями і видаліть довільне значення за допомогою оператору "delete" // * Виведіть результат в консоль за допомогою "console.log" let arr = [1,2,3,4,5,6,7,8,9,0] delete arr[9] console.log(arr) // 16) Створіть об'єкт з довільними ключами і за допомогою оператору "in" визначіть наявність ключів у об'єкті. Одне значення повинно бути наявне а інше повинно бути відсутнє // * Виведіть результат в консоль за допомогою "console.log" let someObj = { prop1: 'value', prop2: 'value' } console.log('prop1' in someObj) //true console.log('prop3' in someObj) //false // 16) Створіть масив з довільними значеннями і за допомогою оператору "in" визначіть наявність значення у масиві. Одне значення повинно бути наявне а інше повинно бути відсутнє // * Виведіть результат в консоль за допомогою "console.log" let someArr = [1,2,3,4,5,6,7,8,9,0] console.log('1' in someArr) //true console.log('11' in someArr) //false<file_sep>/home_work9/index.js // 1. Створіть index.html file and index.js file. Підключіть джс до html. console.log('// 2. Виведіть в консоль body') console.log(document.body) console.log('// 3. Виведіть в консоль довільний eлемент викoристовуючи getElementById') console.log(document.getElementById('titleH1')) console.log('// 4. Виведіть в консоль довільний eлемент викoристовуючи getElementsByClassName') console.log(document.getElementsByClassName('navigation')[0]) console.log('// 5. Виведіть в консоль довільний eлемент викoристовуючи getElementsByTagName') console.log(document.getElementsByTagName('ul')[0]) // 6. Створіть елементи для взяємодії з користувачем (button and input) // 7. Напишіть функцію яка буде взяємодіяти з button і буде виводити alert користувачу з довільним текстом const button7 = document.getElementById('button7') button7.onclick = function(){ alert('Button was clicked!') } // 8. Напишіть функцію яка буде взяємодіяти з input і буде виводити в консоль значення яке ввів користувач const inputText8 = document.getElementById('inputText8') inputText8.onchange = function(event){ console.log(event.target.value) } // For fun const forFunButton = document.getElementById('forFunButton') forFunButton.onmouseover = function(event){ let offset = event.target.style let goX = getRandom() let goY = getRandom() event.target.style.top = (parseInt(getComputedStyle(event.target).top) + 30 * goY) + 'px' event.target.style.left = (parseInt(getComputedStyle(event.target).left) + 30 * goX) + 'px' } const getRandom = function(){ return Math.random() < 0.5 ? -1 : 1; }<file_sep>/home_work6.js // 1. Створіть одновимірний масив і присвойте його в змінну. // *Виведіть значення масиву в консоль. // *Виведіть кожне значення масиву використовуючи довільний цикл. let arr1 = [1,2,3,4,5,6,7,8] console.log(arr1) for(const item of arr1){ console.log(item) } // 2. Створіть одновимірний обєкт і присвойте його в змінну. // *Виведіть значення обєкту в консоль. // *Виведіть кожний ключ і його значення в консоль. let obj1 = { id: 1, type: 'test object', name: 'obj1', purpose: 'to be printed', alive: false, willBeUsedAgain: false, originCountry: 'Ukraine' } console.log(obj1) for(const item in obj1){ console.log(item, ': ', obj1[item]) } // 3. Створіть масив і видаліть останнє значення з масиву, викoристовуючи "pop" // *Виведіть в консоль нову довжину масиву let arr2 = [1, 2, 3, 4, 5, '6', '7', 8, 9, '10'] arr2.pop() console.log(arr2.length) // 4. Створіть масив і додайте нове значення до масиву з кінця, викoристовуючи "push" // *Виведіть в консоль нову довжину масиву let arr3 = ['a', 'b', 'c'] console.log(arr3.push('d')) // 5. Створіть масив і видаліть перше значення з масиву, викoристовуючи "shift" // *Виведіть в консоль нову довжину масиву let arr4 = ['to be deleted', 'a', 'b', 'c'] arr4.shift() console.log(arr4.length) // 6. Створіть масив і додайте нове значення до масиву з початку, викoристовуючи "unshift" // *Виведіть в консоль нову довжину масиву let arr5 = [1,2,3,4,5,6,7,8] console.log(arr5.unshift(0)) // 7. Створіть рекурсивну функцію для того, щоб вивести в консоль всі значення багатовимірного масиву const printAllItemsInMultiDimensionalArray = function(inputArray){ for(const item of inputArray){ if(Array.isArray(item)){ printAllItemsInMultiDimensionalArray(item) } else console.log(item) } } // 8. Створіть рекурсивну функцію для того, щоб вивести в консоль всі ключі багатовимірного обєкту const printAllKeysInObject = function(inputObject, mode){ for(const item in inputObject){ if (mode == 'keysOnly') { console.log(item) } else if (mode === 'withValues'){ console.log(item, ':', inputObject[item]) } if(typeof inputObject[item] === 'object'){ printAllKeysInObject(inputObject[item]) } } } // 9. Створіть багатовимірний масив і присвойте його в змінну. // *Виведіть значення масиву в консоль. // *Виведіть кожне значення масиву використовуючи функцію з завдання 7. let testArr = [1,2,3,[4,5,6, ['x', 'y', 'z', ['x15', 'y15']]], 'a', 'b', 'c', 10 , 13] console.log(testArr) printAllItemsInMultiDimensionalArray(testArr) // 10. Створіть багатовимірний обєкт і присвойте його в змінну. // *Виведіть значення обєкт в консоль. // *Виведіть кожний ключ і його значення в консоль використовуючи функцію з завдання 8. let testObj = { id: 2, type: 'test object', name: 'obj2', purpose: 'to be printed', alive: false, willBeUsedAgain: false, sex: 'male', origin: { planet: 'Earth', country: 'Ukraine', city: 'Uzhorod' }, realatievs: { children: 'none', brother: { id: 3, type: 'test object', name: 'obj3', purpose: 'to be printed', alive: false, willBeUsedAgain: true, sex: 'male', origin: { planet: 'Earth', country: 'Ukraine', city: 'IvanoFrankivsk' } }, sister: { id: 4, type: 'test object', name: 'obj4', purpose: 'to be printed', alive: false, willBeUsedAgain: true, sex: 'female', origin: { planet: 'Earth', country: 'Ukraine', city: 'Kharkiv' } } } } console.log(testObj) printAllKeysInObject(testObj, 'withValues')<file_sep>/home_work5.js // 1. Використовуючи цикл "while" виведіть в консоль цифри від 0 до 10; // * Зробіть те саме за допомогою циклу "do while" i "for" let i = 0 while(i < 11){ console.log('i=',i) i++ } i = 0 do{ console.log('i=',i) i++ }while(i < 11) for (i = 0; i < 11; i++){ console.log('i=',i) } // 2. Яке останнє значення буде виведено в консоль? // let i = 0; // // while (i > 10) { // console.log(i); // ++i; // } // Відповідь: Ніяке, цикл не почнеться так як i = 0, а (i > 10) дасть false // 3. Яке останнє значення буде виведено в консоль? // let i = 0; // // do { // console.log(i); // ++i; // } while (i < 10) // Відповідь: Останній виклики console.log виведе 9. // 4. Замініть цей приклад використовуючи "while" // // for (let i = 0; i < 10; i++) { // console.log('i', i); // } let i = 0 while(i < 10){ console.log('i',i) i++ } // 5. Яке перше значення буде виведено в консоль? // let i = 0; // // while (i > 10) { // ++i; // console.log(i); // } // Відповідь: Ніяке, цикл не почнеться так як i = 0, а (i > 10) дасть false // 6. Яке перше значення буде виведено в консоль? // let i = 1; // // do { // i++; // console.log(i); // } while (i < 10) // Відповідь: перший виклик console.log виведе 2<file_sep>/home_work2.js // 1) Оголосіть змінну типу number і зробіть явне перетворення до типу string використовуючи “String()” // * Bиведіть в консоль тип змінної використовуючи оператор "typeof" і функцію "console.log()" let testVar1 = 2 testVar1 = String(testVar1) console.log(typeof testVar1) // 2) Оголосіть змінну типу number і зробіть явне перетворення до типу boolean використовуючи “Boolean()” // * Bиведіть в консоль тип змінної використовуючи оператор "typeof" і функцію "console.log()" let testVar2 = 2 testVar2 = Boolean(testVar2) console.log(typeof testVar2) // 3) Оголосіть змінну типу number і зробіть явне перетворення до типу null використовуючи “Null()” // * Bиведіть в консоль тип змінної використовуючи оператор "typeof" і функцію "console.log()" let testVar3 = 2 testVar3 = null console.log(typeof testVar3) // АБО другий варіант let testVar3_1 = 2 function Null(){ return null } testVar3_1 = Null() console.log(typeof testVar3_1) // 4) Оголосіть змінну типу string і зробіть явне перетворення до типу number використовуючи “Number()” // * Bиведіть в консоль тип змінної використовуючи оператор "typeof" і функцію "console.log()" let testVar4 = 'this is a string' testVar4 = Number(testVar4) console.log(typeof testVar4) // 5) Оголосіть змінну типу string і зробіть явне перетворення до типу boolean використовуючи “Boolean()” // * Bиведіть в консоль тип змінної використовуючи оператор "typeof" і функцію "console.log()" let testVar5 = 'this is a string' testVar5 = Boolean(testVar5) console.log(typeof testVar5) // 6) Оголосіть змінну типу string і зробіть явне перетворення до типу null використовуючи “Null()” // * Bиведіть в консоль тип змінної використовуючи оператор "typeof" і функцію "console.log()" let testVar6 = 'this is a string' testVar6 = null console.log(typeof testVar6) // АБО другий варіант let testVar6_1 = 'this is a string' testVar6_1 = Null() console.log(typeof testVar6_1) // 7) Оголосіть змінну типу boolean і зробіть явне перетворення до типу string використовуючи “String()” // * Bиведіть в консоль тип змінної використовуючи оператор "typeof" і функцію "console.log()" let testVar7 = true testVar7 = String(testVar7) console.log(typeof testVar7) // 8) Оголосіть змінну типу boolean і зробіть явне перетворення до типу number використовуючи “Number()” // * Bиведіть в консоль тип змінної використовуючи оператор "typeof" і функцію "console.log()" let testVar8 = true testVar8 = Number(testVar8) console.log(typeof testVar8) // 9) Оголосіть змінну типу boolean і зробіть явне перетворення до типу null використовуючи Null()” // * Bиведіть в консоль тип змінної використовуючи оператор "typeof" і функцію "console.log()" let testVar9 = true testVar9 = null console.log(typeof testVar9) // АБО другий варіант let testVar9_1 = true testVar9_1 = Null() console.log(typeof testVar9_1) // 10) Оголосіть змінну типу null і зробіть явне перетворення до типу string використовуючи “String()” // * Bиведіть в консоль тип змінної використовуючи оператор "typeof" і функцію "console.log()" let testVar10 = null testVar10 = String(testVar10) console.log(typeof testVar10) // 11) Оголосіть змінну типу null і зробіть явне перетворення до типу number використовуючи “Number()” // * Bиведіть в консоль тип змінної використовуючи оператор "typeof" і функцію "console.log()" let testVar11 = null testVar11 = Number(testVar11) console.log(typeof testVar11) // 12) Оголосіть змінну типу null і зробіть явне перетворення до типу boolean використовуючи Boolean()” // * Bиведіть в консоль тип змінної використовуючи оператор "typeof" і функцію "console.log()" let testVar12 = null testVar12 = Boolean(testVar12) console.log(typeof testVar12) // 13) Напишіть всі способи створення функції. function option1(){} let option2 = function(){} let option3 = new Funciton() let option4 = () =>{} (function(){}) //option 5 // 14) Напишіть функцію яка нічого не повертає // * Викличіть функцію function testFunc15(){} testFunc15() // 15) Напишіть функцію яка завжди буде повертати ваше імя // * Викличіть функцію function getMichaelsName(){ return 'Michael' } getMichaelsName() // 16) Створіть функцію яка приймає 1 аргумент і повертає його без змін. // * Викличіть функцію у двох різних варіантах, з даними напряму вбо із змінними. let testVar16 = 5 function returnWithoutChange(arg){ return arg } returnWithoutChange(3) returnWithoutChange(testVar16) // 17) Створіть функцію яка приймає 2 аргументи і повертає суму цих 2 аргументів. // * Викличіть функцію у двох різних варіантах, з даними напряму вбо із змінними. let testVar17_1 = 4 let testVar17_2 = 5 function getSum(arg1, arg2){ return arg1 + arg2 } getSum(3,4) getSum(testVar17_1, testVar17_2) // 18) Створіть функцію яка приймає 3 аргументи і повертає суму цих 3 аргументів. // * Викличіть функцію у двох різних варіантах, з даними напряму вбо із змінними. let testVar18_1 = 7 let testVar18_2 = 8 let testVar18_3 = 9 function getSum(arg1, arg2, arg3){ return arg1 + arg2 + arg3 } getSum(3,4,5) getSum(testVar18_1, testVar18_2, testVar18_3) <file_sep>/test_1.js // 1) Оголосіть одну змінну якій можна міняти значення і одну змінну якій не можна міняти значення let first const second // 2) Напишіть 1 коментар в 1 рядок і напишіть ще один коментар на 4 рядки // 1 коментар в 1 рядок /*Коментар на 4 рядки*/ // 3) Створіть "масив" який буде містити 5 довільних значень. let testArr = [1,2,3,4,5] console.log(testArr)// * Виведіть змінну в консоль за допомогою "console.log" delete testArr[0] delete testArr[testArr.length-1]// * Видаліть з масиву перше і останнє значення. console.log(testArr)// * Виведіть змінну в консоль за допомогою "console.log" // 4) Створіть "об'єкт" який буде містити 5 довільних ключів із довільними значеннями. let testObj = { first: 1, second: 2, third: 3, fourth: 4, fifth: 5 } console.log(testObj) // * Виведіть змінну в консоль за допомогою "console.log" delete testObj.first delete testObj.fifth// * Видаліть з об'єкту перший і останній ключ console.log(testObj)// * Виведіть змінну в консоль за допомогою "console.log" // 5) Напишіть всі способи створення функції. function option1(){} let option2 = function(){} let option3 = new Funciton() let option4 = () =>{} (function(){}) // 6) Створіть функцію яка приймає 3 аргументи і повертає суму цих 3 аргументів. function sumOfThre(arg1, arg2, arg3){ return arg1 + arg2 + arg3 } // * Викличіть функцію у двох різних варіантах, з даними aбо із змінними. let testVar1 = 3, testVar2 = 23, testVar3 = 435 console.log(sumOfThre(23, 123, 44)) console.log(sumOfThre(testVar1, testVar2, testVar3)) // 7) За допомогою тернарного оператору присвойте значення у змінну "salary" використовуючи змінну "workType". Якщо workType дорівнює "fulltime", тоді значення змінної має бути "1000" інакше "500". // * Виведіть "salary" в консоль за допомогою "console.log". Зробіть два варіанти в одному резyльтат в консолі має бути "1000" в іншому "500" let workType = 'fulltime' let salary = (workType === 'fulltime')?'1000':'500' console.log(salary) workType = 'parttime' salary = (workType === 'fulltime')?'1000':'500' console.log(salary) // 8) Виведіть користувачу попап використовуючи функцію "prompt" який містить довільне питання і не має дефолтного значення. Результат присвойте у змінну. let userInput = prompt('Press 1 or 2') // * Виведіть змінну в консоль за допомогою "console.log" console.log(userInput) // * Використовуючи "switch" виведіть в консоль "a" або "b" або "c", виконайте те саме за допомогою "if else"; switch (userInput){ case '1': console.log('a') break case '2': console.log('b') break default: console.log('c') break } if(userInput == '1'){ console.log('a') } else if(userInput == '2'){ console.log('b') } else { console.log('c') } // * Зробіть два різні приклади let userInput2 = prompt('Press 1 or 2') switch (userInput2){ case '1': console.log('You have pressed 1') break case '2': console.log('You have pressed 2') break default: console.log('You pressed the wrong key') break } if(userInput2 == '1'){ console.log('You have pressed 1') } else if(userInput == '2'){ console.log('You have pressed 2') } else { console.log('You pressed the wrong key') }<file_sep>/home_work8.js // 1. Створіть дві змінні типу стрінг і виведіть їх в консоль разом, використовуючи конкатинацію стрiнги. let string1_1 = 'abcdefg' let string1_2 = 'hijklomnp' console.log(`${string1}${string2}`) // 2. Створіть змінну типу стрінг і виведіть в консоль її довжину. let string2 = '9999aaaaa9999vvvvvv00000' console.log(string2.length) // 3. Створіть змінну типу стрінг і виведіть в консоль перший символ стрінги. let string3 = 'asdfjsdflasdhf32i3r23r' console.log(string3[0]) // 4. Створіть змінну типу стрінг і виведіть в консоль останній символ, довільної стрінги. let string4 = 'asdfsdogijqo3i4t023tj;lfkajsdfA' console.log(string4[string4.length-1]) // 5. Створіть змінну типу стрінг і приведіть змінну до верхнього регістру. let string6 = 'dafdsfakjsdfhlsdjfhsdf' string6 = string6.toUpperCase() console.log(string6) // 6. Створіть змінну типу стрінг і приведіть змінну до нижнього регістру. let string7 = 'WEDASDLFKASJDFsdlfjslkdfjSLAKFJSDLFKJSDaksjls' string7 = string7.toLowerCase() console.log(string7) // 7. Створіть змінну і присвойте в неї дату вашого народження. let myBirthday = new Date('1991-07-25') // 8. Виведіть рік вашого народження (Використовуючи змінну з 7 завдання). console.log(myBirthday.getFullYear()) // 9. Виведіть місяць вашого народження (Використовуючи змінну з 7 завдання). console.log(myBirthday.getMonth()) // 10. Виведіть день вашого народження (Використовуючи змінну з 7 завдання). console.log(myBirthday.getDate()) // 11. Виведіть в консоль рік місяць день вашого народження через тире (-) (Використовуючи змінну з 7 завдання). console.log(`${myBirthday.getFullYear()}-${myBirthday.getMonth()}-${myBirthday.getDate()}`) // 12. Створіть нову дату яка має 14 годину і 23 хвилини. let time12 = new Date(2018,2,3,14,23) console.log(`${time12.getHours()}:${time12.getMinutes()}`) // 13. Порівняйте дві дати між собою і результат виведіть в консоль. console.log(myBirthday < time12)<file_sep>/home_work4.js // 1. Виведіть користувачу попап використовуючи функцію "alert" який містить довільне повідомлення. alert('This is a random message') // 2. Виведіть користувачу попап використовуючи функцію "prompt" який містить довільне питання і не має дефолтного значення. Результат присвойте у змінну. // *Виведіть змінну в консоль за допомогою "console.log" let userInput1 = prompt('Type in a random number') console.log(userInput1) // 3. Виведіть користувачу попап використовуючи функцію "prompt" який містить довільне питання і має дефолтнe значення "13". Результат присвойте у змінну. // *Виведіть змінну в консоль за допомогою "console.log" let userInput2 = prompt('Type in a random number', 13) console.log(userInput2) // 4. Виведіть користувачу попап використовуючи функцію "confirm" який містить довільне питання. Результат присвойте у змінну. // *Виведіть змінну в консоль за допомогою "console.log" let userInput3 = confirm('Are you sure?') console.log(userInput3) // 5. Виведіть користувачу попап використовуючи функцію "confirm" який містить довільне питання. Результат присвойте у змінну. // *Виведіть змінну в консоль за допомогою "console.log" // *Використовуючи "if" виведіть в консоль "1" якщо відповідь на питання була позитивна let userInput4 = confirm('Are you sure?') console.log(userInput4) if (userInput4){ console.log('1') } // 6. Виведіть користувачу попап використовуючи функцію "prompt" який містить довільне питання і не має дефолтного значення. Результат присвойте у змінну. // *Виведіть змінну в консоль за допомогою "console.log" // *Використовуючи "if else" виведіть в консоль "1" або "2" let userInput5 = prompt('If you are older than 18, type in \'Yes\'') console.log(userInput5) if (userInput5 == 'Yes'){ console.log('1') } else { console.log('2') } // 7. Виведіть користувачу попап використовуючи функцію "prompt" який містить довільне питання і не має дефолтного значення. Результат присвойте у змінну. // *Виведіть змінну в консоль за допомогою "console.log" // *Використовуючи "if else" виведіть в консоль "1" або "2" або "3" let userInput6 = prompt('For console log 1 type in \'one\', for 2 - \'two\', anything else will be 3') console.log(userInput4) if (userInput6 == 'one'){ console.log('1') } else if(userInput6 == 'two') { console.log('2') } else { console.log('3') } // 8. Виведіть користувачу попап використовуючи функцію "confirm" який містить довільне питання. Результат присвойте у змінну. // *Виведіть змінну в консоль за допомогою "console.log" // *Використовуючи "switch" виведіть в консоль "1" якщо відповідь на питання була позитивна let userInput7 = confirm('Are you sure?') console.log(userInput7) switch (userInput7){ case true: console.log('1') break } // 9. Виведіть користувачу попап використовуючи функцію "prompt" який містить довільне питання і не має дефолтного значення. Результат присвойте у змінну. // *Виведіть змінну в консоль за допомогою "console.log" // *Використовуючи "switch" виведіть в консоль "1" або "2" let userInput8 = prompt('Do you choose 1 or 2?') console.log(userInput8) switch (userInput8){ case '1': console.log('1') break case '2': console.log('2') break } // 10. Виведіть користувачу попап використовуючи функцію "prompt" який містить довільне питання і не має дефолтного значення. Результат присвойте у змінну. // *Виведіть змінну в консоль за допомогою "console.log" // *Використовуючи "switch" виведіть в консоль "1" або "2" або "3" let userInput9 = prompt('Do you choose 1 or 2 or 3?') console.log(userInput9) switch (userInput9){ case '1': console.log('1') break case '2': console.log('2') break case '3': console.log('3') break } // 11. Виведіть користувачу попап використовуючи функцію "prompt" який містить довільне питання і не має дефолтного значення. Результат присвойте у змінну. // *Виведіть змінну в консоль за допомогою "console.log" // *Використовуючи "switch" виведіть в консоль "1" або "2" або "3", виконайте те саме за допомогою "if else"; // *Зробіть два різні приклади // Приклад 1 let userInput10_1 = prompt('Do you choose 1 or 2 or 3?') console.log(userInput10_1) switch (userInput10_1){ case '1': console.log('1') break case '2': console.log('2') break case '3': console.log('3') break } if(userInput10_1 == '1'){ console.log('1') } else if(userInput10_1 == '2'){ console.log('2') } else if(userInput10_1 == '3'){ console.log('3') } // Приклад 2 let userInput10_2 = prompt('What number do you want to see in the console 3 times: 1, 2, or 3?') console.log(userInput10_2) switch (userInput10_2){ case '1': console.log('1') break case '2': console.log('2') break case '3': console.log('3') break } if(userInput10_2 == '1'){ console.log('1') } else if(userInput10_2 == '2'){ console.log('2') } else if(userInput10_2 == '3'){ console.log('3') } <file_sep>/home_work10.js //1 Створіть об'єкт Person який буде містити імя, прізвище і метод для виводу повного імені і просто імені за допомогою трьох різних варіантів let person = { firstName: 'Michael', lastName: 'Pymsenytskiy', getFirstName: function(){ console.log(this.firstName) return this.firstName }, getLastName: function(){ console.log(this.lastName) return this.lastName }, getFullName: function(){ console.log(`${this.firstName} ${this.lastName}`) return this.firstName + '' + this.lastName } } person.getFirstName() person.getLastName() person.getFullName() //2 Просто функції function Person1(){ this.firstName = 'Michael' this.lastName = 'Pymsenytskiy' this.getFirstName = function(){ console.log(this.firstName) return this.firstName } this.getLastName = function(){ console.log(this.lastName) return this.lastName } this.getFullName = function(){ console.log(`${this.firstName} ${this.lastName}`) return this.firstName + '' + this.lastName } } let person1_1 = new Person1() person1_1.getFirstName() person1_1.getLastName() person1_1.getFullName() //3 Функції конструктору function person2(){ const obj = {} obj.firstName = 'Michael' obj.lastName = 'Pymsenytskiy' obj.getFirstName = function(){ console.log(obj.firstName) return obj.firstName } obj.getLastName = function(){ console.log(obj.lastName) return obj.lastName } obj.getFullName = function(){ console.log(`${obj.firstName} ${obj.lastName}`) return obj.firstName + '' + obj.lastName } return obj } let person2_1 = person2() person2_1.getFirstName() person2_1.getLastName() person2_1.getFullName() //4 Класу class Person3 { constructor(){ this.firstName = 'Michael' this.lastName = 'Pymsenytskiy' } getFirstName = function(){ console.log(this.firstName) return this.firstName } getLastName = function(){ console.log(this.lastName) return this.lastName } getFullName = function(){ console.log(`${this.firstName} ${this.lastName}`) return this.firstName + '' + this.lastName } } let person3 = new Person3() person3.getFirstName() person3.getLastName() person3.getFullName()
d6fa067a3b17350997aa7a37cbb31a38d6cef3f0
[ "JavaScript" ]
12
JavaScript
michaelPysmenytskyi/home_work
b04dcd7d45e637d51da1dd25443747d779abf311
926199c74696ddd7d98b5b64e8215efbe9c056fe
refs/heads/master
<file_sep>$(function() { var allow_editing = false; $('body') .click( function() { }) $('.handle') .click( function() { allow_editing = !allow_editing; $(this).siblings('.content').attr('contentEditable', allow_editing); // save the new contents if (!allow_editing) { $(this).css('background-color', '#ffb508'); $.ajax({ type: "POST", data: {contents: $(this).siblings('.content').html()}, success: function(data) {} }) $('#buttons').hide(); } else { $(this).css('background-color', '#0ef400'); $('#buttons').show(); } return false; }) $('.content') .mouseup( function() { if (allow_editing) { //console.log(document.getSelection().toString()); } }) $('#h1-button') .mousedown( function (event) { event.preventDefault(); document.execCommand('formatBlock',false,'h1'); }) $('#h2-button') .mousedown( function (event) { event.preventDefault(); document.execCommand('formatBlock',false,'h2'); }) $('#h2-button') .mousedown( function (event) { event.preventDefault(); document.execCommand('formatBlock',false,'h2'); }) $('#h3-button') .mousedown( function (event) { event.preventDefault(); document.execCommand('formatBlock',false,'h3'); }) $('#h4-button') .mousedown( function (event) { event.preventDefault(); document.execCommand('formatBlock',false,'h4'); }) $('#h5-button') .mousedown( function (event) { event.preventDefault(); document.execCommand('formatBlock',false,'h5'); }) $('#h6-button') .mousedown( function (event) { event.preventDefault(); document.execCommand('formatBlock',false,'h6'); }) $('#h0-button') .mousedown( function (event) { event.preventDefault(); document.execCommand('formatBlock',false,'div'); }) $('#ul-button') .mousedown( function (event) { event.preventDefault(); document.execCommand('insertUnorderedList',false,null); }) $('#ol-button') .mousedown( function (event) { event.preventDefault(); document.execCommand('insertOrderedList',false,null); }) $('#bold-button') .mousedown( function (event) { event.preventDefault(); document.execCommand('bold',false,null); }) $('#italic-button') .mousedown( function (event) { event.preventDefault(); document.execCommand('italic',false,null); }) $('#clear-button') .mousedown( function (event) { event.preventDefault(); document.execCommand('removeFormat',false,null); }) });<file_sep>import lxml import os import redis from twisted.web import server, resource, static from twisted.internet import reactor from jinja2 import Environment, FileSystemLoader from lxml.html.clean import Cleaner from datetime import datetime jinj = Environment(loader=FileSystemLoader(os.path.join(os.getcwd(), 'templates'))) red = redis.StrictRedis(host='localhost', port=6379, db=0) def xstr(s): return '' if s is None else s class Wiki(resource.Resource): isLeaf = True def render_GET(self, request): request.setHeader('Content-Type', 'text/html; charset=UTF-8') url_list = [x for x in request.path.split('/') if x is not ''] url_path = "/".join(url_list) print(str(datetime.now()) + " " + url_path + " " + request.getClientIP()) res = jinj.get_template('wiki.html').render( data=xstr(red.hget('wiki', url_path)).decode('utf8') ) return res.encode('utf-8') def render_POST(self, request): html = request.args['contents'][0] url_list = [x for x in request.path.split('/') if x is not ''] url_path = "/".join(url_list) # Sanitize HTML cleaner = Cleaner(remove_tags=['code']) try: html = cleaner.clean_html(html) except (lxml.etree.XMLSyntaxError, lxml.etree.ParserError): html = '' red.hset('wiki', url_path, html) return '' root = resource.Resource() root.putChild('js', static.File('js')) root.putChild('css', static.File('css')) root.putChild('wiki', Wiki()) site = server.Site(root) reactor.listenTCP(80, site) reactor.run()
3b869fbf733a3fddd4a7df04b9e265be16b72f3d
[ "JavaScript", "Python" ]
2
JavaScript
mdenchev/Wiki
698f158cb8e0335223f50d5c78d0f2fd88e0094d
02bbf3391c3542ebb5e04d6f8d3f9544ac0428d8
refs/heads/master
<file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { Router } from '@angular/router'; import { DatePipe } from '@angular/common'; import { UsuarioService } from './usuario.service'; import { FormBuilder, Validators } from '@angular/forms'; import {UsuarioClass} from './usuario.class'; import {NgbAlert} from '@ng-bootstrap/ng-bootstrap'; @Component({ selector: 'app-usuario', templateUrl: './usuario.component.html', styleUrls: ['./usuario.component.css'] }) export class UsuarioComponent implements OnInit { @ViewChild('cerrarAlerta') cerrarAlerta: NgbAlert; SEXO_USUARIO = [{'clave': 'M', 'nombre': 'Masculino'}, {'clave': 'F', 'nombre': 'Femenino'}]; usuario: any; usuarioForm: any; maxFecha: string; // Alerta tipoAlerta: string = 'danger'; mostrarAlerta: boolean = false; mensajeAlerta: string = 'dasdas '; //carga cargando: boolean = true; usuarioModel: UsuarioClass = new UsuarioClass(); constructor( private formBuilder: FormBuilder, private usuarioServicio: UsuarioService, private router: Router, private datePipe: DatePipe ) { } ngOnInit(): void { this.inicializarForm(); this.obtenerFechaMaxima(); } inicializarForm(){ const emailFormat = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/ this.usuarioForm = this.formBuilder.group({ usuNombres: ['', [Validators.required, Validators.pattern('([a-zA-ZñÑáéíóúÁÉÍÓÚ\s][ ]*)+'), Validators.maxLength(50)]], usuApellidos: ['', [Validators.required, Validators.pattern('([a-zA-ZñÑáéíóúÁÉÍÓÚ\s][ ]*)+'), Validators.maxLength(30)]], usuSexo: [null, Validators.required], usuFechNacimiento: ['', Validators.required], usuDni: ['', [Validators.required, Validators.pattern('[0-9]+'), Validators.minLength(8), Validators.maxLength(8)]], usuEmail: ['', [Validators.required, Validators.pattern(emailFormat), Validators.maxLength(60)]], usuAlias: ['', [Validators.required, Validators.maxLength(15)]], usuContrasenia: ['', [Validators.required, Validators.minLength(8), Validators.maxLength(20)]], usuDireccion: ['', [Validators.required, Validators.maxLength(100)]] }); } obtenerFechaMaxima() { const fechaActual = this.datePipe.transform(new Date(), "yyyy-MM-dd").split('-') const dia = fechaActual[2] const mes = fechaActual[1]; const anio = Number(fechaActual[0]) - 18; this.maxFecha = anio + '-' + mes + '-' + dia; } guardarUsuario(){ if(this.usuarioForm.invalid) { this.mostrarAlerta = true; this.tipoAlerta = "danger"; this.mensajeAlerta = "Uno o más campos no fueron completados o su contenido no es válido."; }else{ this.guardarDatosForm(); if(this.esFechaInvalida()) { setTimeout(()=> { this.mostrarAlerta = true; this.tipoAlerta = 'danger'; this.mensajeAlerta = 'La fecha es inválida.'; },4000); } else{ this.usuarioServicio.registro(this.usuarioModel).subscribe( (mensaje) => { setTimeout(()=> { this.mostrarAlerta = true; this.tipoAlerta = "success"; this.mensajeAlerta = "Usuario registrado con éxito."; },4000); setTimeout(() => { this.router.navigate(['/home']); this.usuarioForm.reset(); }, 2000); }, (error) => { setTimeout(() => { this.mostrarAlerta = true; this.tipoAlerta = "danger"; this.mensajeAlerta = "Ocurrió un problema al registrarse. Por favor intentelo más tarde."; }, 2000); } ); } } } esFechaInvalida() { let fechaInvalida = false; const fechaActual = new Date(); if (this.usuarioModel.USU_FECH_NAC >= this.datePipe.transform(fechaActual.toDateString(), 'yyyy-MM-dd')) { this.mensajeAlerta = 'La fecha de nacimiento no es válida'; fechaInvalida = true; } else if (this.maxFecha < this.usuarioModel.USU_FECH_NAC) { this.mensajeAlerta = 'Debe ser mayor de edad para que la fecha sea válida'; fechaInvalida = true; } return fechaInvalida; } guardarDatosForm(){ this.usuarioModel.USU_NOMBRES = this.usuNombres.value; this.usuarioModel.USU_APELLIDOS = this.usuApellidos.value; this.usuarioModel.USU_SEXO = this.usuSexo.value; this.usuarioModel.USU_FECH_NAC = this.usuFechNacimiento.value; this.usuarioModel.USU_DNI = this.usuDni.value; this.usuarioModel.USU_EMAIL = this.usuEmail.value; this.usuarioModel.USU_ALIAS = this.usuAlias.value; this.usuarioModel.USU_CONTRASENIA = this.usuContrasenia.value; this.usuarioModel.USU_DIRECCION = this.usuDireccion.value; } get usuNombres() { return this.usuarioForm.get('usuNombres'); } get usuApellidos() { return this.usuarioForm.get('usuApellidos'); } get usuSexo() { return this.usuarioForm.get('usuSexo'); } get usuFechNacimiento() { return this.usuarioForm.get('usuFechNacimiento'); } get usuDni() { return this.usuarioForm.get('usuDni'); } get usuEmail() { return this.usuarioForm.get('usuEmail'); } get usuAlias() { return this.usuarioForm.get('usuAlias'); } get usuContrasenia() { return this.usuarioForm.get('usuContrasenia'); } get usuDireccion() { return this.usuarioForm.get('usuDireccion'); } } <file_sep>import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { LayoutComponent } from './layout.component'; const routes: Routes = [ { path: '', component: LayoutComponent, children: [ { path: 'cuenta', loadChildren: () => import('./cuenta/cuenta.module').then(m => m.CuentaModule)}, { path: 'mapa', loadChildren: () => import('./mapa/mapa.module').then(m => m.MapaModule)}, { path: 'imagenes', loadChildren: () => import('./imagenes/imagenes.module').then(m => m.ImagenesModule)}, { path: 'registro', loadChildren: () => import('./usuario/usuario.module').then(m => m.UsuarioModule)} ] } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class LayoutRoutingModule { } <file_sep>import { Component, OnInit , ViewChild} from '@angular/core'; import { Router } from '@angular/router'; import {UsuarioService} from '../layout/usuario/usuario.service'; import { FormBuilder, Validators } from '@angular/forms'; import {NgbAlert} from '@ng-bootstrap/ng-bootstrap'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { @ViewChild('cerrarAlerta') cerrarAlerta: NgbAlert; usuarioForm: any; alias: string; contrasena: string; // Alerta tipoAlerta: string; mostrarAlerta: boolean; mensajeAlerta: string; constructor( private router: Router, private usuarioService: UsuarioService, private formBuilder: FormBuilder ) { } ngOnInit(): void { this.inicializarForm(); } inicializarForm(){ this.usuarioForm = this.formBuilder.group({ usuAlias: ['', [Validators.required, Validators.maxLength(15)]], usuContrasenia: ['', [Validators.required, Validators.minLength(8), Validators.maxLength(20)]] }); } iniciarSesion(){ this.guardarValores(); this.usuarioService.login(this.alias, this.contrasena).subscribe(() => { this.goToCuenta(); }, error =>{ setTimeout(()=> { this.mostrarAlerta = true; this.tipoAlerta = "danger"; this.mensajeAlerta = "El usuario o la contraseña no son correctos"; },4000); }); } goToCuenta(){ this.router.navigate(['/cuenta']); } goToRegistro(ruta){ this.router.navigate([ruta]); } guardarValores() { this.alias = this.usuAlias.value; this.contrasena = this.usuContrasenia.value; } get usuAlias() { return this.usuarioForm.get('usuAlias'); } get usuContrasenia() { return this.usuarioForm.get('usuContrasenia'); } } <file_sep>import { Component, OnInit } from '@angular/core'; declare var google; @Component({ selector: 'app-mapa', templateUrl: './mapa.component.html', styleUrls: ['./mapa.component.css'] }) export class MapaComponent implements OnInit { UBICACION_DESTINO:any; UBICACION_ORIGEN: any; mapEle: HTMLElement; // referencia al identificador del template. map: any; directionsService = new google.maps.DirectionsService(); // retorna la ruta optima directionsRenderer = new google.maps.DirectionsRenderer(); // renderiza la ruta optima constructor() { } ngOnInit(): void { this.obtenerUbicacion().then((data) => { this.UBICACION_ORIGEN = data; this.cargarMapa(); } ) .catch( () => { console.log('Hubo un error al intentar recuperar su ubicación'); } ); this.UBICACION_DESTINO = {"lat": -8.107791, "lng": -79.030251 } } obtenerUbicacion = () => { let data; const ubicacionPromise = new Promise((resolve, reject) => { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( (position) => { data = { lat: position.coords.latitude, lng: position.coords.longitude }; resolve({"lat":data.lat, "lng":data.lng}); } , (err) => { console.log(' Advertencia: El servicio de geolocalización no se puede realizar, debido que bloqueó la ubicación. '); reject(err); } ); } else { console.log(' Error: El navegador no soporta la geolocalización.'); reject('Error: El navegador no soporta la geolocalización.'); } }); return ubicacionPromise; } cargarMapa() { this.mapEle = document.getElementById('map'); // Obtenemos la referencia del html, mediante el id del div. this.map = new google.maps.Map(this.mapEle, { // se crea el mapa con sus punto de origen. center: new google.maps.LatLng(this.UBICACION_ORIGEN.lat, this.UBICACION_ORIGEN.lng) , zoom: 15 }); this.directionsRenderer.setMap(this.map); // Escribimos sobre el mapa google.maps.event.addListenerOnce(this.map, 'idle', () => { this.calculateRoute(); // se calcula la ruta entre el especialista y el cliente. }); } calculateRoute() { this.directionsService.route({ origin: this.UBICACION_ORIGEN, destination: this.UBICACION_DESTINO , travelMode: google.maps.TravelMode.WALKING, // Modo de trazado(caminando, en taxi, ...) }, (response, status) => { if (status === 'OK') { this.directionsRenderer.setDirections(response); // Dibujamos la ruta desde el punto A hacia el punto B. } else { switch (status) { // En caso de haber un error, se mostrará diferentes estado obtenidos de Google Maps. case 'ZERO_RESULTS': console.log('No se pudo encontrar ninguna ruta entre el origen y el destino.'); break; case 'UNKNOWN_ERROR': console.log('No se pudo procesar una solicitud de indicaciones debido a un error del servidor.'); break; case 'OVER_QUERY_LIMIT': console.log('La página web superó el límite de solicitudes en un período de tiempo demasiado corto.'); break; case 'NOT_FOUND': console.log( 'No se pudo geocodificar al menos uno de los puntos de origen o destino.'); break; } } }); } } <file_sep># MyApp This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 11.1.2. ## Rutas - http://localhost:4200/registro - http://localhost:4200/home - http://localhost:4200/mapa <file_sep>import { Injectable } from '@angular/core'; import { environment } from '../../../environments/environment'; import { retry } from 'rxjs/operators'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import {UsuarioClass} from './usuario.class'; @Injectable({ providedIn: 'root' }) export class UsuarioService { constructor(private http: HttpClient) { } registro(usuario: UsuarioClass): Observable<any> { const url = environment.domain_url + 'usuario/insertar'; let datos = { "USU_NOMBRES": usuario.USU_NOMBRES, "USU_DNI": usuario.USU_DNI, "USU_APELLIDOS": usuario.USU_APELLIDOS, "USU_EMAIL": usuario.USU_EMAIL, "USU_ALIAS": usuario.USU_ALIAS, "USU_CONTRASENIA": usuario.USU_CONTRASENIA, "USU_DIRECCION": usuario.USU_DIRECCION, "USU_SEXO": usuario.USU_SEXO, "USU_FECH_NAC": usuario.USU_FECH_NAC } return this.http.post<any>(url, datos).pipe( retry(2) ); } login(usuAlias: string, usuContrasena: string): Observable<any> { const url = environment.domain_url + 'usuario/login'; let usuario = { "USU_ALIAS": usuAlias, "USU_CONTRASENIA": usuContrasena } return this.http.post<any>(url, usuario).pipe( retry(2) ); } } <file_sep>import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class StorageService { storeString(key: string, value: string) { localStorage.setItem(key, value); } hasKey(key: string) { return !!localStorage.getItem(key); } getString(key: string) { return localStorage.getItem(key); } remove(key: string) { localStorage.removeItem(key); } storeObjeto(key: string, value: any){ localStorage.setItem(key, JSON.stringify(value)); } getObjeto(key: string){ return JSON.parse(localStorage.getItem(key)); } clear(){ localStorage.clear(); } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-sidebar', templateUrl: './sidebar.component.html', styleUrls: ['./sidebar.component.css'] }) export class SidebarComponent implements OnInit { RUTAS; constructor() { } ngOnInit(): void { this.RUTAS = this.rutas(); } rutas(){ return [ { link: '/cuenta', icon: 'fa fa-clipboard', title: 'Mi cuenta' }, { link: '/mapa', icon: 'fa fa-clipboard', title: 'Mapa' }, { link: '/imagenes', icon: 'fa fa-clipboard', title: 'Imagenes' } ] } } <file_sep>export class UsuarioClass { USU_NOMBRES?: string; USU_APELLIDOS?: string; USU_SEXO?:string; USU_FECH_NAC?: string; USU_DNI?: string; USU_DIRECCION?: string; USU_EMAIL?: string; USU_ALIAS?: string; USU_CONTRASENIA?: string; constructor(nombre?: string, apellidos?: string, sexo?:string, fechaDeNacimiento?: string,dni?: string, direccion?: string, email?: string, alias?: string, contrasenia?: string){ this.USU_NOMBRES = nombre; this.USU_APELLIDOS = apellidos; this.USU_SEXO = sexo; this.USU_FECH_NAC = fechaDeNacimiento; this.USU_DNI = dni; this.USU_DIRECCION = direccion; this.USU_EMAIL = email; this.USU_ALIAS = alias; this.USU_CONTRASENIA = contrasenia; } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule, DatePipe} from '@angular/common'; import { UsuarioRoutingModule } from './usuario-routing.module'; import { UsuarioComponent } from './usuario.component'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ declarations: [UsuarioComponent], imports: [ CommonModule, UsuarioRoutingModule, FormsModule, ReactiveFormsModule, NgbModule ], providers: [DatePipe] }) export class UsuarioModule { }
28e37e4cbe3b32701c037ccd14c93c0c045ff4e8
[ "Markdown", "TypeScript" ]
10
TypeScript
ArgomedoKir/all
797301ebee66d17b31edc67d5a8f0fcb2911dab0
45c333061e912d660134c92a6af0c5f04211dc90
refs/heads/main
<repo_name>ujz344/ujz344<file_sep>/39.py print(549 + 348)
c51ea6ee177a3ba45cbabdd0ef4ac727c0071e3c
[ "Python" ]
1
Python
ujz344/ujz344
a633622282a6f57e3e6be1fd59e477ef51f9334f
93de32023ad9d965c5cb682c92c1d9d25e98b637
refs/heads/master
<file_sep>COVID19_JSON_DATA_FILEPATH=/Users/albert/Developer/IdeaProjects/COVID-19-DATA-CONVERTOR/output.json<file_sep>package com.ah.covid19.api.model; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; public class Location { private final String country; private final String province; private final Geography geography; public Location(String country, String province, Geography geography) { this.country = country; this.province = province; this.geography = geography; } public String getCountry() { return country; } public String getProvince() { return province; } public Geography getGeography() { return geography; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Location location = (Location) o; return new EqualsBuilder() .append(country, location.country) .append(province, location.province) .append(geography, location.geography) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .append(country) .append(province) .append(geography) .toHashCode(); } } <file_sep>###COVID-19 API based on the data on https://github.com/CSSEGISandData/COVID-19<file_sep>package com.ah.covid19.api.model; public class Geography { private final float longitude; private final float lagitude; public Geography(float longitude, float lagitude) { this.longitude = longitude; this.lagitude = lagitude; } public float getLongitude() { return longitude; } public float getLagitude() { return lagitude; } }
62355dbdfe4654010477892c8926c97760a31982
[ "Markdown", "Java", "INI" ]
4
INI
alberthhk/covid-19-api
21edc63d292465fc542145a0035b1656016def7d
20bf91718e591193fd68872684f442027a2c3502
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include "client.h" static void initialisation_si_windows(void) { #ifdef WIN32 WSADATA wsa; int err = WSAStartup(MAKEWORD(2, 2), &wsa); if(err < 0) { puts("WSAStartup failed !"); exit(EXIT_FAILURE); } #endif } static void fin_si_windows(void) { #ifdef WIN32 WSACleanup(); #endif } static void principale(const char *address,const int port, const char *name) { SOCKET sock = initialisation_connection(address, port); char buffer[TAILLE_DU_BUFFER]; fd_set rdfs; /* send our name */ ecrire_donnee_client(sock, name); while(1) { FD_ZERO(&rdfs); /* add STDIN_FILENO */ FD_SET(STDIN_FILENO, &rdfs); /* add the socket */ FD_SET(sock, &rdfs); if(select(sock + 1, &rdfs, NULL, NULL, NULL) == -1) { perror("select()"); exit(errno); } /* something from standard input : i.e keyboard */ if(FD_ISSET(STDIN_FILENO, &rdfs)) { fgets(buffer, TAILLE_DU_BUFFER - 1, stdin); { char *p = NULL; p = strstr(buffer, "\n"); if(p != NULL) { *p = 0; } else { /* fclean */ buffer[TAILLE_DU_BUFFER - 1] = 0; } } ecrire_donnee_client(sock, buffer); } else if(FD_ISSET(sock, &rdfs)) { int n = lire_donnee_client(sock, buffer); /* server down */ if(n == 0) { printf("Server disconnected !\n"); break; } puts(buffer); } } fin_connection(sock); } static int initialisation_connection(const char *address, const int port) { SOCKET sock = socket(AF_INET, SOCK_STREAM, 0); SOCKADDR_IN sin = { 0 }; struct hostent *hostinfo; if(sock == INVALID_SOCKET) { perror("socket()"); exit(errno); } hostinfo = gethostbyname(address); if (hostinfo == NULL) { fprintf (stderr, "Unknown host %s.\n", address); exit(EXIT_FAILURE); } sin.sin_addr = *(IN_ADDR *) hostinfo->h_addr; sin.sin_port = htons(port); sin.sin_family = AF_INET; if(connect(sock,(SOCKADDR *) &sin, sizeof(SOCKADDR)) == SOCKET_ERROR) { perror("connect()"); exit(errno); } return sock; } static void fin_connection(int sock) { closesocket(sock); } static int lire_donnee_client(SOCKET sock, char *buffer) { int n = 0; if((n = recv(sock, buffer, TAILLE_DU_BUFFER - 1, 0)) < 0) { perror("recv()"); exit(errno); } buffer[n] = 0; return n; } static void ecrire_donnee_client(SOCKET sock, const char *buffer) { if(send(sock, buffer, strlen(buffer), 0) < 0) { perror("send()"); exit(errno); } } int main(int argc, char **argv) { if(argc < 3) { printf("Usage : %s [address] [PORT] [pseudo]\n", argv[0]); return EXIT_FAILURE; } initialisation_si_windows(); principale(argv[1],atof(argv[2]), argv[3]); fin_si_windows(); return EXIT_SUCCESS; } <file_sep>CC=gcc CFLAGS=-Wall -g all: main main: main.o client.h clean: rm -f main.o <file_sep>#ifndef CLIENT_H #define CLIENT_H #ifdef WIN32 #include <winsock2.h> #elif defined (linux) #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> /* close */ #include <netdb.h> /* gethostbyname */ #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define closesocket(s) close(s) typedef int SOCKET; typedef struct sockaddr_in SOCKADDR_IN; typedef struct sockaddr SOCKADDR; typedef struct in_addr IN_ADDR; #else #error not defined for this platform #endif #define CRLF "\r\n" #define PORT 1977 #define TAILLE_DU_BUFFER 1024 static void initialisation_si_windows(void); static void fin_si_windows(void); static void principale(const char *address,const int port, const char *name); static int initialisation_connection(const char *address, const int port); static void fin_connection(int sock); static int lire_donnee_client(SOCKET sock, char *buffer); static void ecrire_donnee_client(SOCKET sock, const char *buffer); #endif /* guard */
df90e75387ae24793ce4567f8459c4c385d5f6ab
[ "C", "Makefile" ]
3
C
ccenyo/ReseauxClient
d67ef7b4f3a686a8e758aaafd23b11147082f1be
7a82855256b1e930421f6219fcd98d81c2b18b86
refs/heads/master
<file_sep>## Below are 2 functions that are used to create a special object ## that stores a matrix , computes and caches the inverse of the stored matrix. ##`makeCacheMatrix` creates and stores a special "matrix". ##This function also caches the inverse of the "matrix" object. ##Input Parameters: 'x' - An invertible matrix makeCacheMatrix <- function(x = matrix()) { i <- NULL set <- function(y) { x <<- y i <<- NULL } get <- function() x setinverse <- function(inverse) i <<- inverse getinverse <- function() i list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) } ## 'cacheSolve' calculates the inverse of the special "matrix" object created with the above function. ## However, it first checks to see if the inverse has already been calculated. ## If so, it gets the inverse from the cache and skips the computation. ## Otherwise, it calculates the inverse of the data and sets the value of the inverse in the cache via the setinverse function. cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' i <- x$getinverse() if(!is.null(i)) { message("getting cached data") return(i) } data <- x$get() i <- solve(data, ...) x$setinverse(i) i }
76a4d8dacc32008444c5c517a333f43a91a37bf9
[ "R" ]
1
R
yogendrapatil/ProgrammingAssignment2
7a050fc9cb5460f4b1ef0ac06c47420c642b0d49
2fafc402699f49f5544f14911678efd6a9874968
refs/heads/master
<file_sep>### CS389 HW2: Hash it out. #### <NAME> <NAME> #### IMPORTANT Compile using: `g++ -std=c++17 main.cpp` #### Part 2: Testing To test the two different evictors, `evictor_type_` must be changed in the `Impl` declaration. For FIFO evictor, use `"fifo"` and for LRU evictor, use `"lru"`. Also, uncomment the consequent evictor test in main.cpp and comment the other. #### Part 3: Performance We've implemented a universal hashing function for strings from the link(s): https://en.wikipedia.org/wiki/Universal_hashing and http://www.cse.yorku.ca/~oz/hash.html It takes some prime number that is large relative to the length of the string, bit shifts it by 5, and adds a character to that result, looping over all characters in the key, then returns the resulting hash. #### Part 4: Collision resolution Unordered map uses buckets which actually correspond to iterators into singly linked lists of the objects 'in' each bucket. There's no reason to fix what isn't broken so we've decided to just let unordered_map do its thing. This link: https://stackoverflow.com/questions/31112852/how-stdunordered-map-is-implemented/31113618#31113618 provides a stellar account of the mechanics involved in unordered_map's collision resolution. #### Part 6: Eviction policy Again, unordered map provides this functionality. We just initialize my_cache_'s max load factor to be .5, and the table does automatic resizing to handle loads above that limit. <file_sep>#include "cache.hh" #include <iostream> #include <functional> #include <algorithm> #include <cassert> #include <memory> #include <string> #include <unordered_map> #include <list> #pragma using key_equality = std::function<bool(Cache::key_type, Cache::key_type)>; // This is a universal hash function adapted from: // https://en.wikipedia.org/wiki/Universal_hashing and // djb2 from http://www.cse.yorku.ca/~oz/hash.html struct DefaultHash { u_int32_t operator()(const Cache::key_type &key) const { // Initialize p to be large prime number u_int32_t p = 5381; // Loop over each character of key for (auto letter : key) { // Bitshift the prime number p, add it to that result // add the ASCII value of the letter to that p = ((p << 5) + p) + letter; } return p; } }; struct Cache::Impl { index_type maxmem_; evictor_type evictor_; hash_func hasher_; index_type memused_; index_type items_in_; float max_load_; std::unordered_map <key_type, val_type, hash_func> my_cache_; std::list <std::string> key_list_; std::string evictor_type_; Impl(index_type maxmem, evictor_type evictor, hash_func hasher = DefaultHash()) : maxmem_(maxmem), evictor_(evictor), hasher_(hasher), memused_(0), items_in_(0), max_load_(.5), my_cache_(0, hasher), key_list_(maxmem), evictor_type_("fifo") { // Set max load factor for my_cache_ to .5 my_cache_.max_load_factor(max_load_); } ~Impl() = default; // Add a <key, value> pair to the cache. // If key already exists, it will overwrite the old value. // Both the key and the value are to be deep-copied (not just pointer copied). // If maxmem capacity is exceeded, sufficient values will be removed // from the cache to accomodate the new value. void set(key_type key, val_type val, index_type size) { if ((memused_ + size) <= maxmem_) { my_cache_.insert_or_assign(key, val); memused_ += size; evictor(evictor_type_, "include", key); assert(my_cache_.load_factor() <= my_cache_.max_load_factor()); return; } else { while ((memused_ + size) > maxmem_) evictor(evictor_type_, "evict", key); } my_cache_.insert_or_assign(key, val); memused_ += size; evictor(evictor_type_, "include", key); assert(my_cache_.load_factor() <= my_cache_.max_load_factor()); return; } // Retrieve a pointer to the value associated with key in the cache, // or NULL if not found. // Sets the actual size of the returned value (in bytes) in val_size. val_type get(key_type key, index_type &val_size) { auto search = (my_cache_).find(key); if (search != (my_cache_).end()) { // Update value stored in val_size if its in the cache. val_size = (uint32_t) sizeof(search->second); // Update key list for evictor evictor(evictor_type_, "update", key); // Return pointer to the value. val_type point_to_val = search->second; return point_to_val; } else { return NULL; } } // Delete an object from the cache, if it's still there void del(key_type key) { index_type val_size = 0; val_type is_in = get(key, val_size); if (is_in == NULL) { return; } // Reduce the size of memused_appropriately if (val_size != 0) { memused_ -= val_size; } my_cache_.erase(key); evictor(evictor_type_, "erase", key); } // Returns the amount of memory used by all cache values (not keys). index_type space_used() const { return memused_; } void evictor(std::string evictor_type = NULL, std::string action = NULL, key_type key = NULL) { if (evictor_type == "fifo") { fifo_evictor(action, key); } else if (evictor_type == "lru") { lru_evictor(action, key); } else { auto first = my_cache_.begin(); del(first->first); } } void fifo_evictor(std::string action, key_type key) { if (action == "include") { if ((std::find(key_list_.begin(), key_list_.end(), key) != key_list_.end())) { key_list_.remove(key); key_list_.push_front(key); } else { key_list_.push_front(key); } } else if (action == "delete") { key_list_.remove(key); } else if (action == "evict") { std::string fifo_key = key_list_.back().c_str(); key_list_.pop_back(); del(fifo_key); } else { return; } } void lru_evictor(std::string action, key_type key) { if (action == "include") { if ((std::find(key_list_.begin(), key_list_.end(), key) != key_list_.end())) { key_list_.remove(key); key_list_.push_front(key); } else { key_list_.push_front(key); } } else if (action == "delete") { key_list_.remove(key); } else if (action == "update") { key_list_.remove(key); key_list_.push_front(key); } else if (action == "evict") { std::string lru_key = key_list_.back(); key_list_.pop_back(); del(lru_key); } else { return; } } }; // Create a new cache object with a given maximum memory capacity. Cache::Cache(index_type maxmem, evictor_type evictor, hash_func hasher) : pImpl_(new Impl(maxmem, evictor, hasher)) { } Cache::~Cache() { } // Add a <key, value> pair to the cache. // If key already exists, it will overwrite the old value. // Both the key and the value are to be deep-copied (not just pointer copied). // If maxmem capacity is exceeded, sufficient values will be removed // from the cache to accomodate the new value. void Cache::set(key_type key, val_type val, index_type size) { pImpl_->set(key, val, size); } // Retrieve a pointer to the value associated with key in the cache, // or NULL if not found. // Sets the actual size of the returned value (in bytes) in val_size. Cache::val_type Cache::get(key_type key, index_type &val_size) const { return pImpl_->get(key, val_size); } // Delete an object from the cache, if it's still there void Cache::del(key_type key) { pImpl_->del(key); } // Compute the total amount of memory used up by all cache values (not keys) Cache::index_type Cache::space_used() const { return pImpl_->space_used(); }<file_sep>#include "testinglab.cpp" #pragma void testSet() { // Make a cache large enough to hold 2 values; // (size of value is 8 bytes, size of void pointer) Cache test_cache(16); // Initialize some keys const std::string key1 = "one"; const std::string key2 = "two"; const std::string key3 = "three"; const std::string key4 = "four"; // Initialize list of keys std::list <std::string> list_of_keys({"key1", "key2", "key3", "key4"}); // Initialize some values u_int32_t const val1 = 1; u_int32_t const val2 = 2; u_int32_t const val3 = 3; Cache::val_type point1, point2, point3; // Initialize some pointers to the values point1 = &val1; point2 = &val2; point3 = &val3; // Test to make sure space_used and insertion functions work printf("\nTEST FOR space_used AND insertion FUNCTIONS\n-------------------------------------------\n"); u_int32_t memused = test_cache.space_used(); printf("Current memory in use: %u \n", memused); printf("Inserting (key, value): (%s, %u)\n", key1.c_str(), val1); printf("Inserting (key, value): (%s, %u)\n", key2.c_str(), val2); u_int32_t size = sizeof(point1); test_cache.set("key1", point1, size); test_cache.set("key2", point2, size); memused = test_cache.space_used(); printf("Current memory in use: %u \n", memused); assert(memused == (size * 2)); printf("Elements in the cache: "); for (std::list<std::string>::const_iterator i = list_of_keys.begin(); i != list_of_keys.end(); ++i) { std::string key_to_check = i->c_str(); Cache::index_type sized; if (test_cache.get(key_to_check, sized) != NULL) { Cache::val_type thepoint = test_cache.get(key_to_check, sized); const uint32_t &theval = *(static_cast<const u_int32_t *>(thepoint)); printf("[%s, %u] ", key_to_check.c_str(), theval); } } std::cout << std::endl; // Get a value just to ensure the storage and get works correctly printf("\nTEST FOR get FUNCTION\n---------------------\n"); Cache::index_type sized; Cache::val_type thepoint = test_cache.get("key1", sized); const uint32_t &theval = *(static_cast<const u_int32_t *>(thepoint)); printf("Getting value of key1. The value is: %u\n", theval); // Ensure resizing works (Trivial, already implemented in unordered map) // Implemented as asserts within the set function // Ensure hashing works (Trivial, unordered map takes hash function and uses it properly automatically) // If values end up in buckets, (and assuming the hash is a useful function) it's working... // Initialize size address Cache::index_type get_size = 0; // Changing key values printf("\nSWAP OF VALUES OF key1 and key2\n-------------------------------\n"); test_cache.set("key1", point2, size); test_cache.set("key2", point1, size); printf("Elements in the cache: "); for (std::list<std::string>::const_iterator i = list_of_keys.begin(); i != list_of_keys.end(); ++i) { std::string key_to_check = i->c_str(); Cache::index_type sized; if (test_cache.get(key_to_check, sized) != NULL) { Cache::val_type thepoint = test_cache.get(key_to_check, sized); const uint32_t &theval = *(static_cast<const u_int32_t *>(thepoint)); printf("[%s, %u] ", key_to_check.c_str(), theval); } } printf("Swapped \n"); // Delete a key printf("\nKEY DELETION\n------------\n"); // Key 0 not in the cache test_cache.del("key0"); // Key 1 is in the cache test_cache.del("key1"); u_int32_t memused1 = test_cache.space_used(); printf("%u memused after del \n", memused1); printf("Elements in cache: "); for (std::list<std::string>::const_iterator i = list_of_keys.begin(); i != list_of_keys.end(); ++i) { std::string key_to_check = i->c_str(); Cache::index_type sized; if (test_cache.get(key_to_check, sized) != NULL) { Cache::val_type thepoint = test_cache.get(key_to_check, sized); const uint32_t &theval = *(static_cast<const u_int32_t *>(thepoint)); printf("[%s, %u] ", key_to_check.c_str(), theval); } } std::cout << std::endl; // Accessing invalid key printf("\nACCESSING INVALID KEY\n---------------------\n"); if (test_cache.get("key4", get_size) == NULL) { printf("Key \"%s\" is not in the cache \n", key4.c_str()); } ///* // FIFO evictor test printf("\nFIFO EVICTOR TEST\n-----------------\n"); // Sets a new key, evicting the first key inserted. test_cache.set("key3", point3, size); printf("Inserting (key, value): (%s, %u)\n", key3.c_str(), val3); printf("Elements in the cache: "); for (std::list<std::string>::const_iterator i = list_of_keys.begin(); i != list_of_keys.end(); ++i) { std::string key_to_check = i->c_str(); Cache::index_type sized; if (test_cache.get(key_to_check, sized) != NULL) { Cache::val_type thepoint = test_cache.get(key_to_check, sized); const uint32_t &theval = *(static_cast<const u_int32_t *>(thepoint)); printf("[%s, %u] ", key_to_check.c_str(), theval); } } std::string key_to_check = "key1"; if (test_cache.get(key_to_check, sized) == NULL) { printf("\nFIFO evictor is working"); } //*/ /* // LRU evictor test (need to change evictor type in testinglab) printf("\nLRU EVICTOR TEST\n----------------\n"); // Sets key 1 (deleted in previous tests). test_cache.set("key1", point1, size); // Access key 2 to make it last used. std::string key_to_check = "key2"; if (test_cache.get(key_to_check, sized) != NULL) { Cache::val_type thepoint = test_cache.get(key_to_check, sized); const uint32_t &theval = *(static_cast<const u_int32_t *>(thepoint)); printf("Accessing (key, value): (%s, %u)\n", key_to_check.c_str(), theval); } // Sets a new key, evicting the key with the most time unaccessed. test_cache.set("key3", point3, size); printf("Inserting (key, value): (%s, %u)\n", key3.c_str(), val3); printf("Elements in the cache: "); for (std::list<std::string>::const_iterator i = list_of_keys.begin(); i != list_of_keys.end(); ++i) { std::string key_to_check = i->c_str(); Cache::index_type sized; if (test_cache.get(key_to_check, sized) != NULL) { Cache::val_type thepoint = test_cache.get(key_to_check, sized); const uint32_t &theval = *(static_cast<const u_int32_t *>(thepoint)); printf("[%s, %u] ", key_to_check.c_str(), theval); } } // Checks if key1 is evicted (should be as the last acessed was key2). key_to_check = "key1"; if (test_cache.get(key_to_check, sized) == NULL) { printf("\nLRU evictor is working"); } */ } int main() { testSet(); std::cout << std::endl; return 0; }
4103add74f054585f9f021d5ae865b41345028ce
[ "Markdown", "C++" ]
3
Markdown
Continuousbutnotdifferentiable/csci_389_hw2
c56fccf30884b729439b503137adbe76d0314b62
2e2b5472740b79fc2315663a9f73146c8afc265a
refs/heads/master
<repo_name>korynewton/Sorting<file_sep>/src/recursive_sorting/recursive_sorting.py # TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): elements = len(arrA) + len(arrB) # temporary list with 0 as placeholders merged_arr = [0] * elements # TO-DO # initialize index evaluators at 0 j, k, l = 0, 0, 0 # while both of the lists have not been icremented through while j < len(arrA) and k < len(arrB): if arrA[j] < arrB[k]: # replace placeholder with smaller item merged_arr[l] = arrA[j] # increment evaluation index on arrA and merged_arr l += 1 j += 1 else: # replace placeholder with smaller item merged_arr[l] = arrB[k] # increment evaluation index on arrB and merged_arr l += 1 k += 1 # Will only run if arrA has not been incremented through while j < len(arrA): merged_arr[l] = arrA[j] l += 1 j += 1 # Will only run if arrB has not been incremented through while k < len(arrB): merged_arr[l] = arrB[k] l += 1 k += 1 return merged_arr # TO-DO: implement the Merge Sort function below USING RECURSION def merge_sort(arr): print('merge_sort called') if len(arr) > 1: print("array", arr) print("length", len(arr)) mid = len(arr)//2 left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) arr = merge(left, right) return arr # print(merge_sort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])) # print(merge_sort([10, 1])) # STRETCH: implement an in-place merge sort algorithm def merge_in_place(arr, start, mid, end): # TO-DO return arr def merge_sort_in_place(arr, l, r): # TO-DO return arr # STRETCH: implement the Timsort function below # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt def timsort(arr): return arr <file_sep>/src/iterative_sorting/iterative_sorting.py # TO-DO: Complete the selection_sort() function below def selection_sort(arr): # loop through n-1 elements print('before sort', arr) for i in range(0, len(arr) - 1): cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # (hint, can do in 3 loc) for j in range(cur_index+1, len(arr)): if (arr[smallest_index] > arr[j]): smallest_index = j # TO-DO: swap arr[i], arr[smallest_index] = arr[smallest_index], arr[i] # print('after sort', arr) return arr # selection_sort([1, 5, 8, 4, 2, 9, 6, 0, 3, 7]) def bubble_sort(arr): print('before sort:', arr) # Loop through elements] repeat = True while repeat: repeat = False for i in range(0, len(arr) - 1): # if current item is greater than the next item, swap items if (arr[i] > arr[i+1]): arr[i], arr[i+1] = arr[i+1], arr[i] # Reset repeat variable so it loops at least one more time repeat = True print('after:', arr) return arr # bubble_sort([1, 5, 8, 4, 2, 9, 6, 0, 3, 7]) # STRETCH: implement the Count Sort function below def count_sort(arr, maximum=-1): return arr
6fa3533b0e8f0787b1cd3c9d831d56487001fa03
[ "Python" ]
2
Python
korynewton/Sorting
478b747176368b03265509fe4a792c3a6ec1ac9c
46188ab457bc89799776a182cb46c348cd263a18
refs/heads/master
<file_sep>'use strict'; const path = require('path'); const moment = require('moment'); const express = require('express'); const app = express(); app.set('port', (process.env.PORT || 5000)); app.use(express.static(path.resolve(__dirname, 'client'))); app.get('/:timestamp', (req,res) => { let time = moment(req.params.timestamp, 'MMMM DD, YYYY', true); if (!time.isValid()) time = moment.unix(req.params.timestamp); if (!time.isValid()) { res.json({ 'humanReadable': null, 'unix': null }); } res.json({ 'humanReadable': time.format('MMMM DD, YYYY'), 'unix': time.format('X') }); }); app.listen(app.get('port'), () => { console.log(`Server listening on port ${app.get('port')}`); });<file_sep># Timestamp Microservice API ## What is this? This is a microservice API project for Free Code Camp that will accept either a human readable date or a unix formatted date and return a json response with the date formatted as both. If the input is neither it will return `null` values. You can test it at [https://immense-brushlands-3354.herokuapp.com/](https://immense-brushlands-3354.herokuapp.com/) ### Usage ``` https://immense-brushlands-3354.herokuapp.com/January 10, 2015 ``` ``` https://immense-brushlands-3354.herokuapp.com/1420848000 ``` ### Sample Output ```javascript { humanReadable: "January 10, 2015", unix: "1420848000" } ``` ### Running this project Simply launch it with node using `npm run start` or `node server.js`.
c8d03e4c30dcafb29d9eb15f75d4067db38bc060
[ "JavaScript", "Markdown" ]
2
JavaScript
ltegman/timestamp-microservice-api
0f4584c3a7f66420627fca638a321c608d13b541
c9af6bd4d85af6f867d055a9479315d2518f03af
refs/heads/master
<file_sep>import { Controller, Get } from '@nestjs/common'; import { UserService } from './user.service'; import { createConnection } from 'typeorm'; import { TUser } from '../entities/TUser'; @Controller('user') export class UserController { constructor(private readonly userService: UserService) {} @Get('get_all') getAll() { try { await createConnection(); // typeORM db connection console.log('typeORM DB 커넥션 생성됨'); //SQL : selct * from User const users = await TUser.find(); console.log(users); //SQL : select * from User where User.email = '<EMAIL>' const userFound = await User.findOne({email: "<EMAIL>"}); console.log(userFound); return 'done'; } catch (err) { console.log(err); } //return this.userService.getHello(); } } <file_sep>import { Controller, Get, HttpException, UseInterceptors, } from '@nestjs/common'; import { AppService } from './app.service'; import { SuccessInterceptor } from './common/interceptors/success.interceptor'; @UseInterceptors(SuccessInterceptor) @Controller() export class AppController { constructor(private readonly appService: AppService) {} @Get() getHello(): string { // ## __dirname: H:\MyProjects\NestJs\teaching_nestjs\testnest\dist\src console.log(`## __dirname: ${__dirname}`); //throw new HttpException('error test', 200); return this.appService.getHello(); } } <file_sep>import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; import { MongooseModule } from '@nestjs/mongoose'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { CatsModule } from './cats/cats.module'; import { LoggerMiddleware } from './common/middlewares/logger.middleware'; import { ConfigModule } from '@nestjs/config'; import { AuthModule } from './auth/auth.module'; import { UsersModule } from './users/users.module'; import * as mongoose from 'mongoose'; import { TypeOrmModule } from '@nestjs/typeorm'; import { UserModule } from './user/user.module'; import { OrderModule } from './order/order.module'; import { join } from 'path'; @Module({ imports: [ ConfigModule.forRoot(), MongooseModule.forRoot(process.env.MONGODB_CONN, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false, }), TypeOrmModule.forRoot({ type: 'mysql', host: 'localhost', port: 3306, username: 'root', password: '<PASSWORD>', database: 'mydb', entities: [join(__dirname, '/**/*.entity.ts'), 'src/entities/*.ts'], // 설정 부분 synchronize: true, autoLoadEntities: false, }), CatsModule, AuthModule, UsersModule, UserModule, OrderModule, ], controllers: [AppController], providers: [AppService], }) export class AppModule implements NestModule { private readonly isDev: boolean = process.env.MODE === 'dev' ? true : false; configure(consumer: MiddlewareConsumer) { consumer.apply(LoggerMiddleware).forRoutes('*'); mongoose.set('debug', this.isDev); } } <file_sep>import { ApiProperty, PickType } from '@nestjs/swagger'; import { Cat } from '../../../schemas/cat.schema'; /** response로 보낼때 사용하는 dto */ export class ReadOnlyCatDto extends PickType(Cat, ['email', 'name'] as const) { // schema에선 정의하지 않았지만 monoose가 자동으로 주는 필드 @ApiProperty({ example: '3280199', description: 'id', }) id: string; } <file_sep>import { Column, Entity, Index, JoinColumn, ManyToOne, PrimaryGeneratedColumn, } from "typeorm"; import { TUser } from "./TUser"; @Index("user_id", ["userId"], {}) @Entity("t_order", { schema: "mydb" }) export class TOrder { @PrimaryGeneratedColumn({ type: "int", name: "id" }) id: number; @Column("int", { name: "user_id", nullable: true }) userId: number | null; @Column("varchar", { name: "iorder", nullable: true, length: 255 }) iorder: string | null; @ManyToOne(() => TUser, (tUser) => tUser.tOrders, { onDelete: "CASCADE", onUpdate: "CASCADE", }) @JoinColumn([{ name: "user_id", referencedColumnName: "id" }]) user: TUser; } <file_sep>import { Injectable } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; /** guard 에서 strategy가 자동으로 실행 * 정확히 말하면 컨트롤러에서 @useguard(JwtAuthGuard) 이런식으로 사용 * * JwtAuthGuard를 발동시키면 jwt.strategy 안에있는 validate 함수가 발동된다 */ @Injectable() export class JwtAuthGuard extends AuthGuard('jwt') {} <file_sep>import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from "typeorm"; import { TOrder } from "./TOrder"; @Entity("t_user", { schema: "mydb" }) export class TUser { @PrimaryGeneratedColumn({ type: "int", name: "id" }) id: number; @Column("varchar", { name: "name", nullable: true, length: 255 }) name: string | null; @OneToMany(() => TOrder, (tOrder) => tOrder.user) tOrders: TOrder[]; } <file_sep>import { Injectable, NestMiddleware } from '@nestjs/common'; import { Response, Request, NextFunction } from 'express'; @Injectable() export class LoggerMiddleware implements NestMiddleware { use(req: Request, res: Response, next: NextFunction) { console.log(`## ip: ${req.ip}`); next(); } }
d67540f47905a4613cf8ba6173491659056fce4b
[ "TypeScript" ]
8
TypeScript
najongjine/nestjs
1ba4672fdb51e6a685d4ab1ba43a7eabacf2297e
fcb87050978cf3963bfe671888cf49acd846cdd6
refs/heads/master
<repo_name>m4rcelpl/PodatnicyVAT<file_sep>/BialaLista.Standard/VatDataReader.Standard.cs using BialaLista.data; using System; using System.Net.Http; using Newtonsoft.Json; using System.Threading.Tasks; namespace BialaLista.Standard { public class VatDataReader { private readonly HttpClient httpClient; public VatDataReader(HttpClient httpClient, string url = "https://wl-api.mf.gov.pl") { httpClient.BaseAddress = new Uri(url); this.httpClient = httpClient; } /// <summary> /// Zwraca EntityResponse na podstawie podanego numeru nip. /// </summary> /// <param name="nip">Numer NIP</param> /// <param name="dateTime">Data sprawdzenia</param> /// <returns>EntityResponse</returns> public async Task<EntityResponse> GetDataFromNipAsync(string nip, DateTime dateTime) { string GetString = string.Empty; try { if (!Extension.IsValidNIP(nip)) throw new System.Exception($"Invalid nip {nip} format"); var Getresult = await httpClient.GetAsync($"/api/search/nip/{nip}?date={dateTime.ToString("yyyy-MM-dd")}"); GetString = await Getresult.Content.ReadAsStringAsync(); if (Getresult.IsSuccessStatusCode) { return JsonConvert.DeserializeObject<EntityResponse>(GetString); } return new EntityResponse { Exception = JsonConvert.DeserializeObject<data.Exception>(GetString) }; } catch (System.Exception) { throw; } } /// <summary> /// Zwraca EntityListResponse na podstawie podanych numerów nip. Można podać maksymalnie 30 numerów, oddzielonych przecinkami bez spacji. /// </summary> /// <param name="nips">Numery Nip</param> /// <param name="dateTime">Data sprawdzenia</param> /// <returns>EntityListResponse</returns> public async Task<EntityListResponse> GetDataFromNipsAsync(string nips, DateTime dateTime) { string GetString = string.Empty; try { foreach (var item in nips.Split(',')) { if (!Extension.IsValidNIP(item)) throw new System.Exception($"Invalid nip {item} format"); } var Getresult = await httpClient.GetAsync($"/api/search/nips/{nips}?date={dateTime.ToString("yyyy-MM-dd")}"); GetString = await Getresult.Content.ReadAsStringAsync(); if (Getresult.IsSuccessStatusCode) { return JsonConvert.DeserializeObject<EntityListResponse>(GetString); } return new EntityListResponse { Exception = JsonConvert.DeserializeObject<data.Exception>(GetString) }; } catch (System.Exception) { throw; } } /// <summary> /// Zwraca EntityResponse na podstawie podanego numeru Regon. /// </summary> /// <param name="regon">Numer Regon</param> /// <param name="dateTime">Data sprawdzenia</param> /// <returns>EntityResponse</returns> public async Task<EntityResponse> GetDataFromRegonAsync(string regon, DateTime dateTime) { string GetString = string.Empty; try { if (!Extension.IsValidREGON(regon)) throw new System.Exception($"Invalid nip {regon} format"); var Getresult = await httpClient.GetAsync($"/api/search/regon/{regon}?date={dateTime.ToString("yyyy-MM-dd")}"); GetString = await Getresult.Content.ReadAsStringAsync(); if (Getresult.IsSuccessStatusCode) { return JsonConvert.DeserializeObject<EntityResponse>(GetString); } return new EntityResponse { Exception = JsonConvert.DeserializeObject<data.Exception>(GetString) }; } catch (System.Exception) { throw; } } /// <summary> /// Zwraca EntityListResponse na podstawie podanych numerów regon. Można podać maksymalnie 30 numerów, oddzielonych przecinkami bez spacji. /// </summary> /// <param name="regons">Numer Regon</param> /// <param name="dateTime">Data sprawdzenia</param> /// <returns>EntityListResponse</returns> public async Task<EntityListResponse> GetDataFromRegonsAsync(string regons, DateTime dateTime) { string GetString = string.Empty; try { foreach (var item in regons.Split(',')) { if (!Extension.IsValidREGON(item)) throw new System.Exception($"Invalid nip {item} format"); } var Getresult = await httpClient.GetAsync($"/api/search/regons/{regons}?date={dateTime.ToString("yyyy-MM-dd")}"); GetString = await Getresult.Content.ReadAsStringAsync(); if (Getresult.IsSuccessStatusCode) { return JsonConvert.DeserializeObject<EntityListResponse>(GetString); } return new EntityListResponse { Exception = JsonConvert.DeserializeObject<data.Exception>(GetString) }; } catch (System.Exception) { throw; } } /// <summary> /// Zwraca EntityListResponse na podstawie podanego konta bankowego. /// </summary> /// <param name="bankAccount"></param> /// <param name="dateTime"></param> /// <returns></returns> public async Task<EntityListResponse> GetDataFromBankAccountAsync(string bankAccount, DateTime dateTime) { string GetString = string.Empty; try { if (!Extension.IsValidBankAccountNumber(bankAccount)) throw new System.Exception($"Invalid Bank Account {bankAccount} format"); var Getresult = await httpClient.GetAsync($"/api/search/bank-account/{bankAccount}?date={dateTime.ToString("yyyy-MM-dd")}"); GetString = await Getresult.Content.ReadAsStringAsync(); if (Getresult.IsSuccessStatusCode) { return JsonConvert.DeserializeObject<EntityListResponse>(GetString); } return new EntityListResponse { Exception = JsonConvert.DeserializeObject<data.Exception>(GetString) }; } catch (System.Exception) { throw; } } /// <summary> /// Zwraca EntityListResponse na podstawie podanych konta bakowych. Można podać maksymalnie 30 numerów kont bankowych, rozdzielonych przecinkami bez spacji. /// </summary> /// <param name="bankAccounts">Numery kont bankowych</param> /// <param name="dateTime">Data sprawdzenia</param> /// <returns>EntityListResponse<returns> public async Task<EntityListResponse> GetDataFromBankAccountsAsync(string bankAccounts, DateTime dateTime) { string GetString = string.Empty; try { foreach (var item in bankAccounts.Split(',')) { if (!Extension.IsValidBankAccountNumber(item)) throw new System.Exception($"Invalid Bank Account {item} format"); } var Getresult = await httpClient.GetAsync($"/api/search/bank-accounts/{bankAccounts}?date={dateTime.ToString("yyyy-MM-dd")}"); GetString = await Getresult.Content.ReadAsStringAsync(); if (Getresult.IsSuccessStatusCode) { return JsonConvert.DeserializeObject<EntityListResponse>(GetString); } return new EntityListResponse { Exception = JsonConvert.DeserializeObject<data.Exception>(GetString) }; } catch (System.Exception) { throw; } } /// <summary> /// Zwraca EntityCheckResponse na podstawie podanego numeru nip i konta bankowego. /// </summary> /// <param name="nip"></param> /// <param name="bankAccount"></param> /// <param name="dateTime"></param> /// <returns></returns> public async Task<EntityCheckResponse> CheckFromNipAndBankAccountsAsync(string nip, string bankAccount, DateTime dateTime) { string GetString = string.Empty; try { if (!Extension.IsValidNIP(nip)) throw new System.Exception($"Invalid nip {nip} format"); var Getresult = await httpClient.GetAsync($"/api/check/nip/{nip}/bank-account/{bankAccount}?date={dateTime.ToString("yyyy-MM-dd")}"); GetString = await Getresult.Content.ReadAsStringAsync(); if (Getresult.IsSuccessStatusCode) { return JsonConvert.DeserializeObject<EntityCheckResponse>(GetString); } return new EntityCheckResponse { Exception = JsonConvert.DeserializeObject<data.Exception>(GetString) }; } catch (System.Exception) { throw; } } /// <summary> /// Zwraca EntityCheckResponse na podstawie podanego numeru nip i konta bankowego. /// </summary> /// <param name="regon"></param> /// <param name="bankAccount"></param> /// <param name="dateTime"></param> /// <returns></returns> public async Task<EntityCheckResponse> CheckFromRegonAndBankAccountsAsync(string regon, string bankAccount, DateTime dateTime) { string GetString = string.Empty; try { if (!Extension.IsValidREGON(regon)) throw new System.Exception($"Invalid nip {regon} format"); var Getresult = await httpClient.GetAsync($"/api/check/regon/{regon}/bank-account/{bankAccount}?date={dateTime.ToString("yyyy-MM-dd")}"); GetString = await Getresult.Content.ReadAsStringAsync(); if (Getresult.IsSuccessStatusCode) { return JsonConvert.DeserializeObject<EntityCheckResponse>(GetString); } return new EntityCheckResponse { Exception = JsonConvert.DeserializeObject<data.Exception>(GetString) }; } catch (System.Exception) { throw; } } } }<file_sep>/BialaLista/data/EntityPerson.cs using System.Runtime.Serialization; using System.Text.Json.Serialization; namespace BialaLista.data { /// <summary> /// /// </summary> [DataContract] public class EntityPerson : Person { /// <summary> /// Gets or Sets CompanyName /// </summary> [DataMember(Name = "companyName", EmitDefaultValue = false)] [JsonPropertyName("companyName")] public string CompanyName { get; set; } } }<file_sep>/BialaLista/data/Person.cs using System.Runtime.Serialization; using System.Text.Json.Serialization; namespace BialaLista.data { /// <summary> /// /// </summary> [DataContract] public class Person { /// <summary> /// Gets or Sets FirstName /// </summary> [DataMember(Name = "firstName", EmitDefaultValue = false)] [JsonPropertyName("firstName")] public string FirstName { get; set; } /// <summary> /// Gets or Sets LastName /// </summary> [DataMember(Name = "lastName", EmitDefaultValue = false)] [JsonPropertyName("lastName")] public string LastName { get; set; } /// <summary> /// Gets or Sets Pesel /// </summary> [DataMember(Name = "pesel", EmitDefaultValue = false)] [JsonPropertyName("pesel")] public Pesel Pesel { get; set; } /// <summary> /// Gets or Sets Nip /// </summary> [DataMember(Name = "nip", EmitDefaultValue = false)] [JsonPropertyName("nip")] public string Nip { get; set; } } }<file_sep>/BialaLista.Standard/data/EntityPerson.cs using System.Runtime.Serialization; using Newtonsoft.Json; namespace BialaLista.data { /// <summary> /// /// </summary> [DataContract] public class EntityPerson : Person { /// <summary> /// Gets or Sets CompanyName /// </summary> [DataMember(Name = "companyName", EmitDefaultValue = false)] [JsonProperty(PropertyName = "companyName")] public string CompanyName { get; set; } } }<file_sep>/README.md # 💥 Uwaga! Ten pakiet jest przestarzały i nie będzie aktualizowany. Proszę użyć nowego: https://github.com/m4rcelpl/WykazPodatnikow # 💥 Warning! This package is outdated and will not be updated. Please use a new one: https://github.com/m4rcelpl/WykazPodatnikow<file_sep>/BialaLista.xUnitTests/VatDataReader.cs using System; using System.Net.Http; using System.Threading.Tasks; using Xunit; namespace BialaLista.xUnitTests { public class BialaLista { [Theory] [InlineData("6222468959")] public async Task GetDataFromNipAsync(string nip) { var vatDataReader = new VatDataReader(new HttpClient()); var result = await vatDataReader.GetDataFromNipAsync(nip, DateTime.Now); Assert.NotNull(result.Result.RequestId); Assert.Contains(nip, result.Result.Subject.Nip); Assert.Null(result.Exception); } [Theory] [InlineData("6222468959,7811835788,5423288666", 3)] public async Task GetDataFromNipsAsync(string nips, int ReturnCount) { var vatDataReader = new VatDataReader(new HttpClient()); var result = await vatDataReader.GetDataFromNipsAsync(nips, DateTime.Now); Assert.True(result.Result.Subjects.Count == ReturnCount); Assert.NotNull(result.Result.RequestId); Assert.Null(result.Exception); } [Theory] [InlineData("251546820")] public async Task GetDataFromRegonAsync(string regon) { var vatDataReader = new VatDataReader(new HttpClient()); var result = await vatDataReader.GetDataFromRegonAsync(regon, DateTime.Now); Assert.NotNull(result.Result.RequestId); Assert.Contains(regon, result.Result.Subject.Regon); Assert.Null(result.Exception); } [Theory] [InlineData("251546820,301087548,368793892", 3)] public async Task GetDataFromRegonsAsync(string regons, int ReturnCount) { var vatDataReader = new VatDataReader(new HttpClient()); var result = await vatDataReader.GetDataFromRegonsAsync(regons, DateTime.Now); Assert.True(result.Result.Subjects.Count == ReturnCount); Assert.NotNull(result.Result.RequestId); Assert.Null(result.Exception); } [Theory] [InlineData("23109011600000000101980438")] public async Task GetDataFromBankAccountAsync(string bankaccount) { var vatDataReader = new VatDataReader(new HttpClient()); var result = await vatDataReader.GetDataFromBankAccountAsync(bankaccount, DateTime.Now); Assert.NotNull(result.Result.RequestId); Assert.Null(result.Exception); } [Theory] [InlineData("74175010190000000011453438,23109011600000000101980438,50109025900000000135521483", 3)] public async Task GetDataFromBankAccountsAsync(string bankaccounts, int ReturnCount) { var vatDataReader = new VatDataReader(new HttpClient()); var result = await vatDataReader.GetDataFromBankAccountsAsync(bankaccounts, DateTime.Now); Assert.True(result.Result.Subjects.Count == ReturnCount); Assert.NotNull(result.Result.RequestId); Assert.Null(result.Exception); } [Theory] [InlineData("6222468959", "92103011460000000086837021")] public async Task CheckFromNipAndBankAccountsAsync(string nip, string bankaccount) { var vatDataReader = new VatDataReader(new HttpClient()); var result = await vatDataReader.CheckFromNipAndBankAccountsAsync(nip, bankaccount, DateTime.Now); Assert.NotNull(result.Result.RequestId); Assert.Contains(result.Result.AccountAssigned, "TAK"); } [Theory] [InlineData("251546820", "92103011460000000086837021")] public async Task CheckFromRegonAndBankAccountsAsync(string regon, string bankaccount) { var vatDataReader = new VatDataReader(new HttpClient()); var result = await vatDataReader.CheckFromRegonAndBankAccountsAsync(regon, bankaccount, DateTime.Now); Assert.NotNull(result.Result.RequestId); Assert.Contains(result.Result.AccountAssigned, "TAK"); } } }<file_sep>/BialaLista.ConsoleTest/Program.cs using System; using System.Net.Http; namespace BialaLista.ConsoleTest { internal class Program { private static async System.Threading.Tasks.Task Main(string[] args) { string nip = "5270103391"; string regon = "010016565"; string bankaccount = "72103015080000000500217006"; Console.WriteLine("Start!"); var vatDataReader = new VatDataReader(new HttpClient()); try { Console.WriteLine($"Sprawdzam firmę na podstawie NIP: {nip}"); var resultNip = await vatDataReader.GetDataFromNipAsync(nip, DateTime.Now); if (resultNip.Exception is null) { Console.WriteLine($"Id sprawdzenia: {resultNip.Result?.RequestId}"); Console.WriteLine($"Nazwa firmy: {resultNip.Result?.Subject.Name}"); Console.WriteLine($"Regon: {resultNip.Result?.Subject.Regon}"); Console.WriteLine($"Status VAT: {resultNip.Result?.Subject.StatusVat}"); Console.WriteLine($"Konta bankowe:"); foreach (var item in resultNip.Result?.Subject?.AccountNumbers) { Console.WriteLine(item); } Console.WriteLine(); } else { Console.WriteLine($"Wystąpił błąd podczas sprawdzania: Kod {resultNip.Exception.Code} | Komunikat: {resultNip.Exception.Message}"); } } catch (Exception ex) { Console.WriteLine($"[Błąd] {ex.Message}"); } try { Console.WriteLine($"Sprawdzam firmę na podstawie Regon: {regon}"); var resultRegon = await vatDataReader.GetDataFromRegonAsync(regon, DateTime.Now); if (resultRegon.Exception is null) { Console.WriteLine($"Id sprawdzenia: {resultRegon.Result?.RequestId}"); Console.WriteLine($"Nazwa firmy: {resultRegon.Result?.Subject.Name}"); Console.WriteLine($"Regon: {resultRegon.Result?.Subject.Regon}"); Console.WriteLine($"Status VAT: {resultRegon.Result?.Subject.StatusVat}"); Console.WriteLine($"Konta bankowe:"); foreach (var item in resultRegon.Result?.Subject.AccountNumbers) { Console.WriteLine(item); } } else { Console.WriteLine($"Wystąpił błąd podczas sprawdzania: Kod {resultRegon.Exception.Code} | Komunikat: {resultRegon.Exception.Message}"); } Console.WriteLine(); } catch (Exception ex) { Console.WriteLine($"[Błąd] {ex.Message}"); } try { Console.WriteLine($"Sprawdzam parę nip: {nip} i numeru konta: {bankaccount}"); var resultCheckNip = await vatDataReader.CheckFromNipAndBankAccountsAsync(nip, bankaccount, DateTime.Now); if (resultCheckNip.Exception is null) { Console.WriteLine($"Id sprawdzenia: {resultCheckNip.Result?.RequestId}"); Console.WriteLine($"Zwrócony status: {resultCheckNip.Result?.AccountAssigned}"); } else { Console.WriteLine($"Wystąpił błąd podczas sprawdzania: Kod {resultCheckNip.Exception.Code} | Komunikat: {resultCheckNip.Exception.Message}"); } Console.WriteLine(); } catch (Exception ex) { Console.WriteLine($"[Błąd] {ex.Message}"); } try { Console.WriteLine($"Sprawdzam parę regon: {regon} i numeru konta: {bankaccount}"); var resultCheckRegon = await vatDataReader.CheckFromRegonAndBankAccountsAsync(regon, bankaccount, DateTime.Now); if (resultCheckRegon.Exception is null) { Console.WriteLine($"Id sprawdzenia: {resultCheckRegon.Result?.RequestId}"); Console.WriteLine($"Zwrócony status: {resultCheckRegon.Result?.AccountAssigned}"); } else { Console.WriteLine($"Wystąpił błąd podczas sprawdzania: Kod {resultCheckRegon.Exception.Code} | Komunikat: {resultCheckRegon.Exception.Message}"); } } catch (Exception ex) { Console.WriteLine($"[Błąd] {ex.Message}"); } Console.ReadLine(); } } }
d7871b4b36cad5050a3cb0786f84a8099e49f641
[ "Markdown", "C#" ]
7
C#
m4rcelpl/PodatnicyVAT
cfd82904563df00f732ceabbdc3024d04cbd0e39
e6da9deffaf37f6c6b91bd89b35b96a70e41fe09
refs/heads/master
<file_sep>import { Video } from '@andyet/simplewebrtc'; export class VideoChatRoom extends React.Component { constructor(props) { super(props); } render() { return <h1>ruin</h1> } } <file_sep>const jwt = require('jsonwebtoken') export default function validateUserData( req, res ) { console.log(jwt.verify(req.headers.token, "<PASSWORD>" ), 'exp:::::') res.end() }<file_sep> import {Input} from "../../CommonComponents/Input"; export const GetUserData = ({}) => { return( <form> <label>Whats your name</label> <Input /> </form> ) }<file_sep>import {connect} from 'react-redux'; import { VideoChatRoom } from '../components/VideoChatRoom'; import { Actions } from "@andyet/simplewebrtc"; const mapStateToProps = (state /*, ownProps*/) => { console.log(state) return { calls: state.calls } } console.log(Actions) const mapDispatchToProps = () => { getMediaTrack:Actions.getMediaTrack() } export default connect( mapStateToProps, mapDispatchToProps )(VideoChatRoom) <file_sep>// import { VideoChat } from '../VideoChat/container' import dynamic from 'next/dynamic' const VideoChatInitiator = dynamic( () => import('../components/VideoChat'), { ssr: false, loading: () => <p>...</p> } ) export default function() { return <VideoChatInitiator /> }<file_sep>import { PeerList, RemoteMediaList, Video } from '@andyet/simplewebrtc'; import React from "react"; export const PeersGrid = ({roomAddress}) => { console.log(roomAddress) return( <PeerList room={roomAddress} render={({ peers }) => peers.map(peer => { // The content of `peer.customerData` is the data // from the token used by that peer. return ( <div> <p>media terrorists</p> <RemoteMediaList peer={peer.address} render={({ media }) => { console.log(media, 'media') return ( <> a hole in the sky <Video media={media[1]}/> </> ) }} /> </div> ); }) } /> ) };
f901a11a52de5395ef97a547b29e9b92184631dd
[ "JavaScript" ]
6
JavaScript
Leefeater/bistromatic
72540ec2237e2d69a686cedd22553adff5e7cca4
e6b133df5292e4a2cfd224e31fc9fe15708baea5
refs/heads/master
<repo_name>MadMaxOfYore/PrisonTextGame<file_sep>/PrisonTextGame.Unity/PrisonTextGame/Assets/Scripts/PrisonIntroScene.cs using UnityEngine; using UnityEngine.UI; namespace Assets { public class PrisonIntroScene : MonoBehaviour { private GameManager gameManagerScript { get { return GameManager.Instance; } } public Text messageToUserTextPlaceholder; public void Update() { messageToUserTextPlaceholder.text = gameManagerScript.MessageToPlayer; } } } <file_sep>/PrisonTextGame.Core/Entities/GameContext.cs using PrisonTextGame.Core.GameState; using System.Collections.Generic; namespace PrisonTextGame.Core.Entities { public class GameContext { public GameContext() { CurrentGameState = new IntroductionGameState(); } public string CurrentScene { get { return CurrentGameState.SceneName; } } public string MessageToPlayer { get { return CurrentGameState.MessageToPlayer; } } public IEnumerable<string> CurrentDecisionCodes { get { return CurrentGameState.DecisionCodes; } } internal void UpdateGameState(IGameState nextGameState) { CurrentGameState = nextGameState; } public void ProcessDecision(string decisionCode) { CurrentGameState.HandleDecision(this, decisionCode); } internal IGameState CurrentGameState { get; private set; } } } <file_sep>/PrisonTextGame.Core/GameState/CellInitialVisitState.cs using System.Text; namespace PrisonTextGame.Core.GameState { internal class CellInitialVisitState : GameStateBase { public static string GetMessageToPlayer() { var sb = new StringBuilder(); sb.Append("You are awoken by a loud voice in what you assume is a prison cell. "); sb.Append("There is no light aside from the glow coming from the small window in the door. "); sb.AppendLine("You notice some dirty sheets on the bed, a mirror on the wall, and the sound of the door being locked from the outside."); sb.AppendLine(); sb.Append("Press S to view the sheets, M to view Mirror and L to view Lock"); return sb.ToString(); } public CellInitialVisitState() { MessageToPlayer = GetMessageToPlayer(); SceneName = "PrisonIntroScene"; populateNextGameStateOptions(); } private void populateNextGameStateOptions() { NextStateMapping.Add("S", typeof(DirtySheetsInitialVisitState)); //TODO: Write the state objects for the Mirror and Cell Lock scenes and map them to the appropriate key here. } } }<file_sep>/PrisonTextGame.Core.Tests/GameStateTests/BaseBehaviorTests/HandleDecisionTests.cs using FluentAssertions; using NSubstitute; using NUnit.Framework; using PrisonTextGame.Core.Entities; using PrisonTextGame.Core.GameState; using System; using System.Collections.Generic; namespace PrisonTextGame.Core.Tests.GameStateTests.BaseBehaviorTests { [TestFixture] public class HandleDecisionTests { [Test] public void HandleDecisionShouldDoNothingForUnmappedDecisionCode() { //Arrange var nextGameState = Substitute.For<IGameState>(); var mapping = new Dictionary<string, Type>(); var gameStateBase = Substitute.For<GameStateBase>(); gameStateBase.NextStateMapping.Returns(mapping); var gameContext = new GameContext(); //Act gameStateBase.HandleDecision(gameContext, "A"); //Assert gameContext.CurrentGameState.Should().BeAssignableTo<IntroductionGameState>(); } [Test] public void ProcessKeyDownShouldChangeStateForMappedKeyCode() { //Arrange const string DecisionCode = "A"; var nextGameStateType = typeof(Fakes.FakeGameState); var mapping = new Dictionary<string, Type>(); mapping.Add(DecisionCode, nextGameStateType); var gameStateBase = Substitute.For<GameStateBase>(); gameStateBase.NextStateMapping.Returns(mapping); var gameContext = new GameContext(); //Act gameStateBase.HandleDecision(gameContext, DecisionCode); //Assert gameContext.CurrentGameState.Should().BeAssignableTo(nextGameStateType); } } } <file_sep>/PrisonTextGame.Core/GameState/IntroductionGameState.cs using System.Text; namespace PrisonTextGame.Core.GameState { internal class IntroductionGameState : GameStateBase { //This method is a static member of the IntroductionGameState class because we want access to it in our testing framework. //Ideally, static text like this would be stored in a resources file and accessed via a provider so that it can be swapped //out based on localization requirements. //Ex: Display this chunck of text for English speaking players vs this chunk for Spanish speaking players. // //This is just a cheap way of demonstrating a more important point I wanted to make - design code to be testable from the ground up. //In the future, we can kill this static member and replace it by injecting a resources provider into this state object. The state //object could then reach into the provider to retrieve the appropriage verbiage. Our external testing framework would also be able to use //the same provider to assert that the state is displaying the expected message for the given locale. public static string GetMessageToPlayer() { var sb = new StringBuilder(); sb.AppendLine("Wake up worm!"); sb.AppendLine(); //TODO: The text with instructions to the user should be generated within the presentation layer. // This should not exist in any of our state objects. Instead, the UI should read through the decision codes and have mapping // mechanism that translates our decsion codes into key mappings for the given environment (PC, XBox, PS4, etc...) // // I have not done so for a couple of reasons. The first is time - I don't have it =) // The other is that I would like for you to try and figure that part out if to can. sb.Append("Press Space to continue."); return sb.ToString(); } //Your object should be in a competely valid state immediately after construction. Don't design objects that have a "load" or "init" //method that has to be called by a consumer after a "new" declaration. Doing so is like establishing a secret handshake that everyone //that wants to use your object must know just to take advantage of some core business functionlaity. // //Secret handshakes are for douchbags... public IntroductionGameState() { MessageToPlayer = GetMessageToPlayer(); SceneName = "PrisonIntroScene"; populateNextGameStateOptions(); } private void populateNextGameStateOptions() { //I am only using "keyboard" key names for simplicity of this demonstration. In reality, the "Space" keyword should be something like //"CELL_INITIAL." I should then have a mapping of some kind that translates "CELL_INITIAL" to the Space Bar on a PC or the touch pad on a PS4 controller. // //The ideal option would be to establish an Options API (Option 1, Option 2, etc..) //A state object would map it's "next states" to these options, while the presentation layer (Unity) would map environment appropriate keys to the same options. //Ex: IntroductionState maps "CellInitial" to "Option 1." In Unity, the PC key to choose any Option 1 (regardless of GameState) is the Space Bar whereas //the PS4 key for Option 1 could be Touch Pad. The difference is that "Space Bar" could never be used to select Option 2 on any other state. NextStateMapping.Add("Space", typeof(CellInitialVisitState)); } } } <file_sep>/PrisonTextGame.Core.Tests/GameStateTests/DirtySheetTests/ProgressStateTests.cs using FluentAssertions; using NSubstitute; using NUnit.Framework; using PrisonTextGame.Core.Entities; using PrisonTextGame.Core.GameState; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PrisonTextGame.Core.Tests.GameStateTests.DirtySheetTests { [TestFixture] public class ProgressStateTests { [Test] public void InitialVisitShouldProceedToCellReturnVisitState() { //Arrange var gameContext = new GameContext(); var dirtySheetsState = new DirtySheetsInitialVisitState(); //Act dirtySheetsState.HandleDecision(gameContext, "R"); //Assert gameContext.CurrentGameState.Should().BeAssignableTo<CellReturnFromSheetsState>(); } [Test] public void ReturnVisitShouldProceedToCellReturnVisitState() { //Arrange var gameContext = new GameContext(); var dirtySheetsState = new DirtySheetsReturnVisitState(); //Act dirtySheetsState.HandleDecision(gameContext, "R"); //Assert gameContext.CurrentGameState.Should().BeAssignableTo<CellReturnFromSheetsState>(); } } } <file_sep>/PrisonTextGame.Core/GameState/DirtySheetsInitialVisitState.cs using System.Text; namespace PrisonTextGame.Core.GameState { internal class DirtySheetsInitialVisitState : GameStateBase { public static string GetMessageToPlayer() { var sb = new StringBuilder(); sb.AppendLine("Looks like the last resident had a bit of a bladder problem. Gross..."); sb.AppendLine("Press R to return to roaming your cell."); return sb.ToString(); } public DirtySheetsInitialVisitState() { MessageToPlayer = GetMessageToPlayer(); SceneName = "PrisonIntroScene"; populateNextGameStateOptions(); } private void populateNextGameStateOptions() { NextStateMapping.Add("R", typeof(CellReturnFromSheetsState)); } } } <file_sep>/PrisonTextGame.Core/GameState/GameStateBase.cs using PrisonTextGame.Core.Entities; using System; using System.Collections.Generic; namespace PrisonTextGame.Core.GameState { internal abstract class GameStateBase : IGameState { public virtual string MessageToPlayer { get; protected set; } public virtual string SceneName { get; protected set; } public virtual IEnumerable<string> DecisionCodes { get { foreach(string decisionCode in NextStateMapping.Keys) { yield return decisionCode; } } } protected internal virtual Dictionary<string, Type> NextStateMapping { get; private set; } public GameStateBase() { NextStateMapping = new Dictionary<string, Type>(); } public void HandleDecision(GameContext gameContext, string decisionCode) { if (!NextStateMapping.ContainsKey(decisionCode)) { return; } var nextGameStateType = NextStateMapping[decisionCode]; var nextGameState = (IGameState) Activator.CreateInstance(nextGameStateType); gameContext.UpdateGameState(nextGameState); } } } <file_sep>/PrisonTextGame.Core.Tests/GameStateTests/IntroductionState/ProgressStateTests.cs using FluentAssertions; using NSubstitute; using NUnit.Framework; using PrisonTextGame.Core.Entities; using PrisonTextGame.Core.GameState; using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace PrisonTextGame.Core.Tests.GameStateTests.IntroductionState { [TestFixture] public class ProgressStateTests { [Test] public void ShouldSetGameContextCurrentStateToCellInitialVisitStateOnSpaceBarClick() { //Arrange var gameContext = new GameContext(); var introductionState = new IntroductionGameState(); //Act introductionState.HandleDecision(gameContext, "Space"); //Assert gameContext.CurrentGameState.Should().BeAssignableTo<CellInitialVisitState>(); } } } <file_sep>/PrisonTextGame.Core.Tests/GameContextTests/ApplyStateTests.cs using FluentAssertions; using NSubstitute; using NUnit.Framework; using PrisonTextGame.Core.Entities; using PrisonTextGame.Core.GameState; namespace PrisonTextGame.Core.Tests.GameContextTests { [TestFixture] public class ApplyStateTests { [Test] public void CtorShouldInitializeToIntroductionState() { //Act var gameContext = new GameContext(); //Assert gameContext.CurrentGameState.Should().BeAssignableTo<IntroductionGameState>(); gameContext.MessageToPlayer.Should().Be(IntroductionGameState.GetMessageToPlayer()); gameContext.CurrentScene.Should().Be("PrisonIntroScene"); } [Test] public void UpdateShouldSetState() { //Arrange var changedState = Substitute.For<IGameState>(); var gameContext = new GameContext(); //Act gameContext.UpdateGameState(changedState); //Assert gameContext.CurrentGameState.Should().Be(changedState); } } } <file_sep>/PrisonTextGame.Unity/PrisonTextGame/Assets/Scripts/GameManager.cs using UnityEngine; using PrisonTextGame.Core.Entities; using System.Collections.Generic; using UnityEngine.SceneManagement; public class GameManager : MonoBehaviour { internal static GameManager Instance { get; set; } private List<KeyCode> actionKeys; private GameContext Context { get; set; } internal string MessageToPlayer { get; private set; } //This is a simple method of synchronizing access to shared resources in a multithreaded environment. //If we have detected a valid key press and are changing game state, then there is a chance that the next frame could trigger an update before our state change is complete. //If that happens, then we will be looping through the ActiveKeys collection while also changing the referece to the collection - big no, no. //By using a spinlock in the getter/setter as I've done here, we ensure that the reference to the collection is kept clean and we do not get dirty reads. //Additionally, we lock on the same blocker object during frame update to ensure that the collection is not replaced while we are iterating over it. private object actionKeysAccessBlocker = new object(); private List<KeyCode> ActionKeys { get { lock (actionKeysAccessBlocker) { return actionKeys; } } set { lock (actionKeysAccessBlocker) { actionKeys = value; } } } void Awake () { if (Instance == null) { Instance = this; } else if (Instance != this) { Destroy(gameObject); } DontDestroyOnLoad(gameObject); Context = new GameContext(); UpdateUI(); } void Update () { lock (actionKeysAccessBlocker) { foreach (KeyCode actionKey in ActionKeys) { if (Input.GetKeyDown(actionKey)) { var decisionCode = System.Enum.GetName(typeof(KeyCode), actionKey); Context.ProcessDecision(decisionCode); UpdateUI(); } } } } private void UpdateUI() { MessageToPlayer = Context.MessageToPlayer; var actionKeysList = new List<KeyCode>(); foreach (string decisionCode in Context.CurrentDecisionCodes) { var mappedKeyCode = (KeyCode)System.Enum.Parse(typeof(KeyCode), decisionCode); actionKeysList.Add(mappedKeyCode); } ActionKeys = actionKeysList; SceneManager.LoadScene(Context.CurrentScene); } } <file_sep>/PrisonTextGame.Core.Tests/GameStateTests/CellInitialVisitStateTests/ProgressStateTests.cs using FluentAssertions; using NUnit.Framework; using PrisonTextGame.Core.Entities; using PrisonTextGame.Core.GameState; namespace PrisonTextGame.Core.Tests.GameStateTests.CellInitialVisitStateTests { [TestFixture] public class ProgressStateTests { private GameContext gameContext; private IGameState state; [SetUp] public void Setup() { //Arrange gameContext = new GameContext(); state = new CellInitialVisitState(); } [Test] public void ProceedToDirtySheets() { //Act state.HandleDecision(gameContext, "S"); //Assert gameContext.CurrentGameState.Should().BeAssignableTo<DirtySheetsInitialVisitState>(); } [Test] public void ProceedToMirrorInitialVisit() { //Act state.HandleDecision(gameContext, "M"); //Assert Assert.Fail(); } [Test] public void ProceedToLockInitialVisit() { //Act state.HandleDecision(gameContext, "L"); //Assert Assert.Fail(); } } } <file_sep>/PrisonTextGame.Core/GameState/CellReturnFromSheetsState.cs using System.Text; namespace PrisonTextGame.Core.GameState { internal class CellReturnFromSheetsState : GameStateBase { private static string GetMessageToPlayer() { var sb = new StringBuilder(); sb.AppendLine("You return to deliriously gazing about the room. Nothing has changed except the faint odor of tinkle lingers in the air."); sb.AppendLine("Press S to view the sheets, M to view Mirror and L to view Lock"); return sb.ToString(); } public CellReturnFromSheetsState() { MessageToPlayer = GetMessageToPlayer(); SceneName = "PrisonIntroScene"; populateNextGameStateOptions(); } private void populateNextGameStateOptions() { NextStateMapping.Add("S", typeof(DirtySheetsReturnVisitState)); //TODO: Write the state objects for the Mirror and Cell Lock scenes and map them to the appropriate key here. } } } <file_sep>/PrisonTextGame.Core.Tests/Fakes/FakeGameState.cs using PrisonTextGame.Core.GameState; using System; using System.Collections.Generic; using System.Linq; using System.Text; using PrisonTextGame.Core.Entities; using UnityEngine; namespace PrisonTextGame.Core.Tests.Fakes { public class FakeGameState : IGameState { public string SceneName { get; private set; } public IEnumerable<string> DecisionCodes { get { throw new NotImplementedException(); } } public string MessageToPlayer { get; private set; } public void HandleDecision(GameContext gameContext, string decisionCode) { } } } <file_sep>/PrisonTextGame.Core/GameState/DirtySheetsReturnVisitState.cs using System.Text; namespace PrisonTextGame.Core.GameState { internal class DirtySheetsReturnVisitState : DirtySheetsInitialVisitState { public static new string GetMessageToPlayer() { var sb = new StringBuilder(); sb.AppendLine("Oh look..."); sb.AppendLine("Nevermind... The odorous splotches of yellow look exactly like they did before."); sb.AppendLine("Go figure!"); sb.AppendLine(); sb.AppendLine("Press R to return to roaming your cell."); return sb.ToString(); } public DirtySheetsReturnVisitState() { MessageToPlayer = GetMessageToPlayer(); } } } <file_sep>/PrisonTextGame.Core.Tests/GameStateTests/CellReturnVisitStateTests/ProcessStateTests.cs using FluentAssertions; using NUnit.Framework; using PrisonTextGame.Core.Entities; using PrisonTextGame.Core.GameState; namespace PrisonTextGame.Core.Tests.GameStateTests.CellReturnVisitStateTests { [TestFixture] public class ProcessStateTests { private GameContext gameContext; private IGameState state; [SetUp] public void Setup() { //Arrange gameContext = new GameContext(); state = new CellReturnFromSheetsState(); } [Test] public void ProceedToDirtySheetsOnSKeyDown() { //Act state.HandleDecision(gameContext, "S"); //Assert gameContext.CurrentGameState.Should().BeAssignableTo<DirtySheetsReturnVisitState>(); } [Test] public void ProceedToMirrorInitialVisitOnMKeyDown() { //Act state.HandleDecision(gameContext, "M"); //Assert //This forces the test to fail. I've done this to stub out the test for you to complete. //Make sure you remove Assert.Fail when you're done. Assert.Fail(); } [Test] public void ProceedToLockInitialVisitOnLKeyDown() { //Act state.HandleDecision(gameContext, "L"); //Assert Assert.Fail(); } } } <file_sep>/PrisonTextGame.Core/GameState/IGameState.cs using PrisonTextGame.Core.Entities; using System.Collections.Generic; namespace PrisonTextGame.Core.GameState { public interface IGameState { string MessageToPlayer { get; } string SceneName { get; } IEnumerable<string> DecisionCodes { get; } void HandleDecision(GameContext gameContext, string decisionCode); } }
f615344ef1f6c613262edfc38dc543af9f1384a3
[ "C#" ]
17
C#
MadMaxOfYore/PrisonTextGame
41d9fcf7576e0ee25b2b3b81bc173b8a5788faaf
ef70723c351c349cae6434e20880ba345ff471a3
refs/heads/master
<repo_name>Axorion/shingshang<file_sep>/src/presentation/MainConsole.java package presentation; import java.util.List; import abstraction.Board; import abstraction.BushiType; import abstraction.Cell; import abstraction.Game; import abstraction.Player; /** Class gathering all the stuff linked to the console (output and input) * @author <NAME> */ public class MainConsole { // CONSTANTS private final static int NB_LIN = 10; private final static int NB_COL = 10; private final static int X = 0; private final static int Y = 1; // METHODS /** * Displays the board in the console * @param board the board to display on console * @see Board */ static public void displayBoard(Board board) { for (int lin = 0 ; lin < NB_LIN ; lin++ ) { for (int col = 0 ; col < NB_COL ; col++) { displayCell(board.board[col][lin]); System.out.print(" "); } System.out.print("\n\n"); } } /** * Displays a cell in the console. There are different representations depending on the cell state. * @param cell the cell to display on console * @see Cell */ static private void displayCell(Cell cell) { String cellString = ""; if(cell.getBushi() != null) { if(cell.getBushi().getOwner()==Game.player1) cellString += "P1"; else if(cell.getBushi().getOwner()==Game.player2) cellString += "P2"; else cellString += "P?"; } if(cell.isPortal() && cell.getBushi() == null) { cellString += ("|P|"); } else if(!cell.isValid()) { cellString += (" ⬛ "); } else if(cell.isEmpty()) { cellString += (" □ "); } else if(cell.getBushi().getBushiType() == BushiType.DRAGON) { cellString += ("D"); } else if(cell.getBushi().getBushiType() == BushiType.LION) { cellString += ("L"); } else if(cell.getBushi().getBushiType() == BushiType.MONKEY) { cellString += ("M"); } else // Unrecognized { cellString += (" ? "); } System.out.print(cellString); } /** * Displays the current player of the game in the console */ static public void displayCurrentPlayer() { System.out.println(Game.currentPlayer.getPseudonym() + " it is your turn!"); } /** * Displays the current winner of the game in the console */ static public void displayWinner() { System.out.println("The player " + Game.winner.getPseudonym() + " wins! Congratulations!"); } /** * Displays the cells where bushi selected can move in the console * @param cellsWhereBushiSelectedCanMove the cells to display * @see Cell */ static public void displayCellsWhereBushiSelectedCanMove(List<Cell> cellsWhereBushiSelectedCanMove) { System.out.println("Cells were bushi selected can move : "); for(Cell cell : cellsWhereBushiSelectedCanMove) { int[] coordinatesOfCell = Game.board.getCoordinatesOfCell(cell); System.out.println("(" + coordinatesOfCell[X] + "," + coordinatesOfCell[Y] + ")"); } } /** * Alerts the player that he is in Shing Shang, also ask if he wants to continue to jump or not in the console. * @return the choice of the player to continue to jump or not */ static public boolean alertShingShang() { boolean continueShingShang = false; char response = 'X'; while(response != 'Y' && response != 'y' && response != 'N' && response != 'n') { System.out.println("Shing Shang! \n" + "Do you want to jump again?! (Y/N)"); response = Clavier.lireChar(); if(response == 'Y' || response == 'y' || response == 'N'|| response == 'n') { if(response == 'Y' || response == 'y') continueShingShang = true; else if(response == 'N' || response == 'n') continueShingShang = false; } } return continueShingShang; } /** * Alerts the player that he is ate an opponent's bushi, also ask if he wants to continue to play the round or not in the console. * @return the choice of the player to continue to jump or not */ static public boolean alertHasEatenBushi() { boolean continueShingShang = false; char response = 'X'; while(response != 'Y' && response != 'y' && response != 'N' && response != 'n') { System.out.println("You have eaten a bushi! \n" + "Do you want to continue to play the round (with another bushi)?! (Y/N)"); response = Clavier.lireChar(); if(response == 'Y' || response == 'y' || response == 'N'|| response == 'n') { if(response == 'Y' || response == 'y') continueShingShang = true; else if(response == 'N' || response == 'n') continueShingShang = false; } } return continueShingShang; } /** * Asks to the 2 players their pseudonyms * @param players the players of the game * @see Player */ static public void askPseudonyms(List<Player> players) { int currentNbPlayer = 1; for(Player player : players) { System.out.println("Player" + currentNbPlayer + ", enter your pseudonym : "); String playerPseudonym = Clavier.lireString(); if(!playerPseudonym.isBlank()) player.setPseudonym(playerPseudonym); currentNbPlayer++; } } /** * Asks the coordinates of the bushi to select * @return the coordinates of the bushi to select */ static public int[] askCoordinatesOfBushiToSelect() { int[] coordinatesOfCellToSelect = new int[2]; int x = -1; int y = -1; coordinatesOfCellToSelect[X] = x; coordinatesOfCellToSelect[Y] = y; System.out.println("\nPlease select one of your bushi (that hasn't eaten this round)"); while(coordinatesOfCellToSelect[X] == -1) { System.out.println("Enter the column (>=0 && =<9) : "); x = Clavier.lireInt(); if(x >= 0 && x <= 9) coordinatesOfCellToSelect[X] = x; } while(coordinatesOfCellToSelect[Y] == -1) { System.out.println("Enter the line (>=0 && =<9) : "); y = Clavier.lireInt(); if(y >= 0 && y <= 9) coordinatesOfCellToSelect[Y] = y; } return coordinatesOfCellToSelect; } /** * Asks the coordinates where the player wants to move the bushi selected * @return the coordinates where to move bushi selected */ static public int[] askCoordinatesWhereToMoveBushiSelected() { int[] coordinatesOfCellToSelect = new int[2]; int x = -1; int y = -1; coordinatesOfCellToSelect[X] = x; coordinatesOfCellToSelect[Y] = y; System.out.println("\nPlease select the cell where to move your bushi"); while(coordinatesOfCellToSelect[X] == -1) { System.out.println("Enter the column (>=0 && =<9) : "); x = Clavier.lireInt(); if(x >= 0 && x <= 9) coordinatesOfCellToSelect[X] = x; } while(coordinatesOfCellToSelect[Y] == -1) { System.out.println("Enter the line (>=0 && =<9) : "); y = Clavier.lireInt(); if(y >= 0 && y <= 9) coordinatesOfCellToSelect[Y] = y; } return coordinatesOfCellToSelect; } }<file_sep>/test/abstraction/GameTest.java package abstraction; import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class GameTest { Game game; @BeforeEach void setUp() throws Exception { this.game = new Game(true, new Player("Player1"), new Player("Player2")); } @Test public void cells_where_bushi_can_move() { List<Cell> cellsWhereBushiCanMove = new ArrayList<Cell>(); Bushi bushi = Game.board.getCell(2, 1).getBushi(); // This bushi can theorically move to the cells at coordinates : // (0,-1) (2,-1) (4,-1) (All are outside the board) // (0,1) (0,3) (All are invalid cells) // (1,0) (1,1) (1,2) (All are already occupied) // (2,0) (2,2) (2,3) ((2,0) is already occupied)) // (3,0) (3,1) (3,2) ((3,0) is already occupied)) // (4,3) // So in reality, he can move to the cells at coordinates : // (2,2) (2,3) // (3,1) (3,2) // (4,3) Game.cellSelected = bushi.getPosition(); List<Cell> cellsWhereBushiShouldBeAbleToMove = new ArrayList<Cell>(); Cell c2l2 = Game.board.getCell(2, 2); Cell c2l3 = Game.board.getCell(2, 3); Cell c3l1 = Game.board.getCell(3, 1); Cell c3l2 = Game.board.getCell(3, 2); Cell c4l3 = Game.board.getCell(4, 3); cellsWhereBushiShouldBeAbleToMove.add(c2l2); cellsWhereBushiShouldBeAbleToMove.add(c2l3); cellsWhereBushiShouldBeAbleToMove.add(c3l1); cellsWhereBushiShouldBeAbleToMove.add(c3l2); cellsWhereBushiShouldBeAbleToMove.add(c4l3); cellsWhereBushiCanMove.addAll(Game.board.getCellsWhereBushiSelectedCanMove()); assertEquals(cellsWhereBushiCanMove, cellsWhereBushiShouldBeAbleToMove); } @Test public void check_if_player_owns_bushi_selected() { Cell cellWhereAPlayer1BushiIs = Game.board.getCell(1, 0); Bushi bushiOwnedByPlayer1 = cellWhereAPlayer1BushiIs.getBushi(); Cell cellWhereAPlayer2BushiIs = Game.board.getCell(1, 8); Bushi bushiOwnedByPlayer2 = cellWhereAPlayer2BushiIs.getBushi(); assertEquals(bushiOwnedByPlayer1.getOwner(), Game.player1); assertEquals(bushiOwnedByPlayer2.getOwner(), Game.player2); } @Test public void player1_wins_because_player2_has_no_dragon() { Cell cellWhereDragon1OfPlayer2Is = Game.board.getCell(1, 9); Cell cellWhereDragon2OfPlayer2Is = Game.board.getCell(8, 9); cellWhereDragon1OfPlayer2Is.removeBushi(); cellWhereDragon2OfPlayer2Is.removeBushi(); Player winner = Game.board.checkVictory(); assertEquals(Game.player1, winner); } @Test public void player1_wins_because_has_dragon_on_opponent_portal() { Cell cellWhereADragonOfPlayer1Is = Game.board.getCell(1, 0); Bushi aDragonOfPlayer1 = cellWhereADragonOfPlayer1Is.getBushi(); Cell aPortalOfPlayer2 = Game.board.getCell(4, 8); aDragonOfPlayer1.moveToCell(aPortalOfPlayer2); Player winner = Game.board.checkVictory(); assertEquals(Game.player1, winner); } } <file_sep>/src/abstraction/Board.java package abstraction; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import java.lang.Math; /** Represents the board. * @author <NAME> */ public class Board { // CONSTANTS private final static int NB_LIN = 10; private final static int NB_COL = 10; private final static int X = 0; private final static int Y = 1; // INSTANCE VARIABLES (ATTRIBUTES) /** * The board of the game, it's a two dimension tab of Cell */ public Cell board[][]; // METHODS /** * Constructor initializing the Board with the beginning placement of the bushis */ public Board() { reset(); } /** * Resets the board placing the bushis to their beginning placement */ public void reset() { resetBoard(); resetBushis(); } /** * Part of the constructor initializing the board with empty cells */ private void resetBoard() { board = new Cell[NB_COL][NB_LIN]; for (int col = 0 ; col < NB_LIN ; col++ ) { for (int lin = 0 ; lin < NB_COL ; lin++) { // Initialize all cells which are not portals or invalid cells if(((col != 4 || col != 5) && (lin != 1 || lin != 8)) && ((col != 0 && col != 9) || (lin == 4 || lin == 5))) board[col][lin] = new Cell(false, true); // Initialize portals if((col == 4 || col == 5) && (lin == 1 || lin == 8)) board[col][lin] = new Cell(true, true); // Initialize invalid cells if((col == 0 || col == 9) && (lin != 4 && lin != 5)) board[col][lin] = new Cell(false, false); } } } /** * Part of the constructor initializing the bushis on the board */ private void resetBushis() { new Bushi(BushiType.DRAGON, Game.player1, board[1][0]); new Bushi(BushiType.DRAGON, Game.player1, board[8][0]); new Bushi(BushiType.DRAGON, Game.player2, board[1][9]); new Bushi(BushiType.DRAGON, Game.player2, board[8][9]); new Bushi(BushiType.LION, Game.player1, board[2][0]); new Bushi(BushiType.LION, Game.player1, board[7][0]); new Bushi(BushiType.LION, Game.player1, board[1][1]); new Bushi(BushiType.LION, Game.player1, board[8][1]); new Bushi(BushiType.LION, Game.player2, board[2][9]); new Bushi(BushiType.LION, Game.player2, board[7][9]); new Bushi(BushiType.LION, Game.player2, board[1][8]); new Bushi(BushiType.LION, Game.player2, board[8][8]); new Bushi(BushiType.MONKEY, Game.player1, board[3][0]); new Bushi(BushiType.MONKEY, Game.player1, board[6][0]); new Bushi(BushiType.MONKEY, Game.player1, board[2][1]); new Bushi(BushiType.MONKEY, Game.player1, board[7][1]); new Bushi(BushiType.MONKEY, Game.player1, board[1][2]); new Bushi(BushiType.MONKEY, Game.player1, board[8][2]); new Bushi(BushiType.MONKEY, Game.player2, board[3][9]); new Bushi(BushiType.MONKEY, Game.player2, board[6][9]); new Bushi(BushiType.MONKEY, Game.player2, board[2][8]); new Bushi(BushiType.MONKEY, Game.player2, board[7][8]); new Bushi(BushiType.MONKEY, Game.player2, board[1][7]); new Bushi(BushiType.MONKEY, Game.player2, board[8][7]); } /** * Returns a Cell object * @param col the column of the cell * @param lin the line of the cell * @return the cell at the position [col][lin] * @see Cell */ public Cell getCell(int col, int lin) { return board[col][lin]; } /** * Returns the coordinates in the board of a Cell object * @param cell the cell you want to get the coordinates * @return int[] the coordinates of the cell * @see Cell */ public int[] getCoordinatesOfCell(Cell cell) { int[] coordinates = new int[2]; for (int col = 0 ; col < NB_LIN ; col++ ) { for (int lin = 0 ; lin < NB_COL ; lin++) { if(getCell(col,lin) == cell) { coordinates[X] = col; coordinates[Y] = lin; } } } return coordinates; } /** * Returns a list of cells where the bushi selected can move * @return the cells where the bushi selected can move * @see Cell */ public List<Cell> getCellsWhereBushiSelectedCanMove() { List<Cell> cellsWhereBushiSelectedCanMove = new ArrayList<Cell>(); cellsWhereBushiSelectedCanMove.addAll(getCellsWhichBushiSelectedCanReach()); this.removeCellsBlockedByOtherBushi(cellsWhereBushiSelectedCanMove); cellsWhereBushiSelectedCanMove.addAll(getCellsWhereBushiSelectedCanJump()); this.removeCellsInvalidInList(cellsWhereBushiSelectedCanMove); this.removeCellsOccupiedInList(cellsWhereBushiSelectedCanMove); if(Game.cellSelected.getBushi().getBushiType() != BushiType.DRAGON) this.removeCellsPortalInList(cellsWhereBushiSelectedCanMove); return cellsWhereBushiSelectedCanMove; } /** * Returns a list of cells which the bushi selected can reach * @return the cells which the bushi selected can reach * @see Cell */ private List<Cell> getCellsWhichBushiSelectedCanReach() { List<Cell> cellsWhichBushiSelectedCanReach = new ArrayList<Cell>(); int[] coordinatesOfCellSelected = getCoordinatesOfCell(Game.cellSelected); Bushi bushiSelected = Game.cellSelected.getBushi(); int movementPoint = bushiSelected.getMovementPoint(); for(int i = coordinatesOfCellSelected[X] - movementPoint ; i <= coordinatesOfCellSelected[X] + movementPoint ; i++) { for(int j = coordinatesOfCellSelected[Y] - movementPoint ; j <= coordinatesOfCellSelected[Y] + movementPoint ; j++) { if(i >= 0 && i < NB_LIN && j >= 0 && j < NB_LIN) { // Exclude the cellSelected if(!(coordinatesOfCellSelected[X] == i && coordinatesOfCellSelected[Y] == j)) { // Add cells which the Bushi can reach horizontally and vertically if(coordinatesOfCellSelected[X] == i || coordinatesOfCellSelected[Y] == j) { cellsWhichBushiSelectedCanReach.add(getCell(i,j)); } // Add cells which the Bushi can reach diagonally else if((Math.abs(coordinatesOfCellSelected[X] - i) == 1 && (Math.abs(coordinatesOfCellSelected[Y] - j) == 1 || (Math.abs(coordinatesOfCellSelected[Y] + j) == 1)) || (Math.abs(coordinatesOfCellSelected[X] + i) == 1 && (Math.abs(coordinatesOfCellSelected[Y] - j) == 1 || (Math.abs(coordinatesOfCellSelected[Y] + j) == 1))))) { cellsWhichBushiSelectedCanReach.add(getCell(i,j)); } else if ((Math.abs(coordinatesOfCellSelected[X] - Math.abs(i)) == 2) && (Math.abs(coordinatesOfCellSelected[Y] - Math.abs(j)) == 2)) { cellsWhichBushiSelectedCanReach.add(getCell(i,j)); } } } } } return cellsWhichBushiSelectedCanReach; } /** * Returns a list of cells where the bushi selected can jump * @return the cells where the bushi selected can jump * @see Cell */ public List<Cell> getCellsWhereBushiSelectedCanJump() { List<Cell> cellsWhereBushiSelectedCanJump = new ArrayList<Cell>(); List<Cell> cellsCloseToBushiSelected = new ArrayList<Cell>(); cellsCloseToBushiSelected.addAll(this.getCellsCloseToBushiSelected()); ListIterator<Cell> itCell = cellsCloseToBushiSelected.listIterator(); while(itCell.hasNext()) { Cell currentCell = itCell.next(); if(currentCell.getBushi() != null) { if(!this.checkIfBushiSelectedCanJumpOver(currentCell.getBushi())) { itCell.remove(); } else { int[] coordinatesOfBushiSelectedAfterJumpingOverOtherBushi = getCoordinatesOfBushiSelectedAfterJumpingOver(currentCell.getBushi()); Cell cellWhereBushiSelectedJump = this.getCell(coordinatesOfBushiSelectedAfterJumpingOverOtherBushi[X], coordinatesOfBushiSelectedAfterJumpingOverOtherBushi[Y]); cellsWhereBushiSelectedCanJump.add(cellWhereBushiSelectedJump); } } else { itCell.remove(); } } return cellsWhereBushiSelectedCanJump; } /** * Returns a list of cells close to the bushi selected * @return the cells close to the bushi selected * @see Cell */ private List<Cell> getCellsCloseToBushiSelected() { List<Cell> cellsCloseToBushiSelected = new ArrayList<Cell>(); int[] coordinatesOfCellSelected = getCoordinatesOfCell(Game.cellSelected); for(int i = coordinatesOfCellSelected[X] - 1 ; i <= coordinatesOfCellSelected[X] + 1 ; i++) { for(int j = coordinatesOfCellSelected[Y] - 1 ; j <= coordinatesOfCellSelected[Y] + 1 ; j++) { if(i >= 0 && i < NB_LIN && j >= 0 && j < NB_LIN) { // Exclude the cellSelected if(!(coordinatesOfCellSelected[X] == i && coordinatesOfCellSelected[Y] == j)) { cellsCloseToBushiSelected.add(getCell(i,j)); } } } } return cellsCloseToBushiSelected; } /** * Returns a boolean indicating if the bushi selected can jump over the other bushi * @param otherBushi the other bushi over which the bushi selected jumps * @return a boolean indicating if the bushi selected can jump over the other bushi * @see Bushi */ private boolean checkIfBushiSelectedCanJumpOver(Bushi otherBushi) { boolean bushiSelectedCanMoveOverOtherBushi = false; boolean bushiIsBiggerOrEqualThanOtherBushi = false; boolean bushiSelectedWillLandOnTheBoard = false; if(Game.cellSelected.getBushi() != null) { Bushi bushiSelected = Game.cellSelected.getBushi(); bushiIsBiggerOrEqualThanOtherBushi = bushiSelected.isBiggerOrEqualThan(otherBushi); int[] coordinatesOfBushiSelectedAfterJumpingOverOtherBushi = getCoordinatesOfBushiSelectedAfterJumpingOver(otherBushi); bushiSelectedWillLandOnTheBoard = coordinatesOfBushiSelectedAfterJumpingOverOtherBushi[X] >= 0 && coordinatesOfBushiSelectedAfterJumpingOverOtherBushi[X] < NB_LIN && coordinatesOfBushiSelectedAfterJumpingOverOtherBushi[Y] >= 0 && coordinatesOfBushiSelectedAfterJumpingOverOtherBushi[Y] < NB_LIN; } bushiSelectedCanMoveOverOtherBushi = bushiIsBiggerOrEqualThanOtherBushi && bushiSelectedWillLandOnTheBoard; return bushiSelectedCanMoveOverOtherBushi; } /** * Returns the coordinates in the board of the bushi selected after jumping overt the other bushi * @param otherBushi the other bushi over which the bushi selected jumps * @return int[] the coordinates of the cell * @see Bushi */ private int[] getCoordinatesOfBushiSelectedAfterJumpingOver(Bushi otherBushi) { Bushi bushiSelected = Game.cellSelected.getBushi(); int[] coordinatesOfBushiSelected = this.getCoordinatesOfCell(bushiSelected.getPosition()); int[] coordinatesOfOtherBushi = this.getCoordinatesOfCell(otherBushi.getPosition()); if(coordinatesOfBushiSelected[X] < coordinatesOfOtherBushi[X]) { coordinatesOfBushiSelected[X] = coordinatesOfOtherBushi[X] + 1; } else if(coordinatesOfBushiSelected[X] > coordinatesOfOtherBushi[X]) { coordinatesOfBushiSelected[X] = coordinatesOfOtherBushi[X] - 1; } if(coordinatesOfBushiSelected[Y] < coordinatesOfOtherBushi[Y]) { coordinatesOfBushiSelected[Y] = coordinatesOfOtherBushi[Y] + 1; } else if(coordinatesOfBushiSelected[Y] > coordinatesOfOtherBushi[Y]) { coordinatesOfBushiSelected[Y] = coordinatesOfOtherBushi[Y] - 1; } return coordinatesOfBushiSelected; } /** * Removes the cells occupied from a list of cells * @param cells a list of cell * @return a list of cell where none is occupied * @see Cell */ private List<Cell> removeCellsOccupiedInList(List<Cell> cells) { ListIterator<Cell> itCell = cells.listIterator(); while(itCell.hasNext()) { if(!itCell.next().isEmpty()) itCell.remove(); } return cells; } /** * Removes the cells which are portals from a list of cells * @param cells a list of cell * @return a list of cell where none is a portal * @see Cell */ private List<Cell> removeCellsPortalInList(List<Cell> cells) { ListIterator<Cell> itCell = cells.listIterator(); while(itCell.hasNext()) { if(itCell.next().isPortal()) itCell.remove(); } return cells; } /** * Removes the invalid cells from a list of cells * @param cells a list of cell * @return a list of cell where none is invalid * @see Cell */ private List<Cell> removeCellsInvalidInList(List<Cell> cells) { ListIterator<Cell> itCell = cells.listIterator(); while(itCell.hasNext()) { if(!itCell.next().isValid()) itCell.remove(); } return cells; } /** * Returns the cell between the two cells passed in parameters * @param Cell the first cell * @param Cell the second cell * @return the cell between the two cells passed in parameters * @see Cell */ private Cell getCellBetweenTwoCells(Cell firstCell, Cell secondCell) { int[] coordinatesOfCellBetweenCellSelectedAndOtherCell = new int[2]; int[] coordinatesOfFirstCell = getCoordinatesOfCell(firstCell); int[] coordinatesOfSecondCell = getCoordinatesOfCell(secondCell); if(coordinatesOfSecondCell[X] < coordinatesOfFirstCell[X] && coordinatesOfFirstCell[X] - 2 == coordinatesOfSecondCell[X]) { coordinatesOfCellBetweenCellSelectedAndOtherCell[X] = coordinatesOfFirstCell[X]-1; } else if (coordinatesOfSecondCell[X] > coordinatesOfFirstCell[X] && coordinatesOfFirstCell[X] + 2 == coordinatesOfSecondCell[X]) { coordinatesOfCellBetweenCellSelectedAndOtherCell[X] = coordinatesOfFirstCell[X]+1; } else coordinatesOfCellBetweenCellSelectedAndOtherCell[X] = coordinatesOfFirstCell[X]; if(coordinatesOfSecondCell[Y] < coordinatesOfFirstCell[Y] && coordinatesOfFirstCell[Y] - 2 == coordinatesOfSecondCell[Y]) { coordinatesOfCellBetweenCellSelectedAndOtherCell[Y] = coordinatesOfFirstCell[Y]-1; } else if (coordinatesOfSecondCell[Y] > coordinatesOfFirstCell[Y] && coordinatesOfFirstCell[Y] + 2 == coordinatesOfSecondCell[Y]) { coordinatesOfCellBetweenCellSelectedAndOtherCell[Y] = coordinatesOfFirstCell[Y]+1; } else coordinatesOfCellBetweenCellSelectedAndOtherCell[Y] = coordinatesOfFirstCell[Y]; if(!(coordinatesOfCellBetweenCellSelectedAndOtherCell[X] == coordinatesOfFirstCell[X] && coordinatesOfCellBetweenCellSelectedAndOtherCell[Y] == coordinatesOfFirstCell[Y])) { return getCell(coordinatesOfCellBetweenCellSelectedAndOtherCell[X], coordinatesOfCellBetweenCellSelectedAndOtherCell[Y]); } else { return null; } } /** * Removes the cells blocked by other bushi (there is a bushi between the bushi selected and the cell he can reach) * @param cells a list of cell * @return a list of cell blocked by other bushi * @see Cell */ private List<Cell> removeCellsBlockedByOtherBushi(List<Cell> cells) { ListIterator<Cell> itCell = cells.listIterator(); while(itCell.hasNext()) { Cell currentCell = itCell.next(); Cell cellBetweenCurrentCellAndCellSelected = getCellBetweenTwoCells(Game.cellSelected, currentCell); if(cellBetweenCurrentCellAndCellSelected != null) { if(cellBetweenCurrentCellAndCellSelected.getBushi() != null) itCell.remove(); } } return cells; } /** * Returns the bushi which have been jumped over by the other bushi * @param otherBushi the other bushi which have jumped over the bushi returned by the function * @param cellWhereOtherBushiWillJump the cell where the other bushi will jump after jumping over * @return cellWhereOtherBushiWillJump the cell where the other bushi will jump after jumping over * @see Bushi * @see Cell */ public Bushi getBushiWhichHaveBeenJumpedOverByOtherBushi(Bushi otherBushi, Cell cellWhereOtherBushiWillJump) { Bushi bushiWhichHaveBeenJumpedOver = null; Cell cellOfOtherBushi = otherBushi.getPosition(); Cell cellOfBushiWhichHaveBeenJumpedOver = getCellBetweenTwoCells(cellOfOtherBushi, cellWhereOtherBushiWillJump); if(cellOfBushiWhichHaveBeenJumpedOver != null) bushiWhichHaveBeenJumpedOver = cellOfBushiWhichHaveBeenJumpedOver.getBushi(); return bushiWhichHaveBeenJumpedOver; } /** * If there is one of the win condition, returns the player who wins * @return the winner with a Player object * @see Player */ public Player checkVictory() { Player winner; winner = checkIfOneDragonIsOnPortal(); if(winner == null) winner = checkIfOnePlayerHasNoDragon(); return winner; } /** * If one dragon is on a portal, returns his owner who wins * @return the winner with a Player object * @see Player */ private Player checkIfOneDragonIsOnPortal() { Player winner = null; for (int col = 0 ; col < NB_LIN ; col++ ) { for (int lin = 0 ; lin < NB_COL ; lin++) { Cell currentCell = getCell(col, lin); if(currentCell.isPortal()) { if(currentCell.getBushi() != null) { Bushi currentBushi = currentCell.getBushi(); if(currentBushi.getBushiType() == BushiType.DRAGON) { winner = currentBushi.getOwner(); } } } } } return winner; } /** * If a player has no dragon, returns his opponent who wins * @return the winner with a Player object * @see Player */ private Player checkIfOnePlayerHasNoDragon() { Player winner = null; int nbDragonPlayer1 = 0; int nbDragonPlayer2 = 0; for (int col = 0 ; col < NB_LIN ; col++ ) { for (int lin = 0 ; lin < NB_COL ; lin++) { Cell currentCell = getCell(col, lin); if(currentCell.getBushi() != null) { Bushi currentBushi = currentCell.getBushi(); if(currentBushi.getBushiType() == BushiType.DRAGON) { if(currentBushi.getOwner() == Game.player1) { nbDragonPlayer1++; } else if(currentBushi.getOwner() == Game.player2) { nbDragonPlayer2++; } } } } } if(nbDragonPlayer1 == 0) winner = Game.player2; if(nbDragonPlayer2 == 0) winner = Game.player1; return winner; } /** * Returns a boolean indicating if the bushi selected is owned by the player in parameter * @param player the player which we want to know if he is the owner of bushi selected * @return a boolean indicating if the bushi selected is owned by player * @see Player */ public boolean checkIfPlayerOwnsBushiSelected(Player player) { if(Game.cellSelected.getBushi() != null) { return(player == Game.cellSelected.getBushi().getOwner()); } else { return false; } } }<file_sep>/src/presentation/Clavier.java package presentation; import java.io.*; /** * @author <NAME> * @version 2020.1 */ public class Clavier { static BufferedReader input =new BufferedReader (new InputStreamReader(System.in)); /** * Saisie au clavier d'un entier * @return Retourne l'entier saisi par l'utilisateur si ce dernier saisit un entier representable par un int. * Retourne Integer.MAX_VALUE dans le cas contraire (notamment si la saisie ne correspond pas a un entier) */ public static int lireInt() { try { return Integer.parseInt(lireString().trim()); } catch (Exception e) { return Integer.MAX_VALUE; } } /** * Saisie au clavier d'un double * @return Retourne la valeur de type double saisie par l'utilisateur si ce dernier saisit un nombre representable par un double. * Retourne Double.MAX_VALUE dans le cas contraire (notamment si la saisie ne correspond pas a un double) */ public static double lireDouble() { try { return Double.parseDouble(lireString().trim()); } catch (Exception e) { return Double.MAX_VALUE; } } /** * Saisie au clavier d'une chaine de caracteres. * @return Retourne la chaine de caracteres saisie par l'utilisateur ("" en cas de levee d'exception) */ public static String lireString() { System.out.flush(); try { return input.readLine(); } catch (Exception e) { return ""; } } /** * Saisie au clavier d'un caractere * @return Retourne le caractere saisi par l'utilisateur ((char)0 en cas de levee d'exception) */ public static char lireChar() { try { return lireString().charAt(0); } catch (Exception e) { return (char)0; } } } <file_sep>/src/abstraction/BushiType.java package abstraction; /** Represents a bushi type. * @author <NAME> */ public enum BushiType { MONKEY, LION, DRAGON }<file_sep>/src/abstraction/Cell.java package abstraction; /** Represents a cell. * @author <NAME> */ public class Cell { // CONSTANTS // INSTANCE VARIABLES (ATTRIBUTES) private Bushi bushi; final private boolean isPortal; final private boolean isValid; // METHODS /** * Constructor initializing a Cell * @param isPortal indicates if the cell is a portal * @param isValid indicates if the cell is valid */ public Cell(Boolean isPortal, Boolean isValid) { this.bushi = null; this.isPortal = isPortal; this.isValid = isValid; } /** * Returns the Bushi object on the cell * @return the bushi on the cell * @see Bushi */ public Bushi getBushi() { return this.bushi; } /** * Sets a Bushi object on the cell * @param bushi the object Bushi to set to the bushi property * @see Bushi */ public void setBushi(Bushi bushi) { this.bushi = bushi; } /** * Remove the Bushi object from the cell * @see Bushi */ public void removeBushi() { this.bushi = null; } /** * Returns a boolean indicating if the cell is a portal * @return a boolean indicating if the cell is a portal */ public boolean isPortal() { return this.isPortal; } /** * Returns a boolean indicating if the cell is valid * @return a boolean indicating if the cell is valid */ public boolean isValid() { return this.isValid; } /** * Returns a boolean indicating if the cell is empty * @return a boolean indicating if the cell is empty */ public boolean isEmpty() { return (this.bushi == null); } }
4202a60f7f70bb9205e69a1e2283717293766e6e
[ "Java" ]
6
Java
Axorion/shingshang
38ea7e1b6572cbb5b18f62675078708341857d7a
b0b144f0f099f0077d0cd210c4076e03afd4e389
refs/heads/main
<repo_name>MichaelFCoyle/GPSError<file_sep>/GPSError/GPSError/MainForm.cs using GPSError.Models; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Windows.Forms; using System.Windows.Forms.DataVisualization.Charting; namespace GPSError { public partial class MainForm : Form { public MainForm() { InitializeComponent(); ChartArea chartArea1 = new ChartArea(); chart1 = new Chart(); ((System.ComponentModel.ISupportInitialize)(chart1)).BeginInit(); // // myElevationProfile // //chartArea1.AxisX.IntervalAutoMode = IntervalAutoMode.VariableCount; chartArea1.AxisX.Title = "latitude (m)"; chartArea1.AxisX.Interval = 0.5; //chartArea1.AxisY.IntervalAutoMode = IntervalAutoMode.VariableCount; chartArea1.AxisY.Title = "longitude (m)"; chartArea1.AxisX.Interval = 0.5; chartArea1.Name = "myChartArea"; chart1.ChartAreas.Add(chartArea1); //chart1.ContextMenuStrip = this.contextMenuStrip1; chart1.Dock = DockStyle.Fill; chart1.Location = new Point(0, 0); chart1.Name = "myElevationProfile"; chart1.Size = new Size(466, 368); chart1.SuppressExceptions = true; chart1.TabIndex = 0; chart1.Text = "Elevation Profile"; splitContainer1.Panel2.Controls.Add(chart1); ((System.ComponentModel.ISupportInitialize)(chart1)).EndInit(); } private readonly Chart chart1; TestData m_testData; private void LoadButton_Click(object sender, EventArgs e) { using var ofd = new OpenFileDialog() { Filter = "GPX File|*.gpx|KML File|*.kml" }; if (ofd.ShowDialog(this) != DialogResult.OK) return; m_testData = Processor.Process(ofd.FileName); chart1.Series.Clear(); chart1.Series.Add(new Series() { ChartArea = "myChartArea", ChartType = SeriesChartType.Point, MarkerColor = Color.Red, MarkerStyle = MarkerStyle.Circle, MarkerSize = 5, Name = "Series1", IsValueShownAsLabel = false, }); var maxX = Math.Max(Math.Abs(m_testData.MaxX), Math.Abs(m_testData.MinX)); var maxY = Math.Max(Math.Abs(m_testData.MaxY), Math.Abs(m_testData.MinY)); var max = Math.Max(Math.Abs(maxX), Math.Abs(maxY)); max=Math.Round(max, 0, MidpointRounding.AwayFromZero); // Output: 2 chart1.ChartAreas[0].AxisY.Minimum = -max; chart1.ChartAreas[0].AxisY.Maximum = max; chart1.ChartAreas[0].AxisX.Minimum = -max; chart1.ChartAreas[0].AxisX.Maximum = max; chart1.ChartAreas[0].AxisX.Interval = 1; chart1.ChartAreas[0].AxisY.Interval = 1; chart1.ChartAreas[0].AxisX.MinorGrid.Interval = 5; chart1.ChartAreas[0].AxisY.MinorGrid.Interval = 5; chart1.ChartAreas[0].AxisX.MinorGrid.LineDashStyle = ChartDashStyle.Dot; chart1.ChartAreas[0].AxisY.MinorGrid.LineDashStyle = ChartDashStyle.Dot; chart1.ChartAreas[0].AxisX.MinorGrid.LineColor = Color.LightBlue; chart1.ChartAreas[0].AxisY.MinorGrid.LineColor = Color.LightBlue; chart1.ChartAreas[0].AxisX.MajorGrid.Interval = 1; chart1.ChartAreas[0].AxisY.MajorGrid.Interval = 1; chart1.ChartAreas[0].AxisX.MajorGrid.LineDashStyle = ChartDashStyle.Dash; chart1.ChartAreas[0].AxisY.MajorGrid.LineDashStyle = ChartDashStyle.Dash; chart1.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.LightBlue; chart1.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.LightBlue; foreach (var entry in m_testData.Entries) chart1.Series["Series1"].Points.AddXY(entry.X, entry.Y); // Draw the circle DrawCircle(m_testData.Circle1, Color.LightGreen, "Circle1"); DrawCircle(m_testData.Circle2, Color.Red, "Circle2"); } private void DrawCircle(List<Entry> circle, Color color, string text) { chart1.Series.Add(text); // Set the type to line chart1.Series[text].ChartType = SeriesChartType.Line; chart1.Series[text].Color = color; chart1.Series[text].BorderWidth = 3; //This function cannot include zero, and we walk through it in steps of 0.1 to add coordinates to our series foreach (var c in circle) chart1.Series[text].Points.AddXY(c.X, c.Y); var first = circle.First(); chart1.Series[text].Points.AddXY(first.X, first.Y); chart1.Series[text].LegendText = text; } private void SaveChartButton_Click(object sender, EventArgs e) { using var sfd = new SaveFileDialog() { Filter = "Chart Image|*.png", DefaultExt=".png" }; if (sfd.ShowDialog(this) != DialogResult.OK) return; chart1.SaveImage(sfd.FileName, ChartImageFormat.Png); } } } <file_sep>/GPSError/GPSError/Extensions.cs using GPSError.GDAL; using System.Collections.Generic; namespace GPSError { static class Extensions { public static List<PointDType> AddItem(this List<PointDType> list, PointDType item) { list.Add(item); return list; } public static bool IsNullOrEmpty(this string source) => string.IsNullOrEmpty(source); } } <file_sep>/GPSError/GPSError/GDAL/GDALHelper.cs using OSGeo.GDAL; using OSGeo.OGR; using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using SpatialReference = OSGeo.OSR.SpatialReference; namespace GPSError.GDAL { /// <summary> /// Assists setting up GDAL /// </summary> public static partial class GDALHelper { private static bool s_configuredOgr; private static bool s_configuredGdal; /// <summary> /// Function to determine which platform we're on /// </summary> private static string GetPlatform() => IntPtr.Size == 4 ? "x86" : "x64"; public static string GDALPath { get; private set; } public static string GDALData { get; private set; } [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetDllDirectory(string lpPathName); /// <summary> Construction of Gdal/Ogr </summary> static GDALHelper() { var executingAssemblyFile = new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase).LocalPath; var executingDirectory = Path.GetDirectoryName(executingAssemblyFile); if (string.IsNullOrEmpty(executingDirectory)) throw new InvalidOperationException("cannot get executing directory"); var gdalPath = Path.Combine(executingDirectory, "gdal"); GDALPath = Path.Combine(gdalPath, GetPlatform()); if (!Directory.Exists(GDALPath)) throw new DirectoryNotFoundException("Could not find GDAL directory"); SetDllDirectory(GDALPath); // Prepend native path to environment path, to ensure the right libs are being used. var path = Environment.GetEnvironmentVariable("PATH"); path = GDALPath + ";" + Path.Combine(GDALPath, "plugins") + ";" + path; Environment.SetEnvironmentVariable("PATH", path); // Set the additional GDAL environment variables. GDALData = Path.Combine(gdalPath, "data"); Environment.SetEnvironmentVariable("GDAL_DATA", GDALData); Gdal.SetConfigOption("GDAL_DATA", GDALData); var driverPath = Path.Combine(GDALPath, "gdalplugins"); Environment.SetEnvironmentVariable("GDAL_DRIVER_PATH", driverPath); Gdal.SetConfigOption("GDAL_DRIVER_PATH", driverPath); Environment.SetEnvironmentVariable("GEOTIFF_CSV", GDALData); Gdal.SetConfigOption("GEOTIFF_CSV", GDALData); var projSharePath = Path.Combine(gdalPath, "projlib"); Environment.SetEnvironmentVariable("PROJ_LIB", projSharePath); Gdal.SetConfigOption("PROJ_LIB", projSharePath); } /// <summary> /// Method to ensure the static constructor is being called. /// </summary> /// <remarks>Be sure to call this function before using Gdal/Ogr/Osr</remarks> public static void ConfigureOgr() { if (s_configuredOgr) return; // Register drivers Ogr.RegisterAll(); s_configuredOgr = true; Trace.TraceInformation(PrintDriversOgr()); } /// <summary> /// Method to ensure the static constructor is being called. /// </summary> /// <remarks>Be sure to call this function before using Gdal/Ogr/Osr</remarks> public static void ConfigureGdal() { if (s_configuredGdal) return; // Register drivers Gdal.AllRegister(); s_configuredGdal = true; Trace.TraceInformation(PrintDriversGdal()); } static string s_version; /// <summary> /// Return the version of GDAL that is installed /// </summary> public static string Version => s_version ??= Gdal.VersionInfo("RELEASE_NAME"); private static string PrintDriversOgr() { StringBuilder sb = new StringBuilder(); var num = Ogr.GetDriverCount(); for (var i = 0; i < num; i++) { var driver = Ogr.GetDriver(i); sb.AppendFormat("OGR {0}: {1}\r\n", i, driver.name); } return sb.ToString(); } public static string PrintDriversGdal() { StringBuilder sb = new StringBuilder(); var num = Gdal.GetDriverCount(); for (var i = 0; i < num; i++) { var driver = Gdal.GetDriver(i); sb.AppendFormat("GDAL {0}: {1}-{2}\r\n", i, driver.ShortName, driver.LongName); } return sb.ToString(); } public static string GetGeogCS(this SpatialReference srs) => //PROJCS, GEOGCS, DATUM, SPHEROID, and PROJECTION srs.GetAttrValue("GEOGCS", 0);//string wkt = srs.ToWkt();//return GetValueOf(wkt, "GEOGCS"); public static string GetProjectionName(this SpatialReference srs) => srs.GetAttrValue("PROJECTION", 0);//string wkt = srs.ToWkt();//return GetValueOf(wkt, "DATUM"); public static string GetDatumName(this SpatialReference srs) => srs.GetAttrValue("DATUM", 0);//string wkt = srs.ToWkt();//return GetValueOf(wkt, "DATUM"); public static string GetProjCS(this SpatialReference srs) => srs.GetAttrValue("PROJCS", 0);//string wkt = srs.ToWkt();//return GetValueOf(wkt, "PROJCS"); public static string GetSpheroidName(this SpatialReference srs) => srs.GetAttrValue("SPHEROID", 0);//string wkt = srs.ToWkt();//return GetValueOf(wkt, "SPHEROID"); public static string GetAuthorityCode(this SpatialReference srs) => srs.GetAuthorityCode(null); public static string GetAuthorityName(this SpatialReference srs) => srs.GetAuthorityName(null); public static SpatialReference SRSFromEPSG(string epsg) { if (epsg.StartsWith("EPSG:")) epsg = epsg.Replace("EPSG:", ""); if (!int.TryParse(epsg, out int code)) { Trace.TraceError("Can't parse EPSG code {0}, not an integer", epsg); return null; } return SRSFromEPSG(code); } public static SpatialReference SRSFromEPSG(int epsg) { try { SpatialReference srs = new SpatialReference(null); int code = srs.ImportFromEPSG(epsg); if (code != Ogr.OGRERR_NONE) { Trace.TraceError("Can't get SRS from EPSG Code \"{0}\": {1}", epsg, GDALHelper.ReportOgrError(code)); return null; } return srs; } catch (Exception ex) { Trace.TraceError("Error trying to create SpatialReference from EPSG code {0}:\r\n{1}", epsg, ex); return null; } } /// <summary> /// Create an SRS from user input /// </summary> /// <param name="input"></param> /// <returns></returns> public static SpatialReference SRSFromUserInput(string input) { if (input.StartsWith("EPSG:")) { int code = Int32.Parse(input.Replace("EPSG:", "")); return SRSFromEPSG(code); } SpatialReference srs = new SpatialReference(null); srs.SetFromUserInput(input); //srs.SetWellKnownGeogCS(input); return srs; } /// <summary> /// Take an OGR Error and convert it to a human readable error string /// </summary> /// <param name="code"></param> /// <returns></returns> public static string ReportOgrError(int code) { StringBuilder sb = new StringBuilder(); if (code == Ogr.OGRERR_CORRUPT_DATA) sb.Append("Corrupt data"); else if (code == Ogr.OGRERR_FAILURE) sb.Append("Failure"); else if (code == Ogr.OGRERR_NONE) sb.Append("No Error"); else if (code == Ogr.OGRERR_NOT_ENOUGH_DATA) sb.Append("Not enough data"); else if (code == Ogr.OGRERR_NOT_ENOUGH_MEMORY) sb.Append("Not enough memory"); else if (code == Ogr.OGRERR_UNSUPPORTED_GEOMETRY_TYPE) sb.Append("Unsupported Geometry Type"); else if (code == Ogr.OGRERR_UNSUPPORTED_OPERATION) sb.Append("Unsupported Operation"); else if (code == Ogr.OGRERR_UNSUPPORTED_SRS) sb.Append("Unsupported Spatial Reference"); else sb.AppendFormat("Unknown error code {0}", code); //if (code != Ogr.OGRERR_NONE) // Trace.TraceError("OGR Error: {0}", sb); return sb.ToString(); } } }<file_sep>/GPSError/GPSError/Models/TestData.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace GPSError.Models { public class TestData { public TestData() { } public int TestDataID { get; set; } #region test statistics /// <summary> Minutes </summary> public float Duration { get; set; } public DateTime? Start { get; set; } public DateTime? End { get; set; } #endregion public ICollection<Entry> Entries { get; set; } = new List<Entry>(); public double AvgX { get; set; } public double AvgY { get; set; } public double StdvX { get; set; } public double StdvY { get; set; } /// <summary> CEP (50%) </summary> public double CEP { get; set; } /// <summary> 2DRMS (95%) </summary> public double TDRMS { get; set; } public double MaxX { get; set; } public double MaxY { get; set; } public double MinX { get; set; } public double MinY { get; set; } /// <summary> # Samples </summary> public int Count => Entries.Count(); public double LocationX { get; set; } public double LocationY { get; set; } public List<Entry> Circle1 { get; set; } public List<Entry> Circle2 { get; set; } public string Platform { get; set; } public string UserAgent { get; set; } #region methods /// <summary> /// Calculate the average value of the data set /// </summary> void CalculateAverage() { if (Entries.Count == 0) return; LocationX = Entries.Average(x => x.Lon); LocationY = Entries.Average(x => x.Lat); AvgX = Entries.Average(x => x.X); AvgY = Entries.Average(x => x.Y); } void CalculateStdev() { double sum = Entries.Sum(x => (x.X - AvgX) * (x.X - AvgX)); StdvX = Math.Sqrt(sum / Entries.Count()); sum = Entries.Sum(x => (x.Y - AvgY) * (x.Y - AvgY)); StdvY = Math.Sqrt(sum / Entries.Count()); } void CalculateCI() { CEP = 0.59 * (StdvX + StdvY); TDRMS = 2.0 * Math.Sqrt(StdvX * StdvX + StdvY * StdvY); } void Circles() { try { // do the circle var p50 = Math.PI / 50.0; Circle1 = new List<Entry>(); Circle2 = new List<Entry>(); for (int i = 0; i < 100; i++) { var ipv = i * p50; Circle1.Add(new Entry() { Y = CEP * Math.Cos(ipv), X = CEP * Math.Sin(ipv) }); Circle2.Add(new Entry() { Y = TDRMS * Math.Cos(ipv), X = TDRMS * Math.Sin(ipv) }); } } catch (Exception ex) { Trace.TraceError("Error\r\n{0}", ex); } } /// <summary> /// Normalize the test data set. /// This makes every point an offset in meters from the average /// </summary> void Normalize() { foreach (var entry in Entries) { entry.X -= AvgX; entry.Y -= AvgY; } } void MinMax() { MaxX = Entries.Max(x => x.X); MaxY = Entries.Max(x => x.Y); MinX = Entries.Min(x => x.X); MinY = Entries.Min(x => x.Y); } /// <summary> /// Process the data set /// </summary> public void Process() { CalculateAverage(); CalculateStdev(); CalculateCI(); Normalize(); // only call this once MinMax(); // min/max after normalization Circles(); } #endregion } public class Entry { public int EntryID { get; set; } public int TestDataID { get; set; } public double X { get; set; } public double Y { get; set; } public double Z { get; set; } public double Lat { get; set; } public double Lon { get; set; } } } <file_sep>/README.md # GPSError Calculate GPS Error <file_sep>/GPSError/GPSError/GDAL/PointDType.cs using System; using System.ComponentModel; using System.Drawing; using System.Xml.Serialization; namespace GPSError.GDAL { [TypeConverter(typeof(ExpandableObjectConverter))] [System.Diagnostics.DebuggerDisplay("({X}, {Y}, {Z})")] public partial class PointDType : ICloneable, IEquatable<PointDType>, IComparable, IComparable<PointDType> { #region constructors public PointDType() : this(0, 0, 0) { } public PointDType(double x, double y, double z = 0) { X = x; Y = y; Z = z; } public PointDType(PointDType point) { X = point.X; Y = point.Y; Z = point.Z; } public PointDType(PointF point) { X = point.X; Y = point.Y; } /// <summary> /// Create a point from an array of double of length three /// </summary> /// <param name="points"></param> public PointDType(double[] points) { if (points.Length == 2) { X = points[0]; Y = points[1]; Z = 0; } else if (points.Length == 3) { X = points[0]; Y = points[1]; Z = points[2]; } else { throw new ArgumentException("point array must be of length 2 or 3"); } } public double X; public double Y; public double Z; #endregion /// <summary> /// return true if this is an empty point /// </summary> public bool IsEmpty => this == Empty; /// <summary> /// return the point structire in array format /// </summary> [XmlIgnore] public double[] Array { get => ToArray(); set { if (value.Length == 2) { X = value[0]; Y = value[1]; } else if (value.Length == 3) { X = value[0]; Y = value[1]; Z = value[2]; } else { throw new ArgumentException("point array must be of length 2 or 3"); } } } private static readonly PointDType m_empty = new PointDType(PointF.Empty); /// <summary> </summary> public static PointDType Empty => m_empty; public static bool Equals(PointDType left, PointDType right) { if (((object)left) == ((object)right)) return true; if ((((object)left) == null) || (((object)right) == null)) return false; return Math.Abs(left.X - right.X) <= double.Epsilon && Math.Abs(left.Y - right.Y) <= double.Epsilon && Math.Abs(left.Z - right.Z) <= double.Epsilon; } #region operators /// <summary> /// Returns part of coordinate. Index 0 = X, Index 1 = Y /// </summary> /// <param name="index"></param> /// <returns></returns> public virtual double this[uint index] { get { if (index == 0) return X; else if (index == 1) return Y; else if (index == 2) return Z; else throw (new Exception("Point index out of bounds")); } set { if (index == 0) X = value; else if (index == 1) Y = value; else if (index == 2) Z = value; else throw (new Exception("Point index out of bounds")); } } /// <summary> /// implicit operator converting from Point to PointType /// </summary> /// <param name="point"></param> /// <returns></returns> public static implicit operator PointDType(PointF point) { if (point == null) throw new ArgumentNullException("point"); return new PointDType(point); } /// <summary> /// implicit operator converting from PointType to Point /// </summary> /// <param name="point"></param> /// <returns></returns> public static explicit operator PointF(PointDType point) { if (point == null) throw new ArgumentNullException("point"); return new PointF((float)point.X, (float)point.Y); } /// <summary> /// Vector + Vector /// </summary> /// <param name="left">Vector</param> /// <param name="right">Vector</param> /// <returns></returns> public static PointDType operator +(PointDType left, PointDType right) { if (left == null) throw new ArgumentNullException("left"); if (right == null) throw new ArgumentNullException("right"); return new PointDType(left.X + right.X, left.Y + right.Y, left.Z + right.Z); } /// <summary> /// Vector - Vector /// </summary> /// <param name="left">Vector</param> /// <param name="right">Vector</param> /// <returns>Cross product</returns> public static PointDType operator -(PointDType left, PointDType right) { if (left == null) throw new ArgumentNullException("left"); if (right == null) throw new ArgumentNullException("right"); return new PointDType(left.X - right.X, left.Y - right.Y, left.Z - right.Z); } /// <summary> /// Vector * Scalar /// </summary> /// <param name="value">Vector</param> /// <param name="d">Scalar (double)</param> /// <returns></returns> public static PointDType operator *(PointDType value, double d) { if (value == null) throw new ArgumentNullException("value"); return new PointDType(value.X * d, value.Y * d, value.Z * d); } /// <summary> /// /// </summary> /// <param name="d"></param> /// <param name="value"></param> /// <returns></returns> public static PointDType operator *(double d, PointDType value) { if (value == null) throw new ArgumentNullException("value"); return new PointDType(value.X * d, value.Y * d, value.Z * d); } /// <summary> /// Vector / Scalar /// </summary> /// <param name="value">Vector</param> /// <param name="d">Scalar (double)</param> /// <returns></returns> public static PointDType operator /(PointDType value, double d) { if (value == null) throw new ArgumentNullException("value"); return new PointDType(value.X / d, value.Y / d, value.Z / d); } /// <summary> /// Unary minus /// </summary> /// <param name="value"></param> /// <returns></returns> public static PointDType operator -(PointDType value) { if (value == null) throw new ArgumentNullException("value"); return new PointDType(-value.X, -value.Y, -value.Z); } public static bool operator ==(PointDType left, PointDType right) => Equals(left, right); public static bool operator !=(PointDType left, PointDType right) => !Equals(left, right); public static bool operator <(PointDType v1, PointDType v2) => v1.SumComponentSqrs() < v2.SumComponentSqrs(); public static bool operator >(PointDType v1, PointDType v2) => v1.SumComponentSqrs() > v2.SumComponentSqrs(); #endregion #region component operations public static PointDType SqrComponents(PointDType v1) => new PointDType(v1.X * v1.X, v1.Y * v1.Y, v1.Z * v1.Z); public void SqrComponents() => Value = SqrtComponents(this); public static PointDType SqrtComponents(PointDType v1) => new PointDType(Math.Sqrt(v1.X), Math.Sqrt(v1.Y), Math.Sqrt(v1.Z)); public void SqrtComponents() => Value = SqrtComponents(this); public static double SumComponentSqrs(PointDType v1) => SqrComponents(v1).SumComponents(); public double SumComponentSqrs() => SumComponentSqrs(this); public static double SumComponents(PointDType v1) => (v1.X + v1.Y + v1.Z); public double SumComponents() => SumComponents(this); #endregion [XmlIgnore] internal PointDType Value { get => new PointDType(Value); set { X = value.X; Y = value.Y; Z = value.Z; } } /// <summary> /// Return the point structure in array format /// </summary> /// <returns></returns> public double[] ToArray() => new double[3] { X, Y, Z }; #region ICloneable Members /// <summary> /// /// </summary> /// <returns></returns> public PointDType Clone() => new PointDType(X, Y, Z); object ICloneable.Clone() => new PointDType(X, Y, Z); #endregion #region IEquatable<PointDType> Members /// <summary> /// /// </summary> /// <param name="other"></param> /// <returns></returns> public bool Equals(PointDType other) => Equals(this, other); #endregion #region overrides public override bool Equals(object obj) { if (obj is null) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals(obj as PointDType); } /// <summary> /// Get the hash value /// </summary> /// <returns></returns> public override int GetHashCode() => (int)((X + Y + Z) % int.MaxValue); public override string ToString() => string.Format("{0}, {1}, {2}", X, Y, Z); #endregion #region IComparable /// <summary> /// /// </summary> /// <param name="other"></param> /// <returns></returns> public int CompareTo(PointDType other) { if (this < other) return -1; else if (this > other) return 1; return 0; } /// <summary> /// /// </summary> /// <param name="other"></param> /// <returns></returns> public int CompareTo(object other) { if (!(other is PointDType)) throw new ArgumentException("not a point"); return CompareTo((PointDType)other); } /// <summary> /// /// </summary> /// <param name="array"></param> public void FromArray(double[] array) => Array = array; /// <summary> /// /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="z"></param> public void Offset(double x, double y, double z = 0) { X += x; Y += y; Z += z; } #endregion } } <file_sep>/GPSError/GPSError/GDAL/SphericalMercatorProjection.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using GPSError.GDAL; using SpatialReference = OSGeo.OSR.SpatialReference; using CoordinateTransformation = OSGeo.OSR.CoordinateTransformation; namespace GPSError { public class SphericalMercatorProjection// : ProjectionBase { public SphericalMercatorProjection() => Initialize("EPSG:3785"); #region fields SpatialReference m_sr; string m_code; CoordinateTransformation m_transform; CoordinateTransformation m_inverseTransform; #endregion /// <summary> /// Parameter can be EPSG code or WKT /// </summary> /// <param name="parameter"></param> private void Initialize(string parameter) { m_code = parameter; m_sr = parameter.ToUpper().StartsWith("EPSG") ? GDALHelper.SRSFromEPSG(parameter) : GDALHelper.SRSFromUserInput(parameter); // initialize this to the geographic coordinate system SpatialReference geog_sr = GDALHelper.SRSFromEPSG("EPSG:4326"); //new SpatialReference(null); try { m_transform = new CoordinateTransformation(geog_sr, m_sr); m_inverseTransform = new CoordinateTransformation(m_sr, geog_sr); } catch (Exception ex) { Trace.TraceError("error creating projection:\r\n{0}", ex); } } #region IProjection Members public string Name => m_sr.GetGeogCS(); public string Datum => m_sr.GetDatumName(); public bool IsGeographic => m_sr.IsGeographic() == 1; public bool IsProjected => m_sr.IsProjected() == 1; public string Code => m_code; /// <summary> /// Project from geographic to UTM /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public PointDType Project(double x, double y) { if (x > 180) x = 180.0; if (x < -180) x = -180.0; if (y > 90) y = 90.0; if (y < -90) y = -90.0; double[] point = new double[3] { x, y, 0 }; m_transform.TransformPoint(point); return new PointDType(point[0], point[1]); //return (IsUTM(m_sr.GetAuthorityCode())) ? // new UTMCoordinate(point[0], point[1], UTMZone.FromLatLon(y, x).ToString()) : // new PointDType(point[0], point[1]);// { IsProjected = true }; } public virtual PointDType Project(PointDType coordinate) => Project(coordinate.X, coordinate.Y); /// <summary> /// Unproject from UTM to Geographic /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public PointDType Unproject(double x, double y) { // do the transform double[] point = new double[3] { x, y, 0.0 }; m_inverseTransform.TransformPoint(point); return new PointDType(point[1], point[0]); } public virtual PointDType Unproject(PointDType coordinate) => Unproject(coordinate.X, coordinate.Y); public IEnumerable<PointDType> Unproject(IEnumerable<PointDType> coordinates) { List<PointDType> list = coordinates.ToList<PointDType>(); if (list.Count == 1) return new List<PointDType>().AddItem(Unproject(list[0])); double[] x = list.Select(s => s.X).ToArray(); double[] y = list.Select(s => s.Y).ToArray(); double[] z = list.Select(s => s.Z).ToArray(); m_inverseTransform.TransformPoints(x.Length, x, y, z); List<PointDType> coords = new List<PointDType>(list.Count); for (int i = 0; i < list.Count; i++) coords.Add(new PointDType(y[i], x[i], z[i]));// { IsProjected = true }); return coords; } public IEnumerable<PointDType> Project(IEnumerable<PointDType> coordinates) { //List<Coordinate> list = new List<Coordinate>(); //foreach (var c in coordinates) // list.Add(Project(c)); //return list; int count = coordinates.ToList().Count; // jump out here if there is just one if (count == 1) return new List<PointDType>().AddItem(Project(coordinates.First())); double[] x = new double[count]; double[] y = new double[count]; double[] z = new double[count]; { int i = 0; foreach (var c in coordinates) { x[i] = c.X; x[i] = (x[i] >= 180.0) ? 179.9 : x[i]; x[i] = (x[i] <= -180.0) ? -179.9 : x[i]; y[i] = c.Y; y[i] = (y[i] >= 90.0) ? 89.9 : y[i]; y[i] = (y[i] <= -90.0) ? -89.9 : y[i]; z[i] = c.Z; i++; } } m_transform.TransformPoints(count, x, y, z); PointDType[] coords = new PointDType[count]; for (int i = 0; i < count; i++) coords[i] = new PointDType(x[i], y[i], z[i]); return coords; } #endregion } } <file_sep>/GPSError/GPSError/Processor.cs using GPSError.GDAL; using GPSError.Models; using SharpGPX; using SharpGPX.GPX1_1; using System; using System.Diagnostics; using System.IO; namespace GPSError { public static class Processor { static SphericalMercatorProjection m_projection; /// <summary> /// Process the file name /// </summary> /// <param name="fileName"></param> /// <returns></returns> internal static TestData Process(string fileName) { if (m_projection == null) m_projection = new SphericalMercatorProjection(); TestData error = new TestData(); var ext = Path.GetExtension(fileName).ToLower(); if (ext == ".gpx") error = ProcessGPX(fileName); else if ( ext == ".kml" || ext == ".kmz") error = ProcessKML(fileName); if (error == null) return null; // process the data set error.Process(); return error; } private static TestData ProcessKML(string fileName) { try { TestData data = new TestData(); //TrueNorth.Geographic.CoordinateCollection collection = new KMLReader().Read(file); //foreach (var c in collection) //{ // Coordinate UTM = m_projection.Project(c); // data.Entries.Add(new Entry() // { // Lat = c.Y, // Lon = c.X, // X = UTM.X, // Y = UTM.Y, // Z = c.Z // }); //} return data; } catch (Exception ex) { Trace.TraceError("Error\r\n{0}", ex); return null; } } private static TestData ProcessGPX(string file) => ProcessGPX(GpxClass.FromFile(file)); //private static TestData ProcessGPX(Stream fileStream) => ProcessGPX(GpxClass.FromStream(fileStream)); private static TestData ProcessGPX(GpxClass gpx) { TestData data = new TestData(); // get all of the points in the tracks and convert them to spherical mercator foreach (var track in gpx.Tracks) { foreach (var seg in track.trkseg) { foreach (var pt in seg.trkpt) { PointDType geo = pt.ToCoordinate(); PointDType mercator = m_projection.Project(geo); // the start time of the track if (seg.trkpt.IndexOf(pt) == 0 && pt.timeSpecified) data.Start = pt.time; // the end time of the track if (seg.trkpt.IndexOf(pt) == (seg.trkpt.Count - 1) && pt.timeSpecified) data.End = pt.time; data.Entries.Add(new Entry() { Lat = geo.Y, Lon = geo.X, X = mercator.X, Y = mercator.Y, Z = geo.Z }); } } } if (data.Start.HasValue && data.End.HasValue) data.Duration = (float)(data.End.Value - data.Start.Value).TotalMinutes; return data; } /// <summary> /// Convert a waypoint to a double precision point /// </summary> /// <param name="wpt"></param> /// <returns></returns> public static PointDType ToCoordinate(this wptType wpt) { PointDType c = new PointDType( Convert.ToDouble(wpt.lon), Convert.ToDouble(wpt.lat)); if (wpt.eleSpecified) c.Z = Convert.ToDouble(wpt.ele); return c; } } }
8161e2893ccc7de477992e873598b02ee3f06717
[ "Markdown", "C#" ]
8
C#
MichaelFCoyle/GPSError
71c118f361a4bcffa7ec806e5834813c07b69444
7902773dce8fa05ded80b469613d009ec963ac7a
refs/heads/main
<repo_name>Christian-Magdiel/unititle5<file_sep>/src/LISTA DE N CANTIDAD.kt fun main(args: Array<String>) { var Lista = MutableList(10){ (1..10).random() } Lista.forEach(){ var i= 1 println("En la posicion $i hay un $it") } fun Buscar ( cont:Int , valor: Int ){ var limite=10 if (cont > 0){ if (cont == limite){ println("5 en la Posicion $cont ") } Buscar(cont - 1 , Lista[cont -1]) } else { if (cont == 1){ println("") } } } var contador = 9 var valor= Lista[contador] Buscar(contador, valor) }
62d6f9fe3bf3a97fffc80630d16110fda38f806d
[ "Kotlin" ]
1
Kotlin
Christian-Magdiel/unititle5
891122652a1d283c846b7d46340456aff1514d1e
b9ffec1b2af37d17293aa7ba27c8408ca347d508
refs/heads/master
<file_sep><?php require_once 'User.php'; require_once __DIR__.'/../Database.php'; class UserMapper { private $database; public function __construct() { $this->database = new Database(); } public function getUser(string $email):User { try { $stmt = $this->database->connect()->prepare('SELECT * FROM users WHERE email = :email;'); $stmt->bindParam(':email', $email, PDO::PARAM_STR); $stmt->execute(); $user = $stmt->fetch(PDO::FETCH_ASSOC); return new User($user['ID'], $user['username'], $user['name'], $user['surname'], $user['email'], $user['password'], $user['role_id']); } catch(PDOException $e) { return 'Error: ' . $e->getMessage(); } } public function getUsers() { try { $stmt = $this->database->connect()->prepare('SELECT * FROM users WHERE email != :email;'); $stmt->bindParam(':email', $_SESSION['email'], PDO::PARAM_STR); $stmt->execute(); $user = $stmt->fetchAll(PDO::FETCH_ASSOC); return $user; } catch(PDOException $e) { die(); } } public function delete(int $id) { try { $stmt = $this->database->connect()->prepare('DELETE FROM users WHERE ID = :id;'); $stmt->bindParam(':id', $id, PDO::PARAM_INT); $stmt->execute(); } catch(PDOException $e) { die(); } } public function registerUser($username, $name, $surname, $email, $password, $role) { try { $stmt = $this->database->connect()->prepare("INSERT INTO `users` (username, name, surname, email, password, role_id) VALUES('$username', '$name', '$surname', '$email', '".md5($password)."', '$role' )"); $stmt->execute(); $this->createUserDirectory($username); $this->createUserGenerateDirectory($username); $this->createUserGeneratedDirectory($username); return true; } catch(PDOException $e) { return 'Error: ' . $e->getMessage(); } } public function createUserDirectory($user){ $folder = dirname(__DIR__).'/public/upload/'.$user; $old_umask = umask(0); if (!mkdir($folder, 0777, true)) { return false; } umask($old_umask); return true; } public function createUserGenerateDirectory($user){ $folder = dirname(__DIR__).'/public/generate/'.$user; $old_umask = umask(0); if (!mkdir($folder, 0777, true)) { return false; } umask($old_umask); return true; } public function createUserGeneratedDirectory($user){ $folder = dirname(__DIR__).'/public/generatedMemes/'.$user; $old_umask = umask(0); if (!mkdir($folder, 0777, true)) { return false; } umask($old_umask); return true; } }<file_sep><?php require_once "AppController.php"; require_once __DIR__.'/../model/User.php'; require_once __DIR__.'/../model/UserMapper.php'; class RegisterController extends AppController { public function __construct() { parent::__construct(); } public function register() { $mapper = new UserMapper(); $newUser = null; if($this->isPost()){ $registerUser = $mapper->registerUser( $_POST['username'], $_POST['name'], $_POST['surname'], $_POST['email'], $_POST['password'], 2 ); if($registerUser) { return $this->render("RegisterController", 'register', [ 'message' => [ 'You are registered successfully. <br/>Click here to <a href=\'?page=login\'>login</a>' ] ]); } else { return $this->render("RegisterController", 'register', ['message' => ['Something went wrong, try again']]); } } $this->render("RegisterController",'register', [ 'message' => ['<br/>Click here to <a href=\'?page=login\'>back to login</a>']]); } }<file_sep><?php require_once "AppController.php"; require_once __DIR__.'/../model/MemeGenerator.php'; require_once __DIR__.'/../model/MemeGeneratorMapper.php'; require_once __DIR__.'/../model/UserMapper.php'; class GenerateController extends AppController { public function __construct() { parent::__construct(); } public function generate() { $userMapper = new UserMapper(); $memeGeneratorMapper = new MemeGeneratorMapper(); $username = $_SESSION['username'].'/'; if ($this->isPost() && is_uploaded_file($_FILES['file']['tmp_name'])) { $uploadDirectory = dirname(__DIR__).self::GENERATE_DIRECTORY.$username.$_FILES['file']['name']; move_uploaded_file( $_FILES['file']['tmp_name'], $uploadDirectory ); $userId = null; if( isset( $_SESSION['email'])) { $userId = $userMapper->getUser($_SESSION['email'])->getId(); } list($width, $height) = getimagesize($uploadDirectory); $generatedDirectory = dirname(__DIR__).GENERATED_DIRECTORY.$username.$_FILES['file']['name']; $memeGenerator = new MemeGenerator($uploadDirectory, $width, $height); $memeGenerator->generateMeme($_POST['toptext'], $_POST['bottomtext']); $memeGeneratorMapper->addGeneratedMeme($_POST['title'], $width, $height, $generatedDirectory,$userId); $this->render("GenerateController",'generated'); } else { $this->render("GenerateController",'generate'); } } public function generated() { $memeMapper = new MemeGeneratorMapper(); $userMapper = new UserMapper(); $userId = null; if( isset( $_SESSION['email'])) { $userId = $userMapper->getUser($_SESSION['email'])->getId(); } header('Content-type: application/json'); http_response_code(200); echo $memeMapper->getLatestUserMeme($userId) ? json_encode($memeMapper->getLatestUserMeme($userId)) : ''; } }<file_sep><!DOCTYPE html> <html> <?php include(dirname(__DIR__).'/head.html'); ?> <body> <?php include(dirname(__DIR__).'/navbar.html'); ?> <div class="container"> <div class="row"> <h4 class="mt-4">Registered Users:</h4> <table class="table table-hover"> <thead> <tr> <th>Username</th> <th>Name</th> <th>Surname</th> <th>Email</th> <th>Role</th> <th>Action</th> </tr> </thead> <tbody> <tr> <td><?= $user->getUsername(); ?></td> <td><?= $user->getName(); ?></td> <td><?= $user->getSurname(); ?></td> <td><?= $user->getEmail(); ?></td> <td><?= $user->getRole(); ?></td> <td>-</td> </tr> </tbody> <tbody class="users-list"> </tbody> </table> <button class="btn btn-dark btn-lg" type="button" onclick=getUsers()>Get all users</button> </div> </div> </body> </html><file_sep><?php /** * Created by PhpStorm. * User: kasia * Date: 21.01.19 * Time: 16:17 */ class MemeGeneratorMapper { private $database; public function __construct() { $this->database = new Database(); } public function addGeneratedMeme($title, $width, $height, $path, $user_id) { try { $date = date('Y-m-d H:i:s'); $stmt = $this->database->connect()->prepare("INSERT INTO `generated_meme` (title, width, height, path, create_date, user_id) VALUES('$title', '$width','$height', '$path', '$date', '$user_id')"); $stmt->bindParam(':title', $title, PDO::PARAM_STR); $stmt->bindParam(':width', $width, PDO::PARAM_STR); $stmt->bindParam(':height', $height, PDO::PARAM_STR); $stmt->bindParam(':path', $path, PDO::PARAM_STR); $stmt->bindParam(':user_id', $user_id, PDO::PARAM_STR); $stmt->execute(); return true; } catch(PDOException $e) { return 'Error: ' . $e->getMessage(); } } public function getLatestUserMeme($user_id) { try { $stmt = $this->database->connect()->prepare('SELECT path, title FROM generated_meme WHERE user_id = :user_id order by create_date desc limit 1;'); $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT); $stmt->execute(); $latest = $stmt->fetchAll(PDO::FETCH_ASSOC); return $latest; } catch(PDOException $e) { die(); } } }<file_sep><?php require_once 'controllers/LoginController.php'; require_once 'controllers/IndexController.php'; require_once 'controllers/RegisterController.php'; require_once 'controllers/UploadController.php'; require_once 'controllers/GenerateController.php'; require_once 'controllers/UserMemesController.php'; require_once 'controllers/MemeDetailsController.php'; class Routing { public $routes = []; public function __construct() { $this->routes = [ 'index' => [ 'controller' => 'IndexController', 'action' => 'index' ], 'index_memes' => [ 'controller' => 'IndexController', 'action' => 'memes' ], 'login' => [ 'controller' => 'LoginController', 'action' => 'login' ], 'register' => [ 'controller' => 'RegisterController', 'action' => 'register' ], 'logout' => [ 'controller' => 'IndexController', 'action' => 'logout' ], 'upload' => [ 'controller' => 'UploadController', 'action' => 'upload' ], 'generate' => [ 'controller' => 'GenerateController', 'action' => 'generate' ], 'generated' => [ 'controller' => 'GenerateController', 'action' => 'generate' ], 'latest_meme' => [ 'controller' => 'GenerateController', 'action' => 'generated' ], 'your_uploaded_memes' => [ 'controller' => 'UserMemesController', 'action' => 'userUploadedMemes' ], 'your_generated_memes' => [ 'controller' => 'UserMemesController', 'action' => 'userGeneratedMemes' ], 'your_memes' => [ 'controller' => 'UserMemesController', 'action' => 'yourMemes' ], 'admin' => [ 'controller' => 'AdminController', 'action' => 'index' ], 'admin_users' => [ 'controller' => 'AdminController', 'action' => 'users' ], 'admin_delete_user' => [ 'controller' => 'AdminController', 'action' => 'userDelete' ], 'add_comment' => [ 'controller' => 'MemeDetailsController', 'action' => 'addComment' ], 'show_comments' => [ 'controller' => 'MemeDetailsController', 'action' => 'showComments' ] ]; } public function run() { $page = isset($_GET['page']) && isset($this->routes[$_GET['page']]) ? $_GET['page'] : 'login'; if ($this->routes[$page]) { $class = $this->routes[$page]['controller']; $action = $this->routes[$page]['action']; $object = new $class; $object->$action(); } } }<file_sep><?php require_once "AppController.php"; require_once "AdminController.php"; require_once __DIR__.'/../model/User.php'; require_once __DIR__.'/../model/UserMapper.php'; class LoginController extends AppController { public function __construct() { parent::__construct(); } public function login() { $mapper = new UserMapper(); $user = null; if ($this->isPost()) { $user = $mapper->getUser($_POST['email']); if(!$user) { return $this->render("LoginController", 'login', ['message' => ['Email not recognized']]); } if ($user->getPassword() !== md5($_POST['password'])) { return $this->render("LoginController", 'login', ['message' => ['Wrong password']]); } else { $_SESSION["ID"] = $user->getId(); $_SESSION["email"] = $user->getEmail(); $_SESSION["username"] = $user->getUsername(); $_SESSION["role_id"] = $user->getRole(); if($_SESSION['role_id']!=1) { $url = "http://$_SERVER[HTTP_HOST]"; header("Location: {$url}?page=index"); } else { $url = "http://$_SERVER[HTTP_HOST]"; header("Location: {$url}?page=admin"); } exit(); } } $this->render("LoginController",'login'); } }<file_sep><?php require_once 'AppController.php'; require_once __DIR__.'/../model/MemeMapper.php'; class IndexController extends AppController { public function __construct() { parent::__construct(); } public function index() { $this->render("IndexController",'index'); } public function logout() { session_unset(); session_destroy(); $this->render("LoginController", 'login', ['message' => ['You have been successfully logged out!']]); } public function memes() { $memeMapper = new MemeMapper(); header('Content-type: application/json'); http_response_code(200); echo $memeMapper->getMemes() ? json_encode($memeMapper->getMemes()) : ''; } }<file_sep><?php require_once "AppController.php"; require_once __DIR__.'/../model/MemeMapper.php'; class MemeDetailsController extends AppController { public function __construct() { parent::__construct(); } public function addComment() { if (!isset($_POST['id']) && !isset($_POST['comment'])) { http_response_code(404); return; } $meme = new MemeMapper(); $meme->addComment((int)$_POST['id'], $_POST['comment']); http_response_code(200); } public function showComments() { if (!isset($_POST['id'])) { http_response_code(404); return; } $meme = new MemeMapper(); http_response_code(200); echo $meme->getAllMemeComments((int)$_POST['id'])? json_encode($meme->getAllMemeComments((int)$_POST['id'])) : ''; } }<file_sep><!DOCTYPE html> <html> <?php include(dirname(__DIR__) . '/head.html'); ?> <body> <?php include(dirname(__DIR__) . '/navbar.html'); ?> <div class="container-fluid"> <!-- <div class="row">--> <!-- <div class="col-sm-12 text-right">--> <!-- --><?php // if(isset($_SESSION) && !empty($_SESSION)) { // echo '<p>Logged as '. $_SESSION["username"].'. To logout click <a href=\'?page=logout\'>here</a></p>'; // } // ?> <!-- </div>--> <!-- </div>--> <div class="row"> <div class="col-sm-12"> <br> <div id="memeCanvas"> <div class="row"> <div class="col-md-7 offset-1 generated-meme"> </div> <div class="col-md-3"> <form method="POST" ENCTYPE="multipart/form-data"> <div class="form-group"> <p>Your meme is ready! Press the button to see it in your memes gallery -> </p> </div> <div class="form-group"> </div> </form> <input type="submit" value="Go to my memes!" class="btn btn-danger form-control" onclick="document.location.href='?page=your_memes';"> <br><br> </div> </div> </div> </div> </body> </html> <file_sep>$(document).ready(function () { const apiUrl = "http://localhost:7000"; const $memesList = $('.memes'); $.ajax({ url : apiUrl + '/?page=index_memes', dataType : 'json' }) .done((res) => { $memesList.empty(); console.log(res); res.forEach(el => { let relativePath = '..' + el.path.slice(33); $memesList.append(`<div class="meme-field center"> <p class="meme-title">${el.title}</p> <img src="${relativePath}" width="100%" alt="${el.title}" class="meme-image"> <p class="author">Author: ${el.username}</p> <button class="btn btn-warning btn-lg" type="button" onclick="showFormComment()">Add Comment </button><br> <form style="display:none;" class="newCommentForm"><hr> <textarea id=${el.id} class="newComment" name="newCommentValue" placeholder="Enter your comment here..."></textarea><br> <input type="button" name="${el.id}" value="Submit" class="btn btn-primary" onclick="addCommentToMeme(${el.id})"><hr> </form><br> <button class="btn btn-danger btn-lg showCommentsButton${el.id}" type="button" onclick="showAllMemeComments(${el.id})">Show All Comments </button> </div> `); }); }); function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $('#uploadedImage').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } $("#chooseImage").change(function() { readURL(this); }); const $generatedMeme = $('.generated-meme'); $.ajax({ url : apiUrl + '/?page=latest_meme', dataType : 'json' }) .done((res) => { console.log(res); res.forEach(el => { let relativePath = '..' + el.path.slice(33); $generatedMeme.append(` <img class="img-responsive" src="${relativePath}" width="80%" alt="${el.title}"> `); }) }); const $uploadedMemes = $('.uploaded-memes'); $.ajax({ url : apiUrl + '/?page=your_uploaded_memes', dataType : 'json' }) .done((res) => { $uploadedMemes.empty(); console.log(res); res.forEach(el => { let relativePath = '..' + el.path.slice(33); $uploadedMemes.append(` <img class="img-responsive" src="${relativePath}" width="80%" alt="${el.title}"><hr> `); }) }); const $generatedMemes = $('.generated-memes'); $.ajax({ url : apiUrl + '/?page=your_generated_memes', dataType : 'json' }) .done((res) => { $generatedMemes.empty(); console.log(res); res.forEach(el => { let relativePath = '..' + el.path.slice(33); $generatedMemes.append(` <img class="img-responsive" src="${relativePath}" width="80%" alt="${el.title}"><hr> `); }) }); }) function getUsers() { const apiUrl = "http://localhost:7000"; const $list = $('.users-list'); $.ajax({ url : apiUrl + '/?page=admin_users', dataType : 'json' }) .done((res) => { console.log(res); $list.empty(); res.forEach(el => { $list.append(`<tr> <td>${el.username}</td> <td>${el.name}</td> <td>${el.surname}</td> <td>${el.email}</td> <td>${el.role_id}</td> <td> <button class="btn btn-danger" type="button" onclick="deleteUser(${el.ID})"> <i class="material-icons">delete_forever</i> </button> </td> </tr>`); }) }); } function deleteUser(id) { if (!confirm('Do you want to delete this user?')) { return; } const apiUrl = "http://localhost:7000"; $.ajax({ url : apiUrl + '/?page=admin_delete_user', method : "POST", data : { id : id }, success: function() { alert('Selected user successfully deleted from database!'); getUsers(); } }); } function addCommentToMeme(id) { const apiUrl = "http://localhost:7000"; let value = $('#'+id+'.newComment').val(); console.log(value); $.ajax({ url : apiUrl + '/?page=add_comment', method : "POST", data : { id : id, comment: value }, success: function(msg) { alert('Add comment successfully!'); console.log(msg); showAllMemeComments(id); }, error: function(e) { console.log(e); } }); } function showFormComment() { $('.newCommentForm').css('display', 'block'); console.log('click!'); } function showAllMemeComments(id) { const showCommentsButton = $('.showCommentsButton'+id); const apiUrl = "http://localhost:7000"; $.ajax({ url: apiUrl + '/?page=show_comments', method: "POST", data: { id: id } }) .done((res) => { showCommentsButton.empty(); var resDecode = JSON.parse(res); showCommentsButton.parent().append(`<table class="table table-hover" id="commentTable`+id+`"> `); $('#commentTable'+id).empty(); resDecode.forEach(el => { $('#commentTable'+id).append(`<tr> <td>${el.id}</td> <td>${el.comment}</td></tr>`); }) showCommentsButton.parent().append(`</table>`); }); $('.showCommentsButton'+id).css('display', 'none'); }<file_sep><?php /** * Created by PhpStorm. * User: kasia * Date: 19.01.19 * Time: 12:58 */ require_once __DIR__.'/../Database.php'; class MemeMapper { private $database; public function __construct() { $this->database = new Database(); } public function addMeme($path, $title, $user_id) { try { $stmt = $this->database->connect()->prepare("INSERT INTO `meme` (path, title, user_id) VALUES('$path', '$title', '$user_id')"); $stmt->bindParam(':path', $path, PDO::PARAM_STR); $stmt->bindParam(':title', $title, PDO::PARAM_STR); $stmt->bindParam(':user_id', $user_id, PDO::PARAM_STR); $stmt->execute(); return true; } catch(PDOException $e) { return 'Error: ' . $e->getMessage(); } } public function getMemes() { try { $stmt = $this->database->connect()->prepare('SELECT meme.id, meme.path, meme.title, users.username FROM meme LEFT JOIN users ON users.ID = meme.user_id ORDER BY meme.id DESC;'); $stmt->execute(); $user = $stmt->fetchAll(PDO::FETCH_ASSOC); return $user; } catch(PDOException $e) { die(); } } public function getUserMemes($user_id) { try { $stmt = $this->database->connect()->prepare('SELECT path, user_id FROM meme WHERE user_id = :user_id'); $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT); $stmt->execute(); $user = $stmt->fetchAll(PDO::FETCH_ASSOC); return $user; } catch(PDOException $e) { die(); } } public function getUserGeneratedMemes($user_id) { try { $stmt = $this->database->connect()->prepare('SELECT path, user_id FROM generated_meme WHERE user_id = :user_id'); $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT); $stmt->execute(); $user = $stmt->fetchAll(PDO::FETCH_ASSOC); return $user; } catch(PDOException $e) { die(); } } public function addComment($meme_id, $comment) { try { $userMapper = new UserMapper(); $userId = null; if( isset( $_SESSION['email'])) { $userId = $userMapper->getUser($_SESSION['email'])->getId(); } $stmt = $this->database->connect()->prepare("INSERT INTO `comment` (comment, meme_id, user_id) VALUES('$comment', '$meme_id', '$userId')"); $stmt->bindParam(':meme_id', $meme_id, PDO::PARAM_INT); $stmt->bindParam(':comment', $comment, PDO::PARAM_STR); $stmt->bindParam(':user_id', $userId, PDO::PARAM_INT); $stmt->execute(); //echo $userId." ".$meme_id." ".$comment; return true; } catch(PDOException $e) { return 'Error: ' . $e->getMessage(); } } public function getAllMemeComments($id) { try { $stmt = $this->database->connect()->prepare('SELECT id, comment FROM comment WHERE meme_id = :id'); $stmt->bindParam(':id', $id, PDO::PARAM_INT); $stmt->execute(); $comments = $stmt->fetchAll(PDO::FETCH_ASSOC); return $comments; } catch(PDOException $e) { die(); } } }<file_sep><?php class User { private $id; private $username; private $name; private $surname; private $email; private $password; private $role_id; public function __construct($id, $username, $name, $surname, $email, $password, $role_id) { $this->id = $id; $this->username = $username; $this->name = $name; $this->surname = $surname; $this->email = $email; $this->password = $password; $this->role_id = $role_id; } public function getUsername() { return $this->username; } public function setUsername($username): void { $this->username = $username; } public function getName() { return $this->name; } public function setName($name): void { $this->name = $name; } public function getSurname() { return $this->surname; } public function setSurname($surname): void { $this->surname = $surname; } public function getEmail() { return $this->email; } public function setEmail($email): void { $this->email = $email; } public function getPassword() { return $this->password; } public function setPassword($password): void { $this->password = md5($password); } public function getId() { return $this->id; } public function getRole(): int { return $this->role_id; } public function setRole(string $role_id): void { $this->role_id = $role_id; } }<file_sep><!DOCTYPE html> <html> <?php include(dirname(__DIR__) . '/head.html'); ?> <body> <?php include(dirname(__DIR__) . '/navbar.html'); ?> <div class="container-fluid"> <div class="row"> <div class="col-sm-12"> <p class="meme-title">GENERATE YOUR MEME</p> <br> <div id="memeCanvas"> <div class="row"> <div class="col-md-7 offset-1"> <img class="img-responsive" id="uploadedImage" alt="" src="http://oliclinic.pl/wp-content/uploads/2016/10/orionthemes-placeholder-image.png" width="80%"> </div> <div class="col-md-3"> <form action="?page=generated" method="POST" ENCTYPE="multipart/form-data"> <div class="form-group"> <label for="title">Title</label> <input type="text" name="title" id="title" class="form-control"> </div> <div class="form-group"> <label for="toptext">Top Text</label> <input type="text" name="toptext" id="toptext" class="form-control"> </div> <div class="form-group"> <label for="bottomtext">Bottom Text</label> <input type="text" name="bottomtext" id="bottomtext" class="form-control"> </div> <div class="form-group"> <input type="file" name="file" value="Upload Your Image" class="form-control" id="chooseImage"> </div> <div class="form-group"> <input type="submit" value="Meme It!" class="btn btn-danger form-control"> </div> </form> <br><br> </div> </div> </div> </div> </body> </html><file_sep><!DOCTYPE html> <html> <?php include(dirname(__DIR__) . '/head.html'); ?> <body> <?php include(dirname(__DIR__) . '/navbar.html'); ?> <div class="container-fluid"> <div class="row"> <div class="col-sm-6 center"> <p class="meme-title">Your uploaded memes</p><hr> <div class="uploaded-memes"> </div> </div> <div class="col-sm-6 center"> <p class="meme-title">Your generated memes</p><hr> <div class="generated-memes"> </div> </div> </div> </div> </body> </html><file_sep><?php require_once "AppController.php"; require_once __DIR__.'/../model/MemeMapper.php'; class UserMemesController extends AppController { public function __construct() { parent::__construct(); } public function userUploadedMemes() { $memeMapper = new MemeMapper(); $userMapper = new UserMapper(); $userId = null; if( isset( $_SESSION['email'])) { $userId = $userMapper->getUser($_SESSION['email'])->getId(); } header('Content-type: application/json'); http_response_code(200); echo $memeMapper->getUserMemes($userId) ? json_encode($memeMapper->getUserMemes($userId)) : ''; } public function userGeneratedMemes() { $memeMapper = new MemeMapper(); $userMapper = new UserMapper(); $userId = null; if( isset( $_SESSION['email'])) { $userId = $userMapper->getUser($_SESSION['email'])->getId(); } header('Content-type: application/json'); http_response_code(200); echo $memeMapper->getUserGeneratedMemes($userId) ? json_encode($memeMapper->getUserGeneratedMemes($userId)) : ''; } public function yourMemes() { $this->render("UserMemesController",'memes'); } }<file_sep><!DOCTYPE html> <html> <?php include(dirname(__DIR__) . '/head.html'); ?> <body> <?php include(dirname(__DIR__) . '/navbar.html'); ?> <div class="container-fluid"> <!-- <div class="row">--> <!-- <div class="col-sm-12 text-right">--> <!-- --><?php // if(isset($_SESSION) && !empty($_SESSION)) { // echo '<p>Logged as '. $_SESSION["username"].'. To logout click <a href=\'?page=logout\'>here</a></p>'; // } // ?> <!-- </div>--> <!-- </div>--> <div class="row"> <div class="col-sm-6 offset-sm-3 memes "> </div> <div class="col-sm-6 offset-sm-3 author "> </div> <div class="col-sm-6 offset-sm-3 comment"> </div> </div> </div> </body> </html><file_sep><!DOCTYPE html> <html> <?php include(dirname(__DIR__).'/head.html') ?> <body> <?php include(dirname(__DIR__).'/navbar.html') ?> <div class="container"> <div class="row"> <div class="col-sm-6 offset-sm-3 upload-form"> <p class="meme-title">UPLOAD YOUR MEME</p> <form action="?page=upload" method="POST" ENCTYPE="multipart/form-data"> <div class="form-group row"> <div class="col-sm-12"> <input type="text" class="form-control" id="inputTitle" name="title" placeholder="title" required/> </div> </div> <div class="form-group row upload"> <input type="file" name="file" value=""/><br/><br/> </div> <input type="submit" value="Upload" class="btn btn-danger"/> </form> <hr> <?php if(isset($message)): ?> <?php foreach($message as $item): ?> <div><?= $item ?></div> <?php endforeach; ?> <?php endif; ?> </div> </div> </div> </body><file_sep><?php const GENERATED_DIRECTORY = '/public/generatedMemes/'; require __DIR__.'/../vendor/autoload.php'; use GDText\Box; use GDText\Color; class MemeGenerator { private $font = '../public/assets/fonts/impact.ttf'; private $image; private $imageWidth; private $imageHeight; public function __construct($image, $imageWidth, $imageHeight) { $this->image = $image; $this->imageWidth = $imageWidth; $this->imageHeight = $imageHeight; } private function createImage($path) { $ext = pathinfo($path, PATHINFO_EXTENSION); if ($ext == 'jpg' || $ext == 'jpeg') return imagecreatefromjpeg($path); else if ($ext == 'png') return imagecreatefrompng($path); else if ($ext == 'gif') return imagecreatefromgif($path); } public function generateMeme($upperText, $lowText) { $uploadedImage = $this->createImage($this->image); $box = new Box($uploadedImage); $box->setFontFace("/home/kasia/Pulpit/pai-meme-maker/public/assets/fonts/impact.ttf"); $box->setFontSize(40); $box->setBox(0, 20, $this->imageWidth, $this->imageHeight); $box->setFontColor(new Color(255, 255, 255)); $box->setStrokeColor(new Color(0, 0, 0)); $box->setStrokeSize(3); $box->setTextAlign('center', 'top'); $box->setLineHeight(1.5); $box->draw(strtoupper($upperText)); $box = new Box($uploadedImage); $box->setFontFace("/home/kasia/Pulpit/pai-meme-maker/public/assets/fonts/impact.ttf"); $box->setFontSize(40); $box->setBox(0, -20, $this->imageWidth, $this->imageHeight); $box->setFontColor(new Color(255, 255, 255)); $box->setStrokeColor(new Color(0, 0, 0)); $box->setStrokeSize(3); $box->setTextAlign('center', 'bottom'); $box->setLineHeight(1.0); $box->draw(strtoupper($lowText)); imagejpeg($uploadedImage, dirname(__DIR__).GENERATED_DIRECTORY.$_SESSION['username'].'/'.$_FILES['file']['name'], 100); } } ?><file_sep><?php require_once __DIR__.'/../model/MemeMapper.php'; class UploadController extends AppController { const MAX_FILE_SIZE = 150000; const SUPPORTED_TYPES = ['image/jpeg', 'image/png', 'image/gif']; private $message = []; public function __construct() { parent::__construct(); } public function upload() { $memeMapper = new MemeMapper(); $userMapper = new UserMapper(); if ($this->isPost() && $this->validate($_FILES['file'])) { $userLogin=$_SESSION['username'].'/'; $userId = null; if( isset( $_SESSION['email'])) { $userId = $userMapper->getUser($_SESSION['email'])->getId(); } $uploadDirectory = dirname(__DIR__).self::GENERATE_DIRECTORY.$userLogin.$_FILES['file']['name']; if(move_uploaded_file( $_FILES['file']['tmp_name'], $uploadDirectory )) { $memeMapper->addMeme($uploadDirectory, $_POST['title'], $userId); $this->message[] = 'File uploaded.'; } } $this->render('UploadController', 'upload', [ 'message' => $this->message]); } private function validate(array $file): bool { if ($file['size'] > self::MAX_FILE_SIZE) { $this->message[] = 'File is too large for destination file system.'; return false; } if (!isset($file['type']) || !in_array($file['type'], self::SUPPORTED_TYPES)) { $this->message[] = 'File type is not supported.'; return false; } return true; } }
1276e1a0acd8e1c9e7918456b60120d234fc515f
[ "JavaScript", "PHP" ]
20
PHP
kaoleksy/meme-generator
533231a3273b58ab19e614278cd05b6f2a13561d
cf80ad2e995264ebc029c015cb519e591ecc21a0
refs/heads/main
<file_sep><? // accesscontrol.php -- this file was missing from the original distribution from the seller ?> <file_sep><?php session_start(); require_once "../main.php"; if(!isset($aid)) { ?> <font face="Tahoma, Arial, sans-serif" color="#000000"><strong>Admin Login</strong> <p><form method="post" action="<?=$PHP_SELF?>" style="background:none;"> <table width="446" cellspacing="5"> <tr> <td width="150"> Admin ID:</td> <td> <input type="text" name="aid" size="8" style="border-color:black"></td> </tr> <tr> <td width="150">Password:</td> <td><input type="<PASSWORD>" name="apass" SIZE="8" style="border-color:black"></td> </tr> <tr><td>&nbsp;</td> <td align=left><input type="submit" value=" Login " style="border-color:black; background-color:#e0e7e9; color:#000000; font-weight:normal"></td> </tr> <tr><td colspan=2 align=center> <a class=TN href=forgot.php> Forgot your password? </a></td></tr> </table> </form></p> </center> <?php include ("../foother.html"); exit; } session_register("aid"); session_register("apass"); $sql = "SELECT * FROM job_admin_login WHERE aid = '$aid' AND apass = '$apass'"; $result = mysql_query($sql); if (!$result) { echo "A database error occurred while checking your login details. <br>If this error persists, please contact $email_address"; } elseif (mysql_num_rows($result) == 0) { session_unregister("aid"); session_unregister("apass"); ?> <table width="446"><tr><td> <strong>Access Denied</strong> <p>Your user ID or password is incorrect, or you are not a registered user on this site. To try logging in again, click <a href="<?=$PHP_SELF?>">here</a>. </p> </td></tr></table> <?php include ("../foother.html"); exit; } ?><file_sep><?php require_once ('session.php'); require_once ('shared.php'); if(isset($_POST['sosl_search'])){ //correction for dynamic magic quotes if(get_magic_quotes_gpc()){ $_POST['sosl_search'] = stripslashes($_POST['sosl_search']); } foreach($_POST as $postKey => $postValue){ $_SESSION[$postKey] = $postValue; } } //Main form logic: When the user first enters the page, display form defaulted to //show the search results with default object selected on a previous page, otherwise // just display the blank form. When the user selects the SCREEN or CSV options, the //search is processed by the correct function if (isset($_POST['searchSubmit']) && isset($_POST['sosl_search'])) { print "<body onLoad='toggleFieldDisabled();'>"; require_once ('header.php'); show_search_form($_POST['sosl_search']); $searchTimeStart = microtime(true); $records = search($_POST['sosl_search']); $searchTimeEnd = microtime(true); $searchTimeElapsed = $searchTimeEnd - $searchTimeStart; show_search_result($records,$searchTimeElapsed); include_once('footer.php'); } else { print "<body onLoad='toggleFieldDisabled();'>"; require_once ('header.php'); show_search_form($_SESSION['sosl_search']); include_once('footer.php'); } //Show the main SOSL search form with default search or last submitted search and export action (screen or CSV) function show_search_form($sosl_search){ print "<script>\n"; print <<<SEARCH_BUILDER_SCRIPT function toggleFieldDisabled(){ if(document.getElementById('SB_searchString').value){ document.getElementById('SB_limit').disabled = false; document.getElementById('SB_fieldTypeSelect').disabled = false; document.getElementById('SB_objSelect1').disabled = false; document.getElementById('SB_objDetail1').disabled = false; } else { document.getElementById('SB_limit').disabled = true; document.getElementById('SB_fieldTypeSelect').disabled = true; document.getElementById('SB_objSelect1').disabled = true; document.getElementById('SB_objDetail1').disabled = true; } if(!document.getElementById('SB_objSelect1').value || document.getElementById('SB_objSelect1').disabled){ document.getElementById('SB_objDetail1').disabled = true; document.getElementById('SB_objSelect2').disabled = true; document.getElementById('SB_objDetail2').disabled = true; } else { document.getElementById('SB_objDetail1').disabled = false; document.getElementById('SB_objSelect2').disabled = false; document.getElementById('SB_objDetail2').disabled = false; } if(!document.getElementById('SB_objSelect2').value || document.getElementById('SB_objSelect2').disabled){ document.getElementById('SB_objDetail2').disabled = true; document.getElementById('SB_objSelect3').disabled = true; document.getElementById('SB_objDetail3').disabled = true; } else { document.getElementById('SB_objDetail2').disabled = false; document.getElementById('SB_objSelect3').disabled = false; document.getElementById('SB_objDetail3').disabled = false; } if(!document.getElementById('SB_objSelect3').value || document.getElementById('SB_objSelect3').disabled){ document.getElementById('SB_objDetail3').disabled = true; } else { document.getElementById('SB_objDetail3').disabled = false; } } //function updateObject(){ // document.search_form.justUpdate.value = 1; // document.search_form.submit(); //} function build_search(){ toggleFieldDisabled(); var searchString = 'FIND {' + document.getElementById('SB_searchString').value + '}'; var fieldTypeSelect = ''; if(document.getElementById('SB_fieldTypeSelect').value && !document.getElementById('SB_fieldTypeSelect').disabled){ fieldTypeSelect = ' IN ' + document.getElementById('SB_fieldTypeSelect').value; } var objSelect1 = ''; if(document.getElementById('SB_objSelect1').value && !document.getElementById('SB_objSelect1').disabled){ objSelect1 = ' RETURNING ' + document.getElementById('SB_objSelect1').value; if(document.getElementById('SB_objDetail1').value && !document.getElementById('SB_objDetail1').disabled){ objSelect1 += '(' + document.getElementById('SB_objDetail1').value + ')'; } } var objSelect2 = ''; if(document.getElementById('SB_objSelect2').value && !document.getElementById('SB_objSelect2').disabled){ objSelect2 = ', ' + document.getElementById('SB_objSelect2').value; if(document.getElementById('SB_objDetail2').value && !document.getElementById('SB_objDetail2').disabled){ objSelect2 += '(' + document.getElementById('SB_objDetail2').value + ')'; } } var objSelect3 = ''; if(document.getElementById('SB_objSelect3').value && !document.getElementById('SB_objSelect3').disabled){ objSelect3 = ', ' + document.getElementById('SB_objSelect3').value; if(document.getElementById('SB_objDetail3').value && !document.getElementById('SB_objDetail3').disabled){ objSelect3 += '(' + document.getElementById('SB_objDetail3').value + ')'; } } var limit = ''; if(document.getElementById('SB_limit').value && !document.getElementById('SB_limit').disabled){ limit = ' LIMIT ' + document.getElementById('SB_limit').value; } if (searchString) document.getElementById('sosl_search_textarea').value = searchString + fieldTypeSelect + objSelect1 + objSelect2 + objSelect3 + limit; } </script> SEARCH_BUILDER_SCRIPT; if($_SESSION['config']['autoJumpToSearchResults']){ print "<form method='POST' name='search_form' action='$_SERVER[PHP_SELF]#sr'>\n"; } else { print "<form method='POST' name='search_form' action='$_SERVER[PHP_SELF]#sr'>\n"; } print "<p><strong>Enter a search string and optionally select the objects and fields to return to build a SOSL search below:</strong></p>\n"; print "<table border='0' width=1>\n<tr>\n"; print "<td>Search for </td><td><input type='text' id='SB_searchString' name='SB_searchString' value=\"" . htmlspecialchars($_SESSION['SB_searchString'],ENT_QUOTES,'UTF-8') . "\" size='37' onKeyUp='build_search();' /> in "; $fieldTypeSelectOptions = array( 'ALL FIELDS' => 'All Fields', 'NAME FIELDS' => 'Name Fields', 'PHONE FIELDS' => 'Phone Fields', 'EMAIL FIELDS' => 'Email Fields' ); print "<select id='SB_fieldTypeSelect' name='SB_fieldTypeSelect' onChange='build_search();'>\n"; foreach ($fieldTypeSelectOptions as $op_key => $op){ print "<option value='$op_key'"; if (isset($_SESSION['SB_fieldTypeSelect']) && $op_key == $_SESSION['SB_fieldTypeSelect']) print " selected='selected' "; print ">$op</option>"; } print "</select>"; print " limited to <input id='SB_limit' name='SB_limit' type='text' value='" . htmlspecialchars($_SESSION['SB_limit'],ENT_QUOTES,'UTF-8') . "' size='5' onKeyUp='build_search();' /> maximum records</td></tr>\n"; print "<tr><td colspan='2'></td></tr>"; print "<tr><td>returning object </td><td NOWRAP>"; myGlobalSelect($_SESSION['SB_objSelect1'],'SB_objSelect1',20,"onChange='build_search();'"); print " including fields <input id='SB_objDetail1' name='SB_objDetail1' type='text' value=\"" . htmlspecialchars($_SESSION['SB_objDetail1'],ENT_QUOTES,'UTF-8') . "\" size='40' onKeyUp='build_search();' />"; print "&nbsp;<img onmouseover=\"Tip('List the API names of the fields to be returned; otherwise, only the Id is returned. Optionally include WHERE and LIMIT statements to futher filter search results.')\" align='absmiddle' src='images/help16.png'/>"; print "</td></tr>"; print "<tr><td colspan='2'></td></tr>"; print "<tr><td>and object </td><td NOWRAP>"; myGlobalSelect($_SESSION['SB_objSelect2'],'SB_objSelect2',20,"onChange='build_search();'"); print " including fields <input id='SB_objDetail2' name='SB_objDetail2' type='text' value=\"" . htmlspecialchars($_SESSION['SB_objDetail2'],ENT_QUOTES,'UTF-8') . "\" size='40' onKeyUp='build_search();' /></td></tr>"; print "<tr><td colspan='2'></td></tr>"; print "<tr><td>and object </td><td NOWRAP>"; myGlobalSelect($_SESSION['SB_objSelect3'],'SB_objSelect3',20,"onChange='build_search();'"); print " including fields <input id='SB_objDetail3' name='SB_objDetail3' type='text' value=\"" . htmlspecialchars($_SESSION['SB_objDetail3'],ENT_QUOTES,'UTF-8') . "\" size='40' onKeyUp='build_search();' /></td></tr>"; print "<tr><td valign='top' colspan='3'><br/>Enter or modify a SOSL search below:" . "<br/><textarea id='sosl_search_textarea' type='text' name='sosl_search' cols='100' rows='4' style='overflow: auto; font-family: monospace, courier;'>". htmlspecialchars($sosl_search,ENT_QUOTES,'UTF-8') . "</textarea>" . "</td></tr>"; print "<tr><td colspan=3><input type='submit' name='searchSubmit' value='Search' />"; print "<input type='reset' value='Reset' />"; print "</td></tr></table><p/></form>\n"; } function search($sosl_search){ try{ global $mySforceConnection; $search_response = $mySforceConnection->search($sosl_search); if(isset($search_response->searchRecords)){ $records = $search_response->searchRecords; } else { $records = null; } return $records; } catch (Exception $e){ $errors = null; $errors = $e->getMessage(); show_error($errors); include_once('footer.php'); exit; } } //If the user selects to display the form on screen, they are routed to this function function show_search_result($records, $searchTimeElapsed){ //Check if records were returned if ($records) { try { print "<a name='sr'></a><div style='clear: both;'><br/><h2>Search Results</h2>\n"; print "<p>Returned " . count($records) . " total record"; if (count($records) !== 1) print 's'; print " in "; printf ("%01.3f", $searchTimeElapsed); print " seconds:</p>"; $searchResultArray = array(); foreach($records as $record){ $recordObject = new Sobject($record->record); $searchResultArray[$recordObject->type][] = $recordObject; } foreach($searchResultArray as $recordSetName=>$records){ echo "<h3 style='color: #0046ad;'>$recordSetName</h3>"; print "<table class='data_table'>\n"; //Print the header row on screen $record0 = $records[0]; print "<tr><td>1</td>"; //If the user queried for the Salesforce ID, this special method is nessisary //to export it from the nested SOAP message. This will always be displayed //in the first column regardless of search order if ($record0->Id){ print "<th>Id</th>"; } if ($record0->fields){ foreach($record0->fields->children() as $field){ print "<th>"; print htmlspecialchars($field->getName(),ENT_QUOTES,'UTF-8'); print "</th>"; } }else { print "</td></tr>"; } print "</tr>\n"; //Print the remaining rows in the body $rowNum = 2; foreach ($records as $record) { print "<tr><td>$rowNum</td>"; $rowNum++; //Another check if there are ID columns in the body if (isset($record->Id)){ print "<td>$record->Id</td>"; } //Print the non-ID fields if (isset($record->fields)){ foreach($record->fields as $datum){ print "<td>"; if($datum){ print htmlspecialchars($datum,ENT_QUOTES,'UTF-8'); } else { print "&nbsp;"; } print "</td>"; } print "</tr>\n"; } else{ print "</td></tr>\n"; } } print "</table><p/>"; } print "</div>\n"; } catch (Exception $e) { $errors = null; $errors = $e->getMessage(); print "<p />"; show_error($errors); include_once('footer.php'); exit; } } else { print "<p><a name='sr'>&nbsp;</a></p>"; show_error("Sorry, no records returned."); } include_once('footer.php'); } ?> <file_sep><? include_once "accesscontrol.php"; if(isset($ok) && $ok == 'Send my application') { $q1 = "select CompanyEmail from job_employer_info where ename = \"$_POST[ename]\""; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); $url = "http://$_SERVER[HTTP_HOST]/employers/EmployerView.php?uname=$uname"; $q2 = "select fname, job_seeker_email, rTitle from job_seeker_info where uname = \"$uname\" "; $r2 = mysql_query($q2) or die(mysql_error()); $a2 = mysql_fetch_array($r2); if(empty($a2[rTitle])) { echo "<table width=446><tr><td><br><br><br><center><br> Please, <a class=TN href=build_resume.php> post </a> resume to apply for a job.</center></td></tr></table>"; exit; } $qui = "insert into job_aplicants set job_id = \"$_POST[job_id]\", aplicant = \"$uname\""; $rui = mysql_query($qui) or die(mysql_error()); $from = "From: $a2[0] <$a2[1]>"; $subject = "New job applicant"; $message = "A job seeker has apliyed for your job offer. <br> To review the applicants resume, go to this address:\n $url\n\n You can access this information from Employers menu/Manage Jobs and then click on the link \"view aplicants list\" for each job offer."; mail($a1[0], $subject, $message, $from); echo "<table width=446><br><br><br><center> Your application has been sent to the employer.</center></td></tr></table>"; } elseif(isset($friend) && $friend == 'Send to a friend') { $url = "http://$_SERVER[HTTP_HOST]/jobseekers/FriendView.php?job_id=$_POST[job_id]"; ?> <br> <br> <form action=Friend2.php method=post style="background:none;"> <table align=center width="446"> <tr> <td><b> Friend's email: </b></td> <td><input type=text name=femail size=31></td> </tr> <tr> <td valign=top><b>Message: </b></td> <td><textarea rows=4 cols=60 name=fmessage>I found a great Job Offer at <?=$site_name?>. Go to this URL to find out more. <?=$url?> </textarea></td> </tr> <tr> <td colspan=2 align=center> <input type=submit name=submit value=Send> </td> </tr> </table> </form> <? } ?> <? include_once('../foother.html'); ?><file_sep><?php require_once ('session.php'); require_once ('shared.php'); put('upsert'); ?> <file_sep>function popUpDocumentForFlash4ProjectPlanDemo(rNum) { var aURL = '/app/flash/IssueTrack-Project-Plan/IssueTrack-Project-Plan.html?nocache=' + ((rNum == null) ? '' : rNum); try {popUpWindowForURL(aURL, 'IssueTrackProjectPlan'); } catch(e) { ezAlertError(ezErrorExplainer(e)); }; } <file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; if (isset($_POST["sub"])) { $res=mysql_query("UPDATE `configuration` SET `active_account` = '" . $_POST["activeaccnt"] . "', `vendorid` = '" . $_POST["vendorid"] . "', `paypal_email` = '" . $_POST["paypal_email"] . "', `site_name` = '" . $_POST["site_name"] . "' , `email` = '" . $_POST["email"] . "', `address` = '" . $_POST["address"] . "' WHERE `conf_id` =" . $_POST["conf_id"]); echo "<br><br><center>Successfully Updated</center><br><br>"; } else { $res=mysql_query("Select * from configuration"); $res2=mysql_fetch_array($res); ?> <form action="<? echo $PHP_SELF;?>" method="post" style="background:none;"> <table width="440" border="0" align="center" cellpadding="0" cellspacing="0"> <!--DWLayoutTable--> <tr> <td width="152" height="21" align="left" valign="middle"><strong>Site Name</strong></td> <td width="288" align="left" valign="middle"><input type="text" name="site_name" value="<? echo $res2["site_name"];?>"></td> </tr> <tr> <td height="21" align="left" valign="middle"><strong>Site Address</strong></td> <td align="left" valign="middle"><input type="text" name="address" value="<? echo $res2["address"];?>"></td> </tr> <tr> <td height="21" align="left" valign="middle"><strong>Email Address</strong></td> <td align="left" valign="middle"><input type="text" name="email" value="<? echo $res2["email"];?>"></td> </tr> <tr> <td height="21" align="left" valign="middle"><strong>Paypal ID</strong></td> <td align="left" valign="middle"><input type="text" name="paypal_email" value="<? echo $res2["paypal_email"];?>"></td> </tr> <tr> <td height="21" align="left" valign="middle"><strong>2Checkout Vendor ID</strong></td> <td align="left" valign="middle"><input type="text" name="vendorid" value="<? echo $res2["vendorid"];?>"></td> </tr> <tr> <td height="21" align="left" valign="middle"><strong>Active Account</strong></td> <td align="left" valign="middle"><select name="activeaccnt"> <option value="pptc" <? if ($res2["active_account"]=="pptc") { echo "selected";}?>>Us Both (PayPal & Checkout)</option> <option value="pp" <? if ($res2["active_account"]=="pp") { echo "selected";}?>>PayPal</option> <option value="tc" <? if ($res2["active_account"]=="tc") { echo "selected";}?>>2CheckOut</option> </select></td> </tr> <tr> <td height="21" align="left" valign="middle"><!--DWLayoutEmptyCell-->&nbsp;</td> <td align="left" valign="middle"><input type="submit" value="Update" name="sub" style="border-color:black; background-color:#e0e7e9; color:#000000; font-weight:normal"> <input type="hidden" name="conf_id" value="<? echo $res2["conf_id"];?>"></td> </tr> </table> </form> <? } ?> <? include_once('../foother.html'); ?><file_sep>function rand(val) { return (Math.floor(val * Math.random())); } <file_sep> <?php include_once("..\includes\documentHeader.php"); ?> <?php $dbNum = 101; $myFile = "debug.txt"; if (file_exists($myFile)) { unlink($myFile); } $dbNum++; $fHand = fopen($myFile, "w") or die("Error $dbNum!!"); fwrite($fHand, "\$_SERVER(1) :: " . count($_SERVER) . "\n" . var_print_r($_SERVER) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$_SERVER(2) :: " . count($_SERVER) . "\n" . var_dump_ret($_SERVER) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$HTTP_POST_VARS(1) :: \n" . var_print_r($HTTP_POST_VARS) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$HTTP_POST_VARS(2) :: \n" . var_dump_ret($HTTP_POST_VARS) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$HTTP_RAW_POST_DATA(1) :: \n" . var_print_r($HTTP_RAW_POST_DATA) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$HTTP_RAW_POST_DATA(2) :: \n" . var_dump_ret($HTTP_RAW_POST_DATA) . "\n\n"); fclose($fHand); $dbNum++; $ServerPacketSend = getXMLPacket($HTTP_POST_VARS); $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$ServerPacketSend(1) :: \n" . var_print_r($ServerPacketSend) . "\n\n"); fclose($fHand); $dbNum++; $ServerPacketSend = getXMLPacket($HTTP_RAW_POST_DATA); $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$ServerPacketSend(2) :: \n" . var_print_r($ServerPacketSend) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$_GET(1) :: " . count($_GET) . "\n" . var_print_r($_GET) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$_GET(2) :: " . count($_GET) . "\n" . var_dump_ret($_GET) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$_POST(1) :: " . count($_POST) . "\n" . var_print_r($_POST) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$_POST(2) :: " . count($_POST) . "\n" . var_dump_ret($_POST) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$_REQUEST(1) :: " . count($_REQUEST) . "\n" . var_print_r($_REQUEST) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$_REQUEST(2) :: " . count($_REQUEST) . "\n" . var_dump_ret($_REQUEST) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$_FILES(1) :: " . count($_FILES) . "\n" . var_print_r($_FILES) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$_FILES(2) :: " . count($_FILES) . "\n" . var_dump_ret($_FILES) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$_COOKIE(1) :: " . count($_COOKIE) . "\n" . var_print_r($_COOKIE) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$_COOKIE(2) :: " . count($_COOKIE) . "\n" . var_dump_ret($_COOKIE) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$_ENV(1) :: " . count($_ENV) . "\n" . var_print_r($_ENV) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$_ENV(2) :: " . count($_ENV) . "\n" . var_dump_ret($_ENV) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$GLOBALS(1) :: " . count($GLOBALS) . "\n" . var_print_r($GLOBALS) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$GLOBALS(2) :: " . count($GLOBALS) . "\n" . var_dump_ret($GLOBALS) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$_SESSION(1) :: " . count($_SESSION) . "\n" . var_print_r($_SESSION) . "\n\n"); fclose($fHand); $dbNum++; $fHand = fopen($myFile, "a") or die("Error $dbNum!!"); fwrite($fHand, "\$_SESSION(2) :: " . count($_SESSION) . "\n" . var_dump_ret($_SESSION) . "\n\n"); fclose($fHand); ?> <?php $xmlstr = <<<XML <?xml version="1.0" encoding="iso-8859-1"?> <response> <status>1</status> </response> XML; echo $xmlstr; ?> <file_sep><? include "accesscontrol.php"; include_once "navigation2.htm"; $job_id=$_GET[job_id]; $q1 = "delete from job_post where job_id = '$job_id'"; $r1 = mysql_query($q1) or die(mysql_error()); $q2 = "delete from job_aplicants where job_id ='$job_id'"; $r2 = mysql_query($q2) or die(mysql_error()); echo "<table width=446><tr><td><br><br><br><center> All the information about Job Offer# $job_id was deleted successfully.</center></td></tr></table>"; ?> <? include_once('../foother.html'); ?><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"> <?php include_once("..\includes\documentHeader.php"); print_r(docHeader('../..')); ?> <script language="JavaScript1.2" type="text/javascript" src="popUpWindowForURL.js"></script> </head> <body> <?php if (stristr($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) == false) { $ar = splitStringToArray($_SERVER['SCRIPT_NAME']); redirectBrowser('/?linkname=' . $ar[count($ar) - 1]); } ?> <?php print(handleNoScript()); ?> <table width="590"> <tr> <td class="primaryContentContainerHeader"> <table width="100%"> <tr> <td align="left"> <p align="justify"><a href="/php/links/getContentForFlashCSharp.php" target="_self">C# using the .Net Framework</a></p> </td> <td align="right"> </td> </tr> </table> </td> </tr> <tr> <td height="200" valign="middle"> <table width="100%"> <tr> <td width="80%" valign="top"> <p align="justify">Welcome to the C# (C-Sharp) .Net Framework Sample(s).</p> <p align="justify">These Flash Samples were NOT created by the Author of this site however they do demonstrate the power of C# and the .Net Framework where Flash is concerned.</p> <p align="justify">Unlike traditionally developed Flash Movies these were created without the need to be concerned about any Timelines or tweening or the like. Physical simulations such as these could perhaps not be created using traditional Flash development techniques since physical simulations require dynamic manipulations of graphical elements. Traditional Flash development stresses how things happen based on the number of Frames per second of animation. C# allows the developer to express the solution set using timeline-independent means which means there is no timeline but there are graphical elements that have behaviors and those behaviors are coded using C# and the .Net Framework.</p> </td> <td width="*" valign="top"> <p align="justify"><NOBR><a href="" onClick="popUpWindowForURL('/app/flash/neoswiff/bubbles.html', 'bubbles', 750, 520); return false;">Bubbles</a></NOBR></p> <p align="justify"><NOBR><a href="" onClick="popUpWindowForURL('/app/flash/neoswiff/grid.html', 'grid', 750, 520); return false;">Grid of Dots</a></NOBR></p> <p align="justify"><NOBR><a href="" onClick="popUpWindowForURL('/app/flash/neoswiff/triangles.html', 'triangles', 750, 520); return false;">Cone of Triangles</a></NOBR></p> <p align="justify"><NOBR><a href="" onClick="popUpWindowForURL('/app/flash/neoswiff/SlideShow.html', 'SlideShow', 750, 520); return false;">SlideShow</a></NOBR></p> </td> </tr> </table> <!-- <h4>Under construction... Come on back a bit later-on...</h4> --> </td> </tr> </table> </body> </html> <file_sep><? unset($step); $step = '2'; include_once "accesscontrol.php"; $E_d = strip_tags($E_d); if ( $submit == 'Add Another') { $d1 = array(); $d1[0] = $ESmonth; $d1[1] = $ESyear; if (is_array($d1)) { $E_Start = implode("/" , $d1); } $d2 = array(); $d2[0] = $EEmonth; $d2[1] = $EEyear; if (is_array($d2)) { $E_End = implode("/" , $d2); } $qs1 = "insert into job_education set uname = \"$uname\", E_i = \"$E_i\", En = \"$En\", E_Start = \"$E_Start\", E_End = \"$E_End\", E_gr = \"$E_gr\", E_d = \"$E_d\" "; $rs1 = mysql_query($qs1) or die(mysql_error()); include "2s.php"; } elseif ($submit == 'Save and go to Step 3 (Skills)') { $E_d = strip_tags($E_d); $d1 = array(); $d1[0] = $ESmonth; $d1[1] = $ESyear; if (is_array($d1)) { $E_Start = implode("/" , $d1); } $d2 = array(); $d2[0] = $EEmonth; $d2[1] = $EEyear; if (is_array($d2)) { $E_End = implode("/" , $d2); } $qs1 = "insert into job_education set uname = \"$uname\", E_i = \"$E_i\", En = \"$En\", E_Start = \"$E_Start\", E_End = \"$E_End\", E_gr = \"$E_gr\", E_d = \"$E_d\" "; $rs1 = mysql_query($qs1) or die(mysql_error()); ?><script language="JavaScript">location.href='3.php';</script> <? } elseif(empty($En)) { include "2s.php"; } ?> <file_sep><? include_once "../main.php"; $q1 = "select * from job_plan"; $r1 = mysql_query($q1) or die(mysql_error()); ?> <html> <body > <table align=center width=500 bgcolor="#FFFFFF"> <tr> <td colspan=2> To access all the features we offer, choose your Employer Plan: </td> </tr> <? while($a1 = mysql_fetch_array($r1)) { echo " <tr> <form action=pay2.php method=post style=\"background:none;\"> <td> <b>$a1[PlanName]</b> <ul> <li>$a1[postings] job postings; </li> <li>$a1[reviews] resume reviews; </li> <li><b>price: <font color=#000000>$ $a1[price] </font</b></li> </ul> </td> <td> <input type=submit name=submit value=\"Buy $a1[PlanName]\"> <input type=hidden name=plan value=\"$a1[PlanName]\"> <input type=hidden name=postings value=\"$a1[postings]\"> <input type=hidden name=reviews value=\"$a1[reviews]\"> <input type=hidden name=price value=\"$a1[price]\"> <input type=hidden name=ename value=\"$ename\"> </td> </form> </tr>"; } ?> <html> </table> </body> </html> <? include_once('../foother.html'); ?><file_sep><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Flash Demos of <NAME> (c).Copyright 1990-2007, All Rights Reserved.</title> </head> <body> <p>It was not the intention of the author to make it appear as though all of these Flash Demos have any specific business purpose as they stand at this time.</p> <p>It was however the intention of the author that these Flash Demos be viewed as a small sample of the rather complex work the Author can easily perform for you assuming you choose to hire <NAME>.</p> </body> </html> <file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; ?> <table width="446"><tr><td> <? $q1 = "select * from job_plan"; $r1 = mysql_query($q1) or die(mysql_error()); $nr = mysql_num_rows($r1); echo "<br><br><br><table align=center width=300>\n"; if($nr < 1) { echo "<table width=440><tr><td><tr><td> You do not have any Price Plans. <br>To add a plan <a class=TNA href=AddPlan.php>click here</a></td></tr></table>"; } else { while($a1 = mysql_fetch_array($r1)) { echo "<table width=240 align=center><tr><td> <b> $a1[PlanName] </b> (<a class=TN href=\"DelPlan.php?PlanName=$a1[PlanName]\">delete </a> / <a class=TN href=\"EditPlan.php?PlanName=$a1[PlanName]\"> edit </a>) <ul> <li>Valid for $a1[numdays] days</li>\n <li>$a1[postings] postings</li>\n <li>$a1[reviews] reviews </li>\n <li>price <b>$$a1[price] </li>\n </ul> </td></tr></table>"; } echo "To add a new plan <a class=TNA href=AddPlan.php>click here</a>"; } ?> </td></tr></table> <? include_once('../foother.html'); ?><file_sep><? include_once "includes/documentHeader.php"; include_once "conn.php"; $day = date(d); $month = date(m); $year = date(Y); $del = "delete from job_post where EXday = \"$day\" and EXmonth = \"$month\" and EXyear = \"$year\" "; $rdel = mysql_query($del) or die(mysql_error()); $configuration=mysql_query("Select * from configuration") or die(mysql_error()); $configuration2=mysql_fetch_array($configuration); $paypal_email_address=$configuration2["paypal_email"]; $vendor_id=$configuration2["vendorid"]; $active_account=$configuration2["active_account"]; $site_name=$configuration2["site_name"]; $email_address=$configuration2["email"]; $site_address=$configuration2["address"]; $_SERVER["HTTP_HOST"] = "$site_address"; if (strlen($_SERVER["HTTP_HOST"]) == 0) { serverHTTPHost(); } ?> <html> <head> <title><?=$site_name?> Jobs</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <link rel="stylesheet" href="http://<?=$_SERVER[HTTP_HOST]?>/style.css" type="text/css"> <SCRIPT LANGUAGE="JavaScript"> function popUp(URL) { day = new Date(); id = day.getTime(); eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=yes,location=0,statusbar=0,menubar=0,resizable=yes,width=600,height=400,left = 100,top = 50');"); } </script> </head> <body bgcolor="#FFFFFF" style="text-align: center"> <table width="664" border="0" cellpadding="0" cellspacing="0" align="center" bgcolor="#FFFFFF"> <tr> <td height="25" colspan="0" valign="top" align="center"> <? include("header2.php"); ?> </td> <TABLE WIDTH=550 BORDER=0 align="center" CELLPADDING=0 CELLSPACING=0> <TR> <TD ROWSPAN=2 background="http://<?=$_SERVER[HTTP_HOST]?>/images/body_01.gif">&nbsp;</TD> <TD height="325" bgcolor="#ffffff">&nbsp;</TD> <TD width="100" valign="top" bgcolor="#ffffff"><? include("left2.php"); ?></TD> <TD width="446" valign="top" bgcolor="#ffffff"> <file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; if(isset($submit) && $submit == "Search by name") { $q1 = "select * from job_seeker_info where $name_type like '%$name%' order by $name_type"; $r1 = mysql_query($q1); if (!$r1) { echo '<table align=center width=446 cellspacing=0 border=0><tr><td><center><br><br><br>Select <b>order by </b> option </center></td></tr></table>'; include ("../foother.html"); exit; } if(mysql_num_rows($r1) == '0') { echo "<table align=center width=446 cellspacing=0><tr><td><center><br><br><br> No results. </center></td></tr></table>"; include("../foother.html"); exit; } echo "<br><br><table align=center width=400 cellspacing=0>\n"; echo "<tr bgcolor=6699cc style=\"font-family:arial; font-weight:bold; color:white\">\n <td>Username </td> <td> Name </td><td>Resume</td><td align=center>Delete </td></tr>"; $col = "e0e7e9"; while($a1 = mysql_fetch_array($r1)) { if($col == "e0e7e9") { $col = "ffffff"; } else { $col = "e0e7e9"; } echo "<tr bgcolor=\"$col\"><td> $a1[uname] </td><td><a class=TN href=\"preview.php?uname=$a1[uname]\"> $a1[fname] $a1[lname] </a></td>"; if ($a1[isupload]==1) echo "<td><a href=\"../jobseekers/$a1[resume]\">Download</a></td>"; else echo "<td>N/A</td>"; echo "<td align=center><a class=TN href=\"ADR.php?uname=$a1[uname]\">resume</a>/<a class=TN href=\"ADU.php?uname=$a1[uname]\">user </a></td></tr>"; } echo "</table>\n"; include ("../foother.html"); exit; } elseif(isset($submit) && $submit == "List users") { if (!$ByPage) $ByPage=25; if (!$Start) $Start=0; $q1 = "select * from job_seeker_info order by $order_type limit $Start,$ByPage"; $r1 = mysql_query($q1); if (!$r1) { echo '<table align=center width=446 cellspacing=0><tr><td><center><br><br><br>Select <b>order by </b> option </center></td></tr></table>'; include ("../foother.html"); exit; } echo "<br><br><table align=center width=400 cellspacing=0>\n"; echo "<tr bgcolor=6699cc style=\"font-family:arial; font-weight:bold; color:white\">\n <td>Username </td> <td> Name </td><td align=center>Delete </td></tr>"; $col = "e0e7e9"; while($a1 = mysql_fetch_array($r1)) { if($col == "e0e7e9") { $col = "ffffff"; } else { $col = "e0e7e9"; } echo "<tr bgcolor=\"$col\"><td> $a1[uname] </td><td><a class=TN href=\"javascript:popUp('preview.php?uname=$a1[uname]')\"> $a1[fname] $a1[lname] </a></td> <td align=center><a class=TN href=\"ADR.php?uname=$a1[uname]\">resume</a>/<a class=TN href=\"ADU.php?uname=$a1[uname]\">user </a></td></tr>"; } echo "</table>\n"; $cp = "select count(uname) from job_seeker_info"; $rcp = mysql_query($cp) or die (mysql_error()); $ap = mysql_fetch_array($rcp); $a = $ap[0]; echo "<table width=446 align=center cellspacing=0><tr>"; if ($a <= $ByPage && $Start == '0') { } elseif ($a > $Start + $ByPage && $Start + $ByPage >= $a || $Start == 0 ) { $nom = $Start + $ByPage; echo "<td align=right><a class=TN href=\"jobseekers.php?submit=$submit&order_type=$order_type&Start=$nom\">next</a></td>"; } elseif ( ($Start < $a && $Start > $ByPage) || ($Start + $ByPage >= $a)) { $nom1 = $Start - $ByPage; echo "<td align=left><a class=TN href=\"jobseekers.php?submit=$submit&order_type=$order_type&Start=$nom1\">previous</a></td>"; } else { $nom1 = $Start - $ByPage; echo "<td align=left><a class=TN href=\"jobseekers.php?submit=$submit&order_type=$order_type&Start=$nom1\">previous</a></td>"; $nom = $Start + $ByPage; echo "<td align=right><a class=TN href=\"jobseekers.php?submit=$submit&order_type=$order_type&Start=$nom\">next</a></td>"; } echo "</tr></table>"; include ("../foother.html"); exit; } ?> <br><br><br> <form method=post style="background:none;"> <table align=center width=400> <tr> <td colspan=2 align=center><b>Explore Jobseekers database </b><br><br></td> </tr> <tr> <td valign=top>Search for a Jobseeker by first name, last name or username</td> <td><font size=2><input type=text name=name><br> <input type=radio name=name_type value="fname">First name<br> <input type=radio name=name_type value="lname">Last name<br> <input type=radio name=name_type value="uname">Username<br> <input type=submit name=submit value="Search by name"> </td> </tr> <tr><td colspan=2></td></tr> <tr> <td valign=top>Give me a list of all the Jobseekers order by:</td> <td><font size=2> <input type=radio name=order_type value="fname">First name<br> <input type=radio name=order_type value="lname">Last name<br> <input type=radio name=order_type value="uname">Username<br> <input type=submit name=submit value="List users"> </td> </tr> <tr><td colspan=2></td></tr> </table> </form> <? include_once('../foother.html'); ?><file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; include_once "navigation.html"; $q1 = "delete from job_banners_t where b_id = \"$b_id\" "; $r1 = mysql_query($q1) or die(mysql_error()); $dir1="banners/"; $userfile = $fn; unlink($dir1.$userfile); $drop1 = "drop table if exists temp_ban"; $dropr1 = mysql_query($drop1) or die(mysql_error()); $tt = "create temporary table temp_ban (tb_id varchar(10) not null, tfn varchar(100) not null, tburl varchar(100) not null, talt varchar(255))"; $ttr = mysql_query($tt) or die(mysql_error()); $q2 = "select * from job_banners_t order by b_id"; $r2 = mysql_query($q2) or die(mysql_error()); while ($a2 = mysql_fetch_array($r2, MYSQL_ASSOC)) { if (!$a) $a = 1; $qt = "insert into temp_ban (tb_id, tfn, tburl, talt) values ('$a', '$a2[fn]', '$a2[burl]', '$a2[alt]')"; $rqt = mysql_query($qt) or die(mysql_error()); $a = $a + 1; } $q3 = "delete from job_banners_t"; $r3 = mysql_query($q3) or die(mysql_error()); $q4 = "select * from temp_ban order by tb_id"; $r4 = mysql_query($q4) or die(mysql_error()); while ($a4 = mysql_fetch_array($r4, MYSQL_ASSOC)) { if (!$w) $w = 1; $qt = "insert into job_banners_t (b_id, fn, burl, alt) values ('$w', '$a4[tfn]', '$a4[tburl]', '$a4[talt]')"; $rqt = mysql_query($qt) or die(mysql_error()); $w = $w + 1; } $drop = "drop table temp_ban"; $dropr = mysql_query($drop) or die(mysql_error()); ?> <? include_once('../foother.html'); ?><file_sep>// 01_getViewportHeight.js function ezGetViewportHeight() { if (window.innerHeight) return window.innerHeight; if (typeof window.document.documentElement.clientHeight == const_number_symbol) return window.document.documentElement.clientHeight; return window.document.body.clientHeight; } <file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; include_once "navigation.html"; $q1 = "delete from job_link_source where link_id = \"$link_id\" "; $r1 = mysql_query($q1) or die(mysql_error()); $drop1 = "drop table if exists temp_link"; $dropr1 = mysql_query($drop1) or die(mysql_error()); $tt = "create temporary table temp_link (tlink_id varchar(10) not null, tlink_code text)"; $ttr = mysql_query($tt) or die(mysql_error()); $q2 = "select * from job_link_source order by link_id"; $r2 = mysql_query($q2) or die(mysql_error()); while ($a2 = mysql_fetch_array($r2, MYSQL_ASSOC)) { if (!$a) $a = 1; $qt = "insert into temp_link (tlink_id, tlink_code) values ('$a', '$a2[link_code]') "; $rqt = mysql_query($qt) or die(mysql_error()); $a = $a + 1; } $q3 = "delete from job_link_source"; $r3 = mysql_query($q3) or die(mysql_error()); $q4 = "select * from temp_link order by tlink_id"; $r4 = mysql_query($q4) or die(mysql_error()); while ($a4 = mysql_fetch_array($r4, MYSQL_ASSOC)) { if (!$w) $w = 1; $qt = "insert into job_link_source (link_id, link_code) values ('$w', '$a4[tlink_code]')"; $rqt = mysql_query($qt) or die(mysql_error()); $w = $w + 1; } $drop = "drop table temp_link"; $dropr = mysql_query($drop) or die(mysql_error()); ?> <? include_once('../foother.html'); ?><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"> <?php include_once("php\includes\documentHeader.php"); print_r(docHeader('', false)); ?> <link href="/commonStyles.css" rel="stylesheet" type="text/css"> </head> <body> <?php print(handleNoScript()); ?> <script language="javascript1.2" type="text/javascript"> window.location.href = "/flex3/FlashSite.html"; </script> <noscript> Click <a href="/flex3/FlashSite.html" target="_blank">here</a> to continue however you do need to enable JavaScript to use this site. </noscript> </body> </html> <file_sep><? include "accesscontrol.php"; include "navigation2.htm"; $q1 = "select * from job_employer_info where ename = \"$ename\" "; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); ?> <html> <head> <title>Company profile for <?=$a1[CompanyName]?></title> </head> <body> <br><br><br><font face=verdana size=2> <table align=center cellspacing=2 cellpadding="2" border=0 bordercolor=black width=446> <caption align=center><b>Company profile for <?=$a1[CompanyName]?> </b><br><br></caption> <tr> <td width=180><b> Company: </b></td> <td> <?=$a1[CompanyName]?> </td> </tr> <tr> <td ><b> Country: </b></td> <td> <?=$a1[CompanyCountry]?> </td> </tr> <tr> <td ><b> City/State/Zip: </b></td> <td> <? echo "$a1[CompanyCity]/"; if(!empty($a1[CompanyState])) { echo "$a1[CompanyState]/"; } echo "$a1[CompanyZip]"; ?> </td> </tr> <tr> <td ><b> Address: </b></td> <td> <?=$a1[CompanyAddress]?> </td> </tr> <tr> <td ><b> Phone/Phone2: </b></td> <td> <? echo "$a1[CompanyPhone]"; if(!empty($a1[CompanyPhone2])) { echo "/$a1[CompanyPhone2]"; } ?> </td> </tr> <tr> <td ><b> Email: </b></td> <td> <a href=sm.php?email=<?=$a1[CompanyEmail]?>> <?=$a1[CompanyEmail]?> </a> </td> </tr> <tr> <td ><b> Posting plan: </b></td> <td> <? if(!empty($a1[plan])) { echo "$a1[plan]"; } else { echo "not selected yet"; } ?> </td> </tr> <tr> <td ><b> This employer can view: </b></td> <td> <?=$a1[JS_number]?> resume(s)</td> </tr> <tr> <td ><b> This employer can post: </b></td> <td> <?=$a1[JP_number]?> job offer(s)</td> </tr> </table> <? include_once('../foother.html'); ?><file_sep>// 01_getViewportWidth.js function ezGetViewportWidth() { if(window.innerWidth) return window.innerWidth - 16; if (typeof window.document.documentElement.clientWidth == const_number_symbol) return window.document.documentElement.clientWidth; return window.document.body.clientWidth; } <file_sep><?php //////////////////////////////////////////////////////// // Function: do_dump // Inspired from: PHP.net Contributions // Description: Better GI than print_r or var_dump function do_dump(&$var, $var_name = NULL, $indent = NULL, $reference = NULL) { $do_dump_indent = "<span style='color:#eeeeee;'>|</span> &nbsp;&nbsp; "; $reference = $reference.$var_name; $keyvar = 'the_do_dump_recursion_protection_scheme'; $keyname = 'referenced_object_name'; if (is_array($var) && isset($var[$keyvar])) { $real_var = &$var[$keyvar]; $real_name = &$var[$keyname]; $type = ucfirst(gettype($real_var)); echo "$indent$var_name <span style='color:#a2a2a2'>$type</span> = <span style='color:#e87800;'>&amp;$real_name</span><br>"; } else { $var = array($keyvar => $var, $keyname => $reference); $avar = &$var[$keyvar]; $type = ucfirst(gettype($avar)); if($type == "String") $type_color = "<span style='color:green'>"; elseif($type == "Integer") $type_color = "<span style='color:red'>"; elseif($type == "Double"){ $type_color = "<span style='color:#0099c5'>"; $type = "Float"; } elseif($type == "Boolean") $type_color = "<span style='color:#92008d'>"; elseif($type == "NULL") $type_color = "<span style='color:black'>"; if(is_array($avar)) { $count = count($avar); echo "$indent" . ($var_name ? "$var_name => ":"") . "<span style='color:#a2a2a2'>$type ($count)</span><br>$indent(<br>"; $keys = array_keys($avar); foreach($keys as $name) { $value = &$avar[$name]; do_dump($value, "['$name']", $indent.$do_dump_indent, $reference); } echo "$indent)<br>"; } elseif(is_object($avar)) { echo "$indent$var_name <span style='color:#a2a2a2'>$type</span><br>$indent(<br>"; foreach($avar as $name=>$value) do_dump($value, "$name", $indent.$do_dump_indent, $reference); echo "$indent)<br>"; } elseif(is_int($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color$avar</span><br>"; elseif(is_string($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color\"$avar\"</span><br>"; elseif(is_float($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color$avar</span><br>"; elseif(is_bool($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color".($avar == 1 ? "TRUE":"FALSE")."</span><br>"; elseif(is_null($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> {$type_color}NULL</span><br>"; else echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $avar<br>"; $var = $var[$keyvar]; } } function splitString($s,$t='') { $toks = array(); if (strlen($t) > 0) { $tok = strtok($s,$t); while ($tok) { array_push($toks,$tok); $tok = strtok($t); } } return $toks; } function join_list($array, $sep='/') { $str = ""; $size = count( $array ); $i = 0; foreach ( $array as $item ) { $str .= $item; $i++; if ( $i < $size - 1) $str .= $sep; elseif ( $i == $size - 1) $str .= $sep; } return $str; } ?> <file_sep><? session_start(); include_once "../main.php"; ?> <table width="446" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"><tr><td align="center"><br> <? //echo $_POST; //foreach ($_POST as $key => $value) { // echo "$key = $value<br />\n"; //} if ($_POST['submit'] == "Register me") { if (is_array($JobCategory)) { $JobStr = implode("," , $JobCategory); } if($careerlevel == '1') { $clname = 'Student (High School)'; } elseif($careerlevel == '2') { $clname = 'Student (undergraduate/graduate)'; } elseif($careerlevel == '3') { $clname = 'Entry Level (less than 2 years of experience)'; } elseif($careerlevel == '4') { $clname = 'Mid Career (2+ years of experience)'; } elseif($careerlevel == '5') { $clname = 'Management (Manager/Director of Staff)'; } elseif($careerlevel == '6') { $clname = 'Executive (SVP, EVP, VP)'; } elseif($careerlevel == '7') { $clname = 'Senior Executive (President, CEO)'; } $query = "insert into job_seeker_info set uname = \"". $_POST["uname"] . "\", upass = \"$upass\", title = \"$title\", fname = \"$fname\", lname = \"$lname\", bmonth = \"$bmonth\", bday = \"$bday\", byear = \"$byear\", maritalstatus = \"$maritalstatus\", income = \"$income\", city = \"$city\", state = \"$state\", country = \"$country\", zip = \"$zip\", address = \"$address\", phone = \"$phone\", phone2 = \"$phone2\", job_seeker_email = \"$job_seeker_email\", job_seeker_web = \"$job_seeker_web\", job_category = \"$JobStr\", careerlevel = \"$clname\", target_company = \"$target_company\", relocate = \"$relocate\" "; $result = mysql_query($query); if (!$result) { echo '<table width=446><tr><td> <br><br><center>This username is already in use. Please choose another. </center></td></tr></table></td></tr></table>'; include ("../foother.html"); exit; } $qcl = "insert into job_careerlevel set uname =\"". $_POST["uname"] . "\", clnumber = \"$careerlevel\", clname = \"$clname\" "; $rcl = mysql_query($qcl) or die(mysql_error()); $to = $job_seeker_email; $subject = "Your account at $site_name"; $message = "This is your account information at $site_name\n\n username: $uname\n password: <PASSWORD> Keep this information in a secure place. \n\n Thanks for your registration. We believe you will find a job at \n http://$_SERVER[HTTP_HOST]"; $from = "From: <$email_address>"; mail($to, $subject, $message, $from); session_register("uname"); session_register("upass"); echo "<br><br><br> <p align=center> Your registration was completed successfully.<br>You can start to <a href=build_resume.php>build your resume </a> or <a href=JobSearch.php> Search for a Job </a> </p> "; } else { echo "<center><br><br><br><font color=red><b> You have a mistake filling the password/confirm password fields. <br> Go <a class=ERR href=jobseeker_registration.php> back </a> and fill all them properly, please.</b></font></center>"; } ?> </td></tr></table> <? include_once('../foother.html'); ?><file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; if(isset($submit) && $submit == 'Add') { $q1 = "insert into job_plan set PlanName = \"$PlanName\", numdays = \"$numdays\", postings = \"$postings\", reviews = \"$reviews\", price = \"$price\""; $r1 = mysql_query($q1) or die(mysql_error()); } ?> <br> <table align=center width=300 border=0> <form action=<?=$PHP_SELF?> method=post> <caption> Add a new plan </caption> <tr> <td><b> Plan name:</b></td> <td>&nbsp;&nbsp;<input type=text name=PlanName></td> </tr> <tr> <td><b>Number of Days</b></td> <td>&nbsp;&nbsp;<input type=text name=numdays size=5></td> </tr> <tr> <td><b>Postings: </b></td> <td>&nbsp;&nbsp;<input type=text name=postings size=5></td> </tr> <tr> <td><b> Reviews: </b></td> <td>&nbsp;&nbsp;<input type=text name=reviews size=5></td> </tr> <tr> <td><b> Price: </b></td> <td><b>$</b><input type=text name=price size=5></td> </tr> <tr> <td></td> <td>&nbsp;&nbsp;&nbsp;<input type=submit name=submit value=Add>&nbsp;<input type=reset></td> </tr> </form> </table> <? include_once('../foother.html'); ?><file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; include_once "navigation.html"; if(isset($submit) && !empty($link_id) && !empty($link_code)) { $il = "insert into job_link_source (link_id, link_code) values ('$link_id', '$link_code') "; $ril = mysql_query($il) or die(mysql_error()); $sb13 = "select * from job_banners_m"; $r13 = mysql_query($sb13) or die(mysql_error()); $ar13 = @mysql_result($r13,0,bc); if(empty($ar13)) { $ubi = "insert into job_banners_m (bc) values ('2') "; $rup = mysql_query($ubi) or die(mysql_error()); } else { $ubi = "update job_banners_m set bc = '2' "; $rup = mysql_query($ubi) or die(mysql_error()); } } $lid = "select count(link_id) from job_link_source"; $rlid = mysql_query($lid) or die(mysql_error()); $alid = mysql_fetch_array($rlid); $link_id = $alid[0] + 1; ?> <html> <head> <title>Add links</title> </head> <body> <br><br> <form method=post action=<?=$PHP_SELF?> style="background:none;"> <table align=center> <tr> <td class=TD_links>Link ID: </td> <td class=TD_links> <b> <?=$link_id?> </b></td> </tr> <tr> <td valign=top class=TD_links> Paste the link-code: </td> <td class=TD_links> <textarea name=link_code rows=4 cols=40 style=border-color:black></textarea> </td> </tr> <tr><td></td><td><input type=submit name=submit value=Submit style="background-color:white; border-color:black"> </table> <input type=hidden name=link_id value=<?=$link_id?>> </form> </body> </html> <? include_once('../foother.html'); ?><file_sep><!-- saved from url=(0014)about:internet --> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>MVC.mxml</title> <link rel="stylesheet" type="text/css" href="../SourceStyles.css"/> </head> <body><pre><span class="MXMLProcessing_Instruction">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;</span> <span class="MXMLComponent_Tag">&lt;mx:Application</span><span class="MXMLDefault_Text"> xmlns:mx = </span>&quot;<span class="MXMLString">http://www.adobe.com/2006/mxml</span><span class="MXMLDefault_Text">&quot; xmlns:view = </span>&quot;<span class="MXMLString">view.*</span><span class="MXMLDefault_Text">&quot; width = </span>&quot;<span class="MXMLString">100%</span><span class="MXMLDefault_Text">&quot; height = </span>&quot;<span class="MXMLString">100%</span><span class="MXMLDefault_Text">&quot; paddingLeft = </span>&quot;<span class="MXMLString">10</span><span class="MXMLDefault_Text">&quot; paddingRight = </span>&quot;<span class="MXMLString">10</span><span class="MXMLDefault_Text">&quot; paddingTop = </span>&quot;<span class="MXMLString">10</span><span class="MXMLDefault_Text">&quot; paddingBottom = </span>&quot;<span class="MXMLString">10</span><span class="MXMLDefault_Text">&quot; viewSourceURL=&quot;</span><span class="MXMLString">srcview/index.html</span><span class="MXMLDefault_Text">&quot;</span><span class="MXMLComponent_Tag">&gt;</span> <span class="MXMLComment">&lt;!--</span><span class="MXMLComment"> This MVC Sample features a full-blown Model View and Controller. Compare this code to MVC Sample #2 to see how much more code was required to make this Application Model functional. Try to imagine how much more code your developers will have to produce when using this approach and how much more expensive an effort would have to be if every single developer was using a stright-up MVC programming pattern. More than 50% of the development time would have been spent on building the Singletons for the controller classes before considering the debugging overhead. Also keep in mind even with MVC every single Controller is going to be bound to the Application such that these Controllers cannot be reused for multiple projects unless the same business logic and every other function was duplicated across projects. The same thing holds for the views that will be unique for each project. Code reuse comes into play when common code modules are required from project to project. Common widgets are beneficial. Common widget event handlers are beneficial. And common Model objects can also be beneficial to a degree. Views will invariable be different from a high-level perspective. Also take into consideration the fact that every single senior developer I have ever talked with has balked at the idea of using MVC when there is no clear benefit in using this approach versus the one outlined in MVC Sample #2. Better to invest one&apos;s time in leveraging code reuse where possible and keep the level of development as light as possible lest one ends-up spending more money than one wanted to for each effort only to find oneself with a ton of code for each project with little functionality to show for the effort. </span><span class="MXMLComment">--&gt;</span> <span class="MXMLComponent_Tag">&lt;mx:VBox</span><span class="MXMLDefault_Text"> label=&quot;</span><span class="MXMLString">Basic Flex MVC Implementation #1</span><span class="MXMLDefault_Text">&quot; width=&quot;</span><span class="MXMLString">100%</span><span class="MXMLDefault_Text">&quot; height=&quot;</span><span class="MXMLString">100%</span><span class="MXMLDefault_Text">&quot; </span><span class="MXMLComponent_Tag">&gt;</span> <span class="MXMLComponent_Tag">&lt;view:MessageInput</span><span class="MXMLDefault_Text"> width=&quot;</span><span class="MXMLString">100%</span><span class="MXMLDefault_Text">&quot; </span><span class="MXMLComponent_Tag">/&gt;</span> <span class="MXMLComponent_Tag">&lt;mx:Spacer</span><span class="MXMLDefault_Text"> height=&quot;</span><span class="MXMLString">25</span><span class="MXMLDefault_Text">&quot; </span><span class="MXMLComponent_Tag">/&gt;</span> <span class="MXMLComponent_Tag">&lt;view:MessageOutput</span><span class="MXMLDefault_Text"> width=&quot;</span><span class="MXMLString">100%</span><span class="MXMLDefault_Text">&quot; </span><span class="MXMLComponent_Tag">/&gt;</span> <span class="MXMLComponent_Tag">&lt;/mx:VBox&gt;</span> <span class="MXMLComponent_Tag">&lt;/mx:Application&gt;</span></pre></body> </html> <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"> <?php include_once("..\includes\documentHeader.php"); print_r(docHeader('../..')); ?> <script language="JavaScript1.2" type="text/javascript" src="popUpWindowForURL.js"></script> </head> <body> <?php if (stristr($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) == false) { $ar = splitStringToArray($_SERVER['SCRIPT_NAME']); redirectBrowser('/?linkname=' . $ar[count($ar) - 1]); } ?> <?php print(handleNoScript()); ?> <table width="590"> <tr> <td class="primaryContentContainerHeader"> <table width="100%"> <tr> <td align="left"> <p align="justify"><a href="/php/links/getContentForFlashMaps.php" target="_self">Flash Maps</a></p> </td> <td align="right"> </td> </tr> </table> </td> </tr> <tr> <td height="200" valign="middle"> <table width="100%"> <tr> <td width="80%" valign="top"> <p align="justify">Yahoo Maps Sample(s) that features the Yahoo Maps Flash API - this was quite easy to code.</p> <p align="justify">Yahoo Maps Sample(s) both samples feature City/State/Zip or Full Address Lookup and All 3 Map types plus Local Search that allows business types to be found and displayed on the map.</p> </td> <td width="*" valign="top"> <p align="justify"><NOBR><a href="" onClick="popUpWindowForURL('/app/flash/maps/ezMapsSample1.html', 'ezMapsSample1', 750, 510); return false;">Yahoo Maps Sample #1 - Local Search Overlay</a></NOBR></p> <p align="justify"><NOBR><a href="" onClick="popUpWindowForURL('/app/flash/maps/ezMapsSample2.html', 'ezMapsSample2', 750, 510); return false;">Yahoo Maps Sample #2 - Traffic Overlay</a></NOBR></p> </td> </tr> </table> <!-- <h4>Under construction... Come on back a bit later-on...</h4> --> </td> </tr> </table> </body> </html> <file_sep><? include_once "../main.php"; ?> <table width="446" bgcolor="#FFFFFF"><tr><td> <? if ($act=="success") { // foreach($_POST as $key=>$value) // { // echo $key . " => " . $value . "<br>"; // } include ("pay222.php"); $q = "select * from job_plan where PlanName = \"$plan\""; $r = mysql_query($q) or die(mysql_error()); $a = mysql_fetch_array($r); $qm = "select CompanyEmail from job_employer_info where ename = \"$epayname\" "; $rqm = mysql_query($qm) or die(mysql_error()); $am = mysql_fetch_array($rqm); $to = "$am[0]"; $subject = "Your employer plan at $site_name"; $message = "Hello,\n here is your employer plan information at $site_name:\n\n Plan name: $plan\n Membership valid until $expireon $a[postings]\n\n <?=$site_name?> Team"; $from = "From: $email_address"; if ($invalidtxn == "false") { echo "<br><br><br><center> <strong>Now you can view $a[reviews] resumes<br> and can post $a[postings] job offers.</strong> </center>"; mail($to, $subject, $message, $from); } } else { $qm = "select CompanyEmail from job_employer_info where ename = \"$epayname\" "; $rqm = mysql_query($qm) or die(mysql_error()); $am = mysql_fetch_array($rqm); $to = "$am[0]"; $subject = "Paypal problem"; $message = "there was a problem with a Paypal.com payment.\n\n this is the referer url: $ar\n User ID: $epayname\n plan: $plan"; $from = "From: $email_address"; mail($to, $subject, $message, $from); echo "<center> There is a problem with your account. <br>The site administrator already know this <br>and will contact you as soon as possible.</center>"; } ?> </td></tr></table> <? include_once('../foother.html'); ?><file_sep><?php include_once("../includes/documentHeader.php"); $errors = array(); $debug = array(); $data = ""; $success = "false"; function echo_errors($errors) { $errorsStream = ""; $errorsStream = $errorsStream . "<error>"; for($i = 0; $i < count($errors); $i++) { $errorsStream = $errorsStream . "<msg>" . cdataEscape($errors[$i]) . "</msg>"; } $errorsStream = $errorsStream . "</error>"; return $errorsStream; } function echo_debug($debug) { $debugStream = ""; $debugStream = $debugStream . "<debug>"; for($i = 0; $i < count($debug); $i++) { $debugStream = $debugStream . "<msg>" . cdataEscape($debug[$i]) . "</msg>"; } $debugStream = $debugStream . "</debug>"; return $debugStream; } array_push($debug,"action=" . $_REQUEST['action']); $t = getdate(); $today = date('m-d-y', $t[0]); $file_path = $_SERVER['DOCUMENT_ROOT']."/#myUploads/" . $today . "/" . $_SERVER['REMOTE_ADDR']; switch($_REQUEST['action']) { case "upload": $file_temp = $_FILES['file']['tmp_name']; $file_name = $_FILES['file']['name']; array_push($debug,"\$file_temp=" . $file_temp); array_push($debug,"\$file_name=" . $file_name); array_push($debug,"\$file_path=" . $file_path); if (!is_dir ( $file_path)) { mkdir( $file_path, 0700, true); } //checks for duplicate files if(!file_exists($file_path."/".$file_name)) { //complete upload $filestatus = move_uploaded_file($file_temp,$file_path."/".$file_name); if(!$filestatus) { $success = "false"; array_push($errors,"Upload failed. Please try again."); } } else { $success = "false"; array_push($errors,"File already exists on server."); } break; default: $success = "false"; array_push($errors,"No action was requested."); } ?> <?php $success = cdataEscape($success); $errStr = echo_errors($errors); $debugStr = echo_debug($debug); $xmlstr = <<<XML <?xml version="1.0" encoding="iso-8859-1"?> <results> <success>$success</success> $data $errStr $debugStr </results> XML; echo $xmlstr; ?> <file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; $q1 = "delete from job_plan where PlanName = \"$PlanName\""; $r1 = mysql_query($q1) or die(mysql_error()); ?> <? include_once('../foother.html'); ?><file_sep><?php include_once('shared.php'); global $version; ?> </div> <div class='disclaimer'> <br/> Workbench v<?php echo $version; ?><br/> <?php //print $_SERVER[SERVER_NAME]; if (!isset($_SERVER['HTTPS']) && $_SERVER['SERVER_NAME'] !== 'localhost' && $_SERVER['SERVER_NAME'] !== '127.0.0.1' && $_SERVER['SERVER_NAME'] !== '10.8.45.11' ){ print "<span style='font-size: 8pt; color: red;'>WARNING: Unsecure connection detected</span><br/>"; } if(isset($GLOBALS['requestTimeStart'])){ $requestTimeEnd = microtime(true); $requestTimeElapsed = $requestTimeEnd - $GLOBALS['requestTimeStart']; printf ("Requested in %01.3f sec<BR/>", $requestTimeElapsed); } if(stristr($version,'beta') || stristr($version,'alpha')){ print "<br/><a href='http://groups.google.com/group/forceworkbench' target='_blank'>THANK YOU FOR BETA TESTING - PLEASE PROVIDE FEEDBACK</a>"; } ?> </div> </body> </html> <?php //USAGE: debug($showSuperVars = true, $showSoap = true, $customName = null, $customValue = null) debug(true,true,null,null); ?><file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; if(isset($update)) { $qu = "update job_story set story = \"$NewStory\" where story_id = \"$story_id\" "; $ru = mysql_query($qu) or die(mysql_error()); echo "<br><br><br><center> The story was updated successfully. </center>"; } else { $q1 = "select * from job_story where story_id = \"$story_id\""; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); ?> <form action=<?=$PHP_SELF?> method=post style="background:none;"> <table align=center width=400 cellspacing=0> <tr> <td>Story ID# <?=$a1[story_id]?> </td> </tr> <tr> <td> <textarea name=NewStory cols=40 rows=10> <?=$a1[story]?> </textarea></td> </tr> <tr><td align=center> <input type=hidden name=story_id value=<?=$a1[story_id]?>> <input type=submit name=update value=Update></td></tr> </table> </form> <? } ?> <? include_once('../foother.html'); ?><file_sep>The code found in this ZIP File is protected by U.S. Federal Copyright Laws and may not be used or distributed in any manner without the prior written permission of <NAME> or Hierarchical Applications Limited, Inc. (c). Copyright 2003-2008, <NAME> and Hierarchical Applications Limited, Inc., All Rights Reserved. <file_sep><? include_once "accesscontrol.php"; $q1 = "select * from job_work_experience where uname = \"$uname\" order by WEn asc "; $r2 = mysql_query($q1) or die(mysql_error()); echo "<br><br><br>"; while ($a1 = mysql_fetch_array($r2)) { echo " <form action=EditWorkExperience.php method=post style=\"background:none;\"> <table align=center width=420 border=0 bordercolor=e0e7e9 cellspacing=0 cellpadding=0> <caption> <input type=submit name=submit value=Delete style=\"border-width:1; border-color:black; font-family:verdana; font-weight:normal; color:#000000; background-color:#e0e7e9\"> <input type=hidden name=WEn value=$a1[WEn]> <font size=2> <strong>Work experience# $a1[WEn]</strong> </font> <input type=submit name=submit value=Edit style=\"border-width:1; border-color:black; font-family:verdana; font-weight:normal; color:#000000; background-color:#e0e7e9\"> <input type=hidden name=WEn value=$a1[WEn]> </caption> </form> <tr> <td colspan=4><b>Position: </b> $a1[WE_p] </td> </tr> <tr> <td><b>From date</b>&nbsp;&nbsp;&nbsp;$a1[WE_Start]</td> <td><b>To date</b>&nbsp;&nbsp;&nbsp;$a1[WE_End]</td> </tr> <tr> <td ></td> <td ></td> </tr> <tr> <td colspan=4> <table cellspacing=0 width=100%> <tr> <td valign=top> <b>Description:&nbsp;</b>&nbsp;$a1[WE_d] </td> </tr> <tr> <td > </td> </tr> </table> </td> </td> </tr> </table><br> "; } $qs = "select count(WEn) from job_work_experience where uname = \"$uname\" "; $rqs = mysql_query($qs) or die(mysql_error()); $aqs = mysql_fetch_array($rqs); $WEn = $aqs[0] + 1; echo "<table width=446><tr><td><center> <a href=EWAdd.php?WEn=$WEn>Add another </a> OR <a href=ER4.php> Go to Step 2 (Education) </a> </center></tr></td></table>"; ?> <? include_once('../foother.html'); ?><file_sep><?php require "../connect.php"; require "version.php"; if(!isset($_GET['locale'])) { ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Surreal ToDo Install</title> <link rel="stylesheet" type="text/css" href="../theme/base.css" /> </head> <body> <div id="install"> <?php echo ' <form action="'.$_SERVER['PHP_SELF'].'" method="get" name="form_locale">'; echo _('Language'); ?> <select title="Language" name="locale"> <?php // open the locale directory $localeDirectory = "../locale/"; $directory = opendir($localeDirectory); // get each entry while($entryName = readdir($directory)) { $localeList[] = $entryName; } // close directory closedir($directory); sort($localeList); // loop through the array of files and print them all foreach ($localeList as $locales) { if (substr("$locales", 0, 1) != "."){ // don't list hidden files if (filetype($localeDirectory.$locales) == "file") continue; echo "<option>$locales</option>"; } } ?> </select> <?php echo ' <input name="continue" type="submit" value="'._('Continue').'" /> </form> '; } else { $locale = $_GET['locale']; bindtextdomain($locale, '../locale'); bind_textdomain_codeset($locale, 'UTF-8'); textdomain($locale); setlocale(LC_ALL,$locale); if(!isset($_GET['install'])) { // if the form has NOT been submitted ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Surreal ToDo Install</title> <link rel="stylesheet" type="text/css" href="../theme/base.css" /> </head> <body> <div id="install"> <?php echo '<h1>Surreal ToDo v'.APP_VERSION.' '._('Installation').'</h1>'; $query = mysql_query("show tables"); if(!$query) { echo '<h2>'._('Database connection failed.').'</h2>'; echo '<p>'._('Edit connect.php and set the mysql database connection information.').'</p>'; exit; } $num_results = mysql_num_rows($query); if($num_results > 0) { echo '<h2>'._('The database is not empty.').'</h2>'; echo '<h2>'._('This install script will not continue.').'</h2>'; echo '<p>Surreal ToDo '._('currently does not support sharing a database.').'</p>'; } else { echo '<h2>'._('This script will create the needed tables in your database.').'</h2>'; echo ' <form action="'.$_SERVER['PHP_SELF'].'" method="get" name="form_install"> <input name="locale" type="hidden" value="'.$locale.'" /> <input name="install" type="submit" value="'._('Install').'" /> </form> '; } } if(isset($_GET['install'])) // if the form has been submitted { $default_timezone = date_default_timezone_get(); mysql_query(" CREATE TABLE `config` ( `name` varchar(128) NULL, `value` varchar(128) NULL, PRIMARY KEY (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci "); mysql_query("insert into config set name = 'version', value = '".APP_VERSION."'"); mysql_query("insert into config set name = 'timezone', value = '".$default_timezone."'"); mysql_query("insert into config set name = 'default_site_name', value = 'Surreal ToDo'"); mysql_query("insert into config set name = 'date_format', value = 'Y-m-d'"); mysql_query("insert into config set name = 'time_format', value = 'h:ia'"); mysql_query("insert into config set name = 'locale', value = '".$locale."'"); mysql_query("insert into config set name = 'theme', value = 'default'"); mysql_query("insert into config set name = 'completed_item', value = '8'"); mysql_query(" CREATE TABLE `tabs` ( `tab_id` int(8) unsigned NOT NULL auto_increment, `name` varchar(20) collate utf8_unicode_ci NOT NULL, `date_created` timestamp NOT NULL default CURRENT_TIMESTAMP, `position` int(8) unsigned default '0', `trash` int(1) unsigned default '0', PRIMARY KEY (`tab_id`), KEY `tab` (`trash`,`position`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; "); mysql_query(" insert into tabs set name = '"._('Main Tab')."'; "); mysql_query(" CREATE TABLE `pages` ( `page_id` int(8) unsigned NOT NULL auto_increment, `name` varchar(20) collate utf8_unicode_ci NOT NULL, `tab_id` int(8) unsigned NOT NULL default '0', `date_created` timestamp NOT NULL default CURRENT_TIMESTAMP, `position` int(8) unsigned default '1', `columns` int(1) unsigned default '3', `trash` int(1) unsigned default '0', PRIMARY KEY (`page_id`), KEY `page` (`tab_id`,`trash`,`position`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; "); mysql_query(" insert into pages set name = '"._('Main Page')."', tab_id = 1, position = 1; "); mysql_query(" CREATE TABLE `lists` ( `list_id` int(8) unsigned NOT NULL auto_increment, `name` varchar(50) collate utf8_unicode_ci NOT NULL, `page_id` int(8) unsigned NOT NULL default '0', `date_created` timestamp NOT NULL default CURRENT_TIMESTAMP, `column_id` int(8) unsigned default NULL, `position` int(8) unsigned default '1', `expanded` int(1) NOT NULL default '1', `trash` int(1) unsigned default '0', `show_item_date` int(1) unsigned default '0', PRIMARY KEY (`list_id`), KEY `list` (`page_id`,`trash`,`column_id`,`position`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; "); mysql_query(" CREATE TABLE `items` ( `id` int(8) unsigned NOT NULL auto_increment, `list_id` int(8) unsigned NOT NULL, `text` mediumText collate utf8_unicode_ci NOT NULL, `date_created` timestamp NOT NULL default CURRENT_TIMESTAMP, `date_completed` datetime default NULL, `position` int(8) unsigned NOT NULL default '0', `trash` int(1) unsigned default '0', PRIMARY KEY (`id`), KEY `item` (`list_id`,`trash`,`position`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; "); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Surreal ToDo Install</title> <link rel="stylesheet" type="text/css" href="../theme/base.css" /> </head> <body> <div id="install"> <?php echo '<h2>'._('Install Complete').'</h2>'; echo '<a href="../index.php">'._('Continue').'</a>'; } // close if(isset($_GET['install'])) } //close else $_GET['locale'] ?> </div> </body> </html> <file_sep><?php // Set the version of Surreal ToDO we are using define('APP_VERSION', '0.6.1.2'); <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"> <?php include_once("..\includes\documentHeader.php"); print_r(docHeader('../..')); ?> </head> <body> <?php if (stristr($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) == false) { $ar = splitStringToArray($_SERVER['SCRIPT_NAME']); redirectBrowser('/?linkname=' . $ar[count($ar) - 1]); } ?> <table width="590"> <tr> <td class="primaryContentContainerHeader"> <p align="justify"><a href="/php/links/getContentForFlash8.php" target="_self"><img src="/app/flash/images/undo.gif" width="33" height="18" border="0" title="Back to the Previous Page."></a>&nbsp;<a href="/php/links/getContentForFlash8MenuBarSample.php" target="_self">Flash 8 Menu Bar Sample for www.ez-ajax.com</a></p> </td> </tr> <tr> <td valign="top" bgcolor="#0060E0"> <?php print_r(flashContent("sampleMenuBar", 760, 120, "/app/flash/sampleMenuBar/main-menu-movie.swf?nocache=" . rand(1, 32767), "#164f9f")); ?> </td> </tr> <tr> <td valign="top"> <p align="justify">This Flash 8 Menu Bar Sample was created to act as a Menu Bar for www.ez-ajax.com. It was coded using a proprietary technique that allows for Rapid Development of Flash components that can be quite complex using very little development time.</p> <p align="justify">Notice the simulated computer monitor display that seems to be displaying animated text that scrolls from bottom to top; not a bad way to add some realism to a spiffy Flash component, huh ?</p> </td> </tr> </table> </body> </html> <file_sep><?php require_once ('session.php'); require_once ('shared.php'); require_once('header.php'); require_once ('soapclient/SforceApexClient.php'); //correction for dynamic magic quotes if(isset($_POST['scriptInput']) && get_magic_quotes_gpc()){ $_POST['scriptInput'] = stripslashes($_POST['scriptInput']); } if(isset($_POST['execute'])){ $_SESSION['scriptInput'] = $_POST['scriptInput']; $_SESSION['LogCategory'] = $_POST['LogCategory']; $_SESSION['LogCategoryLevel'] = $_POST['LogCategoryLevel']; $_SESSION['apiVersion'] = $_POST['apiVersion']; } else if(!isset($_SESSION['LogCategory']) && !isset($_SESSION['LogCategoryLevel'])){ $_SESSION['LogCategory'] = $_SESSION['config']['defaultLogCategory']; $_SESSION['LogCategoryLevel'] = $_SESSION['config']['defaultLogCategoryLevel']; preg_match("/(\d\d?\.\d)/",$_SESSION['location'],$apiVersionCurrent); $_SESSION['apiVersion'] = $apiVersionCurrent[1]; } ?> <form id="executeForm" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST"> <table border="0"> <tr> <td><strong>Enter Apex code to be executed as an anonymous block:</strong><p/></td> </tr> <tr> <td align="right"> Log Category: <select id="LogCategory" name="LogCategory"> <?php printSelectOptions($config['defaultLogCategory']['valuesToLabels'],$_SESSION['LogCategory']); ?> </select> &nbsp; Log Level: <select id="LogCategoryLevel" name="LogCategoryLevel"> <?php printSelectOptions($config['defaultLogCategoryLevel']['valuesToLabels'],$_SESSION['LogCategoryLevel']); ?> </select> &nbsp; Apex API Version: <select id="apiVersion" name="apiVersion"> <?php $apiVersions = array( "15.0", "14.0", "13.0", "12.0", "11.1", "11.0", "10.0", "9.0", "8.0" ); $apiVersionMatched = false; foreach($apiVersions as $verion){ print "<option value=\"" . $verion . "\""; if($_SESSION['apiVersion'] == $verion){ print " selected=\"selected\""; $apiVersionMatched = true; } print ">" . $verion . "</option>"; } ?> </select> &nbsp;<img onmouseover="Tip('Apex API Version defaults to the logged in API version, but can be set independently and specifies against which version the Apex script will be compiled.')" align='absmiddle' src='images/help16.png'/> </td> </tr> <tr> <td colspan="2"> <textarea id='scriptInput' name='scriptInput' cols='100' rows='7' style='overflow: auto; font-family: monospace, courier;'><?php echo htmlspecialchars($_SESSION['scriptInput'],ENT_QUOTES,'UTF-8'); ?></textarea> <p/> <input type='submit' name="execute" value='Execute'/> <input type='reset' value='Reset'/> </td> </tr> </table> </form> <script type="text/javascript"> document.getElementById('scriptInput').focus(); </script> <?php if(!$apiVersionMatched){ show_info("API version used for login is not supported for Apex execution. Execute will use default Apex API version unless otherwise specified."); } if(isset($_POST['execute']) && isset($_POST['scriptInput']) && $_POST['scriptInput'] != ""){ print "<h2>Results</h2>"; $apexServerUrl = str_replace("/u/","/s/",$_SESSION['location']); $apexServerUrl = preg_replace("/\d\d?\.\d/",$_POST['apiVersion'],$apexServerUrl); $apexBinding = new SforceApexClient("soapclient/sforce.150.apex.wsdl",$apexServerUrl,$_POST['LogCategory'],$_POST['LogCategoryLevel']); try { $executeAnonymousResultWithDebugLog = $apexBinding->executeAnonymous($_POST['scriptInput']); } catch(Exception $e) { show_error($e->getMessage()); } if($executeAnonymousResultWithDebugLog->executeAnonymousResult->success){ if(isset($executeAnonymousResultWithDebugLog->debugLog) && $executeAnonymousResultWithDebugLog->debugLog != ""){ print('<pre>' . htmlspecialchars($executeAnonymousResultWithDebugLog->debugLog,ENT_QUOTES,'UTF-8') . '</pre>'); } else { show_info("Execution was successful, but returned no results. Confirm log category and level."); } } else { $error; if(isset($executeAnonymousResultWithDebugLog->executeAnonymousResult->compileProblem)){ $error .= "COMPILE ERROR: " . $executeAnonymousResultWithDebugLog->executeAnonymousResult->compileProblem; } if(isset($executeAnonymousResultWithDebugLog->executeAnonymousResult->exceptionMessage)){ $error .= "\nEXCEPTION: " . $executeAnonymousResultWithDebugLog->executeAnonymousResult->exceptionMessage; } if(isset($executeAnonymousResultWithDebugLog->executeAnonymousResult->exceptionStackTrace)){ $error .= "\nSTACKTRACE: " . $executeAnonymousResultWithDebugLog->executeAnonymousResult->exceptionStackTrace; } if(isset($executeAnonymousResultWithDebugLog->executeAnonymousResult->line)){ $error .= "\nLINE: " . $executeAnonymousResultWithDebugLog->executeAnonymousResult->line; } if(isset($executeAnonymousResultWithDebugLog->executeAnonymousResult->column)){ $error .= " COLUMN: " . $executeAnonymousResultWithDebugLog->executeAnonymousResult->column; } show_error($error); print('<pre style="color: red;">' . htmlspecialchars($executeAnonymousResultWithDebugLog->debugLog,ENT_QUOTES,'UTF-8') . '</pre>'); } // print('<pre>'); // print_r($executeAnonymousResultWithDebugLog); // print('</pre>'); } else if(isset($_POST['execute']) && isset($_POST['scriptInput']) && $_POST['scriptInput'] == ""){ show_info("Anonymous block must not be blank."); } require_once('footer.php'); ?> <file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; if(isset($submit)) { if($submit == 'Search by name') { $q1 = "select * from job_employer_info where $_POST[name_type] like '%$_POST[name]%' order by $_POST[name_type]"; $r1 = mysql_query($q1); if (!$r1) { echo '<table align=center width=446 cellspacing=0 border=0><tr><td><center><br><br><br>Select <b>order by </b> optionzzzz </center></td></tr></table>'; include ("../foother.html"); exit; } if(mysql_num_rows($r1) == '0') { echo "<table align=center width=446 cellspacing=0><tr><td><center><br><br><br> No results. </center></td></tr></table>"; include_once('../foother.html'); exit; } } if($submit == 'List users') { $q1 = "select * from job_employer_info order by $_POST[order_type]"; $r1 = mysql_query($q1); if (!$r1) { echo '<table align=center width=446 cellspacing=0 border=0><tr><td><center><br><br><br>Select <b>order by </b> optionzzzz </center></td></tr></table>'; include ("../foother.html"); exit; } if(mysql_num_rows($r1) == '0') { echo "<table align=center width=446 cellspacing=0 border=0><tr><td><center><br><br><br> No results. </center></td></tr></table>"; include_once('../foother.html'); exit; } } echo "<br><br><table align=center width=400 cellspacing=0>\n"; echo "<tr bgcolor=6699cc style=\"font-family:arial; font-weight:bold; color:white; font-size:12\">\n <td>Username </td> <td>Company name / profile</td><td align=center>Action </td></tr>"; $col = "e0e7e9"; while($a1 = mysql_fetch_array($r1)) { if($col == "e0e7e9") { $col = "ffffff"; } else { $col = "e0e7e9"; } echo "<tr bgcolor=\"$col\"><td style=\"font-size:12\"> $a1[ename] </td><td><a class=TN href=\"cinfo.php?ename=$a1[ename]\"> $a1[CompanyName] </a></td> <td align=center><a class=TN href=\"ALO.php?ename=$a1[ename]\">list offers</a></td></tr>"; } ?> </table> <? include_once('../foother.html'); exit; } ?> <br><br><br> <form method=post style="background:none;"> <table align=center width=400> <tr> <td colspan=2 align=center><b>Explore Employers database </b><br><br></td> </tr> <tr> <td valign=top>Search for an Employer by Company name or username</td> <td><font size=2><input type=text name=name><br> <input type=radio name=name_type value="CompanyName">Company name<br> <input type=radio name=name_type value="ename">Username<br> <input type=submit name=submit value="Search by name"> </td> </tr> <tr><td colspan=2></td></tr> <tr> <td valign=top>Give me a list of all the Employers order by:</td> <td><font size=2> <input type=radio name=order_type value="CompanyName">Company name<br> <input type=radio name=order_type value="ename">Username<br> <input type=submit name=submit value="List users"> </td> </tr> <tr><td colspan=2></td></tr> </table> </form> <? include_once('../foother.html'); ?><file_sep><? include_once "../main.php"; echo "<center><font color=red><b> There is a problem with your payment.</b></font></canter>"; ?> <? include_once('../foother.html'); ?><file_sep><? include_once "accesscontrol.php"; ?> <table width=446 align=center > <tr> <td><a class=TNA href=your_choice.php> Banners </a></td> <td><a class=TNA href=stories.php> Stories </a></td> <td><a class=TNA href=jobseekers.php> Jobseekers </a></td> <td><a class=TNA href=employers.php> Employers </a></td> <td><a class=TNA href=mail.php> Mails </a></td> <td><a class=TNA href=prices.php> Prices </a></td> <td><a class=TNA href=conf.php> Configuration </a></td> <td><a class=TNA href=admins.php> Admins </a></td> <td><a class=TNA href=admin_logout.php> Logout </a></td> </tr> </table> <? include ("../foother.html"); ?><file_sep><? include("../conn.php"); class PayPalIPN { var $paypal_post_arr = array(); var $paypal_post_vars_in_str; //the paypal post array vars as string var $paypal_response = ""; //paypals response for our posted vars var $paypal_receiver_emails = array(); //array of expected paypal receiver emails var $error; //error no of transaction var $db; function PayPalIPN($paypal_post_arr) //constructor { $this->paypal_post_vars_in_str = ""; foreach($paypal_post_arr as $key=>$value) { $value = urlencode(stripslashes($value)); $this->paypal_post_vars_in_str .= "&$key=$value"; } //we can directly assign $this->paypal_post_arr = $paypal_post_arr;. But, it is safe to check undefined index... $this->paypal_post_arr = $this->_processPayPalPostVars($paypal_post_arr); }/*---PayPalIPN()-----*/ function setPayPalReceiverEmail($email) { //put it in array so that any number of emails can be set as receiver emails $this->paypal_receiver_emails[ ] = $email; } function postResponse2PayPal() { // post back to PayPal system to validate $this->paypal_post_vars_in_str = "cmd=_notify-validate" . $this->paypal_post_vars_in_str; $header = "POST /cgi-bin/webscr HTTP/1.0\r\n"; $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; $header .= 'Content-Length: ' . strlen($this->paypal_post_vars_in_str) . "\r\n\r\n"; //suppress socket connection error by "@"... $fp = @fsockopen ('www.paypal.com', 80, $errno, $errstr, 30); if (!$fp) // ERROR $this->paypal_response = "$errstr ($errno)"; else { //just post it... fputs ($fp, $header . $this->paypal_post_vars_in_str); while(!feof($fp)) { $resp = fgets($fp, 1024); if (strcmp($resp, "VERIFIED") == 0) $this->paypal_response = "VERIFIED"; else if (strcmp($resp, "INVALID") == 0) $this->paypal_response = "INVALID"; } } }/*---postResponse2PayPal()-----*/ function _processPayPalPostVars($post_vars) { $tmp_arr = array(); //the following step is to avoid undefined index error... $tmp_arr['txn_id'] = isset($post_vars['txn_id']) ? $post_vars['txn_id'] : ""; $tmp_arr['payer_email'] = isset($post_vars['payer_email']) ? $post_vars['payer_email'] : ""; $tmp_arr['payment_date'] = isset($post_vars['payment_date']) ? $post_vars['payment_date'] : ""; $tmp_arr['payment_gross'] = isset($post_vars['payment_gross']) ? $post_vars['payment_gross'] : ""; $tmp_arr['payment_fee'] = isset($post_vars['payment_fee']) ? $post_vars['payment_fee'] : ""; $tmp_arr['payment_status'] = isset($post_vars['payment_status']) ? $post_vars['payment_status'] : ""; $tmp_arr['memo'] = isset($post_vars['memo']) ? $post_vars['memo'] : ""; $tmp_arr['receiver_email'] = isset($post_vars['receiver_email']) ? $post_vars['receiver_email'] : ""; $tmp_arr['item_name'] = isset($post_vars['item_name']) ? $post_vars['item_name'] : ""; $tmp_arr['item_number'] = isset($post_vars['item_number']) ? $post_vars['item_number'] : ""; for($i=1; isset($post_vars["option_name{$i}"]) && isset($post_vars["option_selection{$i}"]); ++$i) $tmp_arr[$post_vars["option_name{$i}"]] = $post_vars["option_selection{$i}"]; //following line is to avoid undefined index error... $tmp_arr['ADV_ID'] = isset($tmp_arr['ADV_ID']) ? $tmp_arr['ADV_ID'] : 0; return($tmp_arr); }/*---_processPayPalPostVars()-----*/ function _isVerified() { return(strcmp($this->paypal_response, "VERIFIED")==0); }/*---_isVerified()-------*/ function _isVaidPaymentStatus() { //payment status can be : "Completed", "Pending", "Failed", "Denied" return(strcmp($this->paypal_post_arr['payment_status'], "Completed")==0); }/*---_isVaidPaymentStatus()---*/ function _isTransactionProcessed() { $txn_id = $this->paypal_post_arr['txn_id']; $sql = "SELECT COUNT(*) FROM job_tempacc WHERE txn_id='$txn_id'"; $result = mysql_query($sql); if (!$result) //error... die("Query error at isTransactionProcessed()". mysql_error($this->db)); $num_of_txn_id = mysql_result($result, 0); return($num_of_txn_id!=0); //txn_id processed if num!=0 }/*---_isTransactionProcessed()-----*/ function _isValidReceiverEmail() { //is receiver_email is the expected receiver_emails (one who runs website)?? return( in_array($this->paypal_post_arr['receiver_email'], $this->paypal_receiver_emails)); }/*---_isValidReceiverEmail()-------*/ function validateTransaction() { //set the error no... // check the payment_status is Completed // check that txn_id has not been previously processed // check that receiver_email is an email address in your PayPal account // process payment //This is to trap exact error type //Logic: bit field logic: 0-no error, ... //if all bits are set, then error in all conditions $this->error = 0; //initialize to no error $this->error |= $this->_isVerified() ? 0 : (1<<0); $this->error |= $this->_isVaidPaymentStatus() ? 0 : (1<<1); $this->error |= (!$this->_isTransactionProcessed()) ? 0 : (1<<2); $this->error |= $this->_isValidReceiverEmail() ? 0 : (1<<3); }/*---validateTransaction()------*/ function isTransactionOk() { return( !$this->error ); } function logTransactions($user_id) { $sql = "INSERT INTO job_tempacc SET " . "date_added=NOW(), " . "ip='".$_SERVER['REMOTE_ADDR']."', " . "user_id='".$this->paypal_post_arr['item_number']."', " . "plan_name='".$this->paypal_post_arr['item_name']."', " . "txn_id='".$this->paypal_post_arr['txn_id']."', " . "payer_email='".$this->paypal_post_arr['payer_email']."', " . "payment_date='".$this->paypal_post_arr['payment_date']."', " . "payment_gross='".$this->paypal_post_arr['payment_gross']."', " . "payment_fee='".$this->paypal_post_arr['payment_fee']."', " . "payment_status='".$this->paypal_post_arr['payment_status']."', " . "receiver_email='".$this->paypal_post_arr['receiver_email']."', " . "paypal_response='".$this->paypal_response."', " . "error_no='".$this->error."', " . "memo='".$this->paypal_post_arr['memo']."', " . "paypal_post_vars='".$this->paypal_post_vars_in_str."'"; $result = mysql_query($sql); if (!$result) die("Query Error at logTransactions()" . mysql_error($this->db)); }/*---logTransactions()-----*/ }/*---class PayPalIPN--------*/ ?> <file_sep><? include_once "accesscontrol.php"; if(isset($submit) && $submit = "Login" ) { $q = "select * from job_post where job_id = \"$_POST[job_id]\" "; $r = mysql_query($q) or die(mysql_error()); $a = mysql_fetch_array($r); $nv = $a[nv] + 1; $qn = "update job_post set nv = \"$nv\" where job_id = \"$_POST[job_id]\" "; $rn = mysql_query($qn) or die(mysql_error()); $js = $_POST[job_id]; } else { $q = "select * from job_post where job_id = \"$_GET[job_id]\" "; $r = mysql_query($q) or die(mysql_error()); $a = mysql_fetch_array($r); $nv = $a[nv] + 1; $qn = "update job_post set nv = \"$nv\" where job_id = \"$_GET[job_id]\" "; $rn = mysql_query($qn) or die(mysql_error()); $js = $_GET[job_id]; } $q2 = "select * from job_employer_info where ename = \"$a[ename]\""; $r2 = mysql_query($q2) or die(mysql_error()); $a2 = mysql_fetch_array($r2); ?> <br><br><br> <table align=center width=446> <tr> <td colspan=2 align=center> <b> Details about Job ID# <?=$a[job_id]?> </b></td> </tr> <tr> <td width=200><b> Position: </b></td> <td> <?=$a[position]?> </td> </tr> <tr> <td><b> Job category: </b></td> <td> <?=$a[JobCategory]?> </td> </tr> <tr> <td><b> Target: </b></td> <? if($a[j_target] == '1') { $clname = 'Student (High School)'; } elseif($a[j_target] == '2') { $clname = 'Student (undergraduate/graduate)'; } elseif($a[j_target] == '3') { $clname = 'Entry Level (less than 2 years of experience)'; } elseif($a[j_target] == '4') { $clname = 'Mid Career (2+ years of experience)'; } elseif($a[j_target] == '5') { $clname = 'Management (Manager/Director of Staff)'; } elseif($a[j_target] == '6') { $clname = 'Executive (SVP, EVP, VP)'; } elseif($a[j_target] == '7') { $clname = 'Senior Executive (President, CEO)'; } ?> <td><?=$clname?> </td> </tr> <tr> <td><b> Salary: </b> </td> <td> <?=$a[salary]?> / <?=$a[s_period]?> </td> </tr> <tr> <td valign=top><b> Description: </b></td> <td> <?=$a[description]?> </td> </tr> <tr> <td><b>Company: </b></td> <td><?=$a[Company]?></td> </tr> <tr> <? $day = date(d); $month = date(m); $year = date(Y); $EXdate = "$a[EXyear]"."-"."$a[EXmonth]"."-"."$a[EXday]"; $dnes = "$year"."-"."$month"."-"."$day"; $qd = "select to_days('$EXdate') - to_days('$dnes')"; $rqd = mysql_query($qd) or die(mysql_error()); $ex13 = mysql_fetch_array($rqd); //$ex13 = date('j', mktime(0,0,0, $a[EXmonth] - date(m), $a[EXday] - date(d), $a[EXyear] - date(Y))); ?> <td colspan=2><b>This job offer expire after <?=$ex13[0]?> day(s).</td> </tr> <form action=Send.php method=post style="background:none;"> <tr> <td colspan=2 align=center> <input type=hidden name=job_id value=<?=$a[job_id]?>> <input type=hidden name=ename value=<?=$a[ename]?>> <input type=submit name=ok value="Send my application"> <input type=submit name=friend value="Send to a friend"><br><br> </td> </tr> </form> </table> <? include_once('../foother.html'); ?><file_sep><? include_once "../main.php"; ?> <h3 align="center">Forgot Password</h3> <? if(isset($fu)) { $q1 = "select upass, job_seeker_email from job_seeker_info where uname = \"$_POST[uname]\""; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); if(empty($a1)) { echo "<table width=446><tr><td><br><br><br><center> There is no registered user with username $uname at our database. <br> <a class=TN href=forgot.php>Try again. </a></center></td></tr></table>"; include_once('../foother.html'); exit; } $to = $a1[job_seeker_email]; $subject = "Your username/password for $site_name"; $message = "Hello,\n here is your login information for http://$_SERVER[HTTP_HOST] \n\n Username: $_POST[uname] \n Password: <PASSWORD>] "; $from = "From: $email_address"; mail($to, $subject, $message, $from); echo "<table width=446><tr><td><br><br><br><center> Your login information was sent to $to </center></tr></td></table>"; } elseif(isset($fm)) { $q2 = "select uname, upass from job_seeker_info where job_seeker_email = \"$_POST[SEmail]\""; $r2 = mysql_query($q2) or die(mysql_error()); $a2 = mysql_fetch_array($r2); if(empty($a2)) { echo "<table width=446><tr><td><br><br><br><center> There is no registered user with email $SEmail at our database. <br><a class=TN href=forgot.php> Try again. </a></center></td></tr></table>"; include_once('../foother.html'); exit; } $to = $_POST[SEmail]; $subject = "Your username/password for $site_name"; $message = "Hello,\n here is your login information for http://$_SERVER[HTTP_HOST] \n\n Username: $a2[uname] \n Password: <PASSWORD>] "; $from = "From: $email_address"; mail($to, $subject, $message, $from); echo "<br><br><br><center> Your login information was sent to $to </center>"; } else { ?> <form action=<?=$PHP_SELF?> method=post style="background:none;"> <table align=center width=446> <tr> <td>If you remember your username, but have forgot your password enter your username and in a few seconds will receive your password directly into the email you used at our site registration form.</td> </tr> <tr> <td>Username: <br> <input type=text name=uname> </td> </tr> <tr> <td><input type=submit name=fu value=Submit> </tr> </table> </form> <form action=<?=$PHP_SELF?> method=post style="background:none;"> <table align=center width=446> <tr> <td>If you have forgot all your login information (username & password) but still remember the email you used at our site registration form, just enter it into the box and in a few seconds you will receive your login informstion. </td> </tr> <tr> <td>Email: <br> <input type=text name=SEmail> </td> </tr> <tr> <td><input type=submit name=fm value=Submit> </tr> </table> </form> <? } ?> <? include_once('../foother.html'); ?><file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; include_once "navigation.html"; if ($nch == banners) { if ($b > '0') { $q2 = "update job_banners_m set bc = '1' "; $r2 = mysql_query($q2) or die(mysql_error()); } else { $q2 = "insert into job_banners_m set bc = '1' "; $r2 = mysql_query($q2) or die(mysql_error()); } } elseif ($nch == linkcodes) { if ($b > '0') { $q2 = "update job_banners_m set bc = \"2\" "; $r2 = mysql_query($q2) or die(mysql_error()); } else { $q2 = "insert into job_banners_m set bc = '2' "; $r2 = mysql_query($q2) or die(mysql_error()); } } include_once "your_choice.php"; ?> <? include_once('../foother.html'); ?><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"> <?php include_once("includes\documentHeader.php"); print_r(docHeader('')); ?> </head> <body> <noscript>You must enable JavaScript to use this site.<br>Please adjust your browser's settings to enable JavaScript or use a browser that supports JavaScript.<br> <a href="http://flashx.ez-ajax.com" target="_blank">flashx.ez-ajax.com</a> </noscript> <div id="table_outerContentWrapper" style="position: absolute; width: 900px; top: 0px; left: 0px;"> <div class="ContentWrapper"> <div class="twoColumnLeft"> +++ Menu Goes Here +++ </div> <div class="twoColumnRight" style="<?php if (!ezIsBrowserIE()) { print_r('margin-left: 30px;'); }; ?>"> +++ Banner goes here +++ <div id="div_primaryContentContainer"> <iframe name="contentFrame" id="contentFrame" frameborder="0" scrolling="Auto" width="780" height="600" style="background: #164f9f" src="/links/<?php if ($_REQUEST['linkname'] != '') { print_r($_REQUEST['linkname']); } else { print_r('homePage.php'); }; ?>"></iframe> </div> <?php $today = getdate(); $todayYYYY = $today["year"]; $siteAdvice = ((!ezIsBrowserIE()) ? '<b><i>This site is best when viewed using IE 7.x (1024x768) resolution.</i></b>' : ''); $_poweredHTML = '<p align="justify"><small>' . $siteAdvice . '&nbsp;The contents of this Site are protected under U.S. and International Copyright Laws. &copy 1990-' . $todayYYYY . ' Hierarchical Applications Limited, All Rights Reserved.</small></p>'; print_r($_poweredHTML); ?> </div> </div> </div> </body> </html> <file_sep><? include_once('main.php'); ?> <table border="0" cellpadding="0" cellspacing="0" width="446" align="center"> <tr valign="top"> <td class="w" style="padding-left:10px;padding-top:10px;"> <p><em><strong><font face="Tahoma, Arial, sans-serif" size="4"><font color="#000000">Site map </font></font></strong></em></p> <p align="left"><font size="2" face="Tahoma, Arial, sans-serif" color="#000000"><?=$site_name?> site map: <ul> <li>Home</li> <li>About us</li> <li>Privacy Terms</li> <li>Contact us</li> <li>Link us</li> <li>FAQ</li> <li>Succes story</li> <li>Employer Registration</li> <li>Jobseeker Registration</li> <li>Job Search</li> <li>Site map</li> </ul></font> </td> </tr> </table> <? include_once('foother.html'); ?><file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; if(isset($submit) && $submit == 'Update') { $q1 = "update job_plan set PlanName = \"$PlanName\", postings = \"$postings\", reviews = \"$reviews\", numdays = \"$numdays\", price = \"$price\" where PlanName = \"$OldName\""; $r1 = mysql_query($q1) or die(mysql_error()); } else { $q2 = "select * from job_plan where PlanName = \"$PlanName\""; $r2 = mysql_query($q2) or die(mysql_error()); $a2 = mysql_fetch_array($r2); ?> <br> <table align=center width=300> <form action=<?=$PHP_SELF?> method=post> <caption> Edit plan <b><?=$a2[PlanName]?> </b></caption> <tr> <td><b> Plan name:</b></td> <td>&nbsp;&nbsp;<input type=text name=PlanName value="<?=$a2[PlanName]?>"></td> </tr> <tr> <td><b>Number of Days: </b></td> <td>&nbsp;&nbsp;<input type=text name=numdays size=5 value=<?=$a2[numdays]?>></td> </tr> <tr> <td><b>Postings: </b></td> <td>&nbsp;&nbsp;<input type=text name=postings size=5 value=<?=$a2[postings]?>></td> </tr> <tr> <td><b> Reviews: </b></td> <td>&nbsp;&nbsp;<input type=text name=reviews size=5 value=<?=$a2[reviews]?>></td> </tr> <tr> <td><b> Price: </b></td> <td><b>$</b><input type=text name=price size=5 value=<?=$a2[price]?>></td> </tr> <tr> <td></td> <td><input type=hidden name=OldName value="<?=$a2[PlanName]?>">&nbsp;&nbsp; <input type=submit name=submit value=Update>&nbsp;&nbsp;<input type=reset></td> </tr> </form> </table> <? } ?> <? include_once('../foother.html'); ?><file_sep><?php require_once('session.php'); require_once('shared.php'); ?> <script type="text/javascript" src="script/simpletreemenu.js"> /*********************************************** * Simple Tree Menu- � Dynamic Drive DHTML code library (www.dynamicdrive.com) * This notice MUST stay intact for legal use * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code ***********************************************/ </script> <link rel="stylesheet" type="text/css" href="style/simpletree.css" /> <?php //Main Form Logic: If there is a default object in the session, //describe it when the page loads; else, prompt to choose one. //Note: The POSTed default object is passed to the SESSION default object //in the session.php include if ($_SESSION['default_object']){ show_describeSObject_form(); show_describeSObject_result(); } else { show_describeSObject_form(); include_once('footer.php'); exit; } //Print a form with the global object types to choose for description function show_describeSObject_form(){ require_once ('header.php'); print "<form name='describeForm' method='post' action='$_SERVER[PHP_SELF]' onChange='document.describeForm.submit();'>"; print "<p><strong>Choose an object to describe:</strong></p>\n"; myGlobalSelect($_SESSION['default_object']); print "<input type='submit' name='action' value='Describe' />"; print "</form>"; } //Print the description of selected/default object type in multiple tables function show_describeSObject_result(){ try{ //Ping Apex API $describeSObject_result = describeSObject($_SESSION['default_object']); } catch (Exception $e) { $errors = null; $errors = $e->getMessage(); show_error($errors); exit; } print "<h2>$_SESSION[default_object] Object Description</h2>"; print "<a href=\"javascript:ddtreemenu.flatten('describeTree', 'expand')\">Expand All</a> | <a href=\"javascript:ddtreemenu.flatten('describeTree', 'contact')\">Collapse All</a> | <a href=\"describeTable.php\">Table View</a>\n"; print "<ul id='describeTree' class='treeview'>\n"; print "<li>Attributes<ul>\n"; foreach($describeSObject_result as $key => $value){ //Print strings as is if (is_string($value)){ print "<li>$key: <strong>$value</strong></li> \n"; } //Change bool data to printed as TRUE and FALSE for visibility in table elseif (is_bool($value)){ print "<li>$key: "; if ($value){ print "<strong>True</strong>"; } else { print "<strong>False</strong>"; } print "</li> \n"; } } print "</ul></li>\n"; ///end attributes node print "<li>Fields<ul>\n"; foreach($describeSObject_result->fields as $key => $value){ print "<li>$value->name<ul>\n"; foreach($value as $subkey => $subvalue){ if (is_string($subvalue)){ print "<li>$subkey: <strong>$subvalue</strong></li>\n"; } //Change bool data to printed as TRUE and FALSE for visibility in table elseif (is_bool($subvalue)){ print "<li>$subkey: "; if ($subvalue){ print "<strong>True</strong>"; } else { print "<strong>False</strong>"; } print "</li> \n"; } //Because picklist are deeper in the SOAP message, //it requires more nested foreach loops elseif ($subkey == 'picklistValues'){ print "<li>$subkey<ul>\n"; foreach($subvalue as $subsubkey => $subsubvalue){ print "<li>$subsubvalue->label<ul>\n"; foreach($subsubvalue as $subsubsubkey => $subsubsubvalue){ if (is_string($subsubsubvalue)){ print "<li>$subsubsubkey: <strong>$subsubsubvalue</strong></li> \n"; } elseif (is_bool($subsubsubvalue)){ print "<li>$subsubsubkey: "; if ($subsubsubvalue){ print "<strong>True</strong>"; } else { print "<strong>False</strong>"; } print "</li> \n"; } } print "</ul></li>\n"; //end one picklist node } print "</ul></li>\n"; //end picklist node } elseif ($subkey == 'referenceTo'){ //do this for referenceTo arrays print "<li>$subkey<ul>\n"; foreach($subvalue as $subsubkey => $subsubvalue){ print "<li>$subsubvalue</li>\n"; } print "</ul></li>\n"; //end referenceTo node } } print "</ul></li>\n"; ///end one field node } print "</ul></li>\n"; ///end fields node //Print Record Types, if they exists if (isset($describeSObject_result->recordTypeInfos)){ print "<li>Record Types<ul>\n"; foreach($describeSObject_result->recordTypeInfos as $key => $value){ if(isset($value->name)){ print "<li>$value->name<ul>\n"; foreach($value as $subkey => $subvalue){ if (is_string($subvalue)){ print "<li>$subkey: <strong>$subvalue</strong><li>\n"; } elseif (is_bool($subvalue)){ print "<li>$subkey: "; if ($subvalue){ print "<strong>True</strong>"; } else { print "<strong>False</strong>"; } print "</li> \n"; } } print "</ul></li>\n"; ///end one record type node } } print "</ul></li>\n"; ///end record types node } //end record type exist conditional check //Print Child Relationships, if they exists if (isset($describeSObject_result->childRelationships)){ print "<li>Child Relationships<ul>\n"; foreach($describeSObject_result->childRelationships as $key => $value){ print "<li>$value->childSObject<ul>\n"; foreach($value as $subkey => $subvalue){ if (is_string($subvalue)){ print "<li>$subkey: <strong>$subvalue</strong></li> \n"; } elseif (is_bool($subvalue)){ print "<li>$subkey: "; if ($subvalue){ print "<strong>True</strong>"; } else { print "<strong>False</strong>"; } print "</li> \n"; } } print "</ul></li>\n"; ///end one child relationship node } print "</ul></li>\n"; ///end child relationships node } print "</ul>\n"; //end tree } ?> <script type="text/javascript"> //ddtreemenu.createTree(treeid, enablepersist, opt_persist_in_days (default is 1)) ddtreemenu.createTree("describeTree", true); </script> <?php include_once('footer.php'); ?> <file_sep><?php session_start(); require_once "../conn.php"; include_once "../main.php"; if(!isset($ename) && !isset($epass)) { ?> <h1><font face=arial color=#000000>Employers Login </h1> <p>You must log in to access this area of the site.<br> If you are not a registered user, <a href="employer_registration.php" style="text-decoration:none; color:#000000"><b>click here</b></a> to sign up.</p> <p><form method="post" action="<?=$PHP_SELF?>" style="background:none;"> <table width="446" bgcolor="#FFFFFF"> <tr> <td width="150">Username:</td> <td align=left> <input type="text" name="ename" size="8" style="border-color:black"></td> </tr> <tr> <td width="150">Password:</td> <td align=left><input type="<PASSWORD>" name="epass" SIZE="8" style="border-color:black"></td> </tr> <tr> <td align=right>&nbsp;</td> <td align=left><input name="submit" type="submit" style="border-color:black; background-color:#e0e7e9; color:#000000; font-weight:normal" value=" Login "></td> </tr> <tr><td align=center></td> <td align=left> <a class=TN href=forgot.php> Forgot your username/password? </a>&nbsp;</td> </tr> </table> </form></p> </center> <?php include("../foother.html"); exit; } session_register("ename"); session_register("epass"); $sql = "SELECT * FROM job_employer_info WHERE ename = '$ename' AND epass = '$epass'"; $result = mysql_query($sql); if (!$result) { echo "A database error occurred while checking your login details. <br>If this error persists, please <br>contact $email_address"; } elseif (mysql_num_rows($result) == 0) { session_unregister("ename"); session_unregister("epass"); ?> <table width="446"><tr><td> <font face=verdana> <h1> Access Denied </h1> <p>Your user ID or password is incorrect, or you are not a registered user on this site.<br><br> To try logging in again, click <a href="<?=$PHP_SELF?>">here</a>. <br><br>To register for instant access, click <a href="employer_registration.php">here</a>.</p> </td></tr></table> <?php include("../foother.html"); exit; } ?><file_sep><? include_once "accesscontrol.php"; ?> <table align=center width=595> <tr> <td align="center"> <br> <br> <br> <br> <? //foreach ($_POST as $key=>$value) //{ // echo $key . " => " . $value; //} if ($_POST["submit"]=="Buy Now" && $_POST["sid"]==$paypal_email_address && $_POST["demo"] !="Y") //if ($_POST["submit"]=="Buy Now" && $_POST["sid"]=="522701" && $_POST["demo"] !="Y") { // echo $_SERVER['HTTP_REFERRER']; // foreach ($_POST as $key=>$value) // { // echo $key . " => " . $value . "<br>"; // } $plan=mysql_fetch_array(mysql_query("Select * from job_plan where PlanName='".$_REQUEST["PlanName"]."'")); mysql_query("update job_employer_info set JS_number='".$plan["reviews"]."' , JP_number='".$plan["postings"]."' , plan='".$plan["PlanName"]."' where ename=\"$ename\" ") or die(mysql_error()); // echo ("update job_employer_info set JS_number='".$plan["reviews"]."' , JP_number='".$plan["postings"]."' , plan='".$plan["PlanName"]." where ename=\"$ename\" "); echo "You have Successfully purchased the <strong>" . $_REQUEST["PlanName"] ."</strong> package.<br><br>Now you can post jobs and search resumes."; } ?> </td> </tr> </table> <? include_once('../foother.html'); ?> <file_sep><?php include_once("../includes/documentHeader.php"); //include_once("documentHeader.php"); try { $cmd = getValueFromGetOrPostArray("cmd"); $username = getValueFromGetOrPostArray("username"); $password = getValueFromGetOrPostArray("password"); $password2 = getValueFromGetOrPostArray("password2"); $responseID = 0; $responseMsg = ""; $debugMsg = ""; $db = new MSSQLDB('UserLoginDemo', 'SQL2005', 'sa', 'sisko@76<PASSWORD>'); if ($cmd == "register") { if ( (strlen($username) > 0) && (strlen($password) > 0) && (strlen($password2) > 0) ) { if ($password == $password2) { $_username = $db->sqlEscape($username); $query = "SELECT id, username, password FROM users WHERE (username = '$_username');"; $xRet = $db->query_database($query); if (count($xRet) == 0) { $_password = $db->sqlEscape($password); $query = "INSERT INTO users (username, password) VALUES ('$_username','$_password');"; $recID = $db->query_database($query); $responseID = $recID; $responseMsg = "User Registration Successful."; } else { $responseID = -229; $responseMsg = "Warning: User Name entered has already been taken by someone else..."; } } else { $responseID = -228; $responseMsg = "Warning: Password and Repeated Password do not match..."; } } else { $responseID = -220; $responseMsg = "Warning: Missing parms..."; if (strlen($username) == 0) { $responseID = -222; $responseMsg = "Warning: Missing User Name..."; } else if (strlen($password) == 0) { $responseID = -224; $responseMsg = "Warning: Missing Password..."; } else if (strlen($password2) == 0) { $responseID = -226; $responseMsg = "Warning: Missing Repeated Password..."; } } } else if ($cmd == "login") { if ( (strlen($username) > 0) && (strlen($password) > 0) ) { $username = $db->sqlEscape($username); $password = $db->sqlEscape($password); $query = "SELECT id, userName, password FROM Users WHERE (userName = '$username') AND (password = <PASSWORD>');"; $xRet = $db->query_database($query); if (count($xRet) == 1) { $recID = $xRet[0]->id; $responseID = $recID; $responseMsg = "Login Successful."; } else { $responseID = -100; $responseMsg = "Login unsuccessful. [$query]" . "[" . var_print_r($xRet) . "]"; } } else { $responseID = -210; $responseMsg = "Warning: Missing parms..."; } } else { $responseID = -200; $responseMsg = "Warning: Missing cmd..."; } $responseMsg = "[$responseID] :: " . $responseMsg; } catch (Exception $e) { $responseID = -999; $responseMsg = "Exception: " . var_print_r($e); } ?> <?php $responseID = cdataEscape($responseID); $responseMsg = cdataEscape($responseMsg); $debugMsg = cdataEscape($debugMsg); $xmlstr = <<<XML <?xml version="1.0" encoding="iso-8859-1"?> <response> <status> <code>$responseID</code> <message>$responseMsg</message> </status> <debug>$debugMsg</debug> </response> XML; echo $xmlstr; ?> <file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; if(isset($add)) { if(!empty($naid) && !empty($npass) && !empty($nname) && !empty($nemail)) { $q1 = "insert into job_admin_login set aid = \"$naid\", apass = \"$npass\", name = \"$nname\", email = \"$nemail\" "; $r1 = mysql_query($q1); if (!$r1) { echo "<table width=446><tr><td><center><br><br><br> The Admin ID is already in use. Go <a class=TN href=add_admin.php>back </a> and try another. </center></td></tr></table>"; include ("../foother.html"); exit; } $to = $nemail; $subject = "Your SiteAdmin account"; $message = "You were added as Site Administrator for $site_name \n\nYour login information is:\n Admin ID: $naid\n AdminPass: <PASSWORD> To access the site admin area, go to:\nhttp://$_SERVER[HTTP_HOST]/admin/index.php"; $from = "From: $email_address"; mail($to, $subject, $message, $from); echo "<table width=446><tr><td><br><br><br><center> $nname was added as Site Administrator. </center></td></tr></table>"; include("../foother.html"); exit; } else { echo "<center>You miss to fill one or more fields at the registration form.<br> Go <a class=TN htef=add_admin.php> back </a> and fill all the fields.</center>"; } } else { ?> <br><br><br> <center> <form action=<?=$PHP_SELF?> method=post style="background:none;"> <table align=center width=446> <caption align="center">Use this form to add a Site Administrator </caption> <tr> <td>Admin ID </td> <td><input type=text name=naid></td> </tr> <tr> <td>Admin pass </td> <td><input type=text name=npass></td> </tr> <tr> <td>Name </td> <td><input type=text name=nname></td> </tr> <tr> <td>Email </td> <td><input type=text name=nemail></td> </tr> <tr> <td align=center><input type=submit name=add value=Add></td> <td align=center><input type=reset></td> </tr> </table> </form> <? } ?> <? include_once('../foother.html'); ?><file_sep><? include_once "accesscontrol.php"; ?> <form action=Search2.php method=post style="background:none;"> <table align=center width=446 bgcolor="#FFFFFF"> <tr> <td align=center colspan=2><font size=2> Search our database, using one or more of the following criterias: </td> </tr> <tr> <td valign=top> Job category: </td> <td valign=top> <SELECT NAME="JobCategory" style="width:286"> <option value="">Select </option> <OPTION VALUE="Accounting/Auditing" >Accounting/Auditing</OPTION> <OPTION VALUE="Administrative and Support Services" >Administrative and Support Services</OPTION> <OPTION VALUE="Advertising/Public Relations" >Advertising/Public Relations</OPTION> <OPTION VALUE="Agriculture/Forestry/Fishing" >Agriculture/Forestry/Fishing</OPTION> <OPTION VALUE="Architectural Services" >Architectural Services</OPTION> <OPTION VALUE="Arts, Entertainment, and Media" >Arts, Entertainment, and Media</OPTION> <OPTION VALUE="Banking" >Banking</OPTION> <OPTION VALUE="Biotechnology and Pharmaceutical" >Biotechnology and Pharmaceutical</OPTION> <OPTION VALUE="Community, Social Services, and Nonprofit" >Community, Social Services, and Nonprofit</OPTION> <OPTION VALUE="Computers, Hardware" >Computers, Hardware</OPTION> <OPTION VALUE="Computers, Software" >Computers, Software</OPTION> <OPTION VALUE="Construction, Mining and Trades" >Construction, Mining and Trades</OPTION> <OPTION VALUE="Consulting Services" >Consulting Services</OPTION> <OPTION VALUE="Customer Service and Call Center" >Customer Service and Call Center</OPTION> <OPTION VALUE="Education, Training, and Library" >Education, Training, and Library</OPTION> <OPTION VALUE="Employment Placement Agencies" >Employment Placement Agencies</OPTION> <OPTION VALUE="Engineering" >Engineering</OPTION> <OPTION VALUE="Executive Management" >Executive Management</OPTION> <OPTION VALUE="Finance/Economics" >Finance/Economics</OPTION> <OPTION VALUE="Financial Services" >Financial Services</OPTION> <OPTION VALUE="Government and Policy" >Government and Policy</OPTION> <OPTION VALUE="Healthcare, Other" >Healthcare, Other</OPTION> <OPTION VALUE="Healthcare, Practitioner, and Technician" >Healthcare, Practitioner, and Technician</OPTION> <OPTION VALUE="Hospitality, Tourism" >Hospitality, Tourism</OPTION> <OPTION VALUE="Human Resources" >Human Resources</OPTION> <OPTION VALUE="Information Technology" >Information Technology</OPTION> <OPTION VALUE="Installation, Maintenance and Repair" >Installation, Maintenance and Repair</OPTION> <OPTION VALUE="Insurance" >Insurance</OPTION> <OPTION VALUE="Internet/E-Commerce" >Internet/E-Commerce</OPTION> <OPTION VALUE="Law Enforcement and Security" >Law Enforcement and Security</OPTION> <OPTION VALUE="Legal" >Legal</OPTION> <OPTION VALUE="Manufacturing and Production" >Manufacturing and Production</OPTION> <OPTION VALUE="Marketing" >Marketing</OPTION> <OPTION VALUE="Military" >Military</OPTION> <OPTION VALUE="Other" >Other</OPTION> <OPTION VALUE="Personal Care and Services" >Personal Care and Services</OPTION> <OPTION VALUE="Real Estate" >Real Estate</OPTION> <OPTION VALUE="Restaurant and Food Service" >Restaurant and Food Service</OPTION> <OPTION VALUE="Retail/Wholesale" >Retail/Wholesale</OPTION> <OPTION VALUE="Sales" >Sales</OPTION> <OPTION VALUE="Science" >Science</OPTION> <OPTION VALUE="Sports/Recreation" >Sports/Recreation</OPTION> <OPTION VALUE="Telecommunications" >Telecommunications</OPTION> <OPTION VALUE="Transportation and Warehousing" >Transportation and Warehousing</OPTION> </SELECT><br> </td> </tr> <tr> <td> Career level </td> <td> <select name="careerlevel"> <option value=""> Select</option> <OPTION VALUE="Student (High School)">Student (High School)</OPTION> <OPTION VALUE="Student (undergraduate/graduate)">Student (undergraduate/graduate)</OPTION> <OPTION VALUE="Entry Level (less than 2 years of experience)">Entry Level (less than 2 years of experience)</OPTION> <OPTION VALUE="Mid Career (2+ years of experience)">Mid Career (2+ years of experience)</OPTION> <OPTION VALUE="Management (Manager/Director of Staff)">Management (Manager/Director of Staff)</OPTION> <OPTION VALUE="Executive (SVP, EVP, VP)">Executive (SVP, EVP, VP)</OPTION> <OPTION VALUE="Senior Executive (President, CEO)">Senior Executive (President, CEO)</OPTION> </select> </td> </tr> <tr> <td> Target company </td> <td> <select name="target_company"> <option value=""> Select</option> <option value="Small (up to 99 empl.)"> Small (up to 99 empl.) </option> <option value="Medium (100 - 500 empl.)"> Medium (100 - 500 empl.) </option> <option value="Large (over 500 empl.)"> Large (over 500 empl.) </option> </select> </td> </td> </tr> <tr> <td> Relocate? </td> <td align=left> <input type=radio name=relocate value=Yes checked>yes &nbsp;&nbsp;&nbsp; <input type=radio name=relocate value=No>no </td> </td> </tr> <tr> <td>Country: </td> <td> <select name=country> <OPTION VALUE="">Select</OPTION> <OPTION VALUE="Afghanistan">Afghanistan</OPTION> <OPTION VALUE="Albania">Albania</OPTION> <OPTION VALUE="Algeria">Algeria</OPTION> <OPTION VALUE="American Samoa">American Samoa</OPTION> <OPTION VALUE="Andorra">Andorra</OPTION> <OPTION VALUE="Angola">Angola</OPTION> <OPTION VALUE="Anguilla">Anguilla</OPTION> <OPTION VALUE="Antartica">Antartica</OPTION> <OPTION VALUE="Antigua and Barbuda">Antigua and Barbuda</OPTION> <OPTION VALUE="Argentina">Argentina</OPTION> <OPTION VALUE="Armenia">Armenia</OPTION> <OPTION VALUE="Aruba">Aruba</OPTION> <OPTION VALUE="Australia">Australia</OPTION> <OPTION VALUE="Austria">Austria</OPTION> <OPTION VALUE="Azerbaidjan">Azerbaidjan</OPTION> <OPTION VALUE="Bahamas">Bahamas</OPTION> <OPTION VALUE="Bahrain">Bahrain</OPTION> <OPTION VALUE="Bangladesh">Bangladesh</OPTION> <OPTION VALUE="Barbados">Barbados</OPTION> <OPTION VALUE="Belarus">Belarus</OPTION> <OPTION VALUE="Belgium">Belgium</OPTION> <OPTION VALUE="Belize">Belize</OPTION> <OPTION VALUE="Benin">Benin</OPTION> <OPTION VALUE="Bermuda">Bermuda</OPTION> <OPTION VALUE="Bhutan">Bhutan</OPTION> <OPTION VALUE="Bolivia">Bolivia</OPTION> <OPTION VALUE="Bosnia-Herzegovina">Bosnia-Herzegovina</OPTION> <OPTION VALUE="Botswana">Botswana</OPTION> <OPTION VALUE="Bouvet Island">Bouvet Island</OPTION> <OPTION VALUE="Brazil">Brazil</OPTION> <OPTION VALUE="British Indian Ocean Territory">British Indian Ocean Territory</OPTION> <OPTION VALUE="Brunei Darussalam">Brunei Darussalam</OPTION> <OPTION VALUE="Bulgaria">Bulgaria</OPTION> <OPTION VALUE="Burkina Faso">Burkina Faso</OPTION> <OPTION VALUE="Burundi">Burundi</OPTION> <OPTION VALUE="Cambodia">Cambodia</OPTION> <OPTION VALUE="Cameroon">Cameroon</OPTION> <OPTION VALUE="Canada">Canada</OPTION> <OPTION VALUE="Cape Verde">Cape Verde</OPTION> <OPTION VALUE="Cayman Islands">Cayman Islands</OPTION> <OPTION VALUE="Central African Republic">Central African Republic</OPTION> <OPTION VALUE="Chad">Chad</OPTION> <OPTION VALUE="Chile">Chile</OPTION> <OPTION VALUE="China">China</OPTION> <OPTION VALUE="Christmas Island">Christmas Island</OPTION> <OPTION VALUE="Cocos (Keeling) Islands">Cocos (Keeling) Islands</OPTION> <OPTION VALUE="Colombia">Colombia</OPTION> <OPTION VALUE="Comoros">Comoros</OPTION> <OPTION VALUE="Congo">Congo</OPTION> <OPTION VALUE="Cook Islands">Cook Islands</OPTION> <OPTION VALUE="Costa Rica">Costa Rica</OPTION> <OPTION VALUE="Croatia">Croatia</OPTION> <OPTION VALUE="Cuba">Cuba</OPTION> <OPTION VALUE="Cyprus">Cyprus</OPTION> <OPTION VALUE="Czech Republic">Czech Republic</OPTION> <OPTION VALUE="Denmark">Denmark</OPTION> <OPTION VALUE="Djibouti">Djibouti</OPTION> <OPTION VALUE="Dominica">Dominica</OPTION> <OPTION VALUE="Dominican Republic">Dominican Republic</OPTION> <OPTION VALUE="East Timor">East Timor</OPTION> <OPTION VALUE="Ecuador">Ecuador</OPTION> <OPTION VALUE="Egypt">Egypt</OPTION> <OPTION VALUE="El Salvador">El Salvador</OPTION> <OPTION VALUE="Equatorial Guinea">Equatorial Guinea</OPTION> <OPTION VALUE="Eritrea">Eritrea</OPTION> <OPTION VALUE="Estonia">Estonia</OPTION> <OPTION VALUE="Ethiopia">Ethiopia</OPTION> <OPTION VALUE="Falkland Islands">Falkland Islands</OPTION> <OPTION VALUE="Faroe Islands">Faroe Islands</OPTION> <OPTION VALUE="Fiji">Fiji</OPTION> <OPTION VALUE="Finland">Finland</OPTION> <OPTION VALUE="Former USSR">Former USSR</OPTION> <OPTION VALUE="France">France</OPTION> <OPTION VALUE="France (European Territory)">France (European Territory)</OPTION> <OPTION VALUE="French Guyana">French Guyana</OPTION> <OPTION VALUE="French Southern Territories">French Southern Territories</OPTION> <OPTION VALUE="Gabon">Gabon</OPTION> <OPTION VALUE="Gambia">Gambia</OPTION> <OPTION VALUE="Georgia">Georgia</OPTION> <OPTION VALUE="Germany">Germany</OPTION> <OPTION VALUE="Ghana">Ghana</OPTION> <OPTION VALUE="Gibraltar">Gibraltar</OPTION> <OPTION VALUE="Greece">Greece</OPTION> <OPTION VALUE="Greenland">Greenland</OPTION> <OPTION VALUE="Grenada">Grenada</OPTION> <OPTION VALUE="Guadeloupe (French)">Guadeloupe (French)</OPTION> <OPTION VALUE="Guam">Guam</OPTION> <OPTION VALUE="Guatemala">Guatemala</OPTION> <OPTION VALUE="Guinea">Guinea</OPTION> <OPTION VALUE="Guinea Bissau">Guinea Bissau</OPTION> <OPTION VALUE="Guyana">Guyana</OPTION> <OPTION VALUE="Haiti">Haiti</OPTION> <OPTION VALUE="Heard and McDonald Islands">Heard and McDonald Islands</OPTION> <OPTION VALUE="Honduras">Honduras</OPTION> <OPTION VALUE="Hong Kong">Hong Kong</OPTION> <OPTION VALUE="Hungary">Hungary</OPTION> <OPTION VALUE="Iceland">Iceland</OPTION> <OPTION VALUE="India">India</OPTION> <OPTION VALUE="Indonesia">Indonesia</OPTION> <OPTION VALUE="Iran">Iran</OPTION> <OPTION VALUE="Iraq">Iraq</OPTION> <OPTION VALUE="Ireland">Ireland</OPTION> <OPTION VALUE="Israel">Israel</OPTION> <OPTION VALUE="Italy">Italy</OPTION> <OPTION VALUE="Ivory Coast">Ivory Coast</OPTION> <OPTION VALUE="Jamaica">Jamaica</OPTION> <OPTION VALUE="Japan">Japan</OPTION> <OPTION VALUE="Jordan">Jordan</OPTION> <OPTION VALUE="Kazakhstan">Kazakhstan</OPTION> <OPTION VALUE="Kenya">Kenya</OPTION> <OPTION VALUE="Kiribati">Kiribati</OPTION> <OPTION VALUE="Kuwait">Kuwait</OPTION> <OPTION VALUE="Kyrgyzstan">Kyrgyzstan</OPTION> <OPTION VALUE="Laos">Laos</OPTION> <OPTION VALUE="Latvia">Latvia</OPTION> <OPTION VALUE="Lebanon">Lebanon</OPTION> <OPTION VALUE="Lesotho">Lesotho</OPTION> <OPTION VALUE="Liberia">Liberia</OPTION> <OPTION VALUE="Libya">Libya</OPTION> <OPTION VALUE="Liechtenstein">Liechtenstein</OPTION> <OPTION VALUE="Lithuania">Lithuania</OPTION> <OPTION VALUE="Luxembourg">Luxembourg</OPTION> <OPTION VALUE="Macau">Macau</OPTION> <OPTION VALUE="Macedonia">Macedonia</OPTION> <OPTION VALUE="Madagascar">Madagascar</OPTION> <OPTION VALUE="Malawi">Malawi</OPTION> <OPTION VALUE="Malaysia">Malaysia</OPTION> <OPTION VALUE="Maldives">Maldives</OPTION> <OPTION VALUE="Mali">Mali</OPTION> <OPTION VALUE="Malta">Malta</OPTION> <OPTION VALUE="Marshall Islands">Marshall Islands</OPTION> <OPTION VALUE="Martinique (French)">Martinique (French)</OPTION> <OPTION VALUE="Mauritania">Mauritania</OPTION> <OPTION VALUE="Mauritius">Mauritius</OPTION> <OPTION VALUE="Mayotte">Mayotte</OPTION> <OPTION VALUE="Mexico">Mexico</OPTION> <OPTION VALUE="Micronesia">Micronesia</OPTION> <OPTION VALUE="Moldavia">Moldavia</OPTION> <OPTION VALUE="Monaco">Monaco</OPTION> <OPTION VALUE="Mongolia">Mongolia</OPTION> <OPTION VALUE="Montserrat">Montserrat</OPTION> <OPTION VALUE="Morocco">Morocco</OPTION> <OPTION VALUE="Mozambique">Mozambique</OPTION> <OPTION VALUE="Myanmar, Union of (Burma)">Myanmar, Union of (Burma)</OPTION> <OPTION VALUE="Namibia">Namibia</OPTION> <OPTION VALUE="Nauru">Nauru</OPTION> <OPTION VALUE="Nepal">Nepal</OPTION> <OPTION VALUE="Netherlands">Netherlands</OPTION> <OPTION VALUE="Netherlands Antilles">Netherlands Antilles</OPTION> <OPTION VALUE="Neutral Zone">Neutral Zone</OPTION> <OPTION VALUE="New Caledonia (French)">New Caledonia (French)</OPTION> <OPTION VALUE="New Zealand">New Zealand</OPTION> <OPTION VALUE="Nicaragua">Nicaragua</OPTION> <OPTION VALUE="Niger">Niger</OPTION> <OPTION VALUE="Nigeria">Nigeria</OPTION> <OPTION VALUE="Niue">Niue</OPTION> <OPTION VALUE="Norfolk Island">Norfolk Island</OPTION> <OPTION VALUE="North Korea">North Korea</OPTION> <OPTION VALUE="Northern Mariana Islands">Northern Mariana Islands</OPTION> <OPTION VALUE="Norway">Norway</OPTION> <OPTION VALUE="Oman">Oman</OPTION> <OPTION VALUE="Pakistan">Pakistan</OPTION> <OPTION VALUE="Palau">Palau</OPTION> <OPTION VALUE="Panama">Panama</OPTION> <OPTION VALUE="Papua New Guinea">Papua New Guinea</OPTION> <OPTION VALUE="Paraguay">Paraguay</OPTION> <OPTION VALUE="Peru">Peru</OPTION> <OPTION VALUE="Philippines">Philippines</OPTION> <OPTION VALUE="Pitcairn Island">Pitcairn Island</OPTION> <OPTION VALUE="Poland">Poland</OPTION> <OPTION VALUE="Polynesia (French)">Polynesia (French)</OPTION> <OPTION VALUE="Portugal">Portugal</OPTION> <OPTION VALUE="Qatar">Qatar</OPTION> <OPTION VALUE="Reunion (French)">Reunion (French)</OPTION> <OPTION VALUE="Romania">Romania</OPTION> <OPTION VALUE="Russian Federation">Russian Federation</OPTION> <OPTION VALUE="Rwanda">Rwanda</OPTION> <OPTION VALUE="S. Georgia &amp; S. Sandwich Islands">S. Georgia &amp; S. Sandwich Islands</OPTION> <OPTION VALUE="Saint Helena">Saint Helena</OPTION> <OPTION VALUE="Saint Kitts &amp; Nevis Anguilla">Saint Kitts &amp; Nevis Anguilla</OPTION> <OPTION VALUE="Saint Lucia">Saint Lucia</OPTION> <OPTION VALUE="Saint Pierre and Miquelon">Saint Pierre and Miquelon</OPTION> <OPTION VALUE="Saint Tome and Principe">Saint Tome and Principe</OPTION> <OPTION VALUE="Saint Vincent &amp; Grenadines">Saint Vincent &amp; Grenadines</OPTION> <OPTION VALUE="Samoa">Samoa</OPTION> <OPTION VALUE="San Marino">San Marino</OPTION> <OPTION VALUE="Saudi Arabia">Saudi Arabia</OPTION> <OPTION VALUE="Senegal">Senegal</OPTION> <OPTION VALUE="Seychelles">Seychelles</OPTION> <OPTION VALUE="Sierra Leone">Sierra Leone</OPTION> <OPTION VALUE="Singapore">Singapore</OPTION> <OPTION VALUE="Slovakia">Slovakia</OPTION> <OPTION VALUE="Slovenia">Slovenia</OPTION> <OPTION VALUE="Solomon Islands">Solomon Islands</OPTION> <OPTION VALUE="Somalia">Somalia</OPTION> <OPTION VALUE="South Africa">South Africa</OPTION> <OPTION VALUE="South Korea">South Korea</OPTION> <OPTION VALUE="Spain">Spain</OPTION> <OPTION VALUE="Sri Lanka">Sri Lanka</OPTION> <OPTION VALUE="Sudan">Sudan</OPTION> <OPTION VALUE="Suriname">Suriname</OPTION> <OPTION VALUE="Svalbard and Jan Mayen Islands">Svalbard and Jan Mayen Islands</OPTION> <OPTION VALUE="Swaziland">Swaziland</OPTION> <OPTION VALUE="Sweden">Sweden</OPTION> <OPTION VALUE="Switzerland">Switzerland</OPTION> <OPTION VALUE="Syria">Syria</OPTION> <OPTION VALUE="Tadjikistan">Tadjikistan</OPTION> <OPTION VALUE="Taiwan">Taiwan</OPTION> <OPTION VALUE="Tanzania">Tanzania</OPTION> <OPTION VALUE="Thailand">Thailand</OPTION> <OPTION VALUE="Togo">Togo</OPTION> <OPTION VALUE="Tokelau">Tokelau</OPTION> <OPTION VALUE="Tonga">Tonga</OPTION> <OPTION VALUE="Trinidad and Tobago">Trinidad and Tobago</OPTION> <OPTION VALUE="Tunisia">Tunisia</OPTION> <OPTION VALUE="Turkey">Turkey</OPTION> <OPTION VALUE="Turkmenistan">Turkmenistan</OPTION> <OPTION VALUE="Turks and Caicos Islands">Turks and Caicos Islands</OPTION> <OPTION VALUE="Tuvalu">Tuvalu</OPTION> <OPTION VALUE="Uganda">Uganda</OPTION> <OPTION VALUE="UK">UK</OPTION> <OPTION VALUE="Ukraine">Ukraine</OPTION> <OPTION VALUE="United Arab Emirates">United Arab Emirates</OPTION> <OPTION VALUE="Uruguay">Uruguay</OPTION> <OPTION VALUE="US">US</OPTION> <OPTION VALUE="USA Minor Outlying Islands">USA Minor Outlying Islands</OPTION> <OPTION VALUE="Uzbekistan">Uzbekistan</OPTION> <OPTION VALUE="Vanuatu">Vanuatu</OPTION> <OPTION VALUE="Vatican City">Vatican City</OPTION> <OPTION VALUE="Venezuela">Venezuela</OPTION> <OPTION VALUE="Vietnam">Vietnam</OPTION> <OPTION VALUE="Virgin Islands (British)">Virgin Islands (British)</OPTION> <OPTION VALUE="Virgin Islands (USA)">Virgin Islands (USA)</OPTION> <OPTION VALUE="Wallis and Futuna Islands">Wallis and Futuna Islands</OPTION> <OPTION VALUE="Western Sahara">Western Sahara</OPTION> <OPTION VALUE="Yemen">Yemen</OPTION> <OPTION VALUE="Yugoslavia">Yugoslavia</OPTION> <OPTION VALUE="Zaire">Zaire</OPTION> <OPTION VALUE="Zambia">Zambia</OPTION> <OPTION VALUE="Zimbabwe">Zimbabwe</OPTION> </select> </td> </tr> <tr> <td>City: </td> <td><input type=text name=city style="width:225"></td> </tr> <tr> <td> State: </td> <td> <select name=state style="width:177"> <OPTION VALUE="">Select</OPTION> <OPTION VALUE="Alabama">Alabama</OPTION> <OPTION VALUE="Alaska">Alaska</OPTION> <OPTION VALUE="Arizona">Arizona</OPTION> <OPTION VALUE="Arkansas">Arkansas</OPTION> <OPTION VALUE="California">California</OPTION> <OPTION VALUE="Colorado">Colorado</OPTION> <OPTION VALUE="Connecticut">Connecticut</OPTION> <OPTION VALUE="Delaware">Delaware</OPTION> <OPTION VALUE="District of Columbia">District of Columbia</OPTION> <OPTION VALUE="Florida">Florida</OPTION> <OPTION VALUE="Georgia">Georgia</OPTION> <OPTION VALUE="Hawaii">Hawaii</OPTION> <OPTION VALUE="Idaho">Idaho</OPTION> <OPTION VALUE="Illinois">Illinois</OPTION> <OPTION VALUE="Indiana">Indiana</OPTION> <OPTION VALUE="Iowa">Iowa</OPTION> <OPTION VALUE="Kansas">Kansas</OPTION> <OPTION VALUE="Kentucky">Kentucky</OPTION> <OPTION VALUE="Louisiana">Louisiana</OPTION> <OPTION VALUE="Maine">Maine</OPTION> <OPTION VALUE="Maryland">Maryland</OPTION> <OPTION VALUE="Massachusetts">Massachusetts</OPTION> <OPTION VALUE="Michigan">Michigan</OPTION> <OPTION VALUE="Minnesota">Minnesota</OPTION> <OPTION VALUE="Mississippi">Mississippi</OPTION> <OPTION VALUE="Missouri">Missouri</OPTION> <OPTION VALUE="Montana">Montana</OPTION> <OPTION VALUE="Nebraska">Nebraska</OPTION> <OPTION VALUE="Nevada">Nevada</OPTION> <OPTION VALUE="New Hampshire">New Hampshire</OPTION> <OPTION VALUE="New Jersey">New Jersey</OPTION> <OPTION VALUE="New Mexico">New Mexico</OPTION> <OPTION VALUE="New York">New York</OPTION> <OPTION VALUE="North Carolina">North Carolina</OPTION> <OPTION VALUE="North Dakota">North Dakota</OPTION> <OPTION VALUE="Ohio">Ohio</OPTION> <OPTION VALUE="Oklahoma">Oklahoma</OPTION> <OPTION VALUE="Oregon">Oregon</OPTION> <OPTION VALUE="Pennsylvania">Pennsylvania</OPTION> <OPTION VALUE="Puerto Rico">Puerto Rico</OPTION> <OPTION VALUE="Rhode Island">Rhode Island</OPTION> <OPTION VALUE="South Carolina">South Carolina</OPTION> <OPTION VALUE="South Dakota">South Dakota</OPTION> <OPTION VALUE="Tennessee">Tennessee</OPTION> <OPTION VALUE="Texas">Texas</OPTION> <OPTION VALUE="Utah">Utah</OPTION> <OPTION VALUE="Vermont">Vermont</OPTION> <OPTION VALUE="Virgin Islands">Virgin Islands</OPTION> <OPTION VALUE="Virginia">Virginia</OPTION> <OPTION VALUE="Washington">Washington</OPTION> <OPTION VALUE="West Virginia">West Virginia</OPTION> <OPTION VALUE="Wisconsin">Wisconsin</OPTION> <OPTION VALUE="Wyoming">Wyoming</OPTION> </select> </td> </tr> <tr> <td> Keyword: </td> <td> <input type=text name=kw style="width:177"></td> </tr> <tr> <td>Search method: </td> <td> <input type=radio name=sm value=or checked>or &nbsp;&nbsp;&nbsp;&nbsp; <input type=radio name=sm value=and>and </td> </tr> <tr> <td align=left>&nbsp; </td> <td align=left> <input type=submit name=submit value=Search> <input type=reset name=reset value=Reset> </td> </tr> <tr><td colspan=2> <br><br> <font size=2 face=verdana> *If you leave some fields blank, they will not take part in the search process.</font></td> </tr> </table> </form> <? include_once('../foother.html'); ?><file_sep><? include_once "accesscontrol.php"; $E_d = strip_tags($E_d); $E_i = strip_tags($E_i); $d1 = array(); $d1[0] = $ESmonth; $d1[1] = $ESyear; if (is_array($d1)) { $E_Start = implode("/" , $d1); } $d2 = array(); $d2[0] = $EEmonth; $d2[1] = $EEyear; if (is_array($d2)) { $E_End = implode("/" , $d2); } $E_i = addslashes($E_i); $q1 = "update job_education set E_i = \"$E_i\", E_Start = \"$E_Start\", E_End = \"$E_End\", E_gr = \"$E_gr\", E_d = \"$E_d\" where uname = \"$uname\" and En = \"$_POST[En]\""; $r2 = mysql_query($q1) or die(mysql_error()); include "ER4.php"; ?> <file_sep><? include_once "accesscontrol.php"; $q1 = "select plan, expiryplan,JS_number, JP_number from job_employer_info where ename = \"$ename\" "; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); if(!empty($a1[plan])) { $a11 = $a1[expiryplan]; $a112 = $a1[JP_number]; if(isset($submit) && $submit == 'Post this job') { $q2 = "select * from job_employer_info where ename = \"$ename\" "; $r2 = mysql_query($q2) or die(mysql_error()); $a2 = mysql_fetch_array($r2); if (is_array($JobCategory)) { $JobStr = implode("," , $JobCategory); } $qc = "select job_id from job_post order by job_id desc"; $rc = mysql_query($qc) or die(mysql_error()); $ac = mysql_fetch_array($rc); $job_id = $ac[0] + 1; $position = strip_tags($position); $description = strip_tags($description); $EXday = date('d', mktime(0,0,0,0, date(d) + $_POST[exdays1], 0)); $EXmonth = date('m', mktime(0,0,0, date(m), date(d) + $_POST[exdays1], 0)); $EXyear = date('Y', mktime(0,0,0,date(m) ,date(d) + $_POST[exdays1], date(Y))); $q3 = "insert into job_post set job_id = \"$job_id\", ename = \"$ename\", CompanyCountry = \"$a2[CompanyCountry]\", CompanyState = \"$a2[CompanyState]\", Company = \"$a2[CompanyName]\", position = \"$position\", JobCategory = \"$JobStr\", description = \"$description\", j_target = \"$j_target\", salary = \"$salary\", s_period = \"$s_period\", EXmonth = \"$EXmonth\", EXday = \"$EXday\", EXyear = \"$EXyear\" "; // echo $q3; $r3 = mysql_query($q3) or die(mysql_error()); $a112 = $a112 - 1; $q4 = "update job_employer_info set JP_number = \"$a112\" where ename = \"$ename\" "; $r4 = mysql_query($q4) or die(mysql_error()); $to = $a2[CompanyEmail]; $subject = "Your Job post at $site_name"; $message = "This is an automate sent copy of your Job post.\n\n Details:\n Job ID# $job_id \n Position: $position \n Category: $JobStr \n Description: $description \n Target: $clname \n Salary: $salary/$s_period \n Expire date: $EXmonth/$EXday/$EXyear\n\n\n To edit or delete this job, click here: http://$_SERVER[HTTP_HOST]/employers/DeleteJob.php "; $from = "From: $email_address"; mail($to, $subject, $message, $from); echo "<br><br><center> Job offer has been posted successfully. <br><br><br> </center>"; } // this will echo date in this format Jan-23-2006, first i extract month, year and date from date field of sql and then put then in mktime function // echo date("M-d-Y",mktime(0,0,0,substr($a1['expiryplan'],5,2),substr($a1['expiryplan'],8,2),substr($a1['expiryplan'],0,4))); $expiryon=mktime(0,0,0,substr($a1['expiryplan'],5,2),substr($a1['expiryplan'],8,2),substr($a1['expiryplan'],0,4)); $today=mktime(0,0,0,substr(date("Y.m.d"),5,2),substr(date("Y.m.d"),8,2),substr(date("Y.m.d"),0,4)); if ($today > $expiryon || $a112 < 1) { echo "<center><br><br><br>You can not post jobs. <br>To do this, you must buy one of our Employer's Plans:</center>"; include_once "pay10.php"; } else { echo ""; ?> <SCRIPT LANGUAGE="JavaScript"> function checkFields() { missinginfo = ""; if (document.form.position.value == "") { missinginfo += "\n - Position"; } if (document.form.description.value == "") { missinginfo += "\n - Description"; } if (document.form.salary.value == "") { missinginfo += "\n - Salary"; } //if (document.form.exdays1.value == "") { //missinginfo += "\n - Expire date/Day"; //} if (missinginfo != "") { missinginfo ="_____________________________\n" + "You failed to correctly fill in your:\n" + missinginfo + "\n_____________________________" + "\nPlease re-enter and submit again!"; alert(missinginfo); return false; } else return true; } </script> <form action="<?=$PHP_SELF?>" method="post" name="form" onSubmit="return checkFields();"? style="background:none;"> <table width=446 bgcolor="#FFFFFF"> <tr> <td colspan=2> You are using <strong>'<?=$a1[plan]?>'</strong> Package. <br>Your account status is positive.<br> Your membership is valid till <strong>'<?=date("d-M-Y",mktime(0,0,0,substr($a1['expiryplan'],5,2),substr($a1['expiryplan'],8,2),substr($a1['expiryplan'],0,4)));?>'</strong>.<br> <li><strong><?=dateDiff("/",date("m/d/Y",$expiryon),date("m/d/Y"));?> Days</strong> left to expiration.</li> <li>You can post <strong><?=$a112?></strong> jobs;</li> <li>You can review <strong><?=$a1[JS_number]?></strong> resumes; </li> </td> <tr> <tr><td colspan=2 align=center> To post a job, use the form below:</td></tr> <tr><td>Position:</td> <td> <input type=text name=position> </td> </tr> <tr> <td valign=top> Job Category: <br> </td> <td valign=top> <SELECT NAME="JobCategory[]" multiple size=5> <option value="Accounting/Auditing">Accounting/Auditing</option> <option value="Administrative and Support Services">Administrative and Support Services</option> <option value="Advertising/Public Relations">Advertising/Public Relations</option> <option value="Computers, Hardware">Computers, Hardware</option> <option value="Computers, Software">Computers, Software</option> <option value="Consulting Services">Consulting Services</option> <option value="Customer Service and Call Center">Customer Service and Call Center</option> <option value="Director">Director</option> <option value="Executive Management">Executive Management</option> <option value="Finance/Economics">Finance/Economics</option> <option value="Human Resources">Human Resources</option> <option value="Information Technology">Information Technology</option> <option value="Installation, Maintenance and Repair">Installation, Maintenance and Repair</option> <option value="Internet/E-Commerce">Internet/E-Commerce</option> <option value="Legal">Legal</option> <option value="Marketing">Marketing</option> <option value="Sales">Sales</option> <option value="Supervisor">Supervisor</option> <option value="Telecommunications">Telecommunications</option> <option value="Transportation and Warehousing">Transportation and Warehousing</option> <option value="Other">Other</option> </SELECT><br> </td> <tr><td valign=top>Description:</td> <td><textarea rows=6 cols=35 name=description></textarea></td> </tr> <tr> <td>Target: </td> <td> <select name="j_target"> <option value="1">Student (School Leaver)</option> <option value="2">Student (undergraduate/graduate)</option> <option value="3">Entry Level (less than 2 years of experience)</option> <option value="4">Mid Career (2+ years of experience)</option> <option value="5">Management (Manager/Director of Staff)</option> <option value="6">Executive </option> <option value="7">Senior Executive (President, CEO)</option> </select> </td> </tr> <tr><td>Salary: </td> <td> <input type=text name=salary size=11> <select name=s_period> <option value="Yearly">Yearly </option> <option value="Monthly">Monthly </option> </select> </td></tr> <tr> <td> This job posting will expire in: </td> <td> <strong><? $date2=date("m/d/Y",$expiryon); $date1=date("m/d/Y"); // echo $date1 . " ". $date2; // $expiryon=mktime(0,0,0,substr($a1['expiryplan'],5,2),substr($a1['expiryplan'],8,2),substr($a1['expiryplan'],0,4)); // $today=mktime(0,0,0,substr(date("Y.m.d"),5,2),substr(date("Y.m.d"),8,2),substr(date("Y.m.d"),0,4)); // echo date("d.m.y",($expiryon - ($expiryon - $today))); // $ar1=mysql_fetch_array(mysql_query("Select * from job_plan where PlanName=\"$a1[plan]\" ")); // echo $ar1[numdays]; if (dateDiff("/", $date2, $date1) == 0) echo "Today."; else echo dateDiff("/", $date2, $date1) . " days."; ?> </strong> <input type="hidden" name="exdays1" value="<?=dateDiff("/", $date2, $date1)?>"> <!-- <select name=exdays1> <option value="7">7</option> <option value="14">14</option> <option value="21">21</option> <option value="28">28</option> --> </select> </td> </tr> <tr> <td align=left>&nbsp; </td> <td align=left> <input type=submit name=submit value="Post this job"> <input type=submit name=reset2 value=Reset> </td> </tr> </table> </form> <? } } else { include "pay10.php"; } ?> <? include_once('../foother.html'); ?> <? function dateDiff($dformat, $endDate, $beginDate) { $date_parts1=explode($dformat, $beginDate); $date_parts2=explode($dformat, $endDate); $start_date=gregoriantojd($date_parts1[0], $date_parts1[1], $date_parts1[2]); $end_date=gregoriantojd($date_parts2[0], $date_parts2[1], $date_parts2[2]); return $end_date - $start_date; } ?><file_sep><div id="contentMenu"> <ul> <li><a href="" class="emptyTrash"><?php echo _('Empty Trash'); ?></a></li> <li><a href="" class="checkAll"><?php echo _('Select All'); ?></a></li> <li><a href="" class="deleteSelected"><?php echo _('Delete Selected'); ?></a></li> <li><a href="" class="restoreSelected"><?php echo _('Restore Selected'); ?></a></li> </ul> </div> <div id="trash"> <div class="legend"> <h1><?php echo _('Legend'); ?></h1> <ul> <li><?php echo _('Folder'); ?> <ul> <li><?php echo _('Page'); ?> <ul> <li><?php echo _('List'); ?> <ul> <li><?php echo _('Item'); ?></li> </ul> </li> </ul> </li> </ul> </li> </ul> <p><?php echo _('Black - Parent (not deleted)'); ?></p> <p class="deleted"><?php echo _('Red - Deleted Object'); ?></p> <p class="deletedChild"><?php echo _('Blue - Deleted Child Object'); ?></p> </div> <?php $tabsProcessed = array(); // Select tabs in trash: $queryTabs = mysql_query(" SELECT distinct tabs.tab_id as tab_id, tabs.name as tab_name, tabs.trash as trash, tabs.position as tab_position FROM tabs FORCE INDEX (tab) LEFT JOIN pages on tabs.tab_id = pages.tab_id LEFT JOIN lists on pages.page_id = lists.page_id LEFT JOIN items on lists.list_id = items.list_id WHERE tabs.trash = 1 OR tabs.trash = 9 OR (pages.trash = 1 AND tabs.trash = 0) OR (lists.trash = 1 AND tabs.trash = 0) OR (items.trash = 1 AND tabs.trash = 0) ORDER BY tab_position "); $tabIteration = 1; $numTabs = mysql_num_rows($queryTabs); // Process the items in trash while($rowTabs = mysql_fetch_assoc($queryTabs)){ if (in_array($rowTabs['tab_id'], $tabsProcessed)) continue; buildTrashTree($rowTabs, $numTabs, $tabsProcessed, $tabIteration, "items"); $tabsProcessed[] = $rowTabs['tab_id']; $tabIteration++; } // close items in trash loop if (count($tabsProcessed) == 0) echo ' <div class="noResults"> '._('Trash is Empty').'. </div> '; function buildTrashTree($rowTabs = array(), $numTabs, $tabsProcessed, $tabIteration, $level = "") { echo '<div class="trashTree"> <ul>'; echo '<li>'; if ($rowTabs['trash'] == 1) echo '<input name="" type="checkbox" value="Tab-'.$rowTabs['tab_id'].'" class="trashCheckbox" />'; if ($rowTabs['trash'] == 1) echo '<span class="deleted">'; echo $rowTabs['tab_name']; if ($rowTabs['trash'] == 1) echo '</span>'; // Select the pages on the tab if ($rowTabs['trash'] == 1) $queryPages = mysql_query(" SELECT distinct pages.page_id as page_id, pages.name as name, pages.trash as trash, pages.position as page_position FROM pages WHERE pages.tab_id = ".$rowTabs['tab_id']." ORDER BY page_position "); if ($rowTabs['trash'] == 0) $queryPages = mysql_query(" SELECT distinct pages.page_id as page_id, pages.name as name, pages.trash as trash, pages.position as page_position FROM pages LEFT JOIN lists on pages.page_id = lists.page_id LEFT JOIN items on lists.list_id = items.list_id WHERE pages.tab_id = ".$rowTabs['tab_id']." AND pages.trash = 1 OR (pages.tab_id = ".$rowTabs['tab_id']." AND lists.trash = 1) OR (pages.tab_id = ".$rowTabs['tab_id']." AND items.trash = 1) ORDER BY page_position "); $pageIteration = 1; $numPages = mysql_num_rows($queryPages); $pagesProcessed = array(); // Print the pages beloging to tab while($rowPages = mysql_fetch_assoc($queryPages)){ if (in_array($rowPages['page_id'], $pagesProcessed)) continue; if ($pageIteration == 1) echo '<ul>'; echo '<li>'; if ($rowPages['trash'] == 1) echo '<input name="" type="checkbox" value="Page-'.$rowPages['page_id'].'" class="trashCheckbox" />'; if ($rowPages['trash'] == 1) echo '<span class="deleted">'; if ($rowPages['trash'] == 0 && $rowTabs['trash'] == 1) echo '<span class="deletedChild">'; echo $rowPages['name']; if ($rowPages['trash'] == 1) echo '</span>'; // Select lists in on the page: if ($rowPages['trash'] == 1 or $rowTabs['trash'] == 1) $queryLists = mysql_query(" SELECT distinct lists.list_id as list_id, lists.name as name, lists.trash as trash, lists.position as list_position FROM lists WHERE lists.page_id = ".$rowPages['page_id']." ORDER BY list_position "); elseif ($rowPages['trash'] == 0) $queryLists = mysql_query(" SELECT distinct lists.list_id as list_id, lists.name as name, lists.trash as trash, lists.position as list_position FROM lists LEFT JOIN items on lists.list_id = items.list_id WHERE lists.page_id = ".$rowPages['page_id']." AND lists.trash = 1 OR (lists.page_id = ".$rowPages['page_id']." AND items.trash = 1) ORDER BY list_position "); $listIteration = 1; $numLists = mysql_num_rows($queryLists); if ($numLists == 0) echo '</li>'; $listsProcessed = array(); // Print the lists in trash while($rowLists = mysql_fetch_assoc($queryLists)){ if (in_array($rowLists['list_id'], $listsProcessed)) continue; if ($listIteration == 1) echo '<ul>'; echo '<li>'; if ($rowLists['trash'] == 1) echo '<input name="checkList" type="checkbox" value="List-'.$rowLists['list_id'].'" class="trashCheckbox" />'; if ($rowLists['trash'] == 1) echo '<span class="deleted">'; if ($rowLists['trash'] == 0 && $rowPages['trash'] == 1 or $rowTabs['trash'] == 1) echo '<span class="deletedChild">'; echo $rowLists['name']; if ($rowLists['trash'] == 1) echo '</span>'; // Select items in the list: $queryItems = mysql_query(" SELECT id, text, trash, position FROM items WHERE list_id = ".$rowLists['list_id']." ORDER BY position"); $itemIteration = 1; $numItems = mysql_num_rows($queryItems); if ($numItems == 0) echo '</li>'; // Print the items in trash while($rowItems = mysql_fetch_assoc($queryItems)){ if ($itemIteration == 1) echo '<ul>'; echo ''; if ($rowItems['trash'] == 1) echo '<li><input name="" type="checkbox" value="Item-'.$rowItems['id'].'" class="trashCheckbox" />'; if ($rowItems['trash'] == 1) echo '<span class="deleted">'.strip_html_tags($rowItems['text']).'</span></li>'; if ($rowItems['trash'] == 0 && ($rowLists['trash'] == 1 or $rowPages['trash'] == 1 or $rowTabs['trash'] == 1)) echo '<li><span class="deletedChild">'.strip_html_tags($rowItems['text']).'</span></li>'; if ($itemIteration == $numItems) echo '</ul></li>'; $itemIteration++; } // close item loop if ($listIteration == $numLists) echo '</ul></li>'; $listsProcessed[] = $rowLists['list_id']; $listIteration++; } // close list loop if ($pageIteration == $numPages) echo '</ul></li>'; $pagesProcessed[] = $rowPages['page_id']; $pageIteration++; } // close page loop if ($tabIteration == $numTabs) echo '</ul>'; echo '</div> <!-- close trashTree-->'; } // close function buildTrashTree /** * Remove HTML tags, including invisible text such as style and * script code, and embedded objects. Add line breaks around * block-level tags to prevent word joining after tag removal. */ function strip_html_tags( $text ) { $text = preg_replace( array( // Remove invisible content '@<head[^>]*?>.*?</head>@siu', '@<style[^>]*?>.*?</style>@siu', '@<script[^>]*?.*?</script>@siu', '@<object[^>]*?.*?</object>@siu', '@<embed[^>]*?.*?</embed>@siu', '@<applet[^>]*?.*?</applet>@siu', '@<noframes[^>]*?.*?</noframes>@siu', '@<noscript[^>]*?.*?</noscript>@siu', '@<noembed[^>]*?.*?</noembed>@siu', // Add line breaks before and after blocks '@</?((address)|(blockquote)|(center)|(del))@iu', '@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))@iu', '@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu', '@</?((table)|(th)|(td)|(caption))@iu', '@</?((form)|(button)|(fieldset)|(legend)|(input))@iu', '@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu', '@</?((frameset)|(frame)|(iframe))@iu', ), array( ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", ), $text ); $text = strip_tags( $text ); if (strlen($text) > 100) $text = substr($text,0,100).'...('._('text trimmed').')'; return $text; } ?> </div> <!-- close trash--> <script type="text/javascript" src="min/?f=lib/jquery/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="min/?f=lib/jquery/jquery-ui-1.8.5.min.js"></script> <script type="text/javascript" src="min/?f=lib/script.js"></script> <script type="text/javascript" src="min/?f=lib/gettext.js"></script> <file_sep><?php require_once ('session.php'); require_once ('shared.php'); idOnlyCall('purge'); ?> <file_sep>var bool_ezObjectExplainer_insideObject_stack = []; var bool_ezObjectExplainer_insideObject_cache = []; function ezObjectExplainer(obj, bool_includeFuncs, _cnt) { var _db = ''; var m = -1; var i = -1; var a = []; var cnt = ((_cnt == null) ? '1' : _cnt.toString() + '.0'); bool_includeFuncs = ((bool_includeFuncs == true) ? bool_includeFuncs : false); function isCntComplex(c) { return (c.toString().indexOf('.') > -1); } _db = ''; if ( (obj.toString != null) && ((typeof obj.toString) == const_function_symbol) && (obj.toString.toString().toLowerCase().indexOf('[native code]') == -1) ) { _db += obj.toString(); } else { if ( (obj != null) && ((typeof obj) == const_object_symbol) ) { if (obj.length != null) { for (i = 0; i < obj.length; i++) { if ( ( (bool_includeFuncs) && ((typeof obj[i]) == const_function_symbol) ) || ( (!bool_includeFuncs) && ((typeof obj[i]) != const_function_symbol) ) ) { a.push('[' + obj[i] + ']'); } } } else { for (m in obj) { if ((typeof obj[m]) == const_object_symbol) { a.push(m + ' = [' + ezObjectExplainer(obj[m], bool_includeFuncs, cnt) + ']'); } else if ( ( (bool_includeFuncs) && ((typeof obj[m]) == const_function_symbol) ) || ( (!bool_includeFuncs) && ((typeof obj[m]) != const_function_symbol) ) ) { a.push(m + ' = [' + obj[m] + ']'); } } } _db += a.join(((isCntComplex(cnt)) ? ',' : '\n')); } else if ( ( (bool_includeFuncs) && ((typeof obj) == const_function_symbol) ) || ( (!bool_includeFuncs) && ((typeof obj) != const_function_symbol) ) ) { _db += obj + '\n'; } } return _db; } <file_sep><?php require_once('session.php'); require_once('shared.php'); //Has the user selected a default object and clicked one //of the action buttons. If so, proceed to that page; otherwise, //show the form to do so. if (isset($_POST['actionJump']) && $_POST['actionJump'] != ""){ $_SESSION['default_object'] = $_POST['default_object']; header("Location: $_POST[actionJump]"); } elseif (isset($_POST['select'])){ include_once('header.php'); show_error("Choose an object and an action to which to jump."); show_select_form(); include_once('footer.php');; } else { include_once('header.php'); show_select_form(); include_once('footer.php'); } function show_select_form(){ ?> <body onLoad='toggleObjectSelectDisabled();'/> <script> function toggleObjectSelectDisabled(){ var actionJumpVal = document.getElementById('actionJump').value; if(actionJumpVal == '' || actionJumpVal == 'execute.php'|| actionJumpVal == 'settings.php' || actionJumpVal == 'delete.php' || actionJumpVal == 'undelete.php' || actionJumpVal == 'purge.php' || actionJumpVal == 'search.php'){ document.getElementById('default_object').disabled = true; } else { document.getElementById('default_object').disabled = false; } } </script> <?php try{ print "<form method='post' action='$_SERVER[PHP_SELF]'>\n"; print "<p><strong>Select a default object and action:</strong></p>\n"; //Display a list of actions as submit buttons. Jump to the selected //action's page on refresh (see IF statement at top) print <<<actionJumper <p><strong>Jump to: </strong> <select name='actionJump' id='actionJump' style='width: 20em;' onChange='toggleObjectSelectDisabled();'> <option value=''></option> <option value='describe.php'>Describe</option> <option value='insert.php'>Insert</option> <option value='upsert.php'>Upsert</option> <option value='update.php'>Update</option> <option value='delete.php'>Delete</option> <option value='undelete.php'>Undelete</option> <option value='purge.php'>Purge</option> <option value='query.php'>Query</option> <option value='search.php'>Search</option> <option value='execute.php'>Execute</option> <option value='settings.php'>Settings</option> </select></p> actionJumper; //Describe a list of all the objects in the user's org and display //in a drop down select box print "<p><strong>Object: &nbsp; </strong>"; myGlobalSelect($_SESSION['default_object'],'default_object'); print "<p/><input type='submit' name='select' value='Select' />"; print "</form>\n"; } catch (Exception $e) { $errors = null; $errors = $e->getMessage(); show_error($errors); exit; } } ?> <file_sep><?php include_once "accesscontrol.php"; $q1 = "select * from job_seeker_info"; $r1 = mysql_query($q1) or die(mysql_error()); while($a1 = mysql_fetch_array($r1)) { echo "$a1[0] $a1[1] $a1[2] $a1[careerlevel] <br>"; } ?><file_sep><!--======================== BEGIN COPYING THE HTML-TOP HERE ==========================--> <table border="0" cellpadding="0" cellspacing="0" width="665" align="center" background="images/bg.gif"> <tr> </tr> <tr> <td colspan="11" rowspan="7"> <map name="FPMap0"> <area href="http://<?=$_SERVER[HTTP_HOST]?>/index.php" shape="rect" coords="40, 172, 88, 222"> <area href="http://<?=$_SERVER[HTTP_HOST]?>/about.php" shape="rect" coords="92, 170, 155, 225"> <area href="http://<?=$_SERVER[HTTP_HOST]?>/faq.php" shape="rect" coords="159, 171, 201, 224"> <area href="http://<?=$_SERVER[HTTP_HOST]?>/contactus.php" shape="rect" coords="207, 170, 259, 225"> </map> <img border="0" src="images/top2.jpg" width="665" height="281" usemap="#FPMap0"></td> </tr> </table> <!--========================= STOP COPYING THE HTML-TOP HERE =========================--> <file_sep><? include_once "accesscontrol.php"; $q1 = "select * from job_education where uname = \"$uname\" order by En asc "; $r2 = mysql_query($q1) or die(mysql_error()); echo "<br><br><br>"; while ($a1 = mysql_fetch_array($r2)) { echo " <form action=EditEducation.php method=post style=\"background:none;\"> <table align=center width=420 border=0 bordercolor=e0e7e9 cellspacing=0 cellpadding=0> <caption> <input type=submit name=submit value=Delete style=\"border-width:1; border-color:black; font-family:verdana; font-weight:normal; color:#000000; background-color:#e0e7e9\"> <input type=hidden name=En value=$a1[En]> <font size=2> <strong>Education# $a1[En]</strong> </font> <input type=submit name=submit value=Edit style=\"border-width:1; border-color:black; font-family:verdana; font-weight:normal; color:#000000; background-color:#e0e7e9\"> <input type=hidden name=En value=$a1[En]> </caption> </form> <tr> <td colspan=4><b>&nbsp; Education Institution: </b>"; echo stripslashes($a1[E_i]); echo "</td> </tr> <tr> <td>&nbsp; Graduate Level </td> <td width=100><b>&nbsp; From date </b></td><td width=185 >&nbsp; $a1[E_Start] </td> </tr> <tr> <td > &nbsp; $a1[E_gr] </td> <td width=100><b>&nbsp; To date </b></td><td width=185 >&nbsp; $a1[E_End] </td> </tr> <tr> <td colspan=4> <table cellspacing=0 width=100%> <tr> <td valign=top> <b>&nbsp; Description: </b> </td> </tr> <tr> <td > $a1[E_d] </td> </tr> </table> </td> </td> </tr> </table><br> "; } $qs = "select count(En) from job_education where uname = \"$uname\" "; $rqs = mysql_query($qs) or die(mysql_error()); $aqs = mysql_fetch_array($rqs); $En = $aqs[0] + 1; echo "<table width=446><tr><td><center> <a href=EEAdd.php?En=$En>Add another </a> OR <a href=EditSkills.php> Go to Step 3 (Skills) </a> </center></td></tr></table>"; ?> <? include_once('../foother.html'); ?><file_sep><? include_once "accesscontrol.php"; $q1 = "select * from job_skills where uname = \"$uname\" "; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); $a11 = stripslashes($a1[SK_d]); ?> <SCRIPT LANGUAGE="JavaScript"> function checkFields() { missinginfo = ""; if (document.form.SK_d.value == "") { missinginfo += "\n - Institution name"; } if (missinginfo != "") { missinginfo ="_____________________________\n" + "You failed to correctly fill in your:\n" + missinginfo + "\n_____________________________" + "\nPlease re-enter and submit again!"; alert(missinginfo); return false; } else return true; } </script> <form method=post action=EditSkills2.php name=form onSubmit="return checkFields();" style="background:none;"> <table align=center width=446 bgcolor="#FFFFFF"> <tr> <td valign=top align="center"><b>Skills: </b><br> <font size=1>(describe your skills - languages, courses, seminars, etc.) To insert new row, use &lt;BR&gt; </font></td> </tr> <tr> <td valign=top align="center"><textarea name=SK_d rows=6 cols=70><?=$a11?> </textarea> </td> </tr> <tr> <td align=center> <input type=submit name=submit value="Save and finish"> </td> </tr> </table> </form> <? include_once('../foother.html'); ?><file_sep><? include_once "main.php"; if (isset($submit) && !empty($story)) { $q1 = "select WS_id from job_story_waiting"; $r1 = mysql_query($q1)or die(mysql_error()); $a1 = mysql_num_rows($r1); $story_id = $a1 + 1; $story2 = strip_tags($_POST[story]); $q2 = "insert into job_story_waiting set WS_id = \"$story_id\", story = \"$story2\""; $r2 = mysql_query($q2) or die(mysql_error()); echo "<table align=center width=446 cellpadding=10><tr><td>Thank you.<br>We will incude your story on the firs page of our site, so every one can read it</td></tr></table>"; } else { ?> <form action="<?=$PHP_SELF?>" method="post" style="background:none;"> <table align=center width="446" cellpadding="10" bgcolor="#FFFFFF"> <tr> <td>Tell us your success story while using <b><?=$site_name?> </b></td> </tr> <tr> <td> <textarea name=story rows=6 cols=80></textarea> </td> </tr> <tr> <td align=center> <input type=submit name=submit value=Send> </td> </tr> </table> </form> <? } ?> <? include_once('foother.html'); ?><file_sep> <div id="contentMenu"> <ul> <li><a href=""><?php echo _('Search Results'); ?></a></li> </ul> </div> <div class="clear"></div> <div id="search"> <div class="legend"> <h1><?php echo _('Legend'); ?></h1> <ul> <li><?php echo _('Folder'); ?> <ul> <li><?php echo _('Page'); ?> <ul> <li><?php echo _('List'); ?> <ul> <li><?php echo _('Item'); ?></li> </ul> </li> </ul> </li> </ul> </li> </ul> </div> <?php $search_string = '%'.str_replace("*","%",$_GET['search']).'%'; $tabsProcessed = array(); // Select all the matching tabs: if ($search_string == '%%') $queryTabs = mysql_query(" SELECT tabs.tab_id as tab_id, tabs.name as tab_name, tabs.position as tab_position FROM tabs as tabs WHERE tabs.name like '$search_string' AND tabs.trash = 0 ORDER BY tab_position "); if ($search_string != '%%') $queryTabs = mysql_query(" SELECT distinct tabs.tab_id as tab_id, tabs.name as tab_name, tabs.position as tab_position FROM tabs LEFT JOIN pages on tabs.tab_id = pages.tab_id LEFT JOIN lists on pages.page_id = lists.page_id LEFT JOIN items on lists.list_id = items.list_id WHERE tabs.trash = 0 AND tabs.name like '$search_string' OR (pages.trash = 0 AND tabs.trash = 0 AND pages.name like '$search_string') OR (lists.trash = 0 AND pages.trash = 0 AND tabs.trash = 0 AND lists.name like '$search_string') OR (items.trash = 0 AND lists.trash = 0 AND pages.trash = 0 AND tabs.trash = 0 AND items.text like '$search_string') ORDER BY tab_position "); $tabIteration = 1; $numTabs = mysql_num_rows($queryTabs); // Process the tabs while($rowTabs = mysql_fetch_assoc($queryTabs)){ if (in_array($rowTabs['tab_id'], $tabsProcessed)) continue; echo '<div class="searchTree"> <ul>'; echo '<li>'; echo '<a href="index.php?tab='.$rowTabs['tab_id'].'">'.$rowTabs['tab_name'].'</a>'; // Select the pages on the tab if ($search_string == '%%') $queryPages = mysql_query(" SELECT distinct pages.page_id as page_id, pages.name as name, pages.position as page_position FROM pages as pages WHERE pages.name like '$search_string' AND pages.trash = 0 AND pages.tab_id = ".$rowTabs['tab_id']." ORDER BY page_position "); if ($search_string != '%%') $queryPages = mysql_query(" SELECT distinct pages.page_id as page_id, pages.name as name, pages.position as page_position FROM pages LEFT JOIN lists on pages.page_id = lists.page_id LEFT JOIN items on lists.list_id = items.list_id WHERE pages.name like '$search_string' AND pages.trash = 0 AND pages.tab_id = ".$rowTabs['tab_id']." OR (lists.name like '$search_string' AND lists.trash = 0 AND pages.trash = 0 AND pages.tab_id = ".$rowTabs['tab_id'].") OR (items.text like '$search_string' AND items.trash = 0 AND lists.trash = 0 AND pages.trash = 0 AND pages.tab_id = ".$rowTabs['tab_id'].") ORDER BY page_position "); $pageIteration = 1; $numPages = mysql_num_rows($queryPages); $pagesProcessed = array(); // Print the pages beloging to tab while($rowPages = mysql_fetch_assoc($queryPages)){ if (in_array($rowPages['page_id'], $pagesProcessed)) continue; if ($pageIteration == 1) echo '<ul>'; echo '<li>'; echo '<a href="index.php?tab='.$rowTabs['tab_id'].'&page='.$rowPages['page_id'].'">'.$rowPages['name'].'</a>'; // Select lists in on the page: if ($search_string == '%%') $queryLists = mysql_query(" SELECT distinct lists.list_id as list_id, lists.name as name, lists.column_id as list_column, lists.position as list_position FROM lists as lists WHERE lists.name like '$search_string' AND lists.trash = 0 AND lists.page_id = ".$rowPages['page_id']." ORDER BY list_column, list_position "); if ($search_string != '%%') $queryLists = mysql_query(" SELECT distinct lists.list_id as list_id, lists.name as name, lists.column_id as list_column, lists.position as list_position FROM lists LEFT JOIN items on lists.list_id = items.list_id WHERE lists.name like '$search_string' AND lists.trash = 0 AND lists.page_id = ".$rowPages['page_id']." OR (items.text like '$search_string' AND items.trash = 0 AND lists.trash = 0 AND lists.page_id = ".$rowPages['page_id'].") ORDER BY list_column, list_position "); $listIteration = 1; $numLists = mysql_num_rows($queryLists); if ($numLists == 0) echo '</li>'; $listsProcessed = array(); // Print the lists in trash while($rowLists = mysql_fetch_assoc($queryLists)){ if (in_array($rowLists['list_id'], $listsProcessed)) continue; if ($listIteration == 1) echo '<ul>'; echo '<li>'; echo '<a href="index.php?tab='.$rowTabs['tab_id'].'&page='.$rowPages['page_id'].'">'.$rowLists['name'].'</a>'; // Select items in the list: $queryItems = mysql_query(" SELECT id, text, position FROM items WHERE text like '$search_string' AND trash = 0 AND list_id = ".$rowLists['list_id']." ORDER BY position "); $itemIteration = 1; $numItems = mysql_num_rows($queryItems); if ($numItems == 0) echo '</li>'; // Print the items in trash while($rowItems = mysql_fetch_assoc($queryItems)){ if ($itemIteration == 1) echo '<ul>'; echo '<li>'; echo '<a href="index.php?tab='.$rowTabs['tab_id'].'&page='.$rowPages['page_id'].'">'.strip_html_tags($rowItems['text']).'</a>'; echo '</li>'; if ($itemIteration == $numItems) echo '</ul></li>'; $itemIteration++; } // close item loop if ($listIteration == $numLists) echo '</ul></li>'; $listsProcessed[] = $rowLists['list_id']; $listIteration++; } // close list loop if ($pageIteration == $numPages) echo '</ul></li>'; $pagesProcessed[] = $rowPages['page_id']; $pageIteration++; } // close page loop if ($tabIteration == $numTabs) echo '</ul>'; echo '</div> <!-- close trashTree-->'; $tabsProcessed[] = $rowTabs['tab_id']; $tabIteration++; } // close items in loop if (count($tabsProcessed) == 0) echo ' <div class="noResults"> '._('No matches found').'. </div> '; /** * Remove HTML tags, including invisible text such as style and * script code, and embedded objects. Add line breaks around * block-level tags to prevent word joining after tag removal. */ function strip_html_tags( $text ) { $text = preg_replace( array( // Remove invisible content '@<head[^>]*?>.*?</head>@siu', '@<style[^>]*?>.*?</style>@siu', '@<script[^>]*?.*?</script>@siu', '@<object[^>]*?.*?</object>@siu', '@<embed[^>]*?.*?</embed>@siu', '@<applet[^>]*?.*?</applet>@siu', '@<noframes[^>]*?.*?</noframes>@siu', '@<noscript[^>]*?.*?</noscript>@siu', '@<noembed[^>]*?.*?</noembed>@siu', // Add line breaks before and after blocks '@</?((address)|(blockquote)|(center)|(del))@iu', '@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))@iu', '@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu', '@</?((table)|(th)|(td)|(caption))@iu', '@</?((form)|(button)|(fieldset)|(legend)|(input))@iu', '@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu', '@</?((frameset)|(frame)|(iframe))@iu', ), array( ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", ), $text ); $text = strip_tags( $text ); if (strlen($text) > 100) $text = substr($text,0,100).'...('._('text trimmed').')'; return $text; } ?> </div> <script type="text/javascript" src="min/?f=lib/jquery/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="min/?f=lib/jquery/jquery-ui-1.8.5.min.js"></script> <script type="text/javascript" src="min/?f=lib/script.js"></script> <script type="text/javascript" src="min/?f=lib/gettext.js"></script><file_sep><?php require_once ('SforceMetaObject.php'); class SforceMetadataClient { public $sforce; protected $sessionId; protected $location; protected $namespace = 'http://soap.sforce.com/2006/04/metadata'; public function __construct($wsdl, $loginResult, $sforceConn) { $soapClientArray = null; if (phpversion() > '5.1.2') { $soapClientArray = array ( 'encoding' => 'utf-8', 'trace' => 1, 'compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP, 'sessionId' => $loginResult->sessionId ); } else { $soapClientArray = array ( 'encoding' => 'utf-8', 'trace' => 1, 'sessionId' => $loginResult->sessionId ); } $this->sforce = new SoapClient($wsdl,$soapClientArray); //$this->sforce->__setSoapHeaders($header_array); $sessionVar = array( 'sessionId' => new SoapVar($loginResult->sessionId, XSD_STRING) ); $headerBody = new SoapVar($sessionVar, SOAP_ENC_OBJECT); $session_header = new SoapHeader($this->namespace, 'SessionHeader', $headerBody, false); $header_array = array ( $session_header ); $this->sforce->__setSoapHeaders($header_array); $this->sforce->__setLocation($loginResult->metadataServerUrl); return $this->sforce; } /** * Specifies the session ID returned from the login server after a successful * login. */ protected function _setLoginHeader($loginResult) { $this->sessionId = $loginResult->sessionId; $this->setSessionHeader($this->sessionId); $serverURL = $loginResult->serverUrl; $this->setEndPoint($serverURL); } /** * Set the endpoint. * * @param string $location Location */ public function setEndpoint($location) { $this->location = $location; $this->sforce->__setLocation($location); } /** * Set the Session ID * * @param string $sessionId Session ID */ public function setSessionHeader($sessionId) { $this->sforce->__setSoapHeaders(NULL); $session_header = new SoapHeader($this->namespace, 'SessionHeader', array ( 'sessionId' => $sessionId )); $this->sessionId = $sessionId; $header_array = array ( $session_header ); $this->_setClientId($header_array); $this->sforce->__setSoapHeaders($header_array); } public function create($obj) { $encodedObj = new stdClass; $encodedObj->metadata = new SoapVar($obj, SOAP_ENC_OBJECT, 'CustomObject', $this->namespace); return $this->sforce->create($encodedObj); } public function delete($obj) { $encodedObj = new stdClass; $encodedObj->metadata = new SoapVar($obj, SOAP_ENC_OBJECT, 'CustomObject', $this->namespace); return $this->sforce->delete($encodedObj); } public function checkStatus($ids) { return $this->sforce->checkStatus($ids); } public function getLastRequest() { return $this->sforce->__getLastRequest(); } public function getLastRequestHeaders() { return $this->sforce->__getLastRequestHeaders(); } public function getLastResponse() { return $this->sforce->__getLastResponse(); } public function getLastResponseHeaders() { return $this->sforce->__getLastResponseHeaders(); } } ?> <file_sep><?php print_r('$_SERVER[\'REDIRECT_URL\'] :: '); print_r($_SERVER['REDIRECT_URL']); print_r('<br><br>'); print_r('$_SERVER[\'REQUEST_URI\'] :: '); print_r($_SERVER['REQUEST_URI']); print_r('<br><br>'); ?> <?php print_r('<pre>$_SERVER :: <br>'); print_r($_SERVER); print_r('<br><br></pre>'); print_r('<pre>$_GET :: <br>'); print_r($_GET); print_r('<br><br></pre>'); print_r('<pre>$_POST :: <br>'); print_r($_POST); print_r('<br><br></pre>'); print_r('<pre>$_REQUEST :: <br>'); print_r($_REQUEST); print_r('<br><br></pre>'); print_r('<pre>$_FILES :: <br>'); print_r($_FILES); print_r('<br><br></pre>'); print_r('<pre>$_COOKIE :: <br>'); print_r($_COOKIE); print_r('<br><br></pre>'); print_r('<pre>$_ENV :: <br>'); print_r($_ENV); print_r('<br><br></pre>'); ?> <file_sep><? include_once "../main.php"; $q = "select * from job_post where job_id = \"$job_id\" "; $r = mysql_query($q) or die(mysql_error()); $a = mysql_fetch_array($r); ?> <table align=center width="446"> <tr> <td colspan=2 align=center> <b> Details about Job ID# <?=$a[job_id]?> </b></td> </tr> <tr> <td><b> Position: </b></td> <td> <?=$a[position]?> </td> </tr> <tr> <td><b> Job category: </b></td> <td> <?=$a[JobCategory]?> </td> </tr> <tr> <td><b> Target: </b></td> <? if($a[j_target] == '1') { $clname = 'Student (High School)'; } elseif($a[j_target] == '2') { $clname = 'Student (undergraduate/graduate)'; } elseif($a[j_target] == '3') { $clname = 'Entry Level (less than 2 years of experience)'; } elseif($a[j_target] == '4') { $clname = 'Mid Career (2+ years of experience)'; } elseif($a[j_target] == '5') { $clname = 'Management (Manager/Director of Staff)'; } elseif($a[j_target] == '6') { $clname = 'Executive (SVP, EVP, VP)'; } elseif($a[j_target] == '7') { $clname = 'Senior Executive (President, CEO)'; } ?> <td><?=$clname?> </td> </tr> <tr> <td><b> Salary: </b> </td> <td> <?=$a[salary]?> / <?=$a[s_period]?> </td> </tr> <tr> <td><b> Description: </b></td> <td> <?=$a[description]?> </td> </tr> <form action=Send.php method=post style="background:none;"> <tr> <td colspan=2 align=center> <input type=hidden name=job_id value=<?=$a[job_id]?>> <input type=submit name=ok value="Send my application"> <input type=submit name=friend value="Send to a friend"> </td> </tr> <tr><td colspan=2> </td></tr> </form> </table> <? include_once('../foother.html'); ?><file_sep>// constants.js var const_inline_style = 'inline'; var const_none_style = 'none'; var const_block_style = 'block'; var const_absolute_style = 'absolute'; var const_relative_style = 'relative'; var $cache = []; var const_function_symbol = 'function'; var const_object_symbol = 'object'; var const_number_symbol = 'number'; var const_string_symbol = 'string'; var const_debug_symbol = 'DEBUG'; var const_error_symbol = 'ERROR'; var const_simpler_symbol = 'simpler'; <file_sep><?php require_once ("Mail/mime.php"); require_once "Mail.php"; require_once "documentHeader.php"; require_once 'JSON.php'; $crlf = "\r\n"; $resp = array(); $json = new Services_JSON(); $username = "<EMAIL>"; $password = "<PASSWORD>"; $from = $username; $to = "<NAME> <<EMAIL>>"; $subject = "Hi!"; $body = "<p>Hi,<BR/><BR/>How <u>are</u> you?</p>"; $_is_method_post = false; $resp['DEBUG.1'] = var_dump_ret($_SERVER); $REQUEST_METHOD = "GET"; if (isset($_SERVER['REQUEST_METHOD'])) { $REQUEST_METHOD = strtoupper($_SERVER['REQUEST_METHOD']); } $_is_method_post = strcmp($REQUEST_METHOD,"POST") == 0; $resp['DEBUG.2'] = var_dump_ret($_is_method_post); if ($_is_method_post) { $resp['DEBUG.3'] = var_dump_ret($_POST); try { if (isset($_POST["to"])) { $_to_ = $_POST["to"]; if (strlen($_to_) > 0) { $to = $_to_; } } } catch (Exception $e) { $resp['ERROR.1'] = 'Exception caught: '.$e->getMessage()."\n"; } } if ($_is_method_post) { try { if (isset($_POST["subject"])) { $_subject_ = $_POST["subject"]; if ( ($_subject_) && (strlen($_subject_) > 0) ) { $subject = $_subject_; } } } catch (Exception $e) { $resp['ERROR.2'] = 'Exception caught: '.$e->getMessage()."\n"; } } if ($_is_method_post) { try { if (isset($_POST["body"])) { $_body_ = $_POST["body"]; if ( ($_body_) && (strlen($_body_) > 0) ) { $body = $_body_; } } } catch (Exception $e) { $resp['ERROR.3'] = 'Exception caught: '.$e->getMessage()."\n"; } } $host = "smtp.gmail.com"; $port = "587"; $mime = new Mail_mime($crlf); $headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject); $smtp = Mail::factory('smtp', array ('host' => $host,'port' => $port,'auth' => true,'username' => $username,'password' => $<PASSWORD>)); $mime->setHTMLBody($body); $body= $mime->get(); $headers=$mime->headers($headers); $resp['HEADERS'] = $headers; $mail = $smtp->send($to, $headers, $body); if (PEAR::isError($mail)) { $resp['ERROR'] = $mail->getMessage(); } else { $resp['STATUS'] = "Message successfully sent!"; } echo($json->encode($resp)); ?><file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; $q1 = "delete from job_admin_login where aid = \"$daid\" "; $r1 = mysql_query($q1) or die(mysql_error()); echo "<br><br><br><center> The deleting process finished successfully.</center>"; ?> <? include_once('../foother.html'); ?><file_sep><? // 'server' 'database_username' 'database_password' $connection = mysql_connect("localhost", "root", "peekaboo") or die (mysql_error()); // 'database_name' $db = mysql_select_db("jobpro2", $connection) or die (mysql_error()); ?><file_sep><?php require "connect.php"; require "todo.class.php"; if(isset($_GET['id'])) $id = (int)$_GET['id']; if(isset($_GET['action'])) $action = $_GET['action']; if(isset($_POST['action'])) $action = $_POST['action']; try{ switch($action) { // fetching data actions case 'tabs': ToDo::tabs(); break; case 'pages': ToDo::pages($_GET['tab_id']); break; case 'lists': ToDo::lists($_GET['page_id']); break; // item actions case 'newItem': ToDo::newItem($_GET['list_id'],$_GET['show_item_date']); break; case 'editItem': ToDo::editItem($_POST['id'],$_POST['text']); break; case 'markDeleteItem': ToDo::markDeleteItem($id); break; case 'deleteItem': ToDo::delete($id); break; case 'rearrangeItems': ToDo::rearrangeItems($_GET['positions']); break; case 'changeList': ToDo::changeList($id,$_GET['list_id']); break; case 'taskComplete': ToDo::taskComplete($id,$_GET['value']); break; // list actions case 'newList': ToDo::newList($_GET['page_id']); break; case 'editList': ToDo::editList($id,$_GET['name']); break; case 'markDeleteList': ToDo::markDeleteList($id); break; case 'deleteList': ToDo::deleteList($id); break; case 'rearrangeLists': ToDo::rearrangeLists($_GET['positions']); break; case 'changeColumn': ToDo::changeColumn($_GET['list_id'],$_GET['column_id']); break; case 'listToggleExpanded': ToDo::listToggleExpanded($id); break; case 'listExpanded': ToDo::listExpanded($id); break; case 'duplicateList': ToDo::duplicateList($id); break; case 'showItemDate': ToDo::showItemDate($id,$_GET['value']); break; // page actions case 'newPage': ToDo::newPage($id); break; case 'editPage': ToDo::editPage($_GET['page_id'],$_GET['name']); break; case 'markDeletePage': ToDo::markDeletePage($_GET['page_id']); break; case 'deletePage': ToDo::deletePage($_GET['page_id']); break; case 'rearrangePages': ToDo::rearrangePages($_GET['positions']); break; case 'dropListOnPage': ToDo::dropListOnPage($_GET['list_id'],$_GET['page_id']); break; case 'duplicatePage': ToDo::duplicatePage($id); break; case 'duplicatePageLists': ToDo::duplicatePageLists($id, $_GET['newPageID']); break; case 'returnPage': ToDo::returnPage($id); break; case 'columnsPerPage': ToDo::columnsPerPage($id, $_GET['columns']); break; // tab actions case 'newTab': ToDo::newTab(); break; case 'editTab': ToDo::editTab($id,$_GET['name']); break; case 'markDeleteTab': ToDo::markDeleteTab($id); break; case 'deleteTab': ToDo::deleteTab($id); break; case 'rearrangeTabs': ToDo::rearrangeTabs($_GET['positions']); break; case 'dropListOnTab': ToDo::dropListOnTab($_GET['list_id'],$_GET['tab_id']); break; case 'dropPageOnTab': ToDo::dropPageOnTab($_GET['page_id'],$_GET['tab_id']); break; case 'duplicateTab': ToDo::duplicateTab($id); break; case 'duplicateTabPages': ToDo::duplicateTabPages($id, $_GET['newTabID']); break; case 'returnTab': ToDo::returnTab($id); break; // trash actions case 'emptyTrash': ToDo::emptyTrash(); break; case 'deleteSelected': ToDo::deleteSelected($_GET['strIDs']); break; case 'restoreSelected': ToDo::restoreSelected($_GET['strIDs']); break; case 'updateDate': ToDo::updateDate($_GET['table'],$id,$_GET['dateField'],$_GET['date']); break; } } catch(Exception $e){ // echo $e->getMessage(); die("0"); } echo "1"; ?><file_sep><?php require_once('session.php'); require_once('shared.php'); //Main Form Logic: If there is a default object in the session, //describe it when the page loads; else, prompt to choose one. //Note: The POSTed default object is passed to the SESSION default object //in the session.php include if ($_SESSION[default_object]){ show_describeSObject_form(); show_describeSObject_result(); } else { show_describeSObject_form(); exit; } //Print a form with the global object types to choose for description function show_describeSObject_form(){ require_once ('header.php'); print "<form method='post' action='$_SERVER[PHP_SELF]'>"; print "<p><strong>Choose an object to describe:</strong></p>\n"; myGlobalSelect($_SESSION[default_object]); print "<input type='submit' name='action' value='Describe' />"; print "</form>"; } //Print the description of selected/default object type in multiple tables function show_describeSObject_result(){ try{ //Ping Apex API $describeSObject_result = describeSObject($_SESSION[default_object]); print "<h1>$_SESSION[default_object] Object Description</h1>"; print "<a href='describe.php'>Return to Tree View</a>"; //Print attributes table print "<h2>Attributes</h2>\n"; print "<table class='description'>"; foreach($describeSObject_result as $key => $value){ //Print strings as is if (is_string($value)){ print "<tr><td>$key</td><td>$value</td></tr> \n"; } //Change bool data to printed as TRUE and FALSE for visibility in table elseif (is_bool($value)){ print "<tr><td>$key</td><td>"; if ($value){ print "True"; } else { print "False"; } print "</td></tr> \n"; } } print "</table>"; //Print Fields table with nested foreach loops for buried data print "<h2>Fields</h2>\n"; foreach($describeSObject_result->fields as $key => $value){ print "<h3>$value->name</h3>\n"; print "<table class='description'>"; foreach($value as $subkey => $subvalue){ if (is_string($subvalue)){ print "<tr><td>$subkey</td><td>$subvalue</td></tr> \n"; } //Change bool data to printed as TRUE and FALSE for visibility in table elseif (is_bool($subvalue)){ print "<tr><td>$subkey</td><td>"; if ($subvalue){ print "True"; } else { print "False"; } print "</td></tr> \n"; } //Because picklist are deeper in the SOAP message, //it requires more nested foreach loops elseif ($subkey == 'picklistValues'){ print "<tr><td colspan=2>$subkey</td></tr> \n"; foreach($subvalue as $subsubkey => $subsubvalue){ foreach($subsubvalue as $subsubsubkey => $subsubsubvalue){ if (is_string($subsubsubvalue)){ print "<tr><td>&nbsp; &nbsp; $subsubsubkey</td><td>$subsubsubvalue</td></tr> \n"; } elseif (is_bool($subsubsubvalue)){ print "<tr><td>&nbsp; &nbsp; $subsubsubkey</td><td>"; if ($subsubsubvalue){ print "True"; } else { print "False"; } print "</td></tr> \n"; } } print "<tr><td>&nbsp;</td><td>&nbsp;</td></tr> \n"; } } elseif ($subkey == 'referenceTo'){ //do this for referenceTo arrays print "<tr><td colspan=2>$subkey</td></tr>\n"; foreach($subvalue as $subsubkey => $subsubvalue){ print "<tr><td>&nbsp;</td><td>$subsubvalue</td></tr>\n"; } print "<tr><td>&nbsp;</td><td>&nbsp;</td></tr> \n"; //end referenceTo node } } print "</table>\n<br/>"; } //Print Child Relationships, if they exists (conditional not working) if ($describeSObject_result->childRelationships){ print "<h2>Child Relationships</h2>\n"; foreach($describeSObject_result->childRelationships as $key => $value){ print "<h3>$value->childSObject</h3>\n"; print "<table class='description'>"; foreach($value as $subkey => $subvalue){ if (is_string($subvalue)){ print "<tr><td>$subkey</td><td>$subvalue</td></tr> \n"; } elseif (is_bool($subvalue)){ print "<tr><td>$subkey</td><td>"; if ($subvalue){ print "True"; } else { print "False"; } print "</td></tr> \n"; } } print "</table>\n</br>"; } } //Print Record Types, if they exists (conditional not working) if ($describeSObject_result->recordTypeInfos){ print "<h2>Record Types</h2>\n"; foreach($describeSObject_result->recordTypeInfos as $key => $value){ print "<h3>$value->name</h3>\n"; print "<table class='description'>"; foreach($value as $subkey => $subvalue){ if (is_string($subvalue)){ print "<tr><td>$subkey</td><td>$subvalue</td></tr> \n"; } elseif (is_bool($subvalue)){ print "<tr><td>$subkey</td><td>"; if ($subvalue){ print "True"; } else { print "False"; } print "</td></tr> \n"; } } print "</table>\n<br/>"; } } } catch (Exception $e) { $errors = null; $errors = $e->getMessage(); show_error($errors); exit; } } include_once('footer.php'); ?> <file_sep><? include_once "accesscontrol.php"; if (is_array($JobCategory2)) { $JobStr = implode("," , $JobCategory2); } $position = strip_tags($position); $description = strip_tags($description); $q3 = "update job_post set position = \"$position\", JobCategory = \"$JobStr\", description = \"$description2\", j_target = \"$j_target2\", salary = \"$salary2\", s_period = \"$s_period2\" where job_id = \"$job_id22\" "; $r3 = mysql_query($q3) or die(mysql_error()); echo "<table width=446><tr><td><br><br><center>The position $position was updated.</center></td></tr></table>"; ?> <? include_once('../foother.html'); ?><file_sep>var MenuBar1 = ''; include_js('http://media.vyperlogix.com/spry/freeblogs/header/SpryMenuBar.js',function(){ include_css('http://media.vyperlogix.com/spry/freeblogs/header/SpryMenuBarHorizontal.css'); include_js('http://media.vyperlogix.com/spry/freeblogs/freeblogMenubar.js',function(){}); }); <file_sep>$(document).ready(function(){ /* The following code is executed once the DOM is loaded */ /* Enable translations using JSGettext */ gt = new Gettext({ 'domain' : 'surrealtodo' }); // If any link in the Tab is clicked, assign // the tab id to the currentTab variable for later use. $('.tabItem').live('click',function(e){ currentTab = $(this).closest('.tabItem'); currentTab.data('id',currentTab.attr('id').replace('Tab-','')); currentTabID = $(this).closest('.tabItem').attr('id').replace('Tab-',''); e.preventDefault(); }); // If any link in the Tab is clicked, assign // the tab id to the currentTab variable for later use. $('.page').live('click',function(e){ currentPage = $(this); currentPageID = $(this).attr('id').replace('Page-',''); e.preventDefault(); }); // If any link in the List is clicked, assign // the list item to the currentList variable for later use. $('.list, .newItem').live('click',function(e){ currentList = $(this).closest('.sortableList'); currentList.data('id',currentList.attr('id').replace('List-','')); }); // If any link in the item is clicked, assign // the item to the currentItem variable for later use. $('.item').live('click',function(e){ currentItem = $(this); currentItem.data('id',currentItem.attr('id').replace('Item-','')); }); // When a double click occurs, just simulate a click on the edit button: $('.item').live('dblclick',function(){ editItem(); }); // Listening for key press while editing items: $('.item').live('keydown',function(event){ if (event.keyCode == '13') {// Listening for a enter key press to save task: var text = currentItem.find("textarea").val(); if(text == '') { currentItem.find('.text') .html(currentItem.data('origText')) .end() .removeData('origText'); } else { $.post("ajax.php",{'action':'editItem','id':currentItem.data('id'),'text':text,'rand':Math.random()}); currentItem.removeData('origText') .find(".text") .html(text); } itemContextMenu(); // re-enable the contextmenu for all items enableSorting(); $('.list').removeClass('noHover'); $('.text').removeClass('editItem'); event.preventDefault(); } if (event.keyCode == '27') {// Listening for a ESC key press to cancel edit: currentItem.find('.text') .html(currentItem.data('origText')) .end() .removeData('origText'); itemContextMenu(); // re-enable the contextmenu for all items enableSorting(); $('.list').removeClass('noHover'); $('.text').removeClass('editItem'); } }); // Listening for key press while editing item created date: $('#itemCreated .dateCreatedInput').live('keydown',function(event){ if (event.keyCode == '13') {// Listening for a enter key press: var inputDate = $('#itemCreated .dateCreatedInput').val(); currentItem.data('origDate',currentItem.find('.dateCreated').text()); if (inputDate == '') { $('li.item').nojeegoocontext(); itemContextMenu(); event.preventDefault(); return false; } if (inputDate == currentItem.data('origDate')) { $('li.item').nojeegoocontext(); itemContextMenu(); event.preventDefault(); return false; } if (inputDate != currentItem.data('origDate')) { AJAXupdateDate('items', currentItem.data('id'), 'date_created', inputDate); currentItem.find(".dateCreated") .text(inputDate); } $('li.item').nojeegoocontext(); itemContextMenu(); event.preventDefault(); } if (event.keyCode == '27') {// Listening for a ESC key press to cancel edit: $('li.item').nojeegoocontext(); itemContextMenu(); // re-enable the contextmenu for all items event.preventDefault(); } }); // Listening for key press while editing item completed date: $('#itemCompleted .dateCompletedInput').live('keydown',function(event){ if (event.keyCode == '13') {// Listening for a enter key press: var inputDate = $('#itemCompleted .dateCompletedInput').val(); currentItem.data('origDate',currentItem.find('.dateCompleted').text()); if (inputDate == '') { $('li.item').nojeegoocontext(); itemContextMenu(); event.preventDefault(); return false; } if (inputDate == currentItem.data('origDate')) { $('li.item').nojeegoocontext(); itemContextMenu(); event.preventDefault(); return false; } if (inputDate != currentItem.data('origDate')) { AJAXupdateDate('items', currentItem.data('id'), 'date_completed', inputDate); currentItem.find(".dateCompleted") .text(inputDate); } $('li.item').nojeegoocontext(); itemContextMenu(); event.preventDefault(); } if (event.keyCode == '27') {// Listening for a ESC key press to cancel edit: $('li.item').nojeegoocontext(); itemContextMenu(); // re-enable the contextmenu for all items event.preventDefault(); } }); // The Add New item button: var timestamp=0; $('.newItem').live('click',function(e){ // Only one item per second is allowed: if((new Date()).getTime() - timestamp<1000) return false; showItemDate = currentList.find('.showItemDate').text(); // if the listBody was collapsed, expand it and save setting to database currentList.find('.listBody').css("display",function(value){ if (value = 'hidden') { currentList.find('.listBody').show(); currentList.data('id',currentList.attr('id').replace('List-','')); $.get("ajax.php",{"action":"listExpanded","id":currentList.data('id'),'rand':Math.random()}); } }); var listID = TaskListID.replace('List-',''); $.get("ajax.php",{'action':'newItem','list_id':listID,"show_item_date":showItemDate,'rand':Math.random()},function(msg){ // Appending the new item and fading it into view: $(msg).hide().appendTo('#'+TaskListID+'.listBody').fadeIn(); }); makeItemsSortable(); // Updating the timestamp: timestamp = (new Date()).getTime(); e.preventDefault(); }); // * * * * * * * * * * * * * * * List specific code starts here * * * * * * * * * * * * * * * * * * * * // Add a new List $('.newList').live('click',function(e){ $.get("ajax.php",{'action':'newList','page_id':currentPageID,'rand':Math.random()},function(msg){ // Appending the new list and fading it into view: $(msg).hide().prependTo('#Column-1').fadeIn(); makeListsSortable(); makeItemsSortable(); }); e.preventDefault(); }); // Listening for key press while editing lists: $('.listTitle').live('keyup',function(event){ if (event.keyCode == 13){ // Listening for a enter key press to save task: var text = currentList.find("input[type=text]").val(); if(text == '') { currentList.find('.listName') .text(currentList.data('origText')) .end() .removeData('origText'); } else { $.get("ajax.php",{'action':'editList','id':currentList.data('id'),'name':text,'rand':Math.random()}); currentList.removeData('origText') .find(".listName") .text(text); } listContextMenu(); // re-enable the context menu for all lists enableSorting(); } if (event.keyCode == 27){ // Listening for a ESC key press to cancel edit: currentList.find('.listName') .text(currentList.data('origText')) .end() .removeData('origText'); listContextMenu(); // re-enable the context menu for all lists enableSorting(); } }); var list_dialog_buttons = {}; list_dialog_buttons[_('Cancel')] = function(){ $(this).dialog('close'); } list_dialog_buttons[_('Delete')] = function(){ $.get("ajax.php",{"action":"markDeleteList","id":currentList.data('id'),'rand':Math.random()},function(msg){ currentList.fadeOut('fast'); }) $(this).dialog('close'); } // Configuring the delete confirmation dialog $("#dialog-confirm-delete-list").dialog({ resizable: true, width:300, modal: true, autoOpen:false, buttons: list_dialog_buttons }); // Toggle the expand and collapse of a List $('.listName').live('dblclick',function(e){ $('#notebook').css('-moz-user-select', 'none') .css('-khtml-user-select', 'none'); currentList = $(this).closest('.sortableList'); currentList.data('id',currentList.attr('id').replace('List-','')); var listID = currentList.data('id'); $(currentList).find('.listBody').slideToggle(600); $.get("ajax.php",{action:'listToggleExpanded',id:listID,rand:Math.random()}); }); // Show transaltion information $('a.translation-info').live('click',function(e){ $('.translation-detail').show(); event.preventDefault(); }); // Listening for key press while editing list created date: $('#listCreated .dateCreatedInput').live('keydown',function(event){ if (event.keyCode == '13') {// Listening for a enter key press: var inputDate = $('#listCreated .dateCreatedInput').val(); currentList.data('origDate',currentList.find('.listCreated').text()); if (inputDate == '') { $('.listName').nojeegoocontext(); listContextMenu(); event.preventDefault(); return false; } if (inputDate == currentList.data('origDate')) { $('.listName').nojeegoocontext(); listContextMenu(); event.preventDefault(); return false; } if (inputDate != currentList.data('origDate')) { AJAXupdateDate('lists', currentList.data('id'), 'date_created', inputDate); currentList.find('.listCreated') .text(inputDate); } $('.listName').nojeegoocontext(); listContextMenu(); event.preventDefault(); } if (event.keyCode == '27') {// Listening for a ESC key press to cancel edit: $('.listName').nojeegoocontext(); listContextMenu(); // re-enable the contextmenu for all lists event.preventDefault(); } }); // * * * * * * * * * * * * * * * List specific code ends here * * * * * * * * * * * * * * * * * * * * // Listening for key press while editing Tab name: $('.tabName').live('keyup',function(event){ if (event.keyCode == '13') {// Listening for a enter key press to save Tab Name: var text = currentTab.find("input[type=text]").val(); if(text == '') { currentTab.find('.tabName') .text(currentTab.data('origText')) .end() .removeData('origText'); } else { $.get("ajax.php",{'action':'editTab','id':currentTab.data('id'),name:text,rand:Math.random()}); currentTab.removeData('origText') .find(".tabName") .text(text); } tabContextMenu(); // re-enable the context menu for all tabs enableSorting(); } if (event.keyCode == '27') {// Listening for a ESC key press to cancel Tab edit: currentTab.find('.tabName') .text(currentTab.data('origText')) .end() .removeData('origText'); tabContextMenu(); // re-enable the context menu for all tabs enableSorting(); } }); // Listening for key press while editing tab created date: $('#tabCreated .dateCreatedInput').live('keydown',function(event){ if (event.keyCode == '13') {// Listening for a enter key press: var inputDate = $('#tabCreated .dateCreatedInput').val(); currentTab.data('origDate',currentTab.find('.tabCreated').text()); if (inputDate == '') { $('.tabItem .tabTitle').nojeegoocontext(); tabContextMenu(); event.preventDefault(); return false; } if (inputDate == currentTab.data('origDate')) { $('.tabItem .tabTitle').nojeegoocontext(); tabContextMenu(); event.preventDefault(); return false; } if (inputDate != currentTab.data('origDate')) { AJAXupdateDate('tabs', currentTab.data('id'), 'date_created', inputDate); currentTab.find('.tabCreated') .text(inputDate); } $('.tabItem .tabTitle').nojeegoocontext(); tabContextMenu(); event.preventDefault(); } if (event.keyCode == '27') {// Listening for a ESC key press to cancel edit: $('.tabItem .tabTitle').nojeegoocontext(); tabContextMenu(); // re-enable the contextmenu for all lists event.preventDefault(); } }); // Listening for key press while editing Page name: $('.page').live('keyup',function(event){ if (event.keyCode == '13') {// Listening for a enter key press to save Tab Name: var text = currentPage.find("input[type=text]").val(); if(text == '') { currentPage.find('.pageName') .text(currentPage.data('origText')) .end() .removeData('origText'); } else { $.get("ajax.php",{'action':'editPage','page_id':currentPageID,'name':text,'rand':Math.random()}); currentPage.removeData('origText') .find('.pageName') .text(text); } pageContextMenu(); // re-enable the context menu for all pages enableSorting(); } if (event.keyCode == '27') {// Listening for a ESC key press to cancel Tab edit: currentPage.find('.pageName') .text(currentPage.data('origText')) .end() .removeData('origText'); pageContextMenu(); // re-enable the context menu for all pages enableSorting(); } }); // Listening for key press while editing page created date: $('#pageCreated .dateCreatedInput').live('keydown',function(event){ if (event.keyCode == '13') {// Listening for a enter key press: var inputDate = $('#pageCreated .dateCreatedInput').val(); currentPage.data('origDate',currentPage.find('.pageCreated').text()); if (inputDate == '') { $('.page').nojeegoocontext(); pageContextMenu(); event.preventDefault(); return false; } if (inputDate == currentPage.data('origDate')) { $('.page').nojeegoocontext(); pageContextMenu(); event.preventDefault(); return false; } if (inputDate != currentPage.data('origDate')) { AJAXupdateDate('pages', currentPage.data('id'), 'date_created', inputDate); currentPage.find('.pageCreated') .text(inputDate); } $('.page').nojeegoocontext(); pageContextMenu(); event.preventDefault(); } if (event.keyCode == '27') {// Listening for a ESC key press to cancel edit: $('.page').nojeegoocontext(); pageContextMenu(); // re-enable the contextmenu for all lists event.preventDefault(); } }); var page_dialog_buttons = {}; page_dialog_buttons[_('Cancel')] = function(){ $(this).dialog('close'); } page_dialog_buttons[_('Delete')] = function(){ $.get("ajax.php",{"action":"markDeletePage","page_id":currentPageID,'rand':Math.random()},function(msg){ currentPage.fadeOut('fast'); // if ($('.page').index() == 0) $('.page').eq(0).click(); // else $('.page').eq(0).click(); }) $(this).dialog('close'); } // Configuring the page delete confirmation dialog $("#dialog-confirm-delete-page").dialog({ resizable: true, width:300, modal: true, autoOpen:false, buttons: page_dialog_buttons }); var tab_dialog_buttons = {}; tab_dialog_buttons[_('Cancel')] = function(){ $(this).dialog('close'); } tab_dialog_buttons[_('Delete')] = function(){ $.get("ajax.php",{"action":"markDeleteTab","id":tabID,'rand':Math.random()},function(msg){ currentTab.fadeOut('fast'); $('.tab').eq(0).click(); }) $(this).dialog('close'); } // Configuring the tab delete confirmation dialog $("#dialog-confirm-delete-tab").dialog({ resizable: true, width:400, modal: true, autoOpen:false, buttons: tab_dialog_buttons }); // Listening for click on emptyTrash $('a.emptyTrash').live('click',function(e){ $.get("ajax.php",{action:'emptyTrash',rand:Math.random()}); $('.trashTree').fadeOut('slow'); e.preventDefault(); }); // Listening for click on checkAll $('a.checkAll').live('click',function(e){ $('.trashCheckbox').attr('checked', true); e.preventDefault(); }); // Listening for click on deleteSelected $('a.deleteSelected').live('click',function(e){ var strIDs = "" $('.trashCheckbox:checked').each(function() { strIDs = strIDs+($(this).val())+','; }); $.get("ajax.php",{action:'deleteSelected','strIDs':strIDs,rand:Math.random()}); $('.trashCheckbox:checked').parent('li').fadeOut('slow'); e.preventDefault(); }); // Listening for click on restoreSelected $('a.restoreSelected').live('click',function(e){ var strIDs = "" $('.trashCheckbox:checked').each(function() { strIDs = strIDs+($(this).val())+','; }); $.get("ajax.php",{action:'restoreSelected','strIDs':strIDs,rand:Math.random()}); $('.trashCheckbox:checked').parent('li').fadeOut('slow'); e.preventDefault(); }); }); // Closing $(document).ready() // * * * * * * * * * * * * * * * Functions here * * * * * * * * * * * * * * * * * * * * // Global variables, holding a jQuery object // containing the current Tab, List and Item id: var currentTab; var currentTabID; var currentPage; var currentPageID; var currentList; var currentItem; var TaskListID; var gt; // Define global variable for Gettext used for language translations function _ (msgid) { return gt.gettext(msgid); } function AJAXupdateDate(table, id, dateField, date) { $.get("ajax.php",{'action':'updateDate','table':table,'id':id,'dateField':dateField,'date':date,'rand':Math.random()}); } function myCallback(caller) { TaskListID = caller.parentNode.id; } function editTab(context) { $(currentTab).find('a.tab').click(); disableSorting(); var container = currentTab.find('.tabName'); if(!currentTab.data('origText')) { // Saving the current value of the tab so we can // restore it later if the user discards the changes: currentTab.data('origText',container.text()); } else { // This will block the edit button if the edit box is already open: return false; } $('<input type="text">').val(container.text()).appendTo(container.empty()); // If the text is the default text of a new tab then highlight it for easy editing if($('.tabName input').val() == _('New Tab')) { $('.tabName input').focus().select(); } // If not then just place the cursor into the field else $('.tabName input').focus(); } function editPage(context){ $(currentPage).find('a.page').click(); var container = currentPage.find('.pageName'); if(!currentPage.data('origText')) { // Saving the current value of the page name so we can // restore it later if the user discards the changes: currentPage.data('origText',container.text()); } else { // This will block the edit button if the edit box is already open: return false; } $('<input type="text">').val(container.text()).appendTo(container.empty()); // If the text is the default text of a new tab then highlight it for easy editing if($('.pageName input').val() == "New Page") { $('.pageName input').focus().select(); } // If not then just place the cursor into the field else $('.pageName input').focus(); disableSorting(); } function editList() { disableSorting(); var container = currentList.find('.listName'); if(!currentList.data('origText')) { // Saving the current value of the list name so we can // restore it later if the user discards the changes: currentList.data('origText',container.text()); } else { // This will block the edit button if the edit box is already open: return false; } $('<input type="text">').val(container.text()).appendTo(container.empty()); // If the text is the default text of a new list then highlight it for easy editing if($('.listName input').val() == _('New List')) { $('.listName input').focus().select(); } // If not then just place the cursor into the field else $('.listName input').focus(); } function editItem() { $('.list').addClass('noHover'); disableSorting(); $('li.item').nojeegoocontext(); // disable the custom context menu while editing var container = currentItem.find('.text'); if(!currentItem.data('origText')) { // Saving the current value of the item so we can // restore it later if the user discards the changes: currentItem.data('origText',container.html()); } else { // This will block the edit button if the edit box is already open: return false; } $('<textarea class="editItem inline"></textarea>').val(container.html()).appendTo(container.empty()); // If the text is the default text of a new task then highlight it for easy editing if($('textarea').val() == _('Double-click to edit')) { $('textarea').focus().select(); } // If not then just place the cursor into the field else $('textarea').focus(); } function advancedEditItem() { $('.list').addClass('noHover'); disableSorting(); $('li.item').nojeegoocontext(); // disable the custom context menu while editing var container = currentItem.find('.text'); if(!currentItem.data('origText')) { // Saving the current value of the item so we can // restore it later if the user discards the changes: currentItem.data('origText',container.html()); } else { // This will block the edit button if the edit box is already open: return false; } $('<textarea name="content" class="inline"></textarea>').val(container.html().replace('<p class="inline">','<p>')).appendTo(container.empty()); enableEditor("300",$('textarea').width()); // If the text is the default text of a new task then highlight it for easy editing if($('textarea').val() == _('Double-click to edit')) { $('textarea').focus().select(); } // If not then just place the cursor into the field else $('textarea').focus(); } function advancedSave(){ var text = tinyMCE.get('content').getContent().replace('<p>','<p class="inline">'); tinyMCE.triggerSave(); if(text == '') { currentItem.find('.text') .html(currentItem.data('origText')) .end() .removeData('origText'); } else { $.post("ajax.php",{'action':'editItem','id':currentItem.data('id'),'text':text,'rand':Math.random()}); currentItem.removeData('origText') .find(".text") .html(text); } itemContextMenu(); // re-enable the contextmenu for all items tinyMCE.execCommand('mceRemoveControl', false, 'content'); $('.list').removeClass('noHover'); enableSorting(); } function advancedCancel(){ currentItem.find('.text') .html(currentItem.data('origText')) .end() .removeData('origText'); itemContextMenu(); // re-enable the contextmenu for all items tinyMCE.execCommand('mceRemoveControl', false, 'content'); $('.list').removeClass('noHover'); enableSorting(); } function deleteItem() { $.get("ajax.php",{"action":"markDeleteItem","id":currentItem.data('id'),'rand':Math.random()}); currentItem.fadeOut('fast'); } function duplicateList(context) { currentList = $(context); currentListID = $(context).parent().attr('id').replace('List-',''); $.get("ajax.php",{action:'duplicateList','id':currentListID,rand:Math.random()},function(msg){ $(context).parents().filter('.column').prepend(msg).fadeIn('fast'); }); } function duplicatePage(context) { currentPage = $(context); currentPageID = $(context).attr('id').replace('Page-',''); $.get("ajax.php",{action:'duplicatePage','id':currentPageID,rand:Math.random()},function(newPageID){ addPage('returnPage',newPageID); }); } function duplicateTab(context) { currentTab = $(context); currentTabID = $(context).parent().attr('id').replace('Tab-',''); $.get("ajax.php",{action:'duplicateTab','id':currentTabID,rand:Math.random()},function(newTabID){ addTab('returnTab',newTabID); }); } function makeListsSortable() { $('.column').sortable({ handle: '.listName', items : '.sortableList', connectWith : '.column', update : function(event, ui){ // The function is called after the lists are rearranged // The toArray method returns an array with the ids of the lists var columnClass = "#"+$(ui.item).parent().attr('id')+".column"; var arr = $(columnClass).sortable('toArray'); arr = $.map(arr,function(val,key){ return val.replace('List-',''); }); // Saving with AJAX $.get('ajax.php',{action:'rearrangeLists',positions:arr,rand:Math.random()}); }, receive : function(event, ui) { //Run this code whenever an item is dragged and dropped into this list var listID = $(ui.item).attr('id').replace('List-',''); var columnID = $(ui.item).parent().attr('id').replace('Column-',''); $.get("ajax.php",{'action':'changeColumn','list_id':listID,'column_id':columnID,rand:Math.random()}); }, /* Opera fix: */ stop: function(e,ui) { ui.item.css({'top':'0','left':'0'}); } }); } function makeItemsSortable() { $('.listBody').sortable({ items : 'li.item', connectWith : '.listBody', update : function(event, ui){ // The function is called after the items are rearranged // The toArray method returns an array with the ids of the items var listClass = "#"+$(ui.item).parent().attr('id')+".listBody"; var arr = $(listClass).sortable('toArray'); // Striping the Item- prefix of the ids: arr = $.map(arr,function(val,key){ return val.replace('Item-',''); }); // Saving with AJAX $.get('ajax.php',{action:'rearrangeItems',positions:arr,rand:Math.random()}); }, receive : function(event, ui) { //Run this code whenever an item is dragged and dropped into this list var itemID = $(ui.item).attr('id').replace('Item-',''); var listID = $(ui.item).parent().attr('id').replace('List-',''); $.get("ajax.php",{'action':'changeList','id':itemID,'list_id':listID,rand:Math.random()}); }, /* Opera fix: */ stop: function(e,ui) { ui.item.css({'top':'0','left':'0'}); } }); } function makeTabsDroppable() { $('.tabItem').droppable({ accept : '.sortableList, .pageItem', tolerance : 'pointer', drop : function(event, ui){ // The function is called after an object is dropped on the tab newParentTabID = $(this).attr('id').replace('Tab-',''); if (ui.draggable.attr('class') == 'sortableList ui-sortable-helper') { listID = $(ui.draggable).attr('id').replace('List-',''); // Saving with AJAX $.get('ajax.php',{action:'dropListOnTab',list_id:listID,tab_id:newParentTabID,rand:Math.random()}); } if (ui.draggable.attr('class') == 'pageItem ui-droppable ui-sortable-helper') { pageID = $(ui.draggable).attr('id').replace('Page-',''); // Saving with AJAX $.get('ajax.php',{action:'dropPageOnTab',page_id:pageID,tab_id:newParentTabID,rand:Math.random()}); if (pageID == currentPageID) $('#contentHolder').empty(); } $(ui.draggable).remove().fadeOut('fast'); } }); } function makePagesDroppable() { $('.pageItem').droppable({ accept : '.sortableList', tolerance : 'pointer', drop : function(event, ui){ // The function is called after an object is dropped on the tab newParentPageID = $(this).attr('id').replace('Page-',''); listID = $(ui.draggable).attr('id').replace('List-',''); // Saving with AJAX $.get('ajax.php',{action:'dropListOnPage',list_id:listID,page_id:newParentPageID,rand:Math.random()}); $(ui.draggable).remove().fadeOut('fast'); } }); } function enableEditor(editorHeight,editorWidth) { tinyMCE.init({ // General options mode : "textareas", height: editorHeight, width : editorWidth, theme : "advanced", save_onsavecallback : "advancedSave", save_oncancelcallback : "advancedCancel", plugins : "safari,style,table,save,advhr,advimage,advlink,emotions,inlinepopups,insertdatetime,preview,media,searchreplace,directionality,fullscreen,nonbreaking,xhtmlxtras", // Theme options theme_advanced_buttons1 : "save,cancel,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull", theme_advanced_buttons2 : "fontselect,fontsizeselect,|,forecolor,backcolor", theme_advanced_buttons3 : "search,replace,|,undo,redo,|,bullist,numlist,|,outdent,indent,|,code,preview,fullscreen", theme_advanced_buttons4 : "link,unlink,|,image,emotions,media,|,hr,advhr,|,insertdate,inserttime", theme_advanced_buttons5 : "tablecontrols", theme_advanced_toolbar_location : "bottom", theme_advanced_toolbar_align : "left", theme_advanced_resizing_min_width : editorWidth, theme_advanced_resizing_max_width : editorWidth, height : editorHeight, theme_advanced_statusbar_location : "bottom", theme_advanced_resizing : true }); } function disableSorting() { $('#tabRow').sortable('disable'); $('#pageList').sortable('disable'); $('.column').sortable('disable'); $('.listBody').sortable('disable'); } function enableSorting() { $('#tabRow').sortable('enable'); $('#pageList').sortable('enable'); $('.column').sortable('enable'); $('.listBody').sortable('enable'); }<file_sep><?php require_once ('session.php'); require_once ('shared.php'); require_once ('header.php'); ?> <h1>Help</h1> <p> The Workbench is not a product of or supported by salesforce.com, inc. For support from the Open Source community, please visit the recources below: <ul> <li><a href="http://wiki.apexdevnet.com/index.php/Workbench#FAQ" target="help">FAQs</a></li> <ul> <li><a href="http://wiki.apexdevnet.com/index.php/Workbench#General" target="help">General</a></li> <li><a href="http://wiki.apexdevnet.com/index.php/Workbench#Login" target="help">Login</a></li> <li><a href="http://wiki.apexdevnet.com/index.php/Workbench#Data_Management" target="help">Data Management</a></li> <li><a href="http://wiki.apexdevnet.com/index.php/Workbench#Query_.26_Search" target="help">Query &amp; Search</a></li> <li><a href="http://wiki.apexdevnet.com/index.php/Workbench#Execute" target="help">Execute</a></li> <li><a href="http://wiki.apexdevnet.com/index.php/Workbench#Settings" target="help">Settings</a></li> </ul> <li><a href="http://groups.google.com/group/forceworkbench" target="help">Feedback &amp; Discussion</a></li> <li><a href="http://code.google.com/p/forceworkbench/issues/list" target="help">Report an Issue</a></li> </ul> </div> <?php include_once ('footer.php'); ?> <file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; $q1 = "delete from job_story_waiting where WS_id = \"$_GET[story_id]\" "; $r1 = mysql_query($q1) or die(mysql_error()); $q2 = "select * from job_story_waiting order by WS_id"; $r2 = mysql_query($q2) or die(mysql_error()); while($a2 = mysql_fetch_array($r2)) { $i = $i + 1; $del_st = addslashes($a2[story]); $q4 = "update job_story_waiting set WS_id = \"$i\" where story = \"$del_st\" "; $r4 = mysql_query($q4) or die(mysql_error()); } ?> <br><br><br><center> The story was deleted successfully.</center> <? include_once('../foother.html'); ?><file_sep><? session_start(); session_unset("uname"); session_unset("upass"); session_unregister("uname"); session_unregister("upass"); session_destroy(); setcookie("uname","", "0", "/", "", ""); setcookie("upass","", "0", "/", "", ""); ?> <html> <head> <META HTTP-EQUIV="REFRESH" CONTENT="0;URL=../index.php"> </head> </html><file_sep><? include_once('main.php'); ?> <table border="0" cellpadding="0" cellspacing="0" width="446" align="center" bgcolor="#FFFFFF"> <tr valign="top"> <td class="w" style="padding-left:10px;padding-top:10px;"> <p><em><strong><font face="Tahoma, Arial, sans-serif" size="4"><font color="#000000"><?=$site_name?> FAQ</font></font></strong></em></p> <p align="left"><font size="2" face="Tahoma, Arial, sans-serif" color="#000000">Our support team will be more than happy to deal with any questions you may have, but before contacting <?=$site_name?> please check the FAQs below. If the answer you require is not here please contact us <ol> <li><b>How do I register with <?=$site_name?> ?</b><br> To register yourself with us click on the login and register button. In the boxes provided enter your login, e-mail address and choose your own password, etc. Don't forget to read our terms and conditions.</li> <li><b>How do I search for a job using <?=$site_name?> ?</b><br> Click on the search jobs link in the navigation bar at the left side or HERE.</li> </ol></font> </td> </tr> </table> <? include_once('foother.html'); ?><file_sep><?php require_once ('session.php'); require_once('shared.php'); /* * For auto-login by GET params, allow users to either provide un/pw or sid, and optionally serverUrl and/or api version. * If the serverUrl is provided, it will be used alone, but if either */ if((isset($_GET['un']) && isset($_GET['pw'])) || isset($_GET['sid'])){ $un = isset($_GET['un']) ? $_GET['un'] : null; $pw = isset($_GET['pw']) ? $_GET['pw'] : null; $sid = isset($_GET['sid']) ? $_GET['sid'] : null; $startUrl = isset($_GET['startUrl']) ? $_GET['startUrl'] : "select.php"; //error handling for these (so users can't set all three //is already done in the process_Login() function //as it applies to both ui and auto-login //make sure the user isn't setting invalid combinations of query params if(isset($_GET['serverUrl']) && isset($_GET['inst']) && isset($_GET['api'])){ //display UI login page with error. display_login("Invalid auto-login parameters. Must set either serverUrl OR inst and/or api."); } else if(isset($_GET['serverUrl']) && !(isset($_GET['inst']) || isset($_GET['api'])) ) { $serverUrl = $_GET['serverUrl']; } else { $serverUrl = "https://"; if(isset($_GET['inst'])){ $serverUrl .= $_GET['inst']; } else { $serverUrl .= $_SESSION['config']['defaultInstance']; } $serverUrl .= ".salesforce.com/services/Soap/u/"; if(isset($_GET['api'])){ $serverUrl .= $_GET['api']; } else { $serverUrl .= $_SESSION['config']['defaultApiVersion']; } } $_REQUEST['autoLogin'] = 1; process_Login($un, $pw, $serverUrl, $sid, $startUrl); } if(isset($_POST['login_type'])){ if ($_POST['login_type']=='std'){ process_login($_POST['usernameStd'], $_POST['passwordStd'], null, null, $_POST['actionJumpStd']); } elseif ($_POST['login_type']=='adv'){ process_login($_POST['usernameAdv'], $_POST['passwordAdv'], $_POST['serverUrl'], $_POST['sessionId'], $_POST['actionJumpAdv']); } } else { display_login(null); } function display_login($errors){ require_once ('header.php'); //Displays errors if there are any if (isset($errors)) { show_error($errors); } $isRemembered = ""; if (isset($_COOKIE['user'])){ $user = $_COOKIE['user']; $isRemembered = "checked='checked'"; print "<body onLoad='givePassFocus();' />"; } elseif (isset($_POST['user'])){ $user = $_POST['user']; print "<body onLoad='giveUserFocus();' />"; } else { $user = null; } //Display main login form body $defaultApiVersion = $_SESSION['config']['defaultApiVersion']; print "<script type='text/javascript' language='JavaScript'>\n"; print "var instNumDomainMap = [];\n"; if($_SESSION['config']['fuzzyServerUrlLookup']){ foreach($GLOBALS['config']['defaultInstance']['valuesToLabels'] as $subdomain => $instInfo){ if(isset($instInfo[1]) && $instInfo[1] != ""){ print "\t" . "instNumDomainMap['$instInfo[1]'] = '$subdomain';" . "\n"; } } } print "\n"; print <<<LOGIN_FORM function fuzzyServerUrlSelect(){ var sid = document.getElementById('sessionId').value var sidIndex = sid.indexOf('00D'); if(sidIndex > -1){ var instNum = sid.substring(sidIndex + 3, sidIndex + 4); var instVal = instNumDomainMap[instNum]; if(instVal != null){ document.getElementById('inst').value = instVal; build_location(); } } } function toggleUsernamePasswordSessionDisabled(){ if(document.getElementById('sessionId').value){ document.getElementById('usernameAdv').disabled = true; document.getElementById('passwordAdv').disabled = true; } else { document.getElementById('usernameAdv').disabled = false; document.getElementById('passwordAdv').disabled = false; } if(document.getElementById('usernameAdv').value || document.getElementById('passwordAdv').value){ document.getElementById('sessionId').disabled = true; } else { document.getElementById('sessionId').disabled = false; } } function form_become_adv() { document.getElementById('login_std').style.display='none'; //document.getElementById('apexLogo').style.display='none'; document.getElementById('login_adv').style.display='inline'; } function form_become_std() { document.getElementById('login_std').style.display='inline'; //document.getElementById('apexLogo').style.display='inline' document.getElementById('login_adv').style.display='none'; } function build_location(){ var inst = document.getElementById('inst').value; var endp = document.getElementById('endp').value; document.getElementById('serverUrl').value = 'https://' + inst + '.salesforce.com/services/Soap/u/' + endp; } function giveUserFocus(){ document.getElementById('username').focus(); } function givePassFocus(){ document.getElementById('password').focus(); } function checkCaps( pwcapsDivId, e ) { var key = 0; var shifted = false; // IE if ( document.all ) { key = e.keyCode; // Everything else } else { key = e.which; } shifted = e.shiftKey; var pwcaps = document.getElementById(pwcapsDivId); var upper = (key >= 65 && key <= 90); var lower = (key >= 97 && key <= 122); if ( (upper && !shifted) || (lower && shifted) ) { pwcaps.style.visibility='visible'; } else if ( (lower && !shifted) || (upper && shifted) ) { pwcaps.style.visibility='hidden'; } } </script> <div id='intro_text'> &nbsp;<!--<p>Use the standard login to login with your salesforce.com username and password to your default instance or use the advanced login for other login options. Go to Settings for more login configurations.</p>--> </div> <div id='logo_block'> <!--<img id='apexLogo' src='images/appex_x_rgb.png' width='200' height='171' border='0' alt='Apex X Logo' />--> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </div> <div id='login_block'> <form id='login_form' action='$_SERVER[PHP_SELF]' method='post'> <div id='login_become_select' style='text-align: right;'> <input type='radio' id='login_become_std' name='login_type' value='std' onClick='form_become_std();' checked='true' /><label for='login_become_std'>Standard</label> <input type='radio' id='login_become_adv' name='login_type' value='adv' onClick='form_become_adv();' /><label for='login_become_adv'>Advanced</label> </div> <div id='login_std'> <p><strong>Username: </strong><input type='text' name='usernameStd' id='username' size='45' value='$user' /></p> <p><strong>Password: </strong><input type='password' name='passwordStd' id='password' size='45' onkeypress="checkCaps('pwcapsStd',event);" /></p> <p><strong>Jump to: </strong> <select name='actionJumpStd' style='width: 24em;'> <option value='select.php'></option> <option value='describe.php'>Describe</option> <option value='insert.php'>Insert</option> <option value='upsert.php'>Upsert</option> <option value='update.php'>Update</option> <option value='delete.php'>Delete</option> <option value='undelete.php'>Undelete</option> <option value='purge.php'>Purge</option> <option value='query.php'>Query</option> <option value='search.php'>Search</option> <option value='execute.php'>Execute</option> <option value='settings.php'>Settings</option> </select></p> <p style='text-align: right;'><span id='pwcapsStd' style='visibility: hidden; color: red; font-weight: bold; margin-right: 30px;'>Caps lock is on!</span><label><input type='checkbox' name='rememberUser' $isRemembered />Remember username</label></p> </div> <div id='login_adv' style='display: none;'> <p><strong>Username: </strong><input type='text' name='usernameAdv' id='usernameAdv' size='65' value='$user' onkeyup='toggleUsernamePasswordSessionDisabled();' onchange='toggleUsernamePasswordSessionDisabled();' /></p> <p><strong>Password: </strong><input type='<PASSWORD>' name='passwordAdv' id='passwordAdv' size='65' onkeyup='toggleUsernamePasswordSessionDisabled();' onchange='toggleUsernamePasswordSessionDisabled();' onkeypress="checkCaps('pwcapsAdv',event);"/></p> <p>-OR-<span id='pwcapsAdv' style='visibility: hidden; color: red; font-weight: bold; margin-left: 75px;'>Caps lock is on!</span></p> <p><strong>Session ID: </strong><input type='text' name='sessionId' id='sessionId' size='65' onkeyup='toggleUsernamePasswordSessionDisabled(); fuzzyServerUrlSelect();' onchange="toggleUsernamePasswordSessionDisabled(); fuzzyServerUrlSelect();"/></p> <p>&nbsp;</p> <p><strong>Server URL: </strong><input type='text' name='serverUrl' id='serverUrl' size='65' value='https://www.salesforce.com/services/Soap/u/$defaultApiVersion' /></p> <p><strong>QuickSelect: </strong> LOGIN_FORM; print "<select name='inst' id='inst' onChange='build_location();'>"; $instanceNames = array(); foreach($GLOBALS['config']['defaultInstance']['valuesToLabels'] as $subdomain => $instInfo){ $instanceNames[$subdomain] = $instInfo[0]; } printSelectOptions($instanceNames,$_SESSION['config']['defaultInstance']); print "</select>"; print "<select name='endp' id='endp' onChange='build_location();'>"; printSelectOptions($GLOBALS['config']['defaultApiVersion']['valuesToLabels'],$_SESSION['config']['defaultApiVersion']); print "</select></p>"; print <<<LOGIN_FORM_PART_2 <p><strong>Jump to: </strong> <select name='actionJumpAdv' style='width: 14em;'> <option value='select.php'></option> <option value='describe.php'>Describe</option> <option value='insert.php'>Insert</option> <option value='upsert.php'>Upsert</option> <option value='update.php'>Update</option> <option value='delete.php'>Delete</option> <option value='undelete.php'>Undelete</option> <option value='purge.php'>Purge</option> <option value='query.php'>Query</option> <option value='search.php'>Search</option> <option value='execute.php'>Execute</option> <option value='settings.php'>Settings</option> </select></p> </div> <div id='login_submit' style='text-align: right;'> <input type='submit' name='loginClick' value='Login'> </div> </form> </div> LOGIN_FORM_PART_2; //if 'adv' is added to the login url and is not 0, default to advanced login if(isset($_GET['adv']) && $_GET['adv'] != 0){ print "<script> document.getElementById('login_become_adv').checked=true; form_become_adv(); </script>"; } include_once ('footer.php'); } //end display_form() function process_Login($username, $password, $serverUrl, $sessionId, $actionJump){ $username = htmlspecialchars(trim($username)); $password = htmlspecialchars(trim($password)); $serverUrl = htmlspecialchars(trim($serverUrl)); $sessionId = htmlspecialchars(trim($sessionId)); $actionJump = htmlspecialchars(trim($actionJump)); if($_POST['rememberUser'] !== 'on') setcookie('user',NULL,time()-3600); if ($username && $password && $sessionId){ $errors = null; $errors = 'Provide only username and password OR session id, but not all three.'; display_login($errors); exit; } try{ require_once ('soapclient/SforcePartnerClient.php'); require_once ('soapclient/SforceHeaderOptions.php'); $wsdl = 'soapclient/sforce.150.partner.wsdl'; $mySforceConnection = new SforcePartnerClient(); $mySforceConnection->createConnection($wsdl); //set call options header for login before a session exists if(isset($_GET['clientId'])){ $mySforceConnection->setCallOptions(new CallOptions($_GET['clientId'], $_SESSION['config']['callOptions_defaultNamespace'])); } else if($_SESSION['config']['callOptions_client'] || $_SESSION['config']['callOptions_defaultNamespace']){ $mySforceConnection->setCallOptions(new CallOptions($_SESSION['config']['callOptions_client'], $_SESSION['config']['callOptions_defaultNamespace'])); } //set login scope header for login before a session exists if(isset($_GET['orgId']) || isset($_GET['portalId'])){ $mySforceConnection->setLoginScopeHeader(new LoginScopeHeader($_GET['orgId'], $_GET['portalId'])); } else if($_SESSION['config']['loginScopeHeader_organizationId'] || $_SESSION['config']['loginScopeHeader_portalId']){ $mySforceConnection->setLoginScopeHeader(new LoginScopeHeader($_SESSION['config']['loginScopeHeader_organizationId'], $_SESSION['config']['loginScopeHeader_portalId'])); } if($username && $password && !$sessionId){ if($serverUrl){ $mySforceConnection->setEndpoint($serverUrl); } else { $mySforceConnection->setEndpoint("https://" . $_SESSION['config']['defaultInstance'] . ".salesforce.com/services/Soap/u/" . $_SESSION['config']['defaultApiVersion']); } $mySforceConnection->login($username, $password); } elseif ($sessionId && $serverUrl && !($username && $password)){ if (stristr($serverUrl,'www') || stristr($serverUrl,'test') || stristr($serverUrl,'prerellogin')) { $errors = null; $errors = 'Must not connect to login server (www, test, or prerellogin) if providing a session id. Choose your specific Salesforce instance on the QuickSelect menu when using a session id; otherwise, provide a username and password and choose the appropriate a login server.'; display_login($errors); exit; } $mySforceConnection->setEndpoint($serverUrl); $mySforceConnection->setSessionHeader($sessionId); } session_unset(); session_destroy(); session_start(); $_SESSION['location'] = $mySforceConnection->getLocation(); $_SESSION['sessionId'] = $mySforceConnection->getSessionId(); $_SESSION['wsdl'] = $wsdl; if($_POST['rememberUser'] == 'on'){ setcookie('user',$username,time()+60*60*24*7,'','','',TRUE); } else { setcookie('user',NULL,time()-3600); } if($_REQUEST['autoLogin'] == 1){ $actionJump .= "?autoLogin=1"; $_SESSION['tempClientId'] = $_GET['clientId']; } session_write_close(); header("Location: $actionJump"); } catch (Exception $e) { $errors = null; $errors = $e->getMessage(); display_login($errors); exit; } } ?> <file_sep>$(document).ready(function(){ /* This code is executed after the DOM has been completely loaded */ $.ajax({ type: "GET", url: "ajax.php", data: "action=tabs", cache: false, dataType: "json", success: function(Tabs){ $.each(Tabs, function(i){ /* Sequentially creating the tabs and assigning a color from the array: */ var tab = $('<li id="Tab-'+Tabs[i].tab_id+'" class="tabItem">'+ '<div class="tabTitle">'+ '<a href="#" class="tab"><span class="left"></span><div class="tabName">'+Tabs[i].name+'</div><span class="right"></span></a>'+ '</div>'+ '<div class="tabCreated">'+Tabs[i].date_created+'</div>'+ '</li>'); /* Adding the tab to the UL container: */ $('#tabRow').append(tab); }); $('#tabRow').sortable({ update : function(event, ui){ // The function is called after the tabs are rearranged // The toArray method returns an array with the ids of the tabs var arr = $("#tabRow").sortable('toArray'); // Striping the Tab- prefix of the ids: arr = $.map(arr,function(val,key){ return val.replace('Tab-',''); }); // Saving with AJAX $.get('ajax.php',{action:'rearrangeTabs',positions:arr,rand:Math.random()}); } }); /* Caching the tabs into a variable for better performance: */ var the_tabs = $('.tab'); the_tabs.live('click',function(e){ /* If it is currently active, return false and exit: */ if($(this).is('.activeTab')) return false; $('#contentHolder').empty(); /* "this" points to the clicked tab hyperlink: */ currentTabID = $(this).closest('.tabItem').attr('id').replace('Tab-',''); /* Set the current tab: */ $('a.tab').removeClass('activeTab'); $(this).addClass('activeTab'); $('#pageList').empty(); $.getJSON("ajax.php",{"action":"pages","tab_id":currentTabID,rand:Math.random()},function(Pages){ $.each(Pages, function(i){ /* Sequentially creating the pages and assigning a color from the array: */ var pageItem = $('<li id="Page-'+Pages[i].page_id+'" class="pageItem">'+ '<div class="pageTitle">'+ '<a href="" id="Page-'+Pages[i].page_id+'" class="page">'+ '<span class="left"></span><span class="pageName">'+Pages[i].name+ '</span><span class="right"></span></a>'+ '</div>'+ '<div class="pageCreated">'+Pages[i].date_created+'</div>'+ '<div class="columns">'+Pages[i].columns+'</div>'+ '</li>'); /* Setting the page data for each hyperlink: */ pageItem.find('a').data('page','ajax.php?action=lists&page_id='+Pages[i].page_id); makeTabsDroppable(); /* Adding the tab to the UL container: */ $('#pageList').append(pageItem).fadeIn('fast'); }); // close $.each(Pages) // add link to create a new page var newPage = $( '<li id="newPageItem">'+ '<abbr title="'+_('New Page')+'"><a href="" class="notebookIcons newPage">'+ '</a></abbr>'+ '</li>'); $('#pageList').append(newPage); makePagesDroppable(); // Make the first page the active page clickPage(); // function located in notebook.php $('#pageList').sortable({ items : 'li.pageItem', update : function(event, ui){ // The function is called after the tabs are rearranged // The toArray method returns an array with the ids of the tabs var arr = $("#pageList").sortable('toArray'); // Striping the Tab- prefix of the ids: arr = $.map(arr,function(val,key){ return val.replace('Page-',''); }); // Saving with AJAX $.get('ajax.php',{action:'rearrangePages',positions:arr,rand:Math.random()}); } }); }); // close $.get("ajax.php") e.preventDefault(); }) $('a.page').live('click',function(e){ /* "this" points to the clicked page hyperlink: */ var element = $(this); /* If it is currently active, return false and exit: */ // if($(this).is('.activePage')) return false; /* Set the current page: */ $('a.page').removeClass('activePage'); $(this).addClass('activePage'); /* Checking whether the AJAX fetched page has been cached: */ if(!element.data('cache')) { /* If no cache is present, show the gif preloader and run an AJAX request: */ $('#contentHolder').html('<img src="theme/default/images/ajax_preloader.gif" width="64" height="64" class="preloader" />'); $.get(element.data('page'),{'rand':Math.random()},function(msg){ $('#contentHolder').html(msg); }); } }) //close .page live click /* Emulating a click on the first tab so page list is not empty: */ clickTab(); // function located in notebook.php // Listen for click on New Tab icon $('.newTab').live('click',function(e){ addTab('newTab',0); }); // close #newTab click // Listen for click on Add Page icon $('.newPage').live('click',function(e){ addPage('newPage', currentTabID); e.preventDefault(); }); // close #newTab click } // closing ajax success: }); // close ajax }); function addTab(action, id) { var d = new Date(); var curr_date = d.getDate(); var curr_month = d.getMonth(); curr_month++; var curr_year = d.getFullYear(); var curr_hour = d.getHours(); var curr_min = d.getMinutes(); currentDate = curr_year + "-" + curr_month + "-" + curr_date + " " + curr_hour + ":" + curr_min ; $.getJSON("ajax.php",{'action':action,'id':id,rand:Math.random()},function(Tabs){ $.each(Tabs, function(i){ var tabCreated = Tabs[i].date_created; tabCreated = tabCreated.substring(0,tabCreated.length-3); // remove the seconds section from the date /* Build the new tab and append it to the tabRow */ var tab = $( '<li id="Tab-'+Tabs[i].tab_id+'" class="tabItem">'+ '<div class="tabTitle">'+ '<a href="#" class="tab"><span class="left"></span><div class="tabName">'+Tabs[i].name+'</div><span class="right"></span></a>'+ '</div>'+ '<div class="tabCreated">'+tabCreated+'</div>'+ '</li>'); /* Adding the tab to the UL container: */ $('#tabRow').append(tab); }); // close .each loop makeTabsDroppable(); }); // close newTab ajax call } function addPage(action,id) { var d = new Date(); var curr_date = d.getDate(); var curr_month = d.getMonth(); curr_month++; var curr_year = d.getFullYear(); var curr_hour = d.getHours(); var curr_min = d.getMinutes(); currentDate = curr_year + "-" + curr_month + "-" + curr_date + " " + curr_hour + ":" + curr_min ; $.getJSON("ajax.php",{'action':action,'id':id,rand:Math.random()},function(Pages){ $.each(Pages, function(i){ var pageCreated = Pages[i].date_created; pageCreated = pageCreated.substring(0,pageCreated.length-3); // remove the seconds section from the date /* Sequentially creating the pages and assigning a color from the array: */ var pageItem = $('<li id="Page-'+Pages[i].page_id+'" class="pageItem">'+ '<div class="pageTitle">'+ '<a href="" id="Page-'+Pages[i].page_id+'" class="page">'+ '<span class="left"></span><span class="pageName">'+Pages[i].name+ '</span><span class="right"></span></a>'+ '</div>'+ '<div class="pageCreated">'+pageCreated+'</div>'+ '<div class="columns">'+Pages[i].columns+'</div>'+ '</li>'); /* Setting the page data for each hyperlink: */ pageItem.find('a').data('page','ajax.php?action=lists&page_id='+Pages[i].page_id); // remove the new page and settings links so they can be added back to the end $('#newPageItem').remove(); /* Adding the tab to the UL container: */ $('#pageList').append(pageItem).fadeIn('fast'); // add link to create a new page var newPage = $( '<li id="newPageItem">'+ '<abbr title="'+_('New Page')+'"><a href="" class="notebookIcons newPage">'+ '</a></abbr>'+ '</li>'); $('#pageList').append(newPage); $('#pageList').append(newPage).fadeIn('fast'); }); // close $.each(Pages) makePagesDroppable(); }); // close newTab ajax call } <file_sep><? include_once "../main.php"; $day = date(d); $month = date(m); $year = date(Y); $del = "delete from job_post where EXday = \"$day\" and EXmonth = \"$month\" and EXyear = \"$year\" "; $rdel = mysql_query($del) or die(mysql_error()); $sch = array(); if (!empty($position)) { $sch[] = "position like '%$_POST[position]%'"; } if (!empty($country)) { $sch[] = "CompanyCountry = \"$_POST[country]\" "; } if (!empty($state)) { $sch[] = "CompanyState = '$_POST[state]' "; } if (!empty($JobCategory)) { $sch[] = "JobCategory like '%$_POST[JobCategory]%' "; } if (!empty($careerlevel)) { $sch[] = "j_target = '$_POST[careerlevel]'"; } if (!empty($kw)) { $sch[] = "description like '%$_POST[kw]%'"; } if (!$ByPage) $ByPage=25; if (!$Start) $Start=0; if($sm == 'or') { $qs = "select * from job_post ".(($sch)?"where ".join(" or ", $sch):"")." limit $Start,$ByPage"; $qss = "select * from job_post ".(($sch)?"where ".join(" or ", $sch):""); } elseif($sm == 'and') { $qs = "select * from job_post ".(($sch)?"where ".join(" and ", $sch):"")." limit $Start,$ByPage"; $qss = "select * from job_post ".(($sch)?"where ".join(" and ", $sch):""); } $rqs = mysql_query($qs) or die(mysql_error()); $rqss = mysql_query($qss) or die(mysql_error()); $rr = mysql_num_rows($rqss); if($rr == '0') { echo "<table width=446><tr><td><br><br><center> No results found.</center></td></tr></table>"; include ("../foother.html"); exit; } elseif($rr == '1') { echo "<br><br><center> Your search return one result. </center>"; } elseif($rr > '1') { echo "<br><br><center> Your search return $rr results. </center>"; } $col = "cococo"; echo "<br><table align=center width=446 cellspacing=0> <tr style=\"font-family:arial; color:#000000; font-weight:bold; font-size:11\"> <td>Position </td><td>Job Category </td><td width=85>Days to expire </td></tr>"; while($as = mysql_fetch_array($rqs)) { //$ex13 = date('d', mktime(0,0,0, $as[EXmonth] - date(m), $as[EXday] - date(d), $as[EXyear] - date(Y))); $day = date(d); $month = date(m); $year = date(Y); $EXdate = "$as[EXyear]"."-"."$as[EXmonth]"."-"."$as[EXday]"; $dnes = "$year"."-"."$month"."-"."$day"; $qd = "select to_days('$EXdate') - to_days('$dnes')"; $rqd = mysql_query($qd) or die(mysql_error()); $ex13 = mysql_fetch_array($rqd); if($col == "FFCC99") { $col = "FFFFCC"; } else { $col = "FFCC99"; } echo "<tr bgcolor=\"$col\" style=\"font-size:12\"> <td><a class=TN href=\"JobInfo.php?job_id=$as[job_id]\"> $as[position] </a></td><td> $as[JobCategory] </td><td align=center> $ex13[0] </td> </tr>"; } if($sm == 'or') { $qs2 = "select * from job_post ".(($sch)?"where ".join(" or ", $sch):""); } elseif($sm == 'and') { $qs2 = "select * from job_post ".(($sch)?"where ".join(" and ", $sch):""); } $rqs2 = mysql_query($qs2) or die(mysql_error()); $rr2 = mysql_num_rows($rqs2); echo "</table>"; echo "<table width=446 align=center><tr>"; if ($rr2 <= $ByPage && $Start == '0') { } if ( $Start > 0 ) { $nom1 = $Start - $ByPage; echo "<td align=left><a class=TN href=\"JobSearch3.php?sm=$sm&position=$position&CompanyCountry=$CompanyCountry&CompanyState=$CompanyState&JobCategory=$JobCategory&careerlevel=$careerlevel&target_company=$target_company&relocate=$relocate&country=$country&city=$city&kw=$kw&Start=$nom1\">previous</a></td>"; } if ($rr2 > $Start + $ByPage || ($Start == 0 && $rr2 > $ByPage)) { $nom = $Start + $ByPage; echo "<td align=right><a class=TN href=\"JobSearch3.php?sm=$sm&position=$position&CompanyCountry=$CompanyCountry&CompanyState=$CompanyState&JobCategory=$JobCategory&careerlevel=$careerlevel&target_company=$target_company&relocate=$relocate&country=$country&city=$city&kw=$kw&Start=$nom\">next</a></td>"; } echo "</tr></table>"; ?> <? include_once('../foother.html'); ?><file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; include_once "navigation.html"; $dir="banners/"; if (isset($submitok) && !empty($userfile)) { if (empty($burl)) { echo "<center><font face=verdana size=3 color=red><b> You left blank some of the required fields. </b></font></center>"; } $qcbn = "select fn from job_banners_t"; $rcn = mysql_query($qcbn) or die(mysql_error()); $arc = mysql_fetch_array($rcn); if ($arc[0] == $userfile_name) { echo "<br><br><center><font face=verdana>Already exist a banner with file name <b>$userfile_name</b><br>Change the name of the new file and try to upload it again. </center>"; } else { copy($userfile,$dir.$userfile_name); $qbn = "select * from job_banners_t"; $rbn = mysql_query($qbn) or die (mysql_error()); $cbn = mysql_num_rows($rbn); $nbn = $cbn + 1; $q2 = "insert into job_banners_t (b_id, fn, burl, alt) values ('$nbn', '$userfile_name', '$burl', '$alt')"; $rq2 = mysql_query($q2) or die(mysql_error()); $sb13 = "select count(bc) from job_banners_m"; $r13 = mysql_query($sb13) or die(mysql_error()); $ar13 = mysql_fetch_array($r13); if($ar13[0] == 0) { $ubi = "insert into job_banners_m (bc) values ('1') "; $rup = mysql_query($ubi) or die(mysql_error()); } else { $ubi = "update job_banners_m set bc = '1' "; $rup = mysql_query($ubi) or die(mysql_error()); } } } unset($submitok); unset($userfile); ?> <html> <head> <title></title> </head> <body> <br><br> <center> <table> <form method=post action=<?=$PHP_SELF?> enctype="multipart/form-data" style="background:none;"> <tr> <td class=TD_links> <font face=verdana>URL to the banner target web site: </td> <td class=TD_links> <input type=text size=36 name=burl value="http://" style="background-color:white; color:051dba; font-weight:bold; font-size:10; border-color:black"> </td> </tr> <tr> <td class=TD_links> <font face=verdana>Alt text:</font> </td> <td class=TD_links> <input type=text name=alt size=36 maxlenght=255 style="background-color:white; color:051dba; font-weight:bold; font-size:10; border-color:black"> </td> <tr> <td class=TD_links> <font face=verdana>Browse you local HDD: </td> <td class=TD_links> <input type=file size=25 name="userfile" style="background-color:white; color:051dba; font-weight:bold; font-size:10; border-color:black"> </td> </tr> <tr> <td></td> <td class=TD_links> <input type=submit name="submitok" value=" Upload " style="background-color:white; color:051dba; font-weight:bold; font-size:10; border-color:black" disabled> </td> </tr> </table> </form> </center> </body> </html> <? include_once('../foother.html'); ?><file_sep><? session_start(); session_unset("aid"); session_unset("apass"); session_unregister("aid"); session_unregister("apass"); session_destroy(); setcookie("aid","", "0", "/", "", ""); setcookie("aid","", "0", "/", "", ""); ?> <html> <head> <META HTTP-EQUIV="REFRESH" CONTENT="0;URL=../index.php"> </head> </html><file_sep>// AnchorPosition.js ezAnchorPosition = function(id, anchorname){ this.id = id; if (!!anchorname) this.getAnchorPosition(anchorname); }; ezAnchorPosition.$ = []; ezAnchorPosition.get$ = function(anchorname) { var instance = ezAnchorPosition.$[ezAnchorPosition.$.length]; if (instance == null) { instance = ezAnchorPosition.$[ezAnchorPosition.$.length] = new ezAnchorPosition(ezAnchorPosition.$.length, anchorname); } return instance; }; ezAnchorPosition.remove$ = function(id) { var ret_val = false; if ( (id > -1) && (id < ezAnchorPosition.$.length) ) { var instance = ezAnchorPosition.$[id]; if (!!instance) { ezAnchorPosition.$[id] = ezObjectDestructor(instance); ret_val = (ezAnchorPosition.$[id] == null); } } return ret_val; }; ezAnchorPosition.remove$s = function() { var ret_val = true; for (var i = 0; i < ezAnchorPosition.$.length; i++) { ezAnchorPosition.remove$(i); } return ret_val; }; ezAnchorPosition.prototype = { id : -1, x : -1, y : -1, anchorname : '', use_gebi : false, use_css : false, use_layers : false, toString : function() { var s = 'ezAnchorPosition(' + this.id + ') :: \n'; s += 'x/y = [' + this.x + ',' + this.y + ']' + '\n'; s += 'anchorname = [' + this.anchorname + ']' + '\n'; s += 'use_gebi = [' + this.use_gebi + ']' + ', use_css = [' + this.use_css + ']' + ', use_layers = [' + this.use_layers + ']' + '\n\n'; return s; }, getPageOffsetLeft : function(el) { var ol = 0; try { ol = el.offsetLeft; while ((el = el.offsetParent) != null) { ol += el.offsetLeft; } } catch(e) { } finally { } return ol; }, getPageOffsetTop : function(el) { var ot = 0; try { ot = el.offsetTop; while ((el = el.offsetParent) != null) { ot += el.offsetTop; } } catch(e) { } finally { } return ot; }, getWindowOffsetLeft : function(el) { var x = 0; var s = 0; try { x = this.getPageOffsetLeft(el); s = document.body.scrollLeft; } catch(e) { } finally { } return x - s; }, getWindowOffsetTop : function(el) { var x = 0; var s = 0; try { x = this.getPageOffsetTop(el); s = document.body.scrollTop; } catch(e) { } finally { } return x - s; }, getAnchorPosition : function(anchorname) { this.anchorname = anchorname; this.x = 0, this.y = 0; this.use_gebi = ((!!document.getElementById) ? true : false); this.use_css = ((!this.use_gebi) ? ((!!document.all) ? true : false) : false); this.use_layers = (((!this.use_gebi) && (!!this.use_css)) ? ((!!document.layers) ? true : false) : false); if (this.use_gebi && document.all) { this.x = this.getPageOffsetLeft(document.all[anchorname]); this.y = this.getPageOffsetTop(document.all[anchorname]); } else if (this.use_gebi) { var o = document.getElementById(anchorname); this.x = this.getPageOffsetLeft(o); this.y = this.getPageOffsetTop(o); } else if (this.use_css) { this.x = this.getPageOffsetLeft(document.all[anchorname]); this.y = this.getPageOffsetTop(document.all[anchorname]); } else if (this.use_layers) { var found = 0; for (var i = 0; i < document.anchors.length; i++) { if (document.anchors[i].name == anchorname) { found = 1; break; } } if (found == 0) { this.x=0; this.y=0; } x = document.anchors[i].x; y = document.anchors[i].y; } else { this.x = 0; this.y = 0; } }, getAnchorWindowPosition : function(anchorname) { this.getAnchorPosition(anchorname); var x=0; var y=0; if (!!document.getElementById) { if (isNaN(window.screenX)) { x = this.x - document.body.scrollLeft + window.screenLeft; y = this.y - document.body.scrollTop + window.screenTop; } else { x = this.x + window.screenX + (window.outerWidth - window.innerWidth) - window.pageXOffset; y = this.y + window.screenY + (window.outerHeight - 24 - window.innerHeight) - window.pageYOffset; } } else if (!!document.all) { x = this.x - document.body.scrollLeft + window.screenLeft; y = this.y - document.body.scrollTop + window.screenTop; } else if (!!document.layers) { x = this.x + window.screenX + (window.outerWidth - window.innerWidth) - window.pageXOffset; y = this.y + window.screenY + (window.outerHeight - 24 - window.innerHeight) - window.pageYOffset; } this.x = x; this.y = y; }, destructor : function() { return (this.id = ezAnchorPosition.$[this.id] = this.x = this.y = null); } }; <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"> <?php include_once("includes\documentHeader.php"); print_r(docHeader('', 'flashx.ez-ajax.com')); ?> </head> <body> <noscript>You must enable JavaScript to use this site.<br>Please adjust your browser's settings to enable JavaScript or use a browser that supports JavaScript.<br> <a href="http://flashx.ez-ajax.com" target="_blank">flashx.ez-ajax.com</a> </noscript> <script type="text/javascript"> var so = new SWFObject("/flash/main/ContentContainer.swf", "ContentContainer", "100%", "100%", "8", "#164f9f"); // so.addVariable("flashVarText", "this is passed in via FlashVars for example only"); so.write("flashcontent"); </script> </body> </html> <file_sep><!--======================== BEGIN COPYING THE HTML-TOP HERE ==========================--> <table border="0" cellpadding="0" cellspacing="0" width="665" align="center"> <!-- Job search and recruitment for Heathrow jobs --> <tr> <td><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/spacer.gif" width="68" height="1" border="0" alt="vacancies Heathrow"></td> <td><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/spacer.gif" width="6" height="1" border="0" alt="recruitment Heathrow"></td> <td><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/spacer.gif" width="73" height="1" border="0" alt="courier airport"></td> <td><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/spacer.gif" width="83" height="1" border="0" alt="search jobs"></td> <td><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/spacer.gif" width="83" height="1" border="0" alt="courier companies"></td> <td><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/spacer.gif" width="34" height="1" border="0" alt="LHR"></td> <td><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/spacer.gif" width="87" height="1" border="0" alt="nursing jobs"></td> <td><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/spacer.gif" width="58" height="1" border="0" alt="airport jobs"></td> <td><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/spacer.gif" width="43" height="1" border="0" alt="catering job"></td> <td><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/spacer.gif" width="69" height="1" border="0" alt="job agency"></td> <td><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/spacer.gif" width="60" height="1" border="0" alt="part time work"></td> <td><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/spacer.gif" width="1" height="1" border="0" alt="courier work"></td> </tr> <tr> <td colspan="11" rowspan="7"><map name="FPMap0"> <area href="http://<?=$_SERVER[HTTP_HOST]?>/index.php" shape="rect" coords="442, 75, 485, 125"> <area href="http://<?=$_SERVER[HTTP_HOST]?>/about.php" shape="rect" coords="498, 74, 560, 125"> <area href="http://<?=$_SERVER[HTTP_HOST]?>/faq.php" shape="rect" coords="564, 74, 598, 125"> <area href="http://<?=$_SERVER[HTTP_HOST]?>/contactus.php" shape="rect" coords="610, 76, 657, 125"> </map> <img border="0" src="images/top.jpg" width="663" height="126" usemap="#FPMap0"></td> <td><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/spacer.gif" width="1" height="11" border="0" alt="jobs search"></td> </tr> <tr> <td><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/spacer.gif" width="1" height="14" border="0" alt="Heathrow jobs"></td> </tr> <tr> <td><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/spacer.gif" width="1" height="21" border="0" alt="employment jobsite"></td> </tr> <tr> <td><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/spacer.gif" width="1" height="22" border="0" alt="job vacancies"></td> </tr> <tr> <td><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/spacer.gif" width="1" height="23" border="0" alt="online job"></td> </tr> <tr> <td><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/spacer.gif" width="1" height="20" border="0" alt="Heathrow courier"></td> </tr> <tr> <td><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/spacer.gif" width="1" height="11" border="0" alt="Heathrow Recruitment - Local jobs"></td> </tr> </table> <!--========================= STOP COPYING THE HTML-TOP HERE =========================--> <file_sep><?php if(!isset($GLOBALS['requestTimeStart'])){ $GLOBALS['requestTimeStart'] = microtime(true); } session_start(); if (!isset($_SESSION['sessionId']) && !(('settings.php' == basename($_SERVER['PHP_SELF'])) || ('about.php' == basename($_SERVER['PHP_SELF']))) ) { header('Location: login.php'); exit; } else { //load default config values require_once('config.php'); foreach($config as $configKey => $configValue){ //only process non-headers if(!isset($configValue['isHeader'])){ //check if the setting is NOT overrideable and if so clear the cookie //this is done to clear previously set cookeies if(!$configValue['overrideable']){ setcookie($configKey,NULL,time()-3600); } //check if user has cookies that override defaults if(isset($_COOKIE[$configKey])){ $_SESSION['config'][$configKey] = $_COOKIE[$configKey]; } else { $_SESSION['config'][$configKey] = $configValue['default']; } } } //check to make sure we have a session id (this is so users can go to settings.php without session id //before login) if(isset($_SESSION['sessionId'])){ try{ require_once ('soapclient/SforcePartnerClient.php'); require_once ('soapclient/SforceHeaderOptions.php'); $location = $_SESSION['location']; $sessionId = $_SESSION['sessionId']; $wsdl = $_SESSION['wsdl']; $mySforceConnection = new SforcePartnerClient(); $sforceSoapClient = $mySforceConnection->createConnection($wsdl); $mySforceConnection->setEndpoint($location); $mySforceConnection->setSessionHeader($sessionId); //Has the user selected a default object on? If so, //pass them to the session if (isset($_POST['default_object'])){ $_SESSION['default_object'] = $_POST['default_object']; } require_once ('soapclient/SforceHeaderOptions.php'); if($_SESSION['config']['callOptions_client'] || $_SESSION['config']['callOptions_defaultNamespace']){ $header = new CallOptions($_SESSION['config']['callOptions_client'], $_SESSION['config']['callOptions_defaultNamespace']); $mySforceConnection->setCallOptions($header); } if($_SESSION['config']['assignmentRuleHeader_assignmentRuleId'] || $_SESSION['config']['assignmentRuleHeader_useDefaultRule']){ $header = new AssignmentRuleHeader($_SESSION['config']['assignmentRuleHeader_assignmentRuleId'], $_SESSION['config']['assignmentRuleHeader_useDefaultRule']); $mySforceConnection->setAssignmentRuleHeader($header); } if($_SESSION['config']['mruHeader_updateMru']){ $header = new MruHeader($_SESSION['config']['mruHeader_updateMru']); $mySforceConnection->setMruHeader($header); } if($_SESSION['config']['queryOptions_batchSize']){ $header = new QueryOptions($_SESSION['config']['queryOptions_batchSize']); $mySforceConnection->setQueryOptions($header); } if($_SESSION['config']['emailHeader_triggerAutoResponseEmail'] || $_SESSION['config']['emailHeader_triggerOtherEmail'] || $_SESSION['config']['emailHeader_triggertriggerUserEmail']){ $header = new EmailHeader($_SESSION['config']['emailHeader_triggerAutoResponseEmail'], $_SESSION['config']['emailHeader_triggerOtherEmail'], $_SESSION['config']['emailHeader_triggertriggerUserEmail']); $mySforceConnection->setEmailHeader($header); } if($_SESSION['config']['UserTerritoryDeleteHeader_transferToUserId']){ $header = new UserTerritoryDeleteHeader($_SESSION['config']['UserTerritoryDeleteHeader_transferToUserId']); $mySforceConnection->setUserTerritoryDeleteHeader($header); } } catch (exception $e){ header('Location: login.php'); exit; } } } ?> <file_sep>/* SmithMicroHeatMapDataModel.js */ SmithMicroHeatMapDataModel = function(id){ this.id = id; // the id is the position within the global GeonosisObj.$ array }; SmithMicroHeatMapDataModel.$ = []; SmithMicroHeatMapDataModel.get$ = function() { // the object.id is the position within the array that holds onto the objects... var instance = SmithMicroHeatMapDataModel.$[SmithMicroHeatMapDataModel.$.length]; if(instance == null) { instance = SmithMicroHeatMapDataModel.$[SmithMicroHeatMapDataModel.$.length] = new SmithMicroHeatMapDataModel(SmithMicroHeatMapDataModel.$.length); } return instance; }; SmithMicroHeatMapDataModel.i = function() { return SmithMicroHeatMapDataModel.get$(); // this is an alias that aids the transmission of code from the server to the client... }; SmithMicroHeatMapDataModel.remove$ = function(id) { var ret_val = false; if ( (id > -1) && (id < SmithMicroHeatMapDataModel.$.length) ) { var instance = SmithMicroHeatMapDataModel.$[id]; if (!!instance) { SmithMicroHeatMapDataModel.$[id] = object_destructor(instance); ret_val = (SmithMicroHeatMapDataModel.$[id] == null); } } return ret_val; }; SmithMicroHeatMapDataModel.remove$s = function() { var ret_val = true; for (var i = 0; i < SmithMicroHeatMapDataModel.$.length; i++) { SmithMicroHeatMapDataModel.remove$(i); } SmithMicroHeatMapDataModel.$ = []; return ret_val; }; SmithMicroHeatMapDataModel.prototype = { id : -1, toString : function() { function toStr() { var s = '['; s += ']'; return s; } var s = 'id = [' + this.id + ']\n' + toStr(); return s; }, init : function(data) { return this; }, destructor : function() { return (this.id = SmithMicroHeatMapDataModel.$[this.id] = null); }, dummy : function() { return false; } }; <file_sep><?php if(isset($_POST['save_settings'])) { if ($_POST) { $kv = array(); foreach ($_POST as $key => $value) { if($key == 'save_settings') continue; mysql_query("UPDATE config set value = '$value' where name = '$key'"); } } header('location: '.BASE_URL); } ?> <div id="notebook"> <div id="tabs"> <ul id="tabRow"> <li class="tabItem"> <div class="tabTitle"> <!-- No need for tabs at this time <a href="#" class="tab active"><span class="left"></span><div class="tabName">Default</div><span class="right"></span></a> --> <a href="#" class="dialog"><span></span><div></div><span></span></a> </div> </li> </ul> <!-- close tabRow --> </div> <!-- close tabs --> <div class="clear"></div> <div id="tabContent"> <div id="contentHolder"> <div id="Settings"> <form action="" method="post" name="form_settings"> <table> <tr> <th><?php echo _('Site Name'); ?>:</th> <td><input name="default_site_name" type="text" value="<?php echo $GLOBALS["config"]["default_site_name"]; ?>" size="25" /></td> <td>&nbsp;</td> </tr> </table> <hr /> <table> <tr> <th><?php echo _('Date Format'); ?>: </td> </th> <td><input type="radio" name="date_format" id="dateYMD" value="Y-m-d" <?php if ($GLOBALS["config"]["date_format"] == 'Y-m-d') echo 'checked="yes"'; ?>/> <label for="dateYMD">YYYY-MM-DD</label></td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td><input type="radio" name="date_format" id="dateMDY" value="m-d-Y" <?php if ($GLOBALS["config"]["date_format"] == 'm-d-Y') echo 'checked="yes"'; ?>/> <label for="dateMDY">MM-DD-YYYY</label></td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td><input type="radio" name="date_format" id="dateDMY" value="d-m-Y" <?php if ($GLOBALS["config"]["date_format"] == 'd-m-Y') echo 'checked="yes"'; ?>/> <label for="dateDMY">DD-MM-YYYY</label></td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <th><?php echo _('Time Format'); ?>: </th> <td><input type="radio" name="time_format" id="time24" value="H:i" <?php if ($GLOBALS["config"]["time_format"] == 'H:i') echo 'checked="yes"'; ?>/> <label for="time24">24 hour</label></td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td><input type="radio" name="time_format" id="timeAMPM" value="h:ia" <?php if ($GLOBALS["config"]["time_format"] == 'h:ia') echo 'checked="yes"'; ?>/> <label for="timeAMPM">AM/PM</label></td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <th><?php echo _('Time Zone'); ?>:</th> <td><select title="<?php echo _('Time Zone'); ?>" name="timezone"> <option selected="selected"><?php echo $GLOBALS["config"]["timezone"]; ?></option> <?php $timezones = DateTimeZone::listIdentifiers(); sort($timezones); foreach ($timezones as $timezone) { echo "<option>$timezone</option>"; } ?> </select></td> <td>&nbsp;</td> </tr> <tr> <th><?php echo _('Language'); ?>:</th> <td><select title="<?php echo _('Language'); ?>" name="locale"> <option selected="selected"><?php echo $GLOBALS["config"]["locale"]; ?></option> <?php // open the locale directory $localeDirectory = BASE_DIR."/locale/"; $directory = opendir($localeDirectory); // get each entry while($entryName = readdir($directory)) { if ($entryName == $GLOBALS["config"]["locale"]) continue; $localeList[] = $entryName; } // close directory closedir($directory); sort($localeList); // loop through the array of files and print them all foreach ($localeList as $locales) { if (substr("$locales", 0, 1) != "."){ // don't list hidden files if (filetype($localeDirectory.$locales) == "file") continue; echo "<option>$locales</option>"; } } ?> </select> <a href="" class="translation-info">Translation Info</a> </td> <td> <div class="translation-detail"> <ol> <li>To translate Surreal ToDo copy the /locale/en_US.utf8 folder and rename it for your language and country. (See the gettext standards for <a href="http://www.gnu.org/software/gettext/manual/gettext.html#Language-Codes">language</a> and <a href="http://www.gnu.org/software/gettext/manual/gettext.html#Country-Codes">country</a> codes.)</li> <li>Rename the LC_MESSAGES/en_US.utf8.po file.</li> <li>Open the file with your utf8 compatible text editor and make your translations. You'll see a msgid line that has the English version. Your translations go into the msgstr line. </li> <li>Send your .po file to <EMAIL> and I'll send you back the compiled version and include it with future releases.</li> </ol> </div> </td> </tr> </table> <hr /> <table> <tr> <th><?php echo _('Theme'); ?></th> <td>&nbsp;</td> </tr> <tr> <td> <?php // open the theme directory $themeDirectory = BASE_DIR."/theme/"; $directory = opendir($themeDirectory); $info = ''; $preview = ''; // get each entry while($entryName = readdir($directory)) { $dirArray[] = $entryName; } // close directory closedir($directory); // count elements in array $indexCount = count($dirArray); // sort 'em sort($dirArray); // print 'em // loop through the array of files and print them all for($index=0; $index < $indexCount; $index++) { if($index == 0) echo '<table>'; if (substr("$dirArray[$index]", 0, 1) != "."){ // don't list hidden files $theme_name = ucwords(str_replace("_"," ",$dirArray[$index])); if (filetype($themeDirectory.$dirArray[$index]) == "file") continue; if (file_exists($themeDirectory.$dirArray[$index].'/info.txt')) { $info = file_get_contents($themeDirectory.$dirArray[$index].'/info.txt');} if (file_exists($themeDirectory.$dirArray[$index].'/preview.png')) { $preview = "<img class='preview' src='".BASE_URL."/theme/$dirArray[$index]/preview.png' />";} print('<tr><td nowrap="nowrap"><input type="radio" name="theme" id="theme" value="'.$dirArray[$index].'"'); if ($GLOBALS["config"]["theme"] == $dirArray[$index]) print('checked="yes"'); print("/> $theme_name</td><td>$preview</td><td>$info</td></tr>"); if ($index == $indexCount) echo '</table'; } } ?> </td> <td>&nbsp;</td> </tr> </table> <hr /> <table cellspacing="12px"> <tr> <th><?php echo _('Completed Item Format'); ?>:</th> <td><input type="checkbox" name="strikethrough" value="1" onclick="calc_completed_item(form_settings)" <?php if (in_array($GLOBALS["config"]["completed_item"],array(1,3,5,9,7,11,13,15))) echo 'checked="yes"'; ?>/> <label for="strikethrough"><?php echo _('Strikethrough'); ?></label></td> <td><input type="checkbox" name="italic" value="2" onclick="calc_completed_item(form_settings)" <?php if (in_array($GLOBALS["config"]["completed_item"],array(2,3,6,10,7,11,14,15))) echo 'checked="yes"'; ?>/> <label for="italic"><?php echo _('Italic'); ?></label></td> <td><input type="checkbox" name="gray" value="8" onclick="calc_completed_item(form_settings)" <?php if (in_array($GLOBALS["config"]["completed_item"], array(8,9,10,12,11,13,14,15))) echo 'checked="yes"'; ?>/> <label for="gray"><?php echo _('Gray'); ?></label></td> <td><input type="checkbox" name="checkmark" value="4" onclick="calc_completed_item(form_settings)" <?php if (in_array($GLOBALS["config"]["completed_item"],array(4,5,6,12,7,13,14,15))) echo 'checked="yes"'; ?>/> <label for="checkmark"><?php echo _('Checkmark'); ?></label></td> </td> <td><input type="hidden" name="completed_item" value="<?php echo $GLOBALS["config"]["completed_item"]; ?>" /></td> </tr> </table> <hr /> <table> <tr> <td><input name="save_settings" type="submit" value="<?php echo _('Save'); ?>" /></td> <td>&nbsp;</td> </tr> </table> </form> </div> </div> <!-- close contentHolder --> </div> <!-- close tabContent --> <script type="text/javascript"> function calc_completed_item(form){ var value = 0; if(form.strikethrough.checked == true) value = value + parseInt(form.strikethrough.value); if(form.italic.checked == true) value = value + parseInt(form.italic.value); if(form.checkmark.checked == true) value = value + parseInt(form.checkmark.value); if(form.gray.checked == true) value = value + parseInt(form.gray.value); form.completed_item.value = value; }</script> </div> <!-- close settings--> <file_sep><? // pay10.php -- this file was missing from the original distribution from the seller ?> <file_sep><?php include_once("../includes/documentHeader.php"); //include_once("documentHeader.php"); function emitComponentRecords($xRet) { $dStream = ""; for ($i = 0; $i < count($xRet); $i++) { $dStream = $dStream . '<component id="' . $xRet[$i]->id . '"/>'; $dStream = $dStream . '<name>' . $xRet[$i]->id . '</name>'; $dStream = $dStream . '<sampleURL>' . $xRet[$i]->sampleURL . '</sampleURL>'; $dStream = $dStream . '<downloadURL>' . $xRet[$i]->downloadURL . '</downloadURL>'; $dStream = $dStream . '<sourceURL>' . $xRet[$i]->sourceURL . '</sourceURL>'; $dStream = $dStream . '</component>'; } return $dStream; } try { $cmd = getValueFromGetOrPostArray("cmd"); $responseID = 0; $responseMsg = ""; $debugMsg = ""; $dataStream = ""; $db = new MSSQLDB('Flex2Components', 'SQL2005', 'sa', 'sisko@7660$boo'); if ($cmd == "getList") { $query = "SELECT id, name, sampleURL, downloadURL, sourceURL FROM Flex2Components ORDER BY name;"; $xRet = $db->query_database($query); if (count($xRet) > 0) { $dataStream = $dataStream . emitComponentRecords($xRet); } } else if ($cmd == "add") { $name = $db->sqlEscape(getValueFromGetOrPostArray("name")); $sample = $db->sqlEscape(getValueFromGetOrPostArray("sample")); $download = $db->sqlEscape(getValueFromGetOrPostArray("download")); $source = $db->sqlEscape(getValueFromGetOrPostArray("source")); $dataField = getValueFromGetOrPostArray("dataField"); $query = "INSERT INTO Flex2Components (name, sampleURL, downloadURL, sourceURL) VALUES ('$name','$sample','$download','$source');"; $xRet = $db->query_database($query); if (count($xRet) > 0) { $dataStream = $dataStream . emitComponentRecords($xRet); } } else { $responseID = -200; $responseMsg = "Warning: Missing cmd..."; } $responseMsg = "[$responseID] :: " . $responseMsg; } catch (Exception $e) { $responseID = -999; $responseMsg = "Exception: " . var_print_r($e); } ?> <?php $responseID = cdataEscape($responseID); $responseMsg = cdataEscape($responseMsg); $debugMsg = cdataEscape($debugMsg); $xmlstr = <<<XML <?xml version="1.0" encoding="iso-8859-1"?> <response> <status> <code>$responseID</code> <message>$responseMsg</message> </status> <debug>$debugMsg</debug> <datum>$dataStream</datum> </response> XML; echo $xmlstr; ?> <file_sep><? unset($step); $step = '3'; include_once "accesscontrol.php"; $SK_d = strip_tags($SK_d, "<br>"); if ( $submit == 'Save and finish') { $q1 = "insert into job_skills set uname = \"$uname\", SK_d = \"$SK_d\" "; $r2 = mysql_query($q1) or die(mysql_error()); echo "<table width=446 border=0><tr><td><br><br><br><center> Please click here to view your resume <a class=TN href=\"javascript:popUp('preview.php?uname=$uname')\"> click here </a></center></td></tr></table>"; include_once('../foother.html'); } else { include "3s.php"; } ?><file_sep> <?php include_once("..\includes\documentHeader.php"); ?> <?php try { $sid = $_GET["sid"]; $x = $_GET["xml"]; $n = $_GET["n"]; $m = ($n - intval($n)); $n = $n - $m; $m = $m * 10; $recID = -1; $l = strlen($x); $db = new MSSQLDB('FlashGames'); $sData = $db->sqlEscape($x); $query = "SELECT id, sid, datum FROM SessionData WHERE (sid = '$sid');"; $xRet = $db->query_database($query); if (count($xRet) == 0) { $query = "INSERT INTO SessionData (sid, datum) VALUES ('$sid','$sData');"; $recID = $db->query_database($query); } else { $recID = $xRet[0]->id; $x = $xRet[0]->datum . $x; $sData = $db->sqlEscape($x); $query = "UPDATE SessionData SET datum = '$sData' WHERE (sid = '$sid');"; $xRet = $db->query_database($query); } $dbNum = 101; $fAction = "a"; $myFile = "debug.txt"; if ($n == 1) { if (file_exists($myFile)) { $fAction = "w"; unlink($myFile); } } $p = -1; if (intval($n) == intval($m)) { $p = new xmlParser(); $p->_parse($x, true); } $dbNum++; $fHand = fopen($myFile, $fAction) or die("Error $dbNum!!"); fwrite($fHand, "\$_GET(1) \$n=[$n] \$m=[$m] \$fAction=[$fAction] \$l=[$l] \$x=[$x]\n" . count($_GET) . "\n" . var_print_r($_GET) . "\n"); fwrite($fHand, "\$p=" . var_print_r($p) . "\n\n"); fclose($fHand); } catch (Exception $e) { echo 'Caught exception: ', var_print_r($e), "\n"; } ?> <?php $xmlstr = <<<XML <?xml version="1.0" encoding="iso-8859-1"?> <response> <status>1</status> <recID>$recID</recID> </response> XML; echo $xmlstr; ?> <file_sep><?php header( 'Location: login.php' ) ; ?> <file_sep><? //include_once "accesscontrol2.php"; include_once "../main.php"; $q = "select * from job_seeker_info where uname = \"$uname\""; $r = mysql_query($q) or die(mysql_error()); $a = mysql_fetch_array($r); $q1 = "select * from job_work_experience where uname = \"$uname\" order by WEn desc "; $r2 = mysql_query($q1) or die(mysql_error()); $q3 = "select * from job_careerlevel where uname = \"$uname\" "; $r3 = mysql_query($q3) or die(mysql_error()); $a3 = mysql_fetch_array($r3); ?> <html> <head> <title> <? echo "$a[fname] $a[lname]'s Resume"; ?> </title> <style> body {font-family:verdana} </style> </head> <body> <table align=center><tr><td> <table width=550 align=center cellpadding=0> <caption align=center><b><? echo "$a[rTitle] <br><p align=left><font size=2 style=\"font-weight:normal\"> $a[rPar] </font></p>"; ?> </b> </caption> <tr> <td valign=top> <table width=250 align=center cellspacing=0 border=1 bordercolor=black> <tr> <td> <b>Name:</b> </td> <td width=175 valign=top> <? echo "$a[fname] $a[lname]"; ?> </td> </tr> <tr> <td> <b>Age: </b> </td> <td valign=top> <? if((date(m) > $a[bmonth]) || (date(m) == $a[bmonth] && date(d) < $a[bday])) { echo date(Y) - $a[byear]; } else { echo date(Y) - $a[byear] - 1; } ?> ?> </td> </tr> <tr> <td> <b>Phone:</b> </td> <td valign=top> <? echo "$a[phone] \n $a[phone2]"; ?> </td> </tr> <tr> <td> <b>E-mail: </b> </td> <td > <?= $a[job_seeker_email]?> </td> </tr> </table> </td> <td valign=top> <table align=center width=300 cellpadding=0 cellspacing=0 border=1 bordercolor=black> <tr> <td colspan=2><b> Address: </b></td> </tr> <tr> <td colspan=2> <?=$a[address]?> </td> </tr> <tr> <td><b> Country: </b></td> <td > <?=$a[country]?> </td> </tr> <tr> <td><b>City/Zip <? if(!empty($a[state])) { echo "/State"; } ?> </b></td> <td > <?=$a[city]?>/<?=$a[zip]?> <? if(!empty($a[state])) { echo "/$a[state]"; } ?> </td> </td> </tr> </table> </td> </tr> </table> <table align=center width=500 border = 1 bordercolor=black cellspacing=0> <tr> <td>Career level </td> <td > <?=$a3[clname]?> </td> </tr> </table> </body> </html> <? echo "<br><br><br>"; while ($a1 = mysql_fetch_array($r2)) { echo " <form action=EditWorkExperience.php method=post style=\"background:none;\"> <table align=center width=510 border=1 bordercolor=black cellspacing=0 cellpadding=0> <caption> <font size=2> Work experience# $a1[WEn] </font> </caption> </form> <tr> <td colspan=4><b>&nbsp; Position: </b> $a1[WE_p] </td> </tr> <tr> <td><b>&nbsp; From date</b></td> <td><b>&nbsp; To date</b></td> </tr> <tr> <td >&nbsp;$a1[WE_Start]</td> <td >&nbsp;$a1[WE_End]</td> </tr> <tr> <td colspan=4> <table cellspacing=0 width=100%> <tr> <td valign=top bgcolor=white> <b>&nbsp; Description: </b> </td> </tr> <tr> <td > $a1[WE_d] </td> </tr> </table> </td> </td> </tr> </table><br> "; } $q1 = "select * from job_education where uname = \"$uname\" order by En asc "; $r2 = mysql_query($q1) or die(mysql_error()); echo "<br><br><br>"; while ($a1 = mysql_fetch_array($r2)) { echo " <form action=EditEducation.php method=post style=\"background:none;\"> <table align=center width=500 border=1 bordercolor=black cellspacing=0 cellpadding=0> <caption> <font size=2> Education# $a1[En] </font> </caption> </form> <tr> <td colspan=4><b>&nbsp; Education Institution: </b>"; echo stripslashes($a1[E_i]); echo "</td> </tr> <tr> <td>&nbsp; Graduate Level </td> <td width=100><b>&nbsp; From date </b></td><td width=185 >&nbsp; $a1[E_Start] </td> </tr> <tr> <td > &nbsp; $a1[E_gr] </td> <td width=100><b>&nbsp; To date </b></td><td width=185 >&nbsp; $a1[E_End] </td> </tr> <tr> <td colspan=4> <table cellspacing=0 width=100%> <tr> <td valign=top bgcolor=white> <b>&nbsp; Description: </b> </td> </tr> <tr> <td > $a1[E_d] </td> </tr> </table> </td> </td> </tr> </table><br> "; } $q4 = "select * from job_skills where uname = \"$uname\" "; $r4 = mysql_query($q4) or die(mysql_error()); while($a4 = mysql_fetch_array($r4)) { $aaa = stripslashes($a4[SK_d]); echo " <table align=center width=500 border=1 bordercolor=black cellspacing=0> <caption><b>My additional skills </b></caption> <tr> <td colspan=2> $aaa </td> </tr> </table> "; } ?> </td></tr></table> <? include_once('../foother.html'); ?><file_sep><? include_once "../main.php"; ?> <SCRIPT LANGUAGE="JavaScript"> function popUp(URL) { day = new Date(); id = day.getTime(); eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=yes,location=0,statusbar=0,menubar=0,resizable=yes,width=600,height=400,left = 100,top = 50');"); } </script> <SCRIPT LANGUAGE="JavaScript"> function checkFields() { missinginfo = ""; if (document.form.Sk_d.value == "") { missinginfo += "\n - Institution name"; } if (missinginfo != "") { missinginfo ="_____________________________\n" + "You failed to correctly fill in your:\n" + missinginfo + "\n_____________________________" + "\nPlease re-enter and submit again!"; alert(missinginfo); return false; } else return true; } </script> <form method=post action="<?=$PHP_SELF?>" name="form" onSubmit="return checkFields();" style="background:none;"> <table align=center width=446 border="0"> <caption align=left><a href="javascript:popUp('preview.php')"> Preview </a> </caption> <tr> <td valign=top> <b>Skills: </b><br> <font size=1>(describe your skills - languages, courses, seminars, etc.) &nbsp;To insert new row, use &lt;BR&gt;<br> </font> <center><textarea name=SK_d rows=6 cols=46></textarea></center> </td> </tr> <tr> <td align=center> <input type=submit name=submit value="Save and finish"> </td> </tr> </table> </form> <? include_once('../foother.html'); ?> <file_sep>function popUpWindowForURL(aURL, winName, aWid, aHt) { winName = ((winName == null) ? 'window' + ezUUID$() : winName); aWid = ((aWid == null) ? ezClientWidth() - 50 : aWid); aHt = ((aHt == null) ? ezClientHeight() - 25 : aHt); window.open(aURL,winName,'width=' + ezClientWidth() + ',height=' + ezClientHeight() + ',resizeable=yes,scrollbars=1'); } <file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- TemplateBeginEditable name="doctitle" --> <title>EzAJAX Downloads</title> <!-- TemplateEndEditable --> <!-- TemplateBeginEditable name="head" --> <!-- TemplateEndEditable --> <style type="text/css"> <!-- body { font: 100% Verdana, Arial, Helvetica, sans-serif; background: #FFFFFF; margin: 0; /* it's good practice to zero the margin and padding of the body element to account for differing browser defaults */ padding: 0; text-align: center; /* this centers the container in IE 5* browsers. The text is then set to the left aligned default in the #container selector */ color: #000000; } /* Tips for Elastic layouts 1. Since the elastic layouts overall sizing is based on the user's default fonts size, they are more unpredictable. Used correctly, they are also more accessible for those that need larger fonts size since the line length remains proportionate. 2. Sizing of divs in this layout are based on the 100% font size in the body element. If you decrease the text size overall by using a font-size: 80% on the body element or the #container, remember that the entire layout will downsize proportionately. You may want to increase the widths of the various divs to compensate for this. 3. If font sizing is changed in differing amounts on each div instead of on the overall design (ie: #sidebar1 is given a 70% font size and #mainContent is given an 85% font size), this will proportionately change each of the divs overall size. You may want to adjust based on your final font sizing. */ .oneColElsCtrHdr #container { width: 46em; /* this width will create a container that will fit in an 800px browser window if text is left at browser default font sizes */ background: #0066FF; margin: 0 auto; /* the auto margins (in conjunction with a width) center the page */ border: 1px solid #000000; text-align: left; /* this overrides the text-align: center on the body element. */ } .oneColElsCtrHdr #header { background: #0066FF; padding: 0 10px 0 20px; /* this padding matches the left alignment of the elements in the divs that appear beneath it. If an image is used in the #header instead of text, you may want to remove the padding. */ } .oneColElsCtrHdr #header h1 { margin: 0; /* zeroing the margin of the last element in the #header div will avoid margin collapse - an unexplainable space between divs. If the div has a border around it, this is not necessary as that also avoids the margin collapse */ padding: 10px 0; /* using padding instead of margin will allow you to keep the element away from the edges of the div */ } .oneColElsCtrHdr #mainContent { padding: 0 20px; /* remember that padding is the space inside the div box and margin is the space outside the div box */ background: #FFFF66; } .oneColElsCtrHdr #footer { padding: 0 10px; /* this padding matches the left alignment of the elements in the divs that appear above it. */ background: #0066FF; } .oneColElsCtrHdr #footer p { margin: 0; /* zeroing the margins of the first element in the footer will avoid the possibility of margin collapse - a space between divs */ padding: 10px 0; /* padding on this element will create space, just as the the margin would have, without the margin collapse issue */ font-size: 9px; color: #FFFF00; } .caption { margin: 5px; padding: 5px; border: none; font-size:90%; color: black } --> </style></head> <body class="oneColElsCtrHdr"> <?php include_once('includes/core.php'); ?> <div id="container"> <div id="header"> <div class="caption left"> <img src="images/ezAJAX Logo 08-17-2006a (125x125).gif" align="top"/> <font size="+3">EzAJAX Download Site</font></div> <!-- end #header --></div> <div id="mainContent"> <h1> EzAJAX 0.94 (04-05-2008) </h1> <?php // echo "BEGIN:<br/>"; $_fpath = $_SERVER['SCRIPT_FILENAME']; $_toks = splitString($_fpath,'/'); // echo "\$_fpath=[$_fpath]<br/>"; array_pop($_toks); $_p = join_list($_toks,"/").'/downloads'; $ii = strpos($_toks[0],":"); // echo "\$ii=[$ii]<br/>"; if ($ii == false) { $_p = '/'.$_p; } // echo "\$_p=[$_p]<br/>"; // do_dump($_toks); $_files = glob($_p.'/*.exe'); foreach ( $_files as $item ) { $toks = splitString($item,'/'); $fname = array_pop($toks); // echo "\$fname=[$fname]<br/>"; echo '<p><a href="downloads/'.$fname.'" target="_blank">'.$fname.'</a></p>'; } // do_dump($_files); // do_dump($_REQUEST); // do_dump($_SERVER); // echo "END!<br/>"; ?> <h2>EzAJAX PAD Files</h2> <?php // echo "BEGIN:<br/>"; $_fpath = $_SERVER['SCRIPT_FILENAME']; $_toks = splitString($_fpath,'/'); // echo "\$_fpath=[$_fpath]<br/>"; array_pop($_toks); $_p = join_list($_toks,"/").'/pad'; $ii = strpos($_toks[0],":"); // echo "\$ii=[$ii]<br/>"; if ($ii == false) { $_p = '/'.$_p; } // echo "\$_p=[$_p]<br/>"; // do_dump($_toks); $_files = glob($_p.'/*.xml'); foreach ( $_files as $item ) { $toks = splitString($item,'/'); $fname = array_pop($toks); // echo "\$fname=[$fname]<br/>"; $t = splitString($fname,'-'); $f = join_list($t," "); echo '<p><a href="pad/'.$fname.'" target="_blank">'.$f.'</a></p>'; } // do_dump($_files); // do_dump($_REQUEST); // do_dump($_SERVER); // echo "END!<br/>"; ?> <h2>Order your Copy of EzAJAX today !</h2> <p><a href="http://www.regnow.com/softsell/nph-softsell.cgi?items=14605-1" target="_blank">Click Here to place your order.</a></p> <p>&nbsp;</p> <!-- end #mainContent --></div> <div id="footer"> <p>&copy; Copyright 2008, Ez-AJAX.Com and EzAJAX.US, All Rights Reserved. </p> <!-- end #footer --></div> <!-- end #container --></div> <p><small>Get your Low-Cost Domain Names and Web Hosting from <a href="http://www.EzCheapSites.Com" target="_blank">EzCheapSites.Com</a></small></p> </body> </html> <file_sep><?php ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // TO CONFIGURE THE WORKBENCH FOR ALL YOUR USERS, ADJUST THE "DEFAULT" VALUES FOR THE KEYS BELOW. // // IF YOU WOULD LIKE TO ALLOW YOUR USERS TO OVERRIDE THE DEFAUTS SET THE "OVERRIDEABLE" VALUE TO true. // THIS WILL CAUSE THE KEY TO APPEAR ON THE 'SETTINGS' PAGE AND WILL BE CUSTOMIZABLE ON A USER-BY-USER // BASIS. THIS IS ACCOMPLISHED BY SETTING COOKIES IN THE USER'S BROWSER AND THE USER'S SETTINGS WILL // RETURN TO THE DEFAULTS SET BELOW IF THE COOKIES ARE CLEARED. THE "LABEL" AND "DESCRIPTION" VALUES CONTROL // HOW THE SETTING IS DISPLAYED ON THE 'SETTINGS' PAGE. // // DO NOT ALTER THE KEY NAME, "DATATYPE", "MAXVALUE", OR "MINVALUE" VALUES. THESE MUST REMAIN AS IS FOR THE // FOR WORKBENCH TO FUNCTION PROPERLY. // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// $config["header_General"] = array( "label" => "General Options", "display" => true, "isHeader" => true ); $config["abcOrder"] = array( "label" => "Alphabetize Field Names", "description" => "Alphabetizes field names for across application. Otherwise, field names are displayed in the order returned by Salesforce.", "default" => true, "overrideable" => true, "dataType" => "boolean" ); $config["mruHeader_updateMru"] = array( "label" => "Update Recent Items on Sidebar", "description" => "Indicates whether to update the list of most recently used (MRU) items on the Salesforce sidebar. For queries, the MRU is only updated when returning one record.", "default" => false, "overrideable" => true, "dataType" => "boolean" ); $config["invalidateSessionOnLogout"] = array( "label" => "Invalidate Session on Logout", "description" => "Invalidates the current API session when logging out of the Workbench. This option is only available when logging in with API version 13.0 and higher; otherwise it is ignored.", "default" => true, "overrideable" => true, "dataType" => "boolean" ); $config["displayRequestTime"] = array( "label" => "Display Request Time", "description" => "Display the time to render the page in the footer.", "default" => true, "overrideable" => false, "dataType" => "boolean" ); $config["checkSSL"] = array( "label" => "Check for Secure Connection", "description" => "Display a warning to users in the footer if an unsecure connection is detected.", "default" => true, "overrideable" => false, "dataType" => "boolean" ); $config["debug"] = array( "label" => "Debug Mode", "description" => "Enables debugging mode for showing supervariables and SOAP messages.", "default" => false, "overrideable" => false, "dataType" => "boolean" ); $config["callOptions_defaultNamespace"] = array( "label" => "Default Namespace", "description" => " A string that identifies a developer namespace prefix", "default" => null, "overrideable" => true, "dataType" => "string" ); $config["header_LoginOptions"] = array( "label" => "Login Options", "display" => true, "isHeader" => true ); $config["defaultApiVersion"] = array( "label" => "Default API Version", "description" => "Default API version to be used for login. Recommended to choose latest version. Some features may act unexpectedly when using older versions.", "default" => "15.0", "overrideable" => true, "dataType" => "picklist", "valuesToLabels" => array( "15.0" => "15.0", "14.0" => "14.0", "13.0" => "13.0", "12.0" => "12.0", "11.1" => "11.1", "11.0" => "11.0", "10.0" => "10.0", "9.0" => "9.0", "8.0" => "8.0", "7.0" => "7.0", "6.0" => "6.0" ) ); $config["defaultInstance"] = array( "label" => "Default Instance", "description" => "Default instance to be used for login. Recommended to use 'www' for all production orgs.", "default" => "www", "overrideable" => true, "dataType" => "picklist", "labelKey" => "0", "valuesToLabels" => array( "www" => array("Production Login (www)",""), "na0-api" => array("NA0 (SSL)","0"), "na1-api" => array("NA1","3"), "na2-api" => array("NA2","4"), "na3-api" => array("NA3","5"), "na4-api" => array("NA4","6"), "na5-api" => array("NA5","7"), "na6-api" => array("NA6","8"), "ap0-api" => array("AP","1"), "eu0-api" => array("EMEA","2"), "test" => array("Sandbox Login (test)",""), "tapp0-api" => array("Sandbox CS0 (tapp0)","T"), "cs1-api" => array("Sandbox CS1","S"), "cs2-api" => array("Sandbox CS2","R"), "cs3-api" => array("Sandbox CS3","Q"), "prerelna1.pre" => array("Pre-Release","t") ) ); $config["fuzzyServerUrlLookup"] = array( "label" => "Enable Server URL Fuzzy Lookup", "description" => "When logging in with a Session Id, Workbench attempts to guess the associated Server URL. This may fail for orgs that have been migrated from one instance to another.", "default" => true, "overrideable" => true, "dataType" => "boolean" ); $config["loginScopeHeader_organizationId"] = array( "label" => "Portal Organization Id", "description" => "Specify an org id for Self-Service, Customer Portal, and Partner Portal Users. Leave blank for standard Salesforce users.", "default" => null, "overrideable" => true, "dataType" => "string" ); $config["loginScopeHeader_portalId"] = array( "label" => "Portal Id", "description" => "Specify an portal id for Customer Portal, and Partner Portal Users. Leave blank for standard Salesforce users.", "default" => null, "overrideable" => true, "dataType" => "string" ); $config["callOptions_client"] = array( "label" => "Client Id", "description" => "Specify a Client Id for a partner with special API functionality.", "default" => null, "overrideable" => true, "dataType" => "string" ); $config["header_DataManagement"] = array( "label" => "Data Management Options", "display" => true, "isHeader" => true ); $config["showReferenceBy"] = array( "label" => "Enable Smart Lookup", "description" => "Show the Smart Lookup column for insert, update, and upsert operations for mapping with foreign keys via relationships.", "default" => true, "overrideable" => true, "dataType" => "boolean" ); $config["fieldsToNull"] = array( "label" => "Insert Null Values", "description" => "Forces null values to be commited to the database when inserting, updating, or upserting records; otherwise null values will be overridden by the existing values in the database", "default" => false, "overrideable" => true, "dataType" => "boolean" ); $config["emailHeader_triggerAutoResponseEmail"] = array( "label" => "Trigger Auto-Response Emails", "description" => "Send Auto-Response e-mails when inserting Leads and Cases", "default" => false, "overrideable" => true, "dataType" => "boolean" ); $config["emailHeader_triggertriggerUserEmail"] = array( "label" => "Trigger User Emails", "description" => "Send e-mails to users when resetting a password, creating a new user, adding comments to a case, or creating or modifying a task", "default" => false, "overrideable" => true, "dataType" => "boolean" ); $config["emailHeader_triggerOtherEmail"] = array( "label" => "Trigger Other Emails", "description" => "Send other e-mails for insert, update, and upsert of records", "default" => false, "overrideable" => true, "dataType" => "boolean" ); $config["allowFieldTruncationHeader_allowFieldTruncation"] = array( "label" => "Allow Field Truncation", "description" => "For API 15.0 and higher, specifies to automatically truncatrate string values that are too long when performing Insert, Update, Upsert, Updelete, or Execute; otherwise a STRING_TOO_LONG error is returned. This is ignored in all previous API versions.", "default" => false, "overrideable" => true, "dataType" => "boolean" ); $config["assignmentRuleHeader_useDefaultRule"] = array( "label" => "Use Default Assignment Rule", "description" => "Apply default Assignment Rule to apply to insert, update, and upsert operations. May not be used in conjuction with Assignment Rule Id option.", "default" => false, "overrideable" => true, "dataType" => "boolean" ); $config["assignmentRuleHeader_assignmentRuleId"] = array( "label" => "Assignment Rule Id", "description" => "Specify an Assignment Rule Id to apply to insert, update, and upsert operations. May not be used if Use Default Assignment Rule option is checked.", "default" => null, "overrideable" => true, "dataType" => "string" ); $config["UserTerritoryDeleteHeader_transferToUserId"] = array( "label" => "Territory Delete Transfer User", "description" => "The ID of the user to whom open opportunities will be assigned when an opportunity's owner is removed from a territory", "default" => null, "overrideable" => true, "dataType" => "string" ); $config["header_queryOptions"] = array( "label" => "Query Options", "display" => true, "isHeader" => true ); $config["linkIdToUi"] = array( "label" => "Link Ids to Record Detail", "description" => "Display queried Id fields as hyperlinks to their cooresponding record in the Salesforce user interface. Note, links to objects without detail pages will fail.", "default" => true, "overrideable" => true, "dataType" => "boolean" ); $config["autoJumpToQueryResults"] = array( "label" => "Automatically Jump to Query Results", "description" => "When displaying query results in the browser, automatically jump to the top of the query results.", "default" => true, "overrideable" => true, "dataType" => "boolean" ); $config["autoRunQueryMore"] = array( "label" => "Automatically Retrieve More Query Results", "description" => "Automatically retrieve all query results with queryMore() API call for browser view; otherwise, 'More...' button is show when additional results are available. If a large query is run with this setting enabled, the operation may be subject to unexpected timeouts. CSV exports automatically retrieve all results.", "default" => false, "overrideable" => true, "dataType" => "boolean" ); $config["queryOptions_batchSize"] = array( "label" => "Preferred Query Batch Size", "description" => "Requested query batch size. This is not a guranteed value and depends on the data set being returned.", "default" => 500, "overrideable" => true, "dataType" => "int", "minValue" => 200, "maxValue" => 2000 ); $config["header_searchOptions"] = array( "label" => "Search Options", "display" => true, "isHeader" => true ); $config["autoJumpToSearchResults"] = array( "label" => "Automatically Jump to Search Results", "description" => "When displaying search results in the browser, automatically jump to the top of the search results.", "default" => true, "overrideable" => true, "dataType" => "boolean" ); $config["header_Execute"] = array( "label" => "Apex Execute Logging Options", "display" => true, "isHeader" => true ); $config["defaultLogCategory"] = array( "label" => "Default Log Category", "description" => "Default Log Category when displaying results from anonymous Apex execution. Defaults will not apply until after logging in again.", "default" => "Apex_code", "overrideable" => true, "dataType" => "picklist", "valuesToLabels" => array( "Db" => "Database", "Workflow" => "Workflow", "Validation" => "Validation", "Callout" => "Callout", "Apex_code" => "Apex Code", "Apex_profiling" => "Apex Profiling" ) ); $config["defaultLogCategoryLevel"] = array( "label" => "Default Log Level", "description" => "Default Log Level when displaying results from anonymous Apex execution. Defaults will not apply until after logging in again.", "default" => "DEBUG", "overrideable" => true, "dataType" => "picklist", "valuesToLabels" => array( "ERROR" => "Error", "WARN" => "Warn", "INFO" => "Info", "DEBUG" => "Debug", "FINE" => "Fine", "FINER" => "Finer", "FINEST" => "Finest" ) ); $config["header_Performance"] = array( "label" => "Performance Options", "display" => true, "isHeader" => true ); $config["cacheGetUserInfo"] = array( "label" => "Cache User Info", "description" => "Caches the results from the getUserInfo() API call. Improves performance of the Workbench in that user info does not need to be retrieved more than once, but not recommended if active session should be checked on each page load.", "default" => true, "overrideable" => true, "dataType" => "boolean" ); $config["cacheDescribeGlobal"] = array( "label" => "Cache Object Names", "description" => "Caches the results from the describeGlobal() API call. Improves performance of the Workbench in that object names do not need to be retrieved more than once. Recommened unless actively making changes to metadata of your Salesforce organization.", "default" => true, "overrideable" => true, "dataType" => "boolean" ); $config["cacheDescribeSObject"] = array( "label" => "Cache Object Descriptions", "description" => "Caches the results from the describeSobject() API calls. Improves performance of the Workbench in that the object descriptions and field names do not need to be retrieved more than once. Recommened unless actively making changes to metadata of your Salesforce organization.", "default" => true, "overrideable" => true, "dataType" => "boolean" ); $config["enableGzip"] = array( "label" => "Enable Compression", "description" => "Enables GZIP compression to improve performance of API call response time. Recommended to leave enabled unless SOAP capturing is necessary.", "default" => true, "overrideable" => true, "dataType" => "boolean" ); $config["batchSize"] = array( "label" => "Record Batch Size", "description" => "Number of records that are batched together in one API call. Recommended to leave at 200.", "default" => 200, "overrideable" => true, "dataType" => "int", "minValue" => 1, "maxValue" => 200 ); $config["maxFileSize"] = array( "label" => "Maxiumum File Size (bytes)", "description" => "Maximum file size for upload in bytes.", "default" => 512000, "overrideable" => false, "dataType" => "int" ); $config["maxFileLengthRows"] = array( "label" => "Maxiumum File Length (rows)", "description" => "Maximum file size for upload in number of CSV rows.", "default" => 2000, "overrideable" => false, "dataType" => "int" ); $config["header_proxyOptions"] = array( "label" => "Proxy Options", "display" => false, "isHeader" => true ); $config["proxyEnabled"] = array( "label" => "Connect with Proxy", "description" => "Check this box to use the proxy information below to connect to Salesforce.", "default" => false, "overrideable" => false, "dataType" => "boolean" ); $config["proxyHost"] = array( "label" => "Proxy Host", "description" => "Proxy Host", "default" => null, "overrideable" => false, "dataType" => "string" ); $config["proxyPort"] = array( "label" => "Proxy Port Number", "description" => "Proxy Port Number", "default" => null, "overrideable" => false, "dataType" => "int", "minValue" => 0, "maxValue" => 65536 ); $config["proxyUsername"] = array( "label" => "Proxy Username", "description" => "Proxy Username", "default" => null, "overrideable" => false, "dataType" => "string" ); $config["proxyPassword"] = array( "label" => "Proxy Password", "description" => "Proxy Password", "default" => null, "overrideable" => false, "dataType" => "password" ); ?> <file_sep><? include_once "accesscontrol.php"; if($action=="") { $q1 = "select * from job_plan"; $r1 = mysql_query($q1) or die(mysql_error()); ?> <body bgcolor="#00FF00"> <table align=center width=446 bgcolor="#FFFFFF"> <tr> <td colspan=2> To access all the features we offer, choose your Employer Plan:<br> </td> </tr> <? while($a1 = mysql_fetch_array($r1)) { if($a1[price] > 0) { echo " <tr> <td> <b>$a1[PlanName]</b> <ul> <li>Valid for $a1[numdays] days; </li> <li>$a1[postings] job postings; </li> <li>$a1[reviews] resume reviews; </li> <li><b>price: <font color=#000000>$ $a1[price] </font</b></li> </ul> </td> <td> <form action='$PHP_SELF?action=$active_account' method=post style='background:none;'> <input type=submit name=paypal value='Continue'> <input type=\"hidden\" name=\"plan_name\" value=\"$a1[PlanName]\"> <input type=\"hidden\" name=\"action\" value=\"$active_account\"> </form> </td> </tr>"; } else { echo " <tr> <td> <b>$a1[PlanName]</b> <ul> <li>Valid for $a1[numdays] days; </li> <li>$a1[postings] job postings; </li> <li>$a1[reviews] resume reviews; </li> <li><b>price: <font color=#000000>$ $a1[price] </font</b></li> </ul> </td> <td> <form action=pay2.php method=post style='background:none;'> <input type=hidden name=item_name value=\"$a1[PlanName]\"> <input type=hidden name=numdays value=\"$a1[numdays]\"> <input type=hidden name=price value=\"$a1[price]\"> <input type=submit value=\"Get if free\"> </form> </td>"; } } ?> </table> <? } if($action=='pp') { $time=time(); $q1 = "select * from job_plan where PlanName='$plan_name'"; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); print <<<HTML <center> <table width=446> <tr><td align=center>&nbsp;</td></tr> <tr><td align=center>&nbsp;</td></tr> <tr><td align=center>&nbsp;</td></tr> <tr><td align=center>&nbsp;</td></tr> <tr><td align=center><b>Click Here To Pay</b></td></tr> <tr><td align=center> <form action="https://www.paypal.com/cgi-bin/webscr" method="post" style="background:#FFFFFF"> <input type="hidden" name="cmd" value="_xclick"> <input type="hidden" name="business" value="$paypal_email_address"> <input type="hidden" name="item_name" value="$a1[PlanName]"> <input type="hidden" name="item_number" value="$ename"> <input type="hidden" name="amount" value="$a1[price]"> <input type="hidden" name="no_shipping" value="1"> <input type="hidden" name="no_note" value="1"> <input type="hidden" name="currency_code" value="USD"> <input type="hidden" name="return" value="http://$_SERVER[HTTP_HOST]/employers/pay22.php?plan=$a1[PlanName]&price=$a1[price]&epayname=$ename&act=success"> <input type="hidden" name="cancel_return" value="http://$_SERVER[HTTP_HOST]/employers/cancel.php"> <input type="image" src="http://$_SERVER[HTTP_HOST]/images/x-click-but01.gif" border="0" name="submit" alt="Make payments with PayPal - it's fast, free and secure!"> </form> </td></tr></table> </body> </html> HTML; }elseif($action=="tc") { $time=time(); $q1 = "select * from job_plan where PlanName='$plan_name'"; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); $crt_id=substr(md5($ename),0,12); $_SESSION["crt_id"]=$crt_id; print <<<HTML <center> <table width=446> <tr><td align=center>&nbsp;</td></tr> <tr><td align=center>&nbsp;</td></tr> <tr><td align=center>&nbsp;</td></tr> <tr><td align=center>&nbsp;</td></tr> <tr><td align=center><b>Click Here To Pay</b></td></tr> <tr><td align=center> <form action="https://www2.2checkout.com/2co/buyer/purchase" method="post" style="background:none"> <input type="hidden" name="cart_order_id" value="$crt_id" /> <input type="hidden" name="PlanName" value="$a1[PlanName]" /> <input type="hidden" value="$vendor_id" name="sid" /> <input type="hidden" name="total" value="$a1[price]" /> <input type="hidden" name="id_type" value="1" /> <input type="hidden" name="c_prod" value="$a1[PlanName],1" /> <input type="hidden" name="c_name" value="$a1[PlanName]" /> <input type="hidden" name="c_description" value="$a1[PlanName]" /> <input type="hidden" name="c_price" value="$a1[price]" /> <input type="hidden" name="x_Receipt_Link_URL" value="http://$_SERVER[HTTP_HOST]/employers/thanks.php"> <input type="hidden" name="return_url" value="http://$_SERVER[HTTP_HOST]/employers/cancel.php"> <input type="image" src="http://$_SERVER[HTTP_HOST]/images/2checkout.gif" name="submit" alt="Make payments with 2Checkout - it's fast,free and secure!"> </form> </td></tr></table> </body> </html> HTML; }elseif($action=="pptc") { $time=time(); $q1 = "select * from job_plan where PlanName='$plan_name'"; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); $crt_id=substr(md5($ename),0,12); $_SESSION["crt_id"]=$crt_id; print <<<HTML <center> <table width=446> <tr><td align=center>&nbsp;</td></tr> <tr><td align=center>&nbsp;</td></tr> <tr><td align=center>&nbsp;</td></tr> <tr><td align=center>&nbsp;</td></tr> <tr><td align=center><b>Click Here To Pay</b></td></tr> <tr><td align=center> <form action="https://www2.2checkout.com/2co/buyer/purchase" method="post" style="background:none"> <input type="hidden" name="cart_order_id" value="$crt_id" /> <input type="hidden" name="PlanName" value="$a1[PlanName]" /> <input type="hidden" value="$vendor_id" name="sid" /> <input type="hidden" name="total" value="$a1[price]" /> <input type="hidden" name="id_type" value="1" /> <input type="hidden" name="c_prod" value="$a1[PlanName],1" /> <input type="hidden" name="c_name" value="$a1[PlanName]" /> <input type="hidden" name="c_description" value="$a1[PlanName]" /> <input type="hidden" name="c_price" value="$a1[price]" /> <input type="hidden" name="x_Receipt_Link_URL" value="http://$_SERVER[HTTP_HOST]/employers/thanks.php"> <input type="hidden" name="return_url" value="http://$_SERVER[HTTP_HOST]/employers/cancel.php"> <input type="image" src="http://$_SERVER[HTTP_HOST]/images/2checkout.gif" name="submit" alt="Make payments with 2Checkout - it's fast,free and secure!"> </form> </td></tr></table> </body> </html> HTML; $time=time(); $q1 = "select * from job_plan where PlanName='$plan_name'"; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); print <<<HTML <center> <table width=446> <tr><td align=center>&nbsp;</td></tr> <tr><td align=center>&nbsp;</td></tr> <tr><td align=center>&nbsp;</td></tr> <tr><td align=center>&nbsp;</td></tr> <tr><td align=center><b>Click Here To Pay</b></td></tr> <tr><td align=center> <form action="https://www.paypal.com/cgi-bin/webscr" method="post" style="background:#FFFFFF"> <input type="hidden" name="cmd" value="_xclick"> <input type="hidden" name="business" value="$paypal_email_address"> <input type="hidden" name="item_name" value="$a1[PlanName]"> <input type="hidden" name="item_number" value="$ename"> <input type="hidden" name="amount" value="$a1[price]"> <input type="hidden" name="no_shipping" value="1"> <input type="hidden" name="no_note" value="1"> <input type="hidden" name="currency_code" value="USD"> <input type="hidden" name="return" value="http://$_SERVER[HTTP_HOST]/employers/pay22.php?plan=$a1[PlanName]&price=$a1[price]&epayname=$ename&act=success"> <input type="hidden" name="cancel_return" value="http://$_SERVER[HTTP_HOST]/employers/cancel.php"> <input type="image" src="http://$_SERVER[HTTP_HOST]/images/x-click-but01.gif" border="0" name="submit" alt="Make payments with PayPal - it's fast, free and secure!"> </form> </td></tr></table> </body> </html> HTML; } include_once('../foother.html'); ?><file_sep><? include_once "accesscontrol.php"; ?> <? if($price == '0') { $qp = "select free, CompanyEmail from job_employer_info where ename = \"$ename\" "; $rp = mysql_query($qp) or die(mysql_error()); $ap = mysql_fetch_array($rp); if($ap[0] == '1') { echo "<table width=446><tr><td><br><br><br><center> You have already used your free trail. <br> Now you know how powerfull our system is.<br> To place a job posting please choose from one<br> of our plans.<br><br>Please, go <a class=TN href=pay1.php> back </a> and choose a plan. <br><br>Thank you.</center></td></tr></table>"; include ("../foother.html"); exit; } else { $qu = "update job_employer_info set free = '1' "; $ru = mysql_query($qu) or die(mysql_error()); } // generate EXPIRY DATE for the number of days $expireon = mktime(0, 0, 0, date("m") , date("d")+$numdays, date("Y")); $expireond=date("d M Y",$expireon); $q1 = "update job_employer_info set plan = \"$plan\", expiryplan='". date("Y-m-d",$expireon)."', JS_number = \"$reviews\", JP_number = \"$postings\" where ename = \"$ename\""; //echo $q1; $r1 = mysql_query($q1) or die(mysql_error()); $to = "$ap[1]"; $subject = "Your employer plan at $site_name"; $message = " Hello,\n here is your employer plan information at $site_name:\n\n Plan name: $plan\n Number of resume viewing: $reviews\n Number of Job Offer postings: $postings\n\n $site_name/resume/resume2 Team"; $from = "From: $email_address"; mail($to, $subject, $message, $from); echo "<table width=446><tr><td><br><br><br><center> Now you can view <strong>$reviews</strong> resumes<br> and can post job <strong>$postings</strong> offers for $numdays days, your package will expire on $expireond. </center></td></tr></table>"; } ?> <? include_once('../foother.html'); ?><file_sep><? include_once "accesscontrol.php"; $WE_d = strip_tags($WE_d); $d1 = array(); $d1[0] = $WSmonth; $d1[1] = $WSyear; if (is_array($d1)) { $WE_Start = implode("/" , $d1); } $d2 = array(); $d2[0] = $WEmonth; $d2[1] = $WEyear; if (is_array($d2)) { $WE_End = implode("/" , $d2); } $WE_p = stripslashes($WE_p); $q1 = "update job_work_experience set WE_Start = \"$WE_Start\", WE_End = \"$WE_End\", WE_p = \"$WE_p\", WE_d = \"$WE_d\" where uname = \"$uname\" and WEn = \"$WEn\""; $r2 = mysql_query($q1) or die(mysql_error()); include "ER3.php"; ?> <file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; include_once "navigation.html"; $q1 = "select * from job_banners_m"; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); $a = $a1[0]; global $a; if($a == '1') { $ch = 'banners'; } elseif($a == '2') { $ch = 'link codes'; } ?> <center><br>At the banner management system you can use banners or link exchange codes. <br> At this time you are using <b> <? if (empty($a)) { echo 'nothing'; } else { echo $ch; } ?></b>. If you want to change this, click on your choice:<br> <b>What will you use: <br><a class=links2 href=ych2.php?nch=banners&b=<?=$a?>> banners </a> OR <a class=links2 href=ych2.php?nch=linkcodes&b=<?=$a?>> link codes </a></b></center> <br><center> You have these banners: </center> <? include_once "manage_banners.php" ?> <center>You have these links: </center> <? include_once "manage_links.php" ?> <? include("../foother.html"); ?> <file_sep><?php // Load all the application config settings $query = mysql_query("SELECT name, value FROM config"); while($row = mysql_fetch_array($query)){ $GLOBALS["config"][ $row["name"] ] = $row["value"]; } $locale = $GLOBALS["config"]["locale"]; bindtextdomain($locale, './locale'); bind_textdomain_codeset($locale, 'UTF-8'); textdomain($locale); setlocale(LC_ALL,$locale); /* Defining the ToDo class */ class ToDo{ /* An array that stores the item data: */ private $data; /* The constructor */ public function __construct($par){ if(is_array($par)) $this->data = $par; } /* This is an in-build "magic" method that is automatically called by PHP when we output the Item objects with echo. */ public function __toString(){ // The string we return is outputted by the echo statement if ( $this->data['date_created'] == '') { $date_created = date($GLOBALS["config"]["date_format"].' '.$GLOBALS["config"]["time_format"]); } else $date_created = date($GLOBALS["config"]["date_format"].' '.$GLOBALS["config"]["time_format"], strtotime($this->data['date_created'])); if ( $this->data['date_completed'] == '') { $date_completed = ''; return ' <li id="Item-'.$this->data['id'].'" class="item">' .ToDo::showDate($GLOBALS["show_item_date"],$this->data).' <div class="text">'.$this->data['text'].'</div> <div class="dateCreated">'.$date_created.'</div> <div class="dateCompleted">'.$date_completed.'</div> </li>'; } else { $date_completed = date($GLOBALS["config"]["date_format"].' '.$GLOBALS["config"]["time_format"], strtotime($this->data['date_completed'])); $build_item = ' <li id="Item-'.$this->data['id'].'" class="item">' .ToDo::completedItemClasses() .ToDo::showDate($GLOBALS["show_item_date"],$this->data) .$this->data['text'].'</div> <div class="dateCreated">'.$date_created.'</div> <div class="dateCompleted">'.$date_completed.'</div> </li>'; return $build_item; } } private static function showDate($show_item_date,$data) { if ($data['date_created'] == '') $data['date_created'] = date($GLOBALS["config"]["date_format"]); else $data['date_created'] = date($GLOBALS["config"]["date_format"], strtotime($data['date_created'])); if ($show_item_date) return '<span class="showDate">'.$data['date_created'].'</span>'; } private static function completedItemClasses(){ $itemClasses = ''; if (in_array($GLOBALS["config"]["completed_item"],array(4,5,6,12,7,13,14,15))) $itemClasses .= '<span class="checkmark"></span>'; $itemClasses .= '<div class="text '; if (in_array($GLOBALS["config"]["completed_item"],array(1,3,5,9,7,13,11,15))) $itemClasses .= 'strikethrough'; if (in_array($GLOBALS["config"]["completed_item"],array(2,3,6,10,7,11,14,15))) $itemClasses .= ' italic'; if (in_array($GLOBALS["config"]["completed_item"], array(8,9,10,12,11,13,14,15))) $itemClasses .= ' gray'; $itemClasses .= '">'; return $itemClasses; } /* The following are static methods. These are available directly, without the need of creating an object. */ /* The tabs method queries for all the tab tabs in the database and returns it JSON encoded. */ public static function tabs(){ // Select all the tabs: $query = mysql_query(" SELECT * FROM tabs WHERE trash = 0 ORDER BY position ASC "); $tabs = array(); // Filling the $tabs array with tab objects: while($row = mysql_fetch_assoc($query)){ $tabs[] = $row; } array_walk($tabs, 'ToDo::formatDate'); echo json_encode($tabs); exit; } // close tabs method /* The formatDate method goes throgh the array and formats the date as specified in the application settings */ private static function formatDate(&$item) { if ($item['date_created']) $item['date_created'] = date($GLOBALS["config"]["date_format"].' '.$GLOBALS["config"]["time_format"], strtotime($item['date_created'])); } /* The pages method queries for all the pages in the database and returns it JSON encoded. */ public static function pages($tab_id){ // Select all the pages: $query = mysql_query(" SELECT * FROM pages WHERE tab_id = $tab_id AND trash = 0 ORDER BY position ASC "); $pages = array(); // Filling the $pages array with new page objects: while($row = mysql_fetch_assoc($query)){ $pages[] = $row; } array_walk($pages, 'ToDo::formatDate'); echo json_encode($pages); exit; } // close pages method public static function lists($page_id){ // Select all the lists: $query = mysql_query(" SELECT * FROM lists WHERE page_id = $page_id AND trash = 0 ORDER BY column_id, position ASC "); $lists = array(); // Filling the $lists array with new list objects: while($row = mysql_fetch_assoc($query)){ $lists[] = $row; } array_walk($lists, 'ToDo::formatDate'); // Select how many columns for page $query_columns = mysql_query(" SELECT columns FROM pages WHERE page_id = $page_id "); $columns = mysql_fetch_array($query_columns); $num_columns = $columns[0]; echo ' <div id="tabData"> '; for ($columns =1; $columns <=$num_columns; ++$columns) { echo '<ul id="Column-'.$columns.'" class="column column-'.$num_columns.'">'; ToDo::buildList($lists, $columns); echo '</ul> <!-- close column -->'; } // close foreach columns echo '</div>'; echo "<script type='text/javascript'> $(document).ready(function(){ itemContextMenu(); listContextMenu(); tabContextMenu(); pageContextMenu(); $('.settings').nojeegoocontext(); // prevent the contextmenu from working on the Settings Page makeItemsSortable(); makeListsSortable(); });</script>"; exit; } private static function buildList($lists = array(), $columns, $ECHO = true) { foreach($lists as $i => $value) { $GLOBALS["show_item_date"] = $lists[$i]['show_item_date']; if($lists[$i]['column_id'] <> $columns) continue; $listID = $lists[$i]['list_id']; $display = ''; if($lists[$i]['expanded'] == 0) $display = "none"; if ($ECHO) echo ' <li id="List-'.$listID.'" class="sortableList"> <ul id="List-'.$listID.'" class="list"> <div id="List-'.$listID.'" class="listTitle"> <abbr title="'._('New Item').'" class="notebookIcons newItem" onclick=myCallback(this)></abbr> <div class="listName" onclick=myCallback(this)>'.$lists[$i]["name"].'</div> <div class="listCreated">'.$lists[$i]["date_created"].'</div> <div class="showItemDate">'.$lists[$i]["show_item_date"].'</div> </div> <!-- close listTitle --> <div id="List-'.$listID.'" class="listBody" style="display:'.$display.'"> '; //close echo // Select all the items, ordered by position: $query = mysql_query(" SELECT * FROM items WHERE list_id = $listID AND trash = 0 ORDER BY position ASC "); $items = array(); // Filling the $items array with new item objects: while($row = mysql_fetch_assoc($query)){ $items[] = new ToDo($row); } // Looping and outputting the $items array. The __toString() method // is used internally to convert the objects to strings: foreach($items as $item){ if ($ECHO) echo $item; } if ($ECHO) echo ' </div> <!-- close listBody --> </ul> <!-- close list --> </li> <!-- close sortableList --> '; if ($ECHO) echo "\n\n"; } // close foreach lists } /* The newItem method takes only the text of the item, writes to the databse and outputs the new item back to the AJAX front-end. */ public static function newItem($list_id,$show_item_date){ $GLOBALS["show_item_date"] = intval($show_item_date); $posResult = mysql_query("SELECT MAX(position)+1 FROM items WHERE list_id = $list_id"); $text = _('Double-click to edit'); if(mysql_num_rows($posResult)) list($position) = mysql_fetch_array($posResult); if(!$position) $position = 1; mysql_query("INSERT INTO items SET text='$text', position = $position, list_id = $list_id"); if(mysql_affected_rows($GLOBALS['link'])!=1) throw new Exception("Error inserting item!"); // Creating a new item and outputting it directly: echo (new ToDo(array( 'id' => mysql_insert_id($GLOBALS['link']), 'text' => $text, 'date_created'=> '', 'date_completed'=> '' ))); exit; } /* The editItem method takes the item id and the new text of the item. Updates the database. */ public static function editItem($id, $text){ // $text = self::esc($text); if(!$text) throw new Exception("Wrong update text!"); mysql_query(" UPDATE items SET text='".$text."' WHERE id=".$id ); if(mysql_affected_rows($GLOBALS['link'])!=1) throw new Exception("Couldn't update item!"); } /* The markDeleteItem method. Takes the id of the item and sets the trash field to 1. */ public static function markDeleteItem($id){ mysql_query("UPDATE items set trash = 1 WHERE id=".$id); if(mysql_affected_rows($GLOBALS['link'])!=1) throw new Exception("Couldn't delete item!"); } /* The delete method. Takes the id of the item and deletes it from the database. */ public static function delete($id){ mysql_query("DELETE FROM items WHERE id=".$id); if(mysql_affected_rows($GLOBALS['link'])!=1) throw new Exception("Couldn't delete item!"); } /* The rearrangeItems method is called when the ordering of the items is changed. Takes an array parameter, which contains the ids of the items in the new order. */ public static function rearrangeItems($key_value){ $updateVals = array(); foreach($key_value as $k=>$v) { $strVals[] = 'WHEN '.(int)$v.' THEN '.((int)$k+1).PHP_EOL; } if(!$strVals) throw new Exception("No data!"); // We are using the CASE SQL operator to update the item positions en masse: mysql_query(" UPDATE items SET position = CASE id ".join($strVals)." ELSE position END"); if(mysql_error($GLOBALS['link'])) throw new Exception("Error updating positions!"); } /* The changeList method takes the item id and the new list ID of the ToDo. Updates the database. */ public static function changeList($id, $list_id){ if(!$list_id) throw new Exception("Wrong update text!"); mysql_query(" UPDATE items SET list_id='".$list_id."' WHERE id=".$id ); if(mysql_affected_rows($GLOBALS['link'])!=1) throw new Exception("Couldn't update item!"); } /* The taskComplete method takes the item id and the current datetime and Updates the database. */ public static function taskComplete($id, $value){ mysql_query(" UPDATE items SET date_completed=".$value." WHERE id=".$id ); if(mysql_affected_rows($GLOBALS['link'])!=1) throw new Exception("Couldn't update item!"); $query = mysql_query("SELECT date_completed from items WHERE id=".$id); while($row = mysql_fetch_assoc($query)){ $date_completed = $row['date_completed']; } echo date($GLOBALS["config"]["date_format"].' '.$GLOBALS["config"]["time_format"], strtotime($date_completed)); exit; } /* The newList method creates a new list and updates the database. */ public static function newList($page_id){ $listName = _('New List'); mysql_query("INSERT INTO lists SET name='".$listName."', column_id = '1', position = '0', page_id = $page_id"); if(mysql_affected_rows($GLOBALS['link'])!=1) throw new Exception("Couldn't update item!"); $listID = mysql_insert_id(); $date_created = date($GLOBALS["config"]["date_format"].' '.$GLOBALS["config"]["time_format"]); echo ' <li id="List-'.$listID.'" class="sortableList"> <ul id="List-'.$listID.'" class="list"> <div id="List-'.$listID.'" class="listTitle"> <abbr title="'._('New Item').'" class="notebookIcons newItem" onclick=myCallback(this)></abbr> <div class="listName" onclick=myCallback(this)>'.$listName.'</div> <div class="listCreated">'.$date_created.'</div> <div class="showItemDate">0</div> </div> <!-- close listTitle --> <div id="List-'.$listID.'" class="listBody"> </div> <!-- close listBody --> </ul> <!-- close list --> </li> '; exit; } /* The editList method takes the List id and the new name of the list and updates the database. */ public static function editList($id, $text){ $text = self::esc($text); if(!$text) throw new Exception("Wrong update text!"); mysql_query(" UPDATE lists SET name='".$text."' WHERE list_id=".$id ); if(mysql_affected_rows($GLOBALS['link'])!=1) throw new Exception("Couldn't update item!"); } /* The markDeleteList method. Takes the id of the List item and sets trash field to 1. */ public static function markDeleteList($id){ mysql_query("UPDATE lists set trash = 1 WHERE list_id=".$id); } /* The deleteList method. Takes the id of the List item and deletes it from the database. Then matches all items and deletes them from the database. */ public static function deleteList($id){ mysql_query("DELETE FROM lists WHERE list_id=".$id); mysql_query("DELETE FROM items WHERE list_id=".$id); } /* The rearrangeLists method is called when the ordering of the tabs is changed. Takes an array parameter, which contains the ids of the tabs in the new order. */ public static function rearrangeLists($key_value){ $updateVals = array(); foreach($key_value as $k=>$v) { $strVals[] = 'WHEN '.(int)$v.' THEN '.((int)$k+1).PHP_EOL; } if(!$strVals) throw new Exception("No data!"); // We are using the CASE SQL operator to update the list positions en masse: mysql_query(" UPDATE lists SET position = CASE list_id ".join($strVals)." ELSE position END"); if(mysql_error($GLOBALS['link'])) throw new Exception("Error updating positions!"); } /* The changeColumn method takes the List id and the new column ID of the List. Updates the database. */ public static function changeColumn($list_id, $column_id){ if(!$list_id) throw new Exception("Wrong update text!"); mysql_query(" UPDATE lists SET column_id='".$column_id."' WHERE list_id=".$list_id ); if(mysql_affected_rows($GLOBALS['link'])!=1) throw new Exception("Couldn't update item!"); } /* The listToggleExpanded method checks the current setting, toggles it and updates the database. */ public static function listToggleExpanded($id){ $query = mysql_query("Select expanded from lists WHERE list_id=".$id); while($row = mysql_fetch_assoc($query)){ $expanded = $row['expanded']; } if($expanded == 0) mysql_query("UPDATE lists set expanded = 1 WHERE list_id=".$id); if($expanded == 1) mysql_query("UPDATE lists set expanded = 0 WHERE list_id=".$id); if(mysql_affected_rows($GLOBALS['link'])!=1) throw new Exception("Couldn't update item!"); } /* The listExpanded method sets the list to expaned and updates the database. */ public static function listExpanded($id){ mysql_query("UPDATE lists set expanded = 1 WHERE list_id=".$id); if(mysql_affected_rows($GLOBALS['link'])!=1) throw new Exception("Couldn't update item!"); } /* The duplicateList method takes a source list_id and creates a new list with the same name and items. */ public static function duplicateList($id, $newPageID = ''){ $queryList = mysql_query("SELECT * FROM lists WHERE list_id=".$id); while($row = mysql_fetch_assoc($queryList)){ $name = $row['name']; $page_id = $row['page_id']; if ($newPageID != '') $page_id = $newPageID; $column_id = $row['column_id']; $expanded = $row['expanded']; $show_item_date = $row['show_item_date']; mysql_query("INSERT INTO lists (name, page_id, column_id, expanded, show_item_date) VALUES ('".$name."',".$page_id.",".$column_id.",".$expanded.",".$show_item_date.")"); $newListID = mysql_insert_id(); $queryItems = mysql_query("SELECT * FROM items WHERE list_id=".$id." AND trash = 0"); while($rowItems = mysql_fetch_assoc($queryItems)){ mysql_query("INSERT INTO items set list_id = ".$newListID.", text = '".$rowItems['text']."', position= ".$rowItems['position']); } $lists = array(array( 'list_id' => $newListID, 'name' => $row['name'], 'column_id' => $row['column_id'], 'date_created' => $row['date_created'], 'expanded' => $row['expanded'], 'show_item_date' => $row['show_item_date'] )); if ($newPageID != '') ToDo::buildList($lists, $row['column_id'], false); if ($newPageID == '') ToDo::buildList($lists, $row['column_id']); } if ($newPageID == '') exit; } public static function showItemDate($id,$value) { mysql_query("update lists set show_item_date = $value where list_id = $id"); } /* The newTab method creates a new tab and updates the database. */ public static function newTab(){ mysql_query("INSERT INTO tabs SET name= '"._('New Tab')."'"); if(mysql_affected_rows($GLOBALS['link'])!=1) throw new Exception("Couldn't update item!"); $tab_id = mysql_insert_id(); // set the position of the newly created tab to its id so that it is last in the order mysql_query("UPDATE tabs SET position=".$tab_id." WHERE tab_id=".$tab_id); mysql_query("INSERT INTO pages SET name = '"._('Main Page')."', tab_id = $tab_id, position = 1"); ToDo::returnTab($tab_id, false); exit; } public static function returnTab($tab_id, $exit = true) { // Select the new tab: $query = mysql_query("SELECT * FROM tabs where tab_id = $tab_id"); $tabs = array(); // Filling the $tabs array with tab objects: while($row = mysql_fetch_assoc($query)){ $tabs[] = $row; } echo json_encode($tabs); if ($exit) exit; } /* The editTab method takes the Tab id and the new name of the tab and updates the database. */ public static function editTab($id, $text){ $text = self::esc($text); if(!$text) throw new Exception("Wrong update text!"); mysql_query(" UPDATE tabs SET name='".$text."' WHERE tab_id=".$id ); if(mysql_affected_rows($GLOBALS['link'])!=1) throw new Exception("Couldn't update item!"); } /* The markDeleteTab method takes the tab id and sets the trash field to 1. */ public static function markDeleteTab($id){ mysql_query("UPDATE tabs set trash = 1 WHERE tab_id=".$id); if(mysql_affected_rows($GLOBALS['link'])!=1) throw new Exception("Couldn't delete item!"); } /* The deleteTab method takes the id of the current Tab and matches all Pages, Lists and Items that belong to that tab and deletes them from the database. */ public static function deleteTab($id){ $queryPages = mysql_query("Select page_id from pages WHERE tab_id=".$id); while($rowPages = mysql_fetch_assoc($queryPages)){ $queryLists = mysql_query("Select list_id from lists WHERE page_id=".$rowPages['page_id']); while($rowLists = mysql_fetch_assoc($queryLists)){ mysql_query("DELETE FROM items WHERE list_id=".$rowLists['list_id']); } mysql_query("DELETE FROM lists WHERE page_id=".$rowPages['page_id']); } mysql_query("DELETE FROM pages WHERE tab_id=".$id); mysql_query("DELETE FROM tabs WHERE tab_id=".$id); if(mysql_affected_rows($GLOBALS['link'])!=1) throw new Exception("Couldn't delete item!"); } /* The rearrangeTabs method is called when the ordering of the tabs is changed. Takes an array parameter, which contains the ids of the tabs in the new order. */ public static function rearrangeTabs($key_value){ $updateVals = array(); foreach($key_value as $k=>$v) { $strVals[] = 'WHEN '.(int)$v.' THEN '.((int)$k+1).PHP_EOL; } if(!$strVals) throw new Exception("No data!"); // We are using the CASE SQL operator to update the Tab positions en masse: mysql_query(" UPDATE tabs SET position = CASE tab_id ".join($strVals)." ELSE position END"); if(mysql_error($GLOBALS['link'])) throw new Exception("Error updating positions!"); } /* Move a list from one tab to another */ public static function dropListOnTab($listID, $tabID) { $query = mysql_query("Select page_id from pages WHERE tab_id = $tabID and position = 1"); while($row = mysql_fetch_assoc($query)){ $pageID = $row['page_id']; } mysql_query(" UPDATE lists SET position = 0, column_id = 1, page_id = $pageID WHERE list_id = $listID"); } /* Move a page from one tab to another */ public static function dropPageOnTab($pageID, $tabID) { mysql_query(" UPDATE pages SET position = 0, tab_id = $tabID WHERE page_id = $pageID"); } /* The duplicateTab method takes a source tab_id and creates a new tab with the same name, pages, lists and items. */ public static function duplicateTab($id){ $query = mysql_query("SELECT * FROM tabs WHERE tab_id=".$id); while ($row = mysql_fetch_assoc($query)){ mysql_query("INSERT INTO tabs set name = '".$row['name']."' "); $newTabID = mysql_insert_id(); mysql_query("update tabs set position = $newTabID where tab_id = $newTabID"); echo $newTabID; ToDo::duplicateTabPages($id, $newTabID); } exit; } public static function duplicateTabPages($id, $newTabID) { $queryPage = mysql_query("SELECT page_id FROM pages WHERE tab_id=".$id." AND trash = 0"); while($rowPage = mysql_fetch_assoc($queryPage)){ $page_id = $rowPage['page_id']; ToDo::duplicatePage($page_id, $newTabID); } exit; } /* The newPage method creates a new page and updates the database. */ public static function newPage($tab_id){ mysql_query("INSERT INTO pages SET name='"._('New Page')."', tab_id = $tab_id"); if(mysql_affected_rows($GLOBALS['link'])!=1) throw new Exception("Couldn't update item!"); $page_id = mysql_insert_id(); // set the position of the newly created tab to its id so that it is last in the order mysql_query("UPDATE pages SET position= $page_id WHERE page_id= $page_id"); ToDo::returnPage($page_id, false); exit; } /* the returnPage private method takes the page_id and echos the JSON encoded data */ public static function returnPage($page_id, $exit = true) { // Select the new page: $query = mysql_query("SELECT * FROM pages where page_id = $page_id"); $pages = array(); // Filling the $tabs array with tab objects: while($row = mysql_fetch_assoc($query)){ $pages[] = $row; } echo json_encode($pages); if($exit) exit; } /* The editPage method takes the Page id and the new name of the page and updates the database. */ public static function editPage($page_id, $text){ $text = self::esc($text); if(!$text) throw new Exception("Wrong update text!"); mysql_query(" UPDATE pages SET name='".$text."' WHERE page_id= $page_id" ); if(mysql_affected_rows($GLOBALS['link'])!=1) throw new Exception("Couldn't update item!"); } /* The markDeletePage method takes the page id and sets the trash field to 1. */ public static function markDeletePage($page_id){ mysql_query("UPDATE pages set trash = 1 WHERE page_id=".$page_id); if(mysql_affected_rows($GLOBALS['link'])!=1) throw new Exception("Couldn't delete item!"); } /* The deletePage method. Takes the id of the current Page and deletes it from the database. Then matches all Lists that belong to that page and deletes them from the database. */ public static function deletepage($page_id){ $query = mysql_query("Select list_id from lists WHERE page_id = $page_id"); while($row = mysql_fetch_assoc($query)){ mysql_query("DELETE FROM items WHERE list_id=".$row['list_id']); } mysql_query("DELETE FROM lists WHERE page_id = $page_id"); mysql_query("DELETE FROM pages WHERE page_id = $page_id"); if(mysql_affected_rows($GLOBALS['link'])!=1) throw new Exception("Couldn't delete item!"); } /* The rearrangePages method is called when the ordering of the pages is changed. Takes an array parameter, which contains the ids of the pages in the new order. */ public static function rearrangePages($key_value){ $updateVals = array(); foreach($key_value as $k=>$v) { $strVals[] = 'WHEN '.(int)$v.' THEN '.((int)$k+1).PHP_EOL; } if(!$strVals) throw new Exception("No data!"); // We are using the CASE SQL operator to update the Page positions en masse: mysql_query(" UPDATE pages SET position = CASE page_id ".join($strVals)." ELSE position END"); if(mysql_error($GLOBALS['link'])) throw new Exception("Error updating positions!"); } /* Move a list from one page to another */ public static function dropListOnPage($listID, $pageID) { mysql_query(" UPDATE lists SET position = 0, column_id = 1, page_id = $pageID WHERE list_id = $listID"); } /* The duplicatePage method takes a source page_id and creates a new page with the same name, lists and items. */ public static function duplicatePage($id, $newTabID = ''){ $query = mysql_query("SELECT * FROM pages WHERE page_id=".$id); while ($row = mysql_fetch_assoc($query)){ $name = $row['name']; $tab_id = $row['tab_id']; if ($newTabID != '') $tab_id = $newTabID; mysql_query("INSERT INTO pages (name, tab_id) VALUES ('".$name."',".$tab_id.")"); $newPageID = mysql_insert_id(); mysql_query("update pages set position = $newPageID where page_id = $newPageID"); if ($newTabID == '') echo $newPageID; ToDo::duplicatePageLists($id, $newPageID); } if ( $newTabID == '') exit; } public static function duplicatePageLists($id, $newPageID) { $queryList = mysql_query("SELECT list_id FROM lists WHERE page_id=".$id." AND trash = 0"); while($rowList = mysql_fetch_assoc($queryList)){ $list_id = $rowList['list_id']; ToDo::duplicateList($list_id, $newPageID); } } public static function columnsPerPage($id, $columns) { mysql_query("UPDATE pages set columns = $columns WHERE page_id = $id"); if ($columns == 2) mysql_query("UPDATE lists set column_id = 2 WHERE page_id = $id AND column_id = 3"); if ($columns == 1) mysql_query("UPDATE lists set column_id = 1 WHERE page_id = $id"); } /* Delete all items in trash */ public static function emptyTrash() { // select all the tabs in trash and delete them $query = mysql_query(" SELECT tab_id FROM tabs WHERE trash = 1 "); while($row = mysql_fetch_assoc($query)){ ToDo::deleteTab($row['tab_id']); } // select all the pages in trash and delete them $query = mysql_query(" SELECT page_id FROM pages WHERE trash = 1 "); while($row = mysql_fetch_assoc($query)){ ToDo::deletePage($row['page_id']); } // select all the lists in trash and delete them $query = mysql_query(" SELECT list_id FROM lists WHERE trash = 1 "); while($row = mysql_fetch_assoc($query)){ echo $row['list_id']."<br />"; ToDo::deleteList($row['list_id']); } // select all the items in trash and delete them $query = mysql_query(" SELECT id FROM items WHERE trash = 1 "); while($row = mysql_fetch_assoc($query)){ ToDo::delete($row['id']); } } /* Delete selected objects from trash */ public static function deleteSelected($stringIDs) { $arrayIDs = explode(",",$stringIDs); $tabIDs = array_filter($arrayIDs, "ToDo::tabIDFilter"); $pageIDs = array_filter($arrayIDs, "ToDo::pageIDFilter"); $listIDs = array_filter($arrayIDs, "ToDo::listIDFilter"); $itemIDs = array_filter($arrayIDs, "ToDo::itemIDFilter"); if (count($tabIDs > 0)) { foreach($tabIDs as $tab_id) { ToDo::deleteTab(str_replace("Tab-","", $tab_id)); } } if (count($pageIDs > 0)) { foreach($pageIDs as $page_id) { ToDo::deletePage(str_replace("Page-","", $page_id)); } } if (count($listIDs > 0)) { foreach($listIDs as $list_id) { ToDo::deleteList(str_replace("List-","", $list_id)); } } if (count($itemIDs > 0)) { foreach($itemIDs as $item_id) { ToDo::delete(str_replace("Item-","", $item_id)); } } } /* Restore selected objects from trash */ public static function restoreSelected($stringIDs) { $arrayIDs = explode(",",$stringIDs); $tabIDs = array_filter($arrayIDs, "ToDo::tabIDFilter"); $pageIDs = array_filter($arrayIDs, "ToDo::pageIDFilter"); $listIDs = array_filter($arrayIDs, "ToDo::listIDFilter"); $itemIDs = array_filter($arrayIDs, "ToDo::itemIDFilter"); if (count($tabIDs > 0)) { foreach($tabIDs as $tab_id) { mysql_query("UPDATE tabs SET trash = 0 where tab_id = ".str_replace("Tab-","", $tab_id)); } } if (count($pageIDs > 0)) { foreach($pageIDs as $page_id) { mysql_query("UPDATE pages SET trash = 0 where page_id = ".str_replace("Page-","", $page_id)); } } if (count($listIDs > 0)) { foreach($listIDs as $list_id) { mysql_query("UPDATE lists SET trash = 0 where list_id = ".str_replace("List-","", $list_id)); } } if (count($itemIDs > 0)) { foreach($itemIDs as $id) { mysql_query("UPDATE items SET trash = 0 where id = ".str_replace("Item-","", $id)); } } } /* Filter functions are used separate ID for tabs, pages, lists and items from a mixed string */ private static function tabIDFilter($str) { if (strstr($str, "Tab-")) return true; } private static function pageIDFilter($str) { if (strstr($str, "Page-")) return true; } private static function listIDFilter($str) { if (strstr($str, "List-")) return true; } private static function itemIDFilter($str) { if (strstr($str, "Item-")) return true; } /* The convertDateForMySQL method takes the user inputed date and converts it to MySQL compatibale date based on what the date format preference is set to. */ private static function convertDateForMySQL($date) { if ($GLOBALS["config"]["date_format"] == 'Y-m-d') { $date = date('Y-m-d H:i', strtotime($date)); return $date; } if ($GLOBALS["config"]["date_format"] == 'm-d-Y') { $time = substr($date,10); $newDate = str_replace($time,"",$date); $dateArray = explode("-",$newDate); $m = $dateArray[0]; $d = $dateArray[1]; $y = $dateArray[2]; $newDate = $y.'-'.$m.'-'.$d.$time; $date = date('Y-m-d H:i', strtotime($newDate)); return $date; } if ($GLOBALS["config"]["date_format"] == 'd-m-Y'){ $date = date('Y-m-d H:i', strtotime($date)); return $date; } } public static function updateDate($table, $id, $dateField, $date){ if ($table == 'items') $idField = 'id'; if ($table == 'lists') $idField = 'list_id'; if ($table == 'pages') $idField = 'page_id'; if ($table == 'tabs') $idField = 'tab_id'; $date = ToDo::convertDateForMySQL($date); mysql_query("update ".$table." set ".$dateField." = '".$date."' where ".$idField." = ".$id); exit; } /* A helper method to sanitize a string: */ public static function esc($str){ if(ini_get('magic_quotes_gpc')) $str = stripslashes($str); return mysql_real_escape_string(strip_tags($str)); } } // closing the class definition <file_sep><? include_once('main.php'); ?> <table border="0" cellpadding="0" cellspacing="0" width="446" align="center"> <tr valign="top"> <td class="w" style="padding-left:10px;padding-top:10px;"> <p><font face="Arial, Helvetica, sans-serif" size="4"><b><i><font color="#000000">Terms & Conditions </font></i></b></font></p> <p align="left"><font size="2" face="Arial, Helvetica, sans-serif" color="#000000"> <b>1. Definitions</b><br>In these conditions the following words and expressions shall have the following meanings: <ul> <li><strong>Client Microsite</strong> means any material posted on the Site for you or on your behalf, including The Corporate Recruiter or Corporate outsource products and /or Corporate Pages, Job Slots, Banners and News Stories as set out in the Sales Order,</li> <li><strong>Job Slot</strong> means a display advertisement space on the Client Microsite,</li> <li><strong>Sales Order</strong> means the order placed by the Buyer with us for Services,</li> <li><strong>Services</strong> means the services which are set out in the Sales Order,</li> <li><strong>Site</strong> means the Internet website specified on the Sales Order or such other website which we may designate,</li> <li><strong>Standard Rolling Contract</strong> shall have the meanings described in the Sales Order,</li> <li><strong>Terms</strong> means these terms and conditions of sale,</li> <li><strong>We/Us</strong> means topjobs.co.uk Ltd,</li> <li><strong>You</strong> means the company, firm or person signing the Sales Order.</li> </ul> <a href="http://www.topjobs.co.uk/net/terms.aspx">http://www.topjobs.co.uk/net/terms.aspx</a><br>OR<br> <a href="http://www.monster.co.uk/terms/">http://www.monster.co.uk/terms/</a><br><br> <b>The Way We Use Information</b><br> &nbsp;<br> We use the information you provide about yourself or others to complete the transaction for which the information is intended. Such transactions may include: administering a service, such as search, community, advertising sales, ecommerce; completing an order; replying to support requests; or contacting you if you have granted us permission to do so. Except as provided in this Privacy Policy and the End-User Agreement, we do not share this information with outside parties without your permission except to the extent that is necessary to administer the services we offer our Clients and End-Users or to comply in responding to subpoenas, court orders or other legal proceedings.<br> &nbsp;<br> From time to time, we also use the information you provide about yourself or others to inform you of additions or improvements to the <?=$site_name?> services. <br> &nbsp;<br> Finally, we never use or share the personally identifiable information provided to us online in ways or for reasons unrelated to the ones described above without also providing an opportunity to opt-out or otherwise prohibit such unrelated uses.<br> &nbsp;<br> <b>Our Commitment to Data Security</b><br> &nbsp;<br> To prevent unauthorized access, maintain data accuracy, and ensure the appropriate use of information, we have put in place appropriate physical, electronic, and managerial procedures reasonably designed to safeguard and secure the information we collect online. Personnel who have access to our database are trained to maintain and secure all information.<br> &nbsp;&nbsp;<br> <b>How You Can Access or Update Your Information</b><br> &nbsp;<br> <b>Clients</b> can access their personally identifiable information that <?=$site_name?> collects online and maintains by logging in to their password-protected account and selecting "Edit My Profile." <br> &nbsp;<br> To protect your privacy and security, we will take reasonable steps to verify your identity before granting access or making corrections to your information</font> </td> </tr> </table> <? include_once('foother.html'); ?><file_sep><? include_once "../main.php"; ?> <script language="JavaScript"> function chk() { if (document.form.uname.value=='') { alert("Please enter name"); document.form.uname.focus(); return false; } if (document.form.upass.value=='') { alert("Please enter password"); document.form.upass.focus(); return false; } if (document.form.cpass.value=='') { alert("Please enter password"); document.form.cpass.focus(); return false; } if (document.form.upass.value != document.form.cpass.value) { alert("Passwords donot match"); document.form.upass.focus(); return false; } if (document.form.title.value=='') { alert("Please select title"); document.form.title.focus(); return false; } if (document.form.fname.value=='') { alert("Please enter first name"); document.form.fname.focus(); return false; } if (document.form.lname.value=='') { alert("Please enter last name"); document.form.lname.focus(); return false; } if (document.form.bmonth.value=='') { alert("Please select month name"); document.form.bmonth.focus(); return false; } if (document.form.bday.value=='') { alert("Please select day"); document.form.bday.focus(); return false; } if (document.form.byear.value=='') { alert("Please select year"); document.form.byear.focus(); return false; } if (document.form.city.value=='') { alert("Please enter city name"); document.form.city.focus(); return false; } if (document.form.country.value=='') { alert("Please select country"); document.form.country.focus(); return false; } if (document.form.zip.value=='') { alert("Please enter zip code"); document.form.zip.focus(); return false; } if (document.form.address.value=='') { alert("Please enter address"); document.form.address.focus(); return false; } if (document.form.phone.value=='') { alert("Please enter phone"); document.form.phone.focus(); return false; } if (document.form.job_seeker_email.value=='') { alert("Please enter email addreess"); document.form.job_seeker_email.focus(); return false; } if (document.form.careerlevel.value=='') { alert("Please select career level"); document.form.careerlevel.focus(); return false; } if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(form.job_seeker_email.value)) { return (true) } else { alert("Invalid E-mail Address! Please re-enter.") document.form.job_seeker_email.focus() return (false) } return true; } </script> <form action=jobseeker_registration2.php method=post name="form" onSubmit="return chk();" style="background:none;"> <table align=center width=446 cellspacing=0 cellpadding="3" bgcolor="#FFFFFF"> <tr> <td> Username:<font color=red>*</font> </td> <td> <input type=text name=uname size=23 maxlength=10><br> <font size=1>max. 10 symbols (letters and/or numbers) </font> </td> </tr> <tr> <td> Password:<font color=red>*</font> </td> <td> <input type=password name=upass size=23 maxlength=10><br> <font size=1>max. 10 symbols (letters and/or numbers) </font> </td> </tr> <tr> <td> Confirm password:<font color=red>*</font> </td> <td> <input type=password name=cpass size=23 maxlength=10> </td> </tr> <tr> <td> Title:<font color=red>*</font> </td> <td> <select name=title> <option value="Mr.">Mr. </option> <option value="Mrs">Mrs</option> <option value="Miss">Miss</option> <option value="Ms.">Ms. </option> </select> </td> </tr> <tr> <td> First name:<font color=red>*</font> </td> <td> <input type=text name=fname size=23> </td> </tr> <tr> <td> Last name:<font color=red>*</font> </td> <td> <input type=text name=lname size=23> </td> </tr> <tr> <td> Date of birth: <font color=red>*</font> </td> <td> <select name=bmonth> <option value=""> Month </option> <option value=1> January </option> <option value=2> February </option> <option value=3> March </option> <option value=4> April </option> <option value=5> May </option> <option value=6> June </option> <option value=7> July </option> <option value=8> August </option> <option value=9> September </option> <option value=10> October </option> <option value=11> November </option> <option value=12> December </option> </select> <select name=bday> <option value=""> Day </option> <option value=1> 1 </option> <option value=2> 2 </option> <option value=3> 3 </option> <option value=4> 4 </option> <option value=5> 5 </option> <option value=6> 6 </option> <option value=7> 7 </option> <option value=8> 8 </option> <option value=9> 9 </option> <option value=10> 10 </option> <option value=11> 11 </option> <option value=12> 12 </option> <option value=13> 13 </option> <option value=14> 14 </option> <option value=15> 15 </option> <option value=16> 16 </option> <option value=17> 17 </option> <option value=18> 18 </option> <option value=19> 19 </option> <option value=20> 20 </option> <option value=21> 21 </option> <option value=22> 22 </option> <option value=23> 23 </option> <option value=24> 24 </option> <option value=25> 25 </option> <option value=26> 26 </option> <option value=27> 27 </option> <option value=28> 28 </option> <option value=29> 29 </option> <option value=30> 30 </option> <option value=31> 31 </option> </select> <select name=byear> <option value=""> Year </option> <option value=1986> 1986 </option> <option value=1985> 1985 </option> <option value=1984> 1984 </option> <option value=1983> 1983 </option> <option value=1982> 1982 </option> <option value=1981> 1981 </option> <option value=1980> 1980 </option> <option value=1979> 1979 </option> <option value=1978> 1978 </option> <option value=1977> 1977 </option> <option value=1976> 1976 </option> <option value=1975> 1975 </option> <option value=1974> 1974 </option> <option value=1973> 1973 </option> <option value=1972> 1972 </option> <option value=1971> 1971 </option> <option value=1970> 1970 </option> <option value=1969> 1969 </option> <option value=1968> 1968 </option> <option value=1967> 1967 </option> <option value=1966> 1966 </option> <option value=1965> 1965 </option> <option value=1964> 1964 </option> <option value=1963> 1963 </option> <option value=1962> 1962 </option> <option value=1961> 1961 </option> <option value=1960> 1960 </option> <option value=1959> 1959 </option> <option value=1958> 1958 </option> <option value=1957> 1957 </option> <option value=1956> 1956 </option> <option value=1955> 1955 </option> <option value=1954> 1954 </option> <option value=1953> 1953 </option> <option value=1952> 1952 </option> <option value=1951> 1951 </option> <option value=1950> 1950 </option> <option value=1949> 1949 </option> <option value=1948> 1948 </option> <option value=1947> 1947 </option> <option value=1946> 1946 </option> <option value=1945> 1945 </option> <option value=1943> 1943 </option> <option value=1942> 1942 </option> <option value=1941> 1941 </option> <option value=1940> 1940 </option> <option value=1939> 1939 </option> <option value=1938> 1938 </option> <option value=1937> 1937 </option> <option value=1936> 1936 </option> <option value=1935> 1935 </option> <option value=1934> 1934 </option> <option value=1933> 1933 </option> <option value=1932> 1932 </option> </select> </td> </tr> <tr> <td> Marital Status: </td> <td> <SELECT NAME="maritalstatus"> <option value="Domestic Partner">Domestic Partner</option> <option value="Engaged">Engaged</option> <option value="Married">Married</option> <option value="Separated/Divorced">Separated/Divorced</option> <option value="Single" selected>Single</option> <option value="Widowed">Widowed</option> </SELECT> </td> </tr> <tr> <td> Salary: </td> <td> <SELECT NAME="income" style=width:149> <option value="1">Under $15,000</option> <option value="2">$15,000-$19,999</option> <option value="3">$20,000-$24,999</option> <option value="4">$25,000 -$29,999</option> <option value="5">$30,000 -$34,999</option> <option value="6">$35,000-$39,999 </option> <option value="7">$40,000-Over</option> </SELECT> </td> </tr> <tr> <td> City:<font color=red>*</font> </td> <td> <input type=text name=city size=33> </td> </tr> <tr> <td> State: </td> <td> <select name=state style=width:154> <option value="Not in US">Not in US</option> <option value="Alabama">Alabama</option> <option value="Alaska">Alaska</option> <option value="Arizona">Arizona</option> <option value="Arkansas">Arkansas</option> <option value="California">California</option> <option value="Colorado">Colorado</option> <option value="Connecticut">Connecticut</option> <option value="Delaware">Delaware</option> <option value="District of Columbia">District of Columbia</option> <option value="Florida">Florida</option> <option value="Georgia">Georgia</option> <option value="Hawaii">Hawaii</option> <option value="Idaho">Idaho</option> <option value="Illinois">Illinois</option> <option value="Indiana">Indiana</option> <option value="Iowa">Iowa</option> <option value="Kansas">Kansas</option> <option value="Kentucky">Kentucky</option> <option value="Louisiana">Louisiana</option> <option value="Maine">Maine</option> <option value="Maryland">Maryland</option> <option value="Massachusetts">Massachusetts</option> <option value="Michigan">Michigan</option> <option value="Minnesota">Minnesota</option> <option value="Mississippi">Mississippi</option> <option value="Missouri">Missouri</option> <option value="Montana">Montana</option> <option value="Nebraska">Nebraska</option> <option value="Nevada">Nevada</option> <option value="New Hampshire">New Hampshire</option> <option value="New Jersey">New Jersey</option> <option value="New Mexico">New Mexico</option> <option value="New York">New York</option> <option value="North Carolina">North Carolina</option> <option value="North Dakota">North Dakota</option> <option value="Ohio">Ohio</option> <option value="Oklahoma">Oklahoma</option> <option value="Oregon">Oregon</option> <option value="Pennsylvania">Pennsylvania</option> <option value="Puerto Rico">Puerto Rico</option> <option value="Rhode Island">Rhode Island</option> <option value="South Carolina">South Carolina</option> <option value="South Dakota">South Dakota</option> <option value="Tennessee">Tennessee</option> <option value="Texas">Texas</option> <option value="Utah">Utah</option> <option value="Vermont">Vermont</option> <option value="Virgin Islands">Virgin Islands</option> <option value="Virginia">Virginia</option> <option value="Washington">Washington</option> <option value="West Virginia">West Virginia</option> <option value="Wisconsin">Wisconsin</option> <option value="Wyoming">Wyoming</option> </select> </td> </tr> <tr> <td> Country:<font color=red>*</font> </td> <td> <select name=country> <option value="UK">UK</option> <option value="Afghanistan">Afghanistan</option> <option value="Albania">Albania</option> <option value="Algeria">Algeria</option> <option value="American Samoa">American Samoa</option> <option value="Andorra">Andorra</option> <option value="Angola">Angola</option> <option value="Anguilla">Anguilla</option> <option value="Antartica">Antartica</option> <option value="Antigua and Barbuda">Antigua and Barbuda</option> <option value="Argentina">Argentina</option> <option value="Armenia">Armenia</option> <option value="Aruba">Aruba</option> <option value="Australia">Australia</option> <option value="Austria">Austria</option> <option value="Azerbaidjan">Azerbaidjan</option> <option value="Bahamas">Bahamas</option> <option value="Bahrain">Bahrain</option> <option value="Bangladesh">Bangladesh</option> <option value="Barbados">Barbados</option> <option value="Belarus">Belarus</option> <option value="Belgium">Belgium</option> <option value="Belize">Belize</option> <option value="Benin">Benin</option> <option value="Bermuda">Bermuda</option> <option value="Bhutan">Bhutan</option> <option value="Bolivia">Bolivia</option> <option value="Bosnia-Herzegovina">Bosnia-Herzegovina</option> <option value="Botswana">Botswana</option> <option value="Bouvet Island">Bouvet Island</option> <option value="Brazil">Brazil</option> <option value="British Indian Ocean Territory">British Indian Ocean Territory</option> <option value="Brunei Darussalam">Brunei Darussalam</option> <option value="Bulgaria">Bulgaria</option> <option value="Burkina Faso">Burkina Faso</option> <option value="Burundi">Burundi</option> <option value="Cambodia">Cambodia</option> <option value="Cameroon">Cameroon</option> <option value="Canada">Canada</option> <option value="Cape Verde">Cape Verde</option> <option value="Cayman Islands">Cayman Islands</option> <option value="Central African Republic">Central African Republic</option> <option value="Chad">Chad</option> <option value="Chile">Chile</option> <option value="China">China</option> <option value="Christmas Island">Christmas Island</option> <option value="Cocos (Keeling) Islands">Cocos (Keeling) Islands</option> <option value="Colombia">Colombia</option> <option value="Comoros">Comoros</option> <option value="Congo">Congo</option> <option value="Cook Islands">Cook Islands</option> <option value="Costa Rica">Costa Rica</option> <option value="Croatia">Croatia</option> <option value="Cuba">Cuba</option> <option value="Cyprus">Cyprus</option> <option value="Czech Republic">Czech Republic</option> <option value="Denmark">Denmark</option> <option value="Djibouti">Djibouti</option> <option value="Dominica">Dominica</option> <option value="Dominican Republic">Dominican Republic</option> <option value="East Timor">East Timor</option> <option value="Ecuador">Ecuador</option> <option value="Egypt">Egypt</option> <option value="El Salvador">El Salvador</option> <option value="Equatorial Guinea">Equatorial Guinea</option> <option value="Eritrea">Eritrea</option> <option value="Estonia">Estonia</option> <option value="Ethiopia">Ethiopia</option> <option value="Falkland Islands">Falkland Islands</option> <option value="Faroe Islands">Faroe Islands</option> <option value="Fiji">Fiji</option> <option value="Finland">Finland</option> <option value="Former USSR">Former USSR</option> <option value="France">France</option> <option value="France (European Territory)">France (European Territory)</option> <option value="French Guyana">French Guyana</option> <option value="French Southern Territories">French Southern Territories</option> <option value="Gabon">Gabon</option> <option value="Gambia">Gambia</option> <option value="Georgia">Georgia</option> <option value="Germany">Germany</option> <option value="Ghana">Ghana</option> <option value="Gibraltar">Gibraltar</option> <option value="Greece">Greece</option> <option value="Greenland">Greenland</option> <option value="Grenada">Grenada</option> <option value="Guadeloupe (French)">Guadeloupe (French)</option> <option value="Guam">Guam</option> <option value="Guatemala">Guatemala</option> <option value="Guinea">Guinea</option> <option value="Guinea Bissau">Guinea Bissau</option> <option value="Guyana">Guyana</option> <option value="Haiti">Haiti</option> <option value="Heard and McDonald Islands">Heard and McDonald Islands</option> <option value="Honduras">Honduras</option> <option value="Hong Kong">Hong Kong</option> <option value="Hungary">Hungary</option> <option value="Iceland">Iceland</option> <option value="India">India</option> <option value="Indonesia">Indonesia</option> <option value="Iran">Iran</option> <option value="Iraq">Iraq</option> <option value="Ireland">Ireland</option> <option value="Israel">Israel</option> <option value="Italy">Italy</option> <option value="Ivory Coast">Ivory Coast</option> <option value="Jamaica">Jamaica</option> <option value="Japan">Japan</option> <option value="Jordan">Jordan</option> <option value="Kazakhstan">Kazakhstan</option> <option value="Kenya">Kenya</option> <option value="Kiribati">Kiribati</option> <option value="Kuwait">Kuwait</option> <option value="Kyrgyzstan">Kyrgyzstan</option> <option value="Laos">Laos</option> <option value="Latvia">Latvia</option> <option value="Lebanon">Lebanon</option> <option value="Lesotho">Lesotho</option> <option value="Liberia">Liberia</option> <option value="Libya">Libya</option> <option value="Liechtenstein">Liechtenstein</option> <option value="Lithuania">Lithuania</option> <option value="Luxembourg">Luxembourg</option> <option value="Macau">Macau</option> <option value="Macedonia">Macedonia</option> <option value="Madagascar">Madagascar</option> <option value="Malawi">Malawi</option> <option value="Malaysia">Malaysia</option> <option value="Maldives">Maldives</option> <option value="Mali">Mali</option> <option value="Malta">Malta</option> <option value="Marshall Islands">Marshall Islands</option> <option value="Martinique (French)">Martinique (French)</option> <option value="Mauritania">Mauritania</option> <option value="Mauritius">Mauritius</option> <option value="Mayotte">Mayotte</option> <option value="Mexico">Mexico</option> <option value="Micronesia">Micronesia</option> <option value="Moldavia">Moldavia</option> <option value="Monaco">Monaco</option> <option value="Mongolia">Mongolia</option> <option value="Montserrat">Montserrat</option> <option value="Morocco">Morocco</option> <option value="Mozambique">Mozambique</option> <option value="Myanmar, Union of (Burma)">Myanmar, Union of (Burma)</option> <option value="Namibia">Namibia</option> <option value="Nauru">Nauru</option> <option value="Nepal">Nepal</option> <option value="Netherlands">Netherlands</option> <option value="Netherlands Antilles">Netherlands Antilles</option> <option value="Neutral Zone">Neutral Zone</option> <option value="New Caledonia (French)">New Caledonia (French)</option> <option value="New Zealand">New Zealand</option> <option value="Nicaragua">Nicaragua</option> <option value="Niger">Niger</option> <option value="Nigeria">Nigeria</option> <option value="Niue">Niue</option> <option value="Norfolk Island">Norfolk Island</option> <option value="North Korea">North Korea</option> <option value="Northern Mariana Islands">Northern Mariana Islands</option> <option value="Norway">Norway</option> <option value="Oman">Oman</option> <option value="Pakistan">Pakistan</option> <option value="Palau">Palau</option> <option value="Panama">Panama</option> <option value="Papua New Guinea">Papua New Guinea</option> <option value="Paraguay">Paraguay</option> <option value="Peru">Peru</option> <option value="Philippines">Philippines</option> <option value="Pitcairn Island">Pitcairn Island</option> <option value="Poland">Poland</option> <option value="Polynesia (French)">Polynesia (French)</option> <option value="Portugal">Portugal</option> <option value="Qatar">Qatar</option> <option value="Reunion (French)">Reunion (French)</option> <option value="Romania">Romania</option> <option value="Russian Federation">Russian Federation</option> <option value="Rwanda">Rwanda</option> <option value="S. Georgia &amp; S. Sandwich Islands">S. Georgia &amp; S. Sandwich Islands</option> <option value="Saint Helena">Saint Helena</option> <option value="Saint Kitts &amp; Nevis Anguilla">Saint Kitts &amp; Nevis Anguilla</option> <option value="Saint Lucia">Saint Lucia</option> <option value="Saint Pierre and Miquelon">Saint Pierre and Miquelon</option> <option value="Saint Tome and Principe">Saint Tome and Principe</option> <option value="Saint Vincent &amp; Grenadines">Saint Vincent &amp; Grenadines</option> <option value="Samoa">Samoa</option> <option value="San Marino">San Marino</option> <option value="Saudi Arabia">Saudi Arabia</option> <option value="Senegal">Senegal</option> <option value="Seychelles">Seychelles</option> <option value="Sierra Leone">Sierra Leone</option> <option value="Singapore">Singapore</option> <option value="Slovakia">Slovakia</option> <option value="Slovenia">Slovenia</option> <option value="Solomon Islands">Solomon Islands</option> <option value="Somalia">Somalia</option> <option value="South Africa">South Africa</option> <option value="South Korea">South Korea</option> <option value="Spain">Spain</option> <option value="Sri Lanka">Sri Lanka</option> <option value="Sudan">Sudan</option> <option value="Suriname">Suriname</option> <option value="Svalbard and Jan Mayen Islands">Svalbard and Jan Mayen Islands</option> <option value="Swaziland">Swaziland</option> <option value="Sweden">Sweden</option> <option value="Switzerland">Switzerland</option> <option value="Syria">Syria</option> <option value="Tadjikistan">Tadjikistan</option> <option value="Taiwan">Taiwan</option> <option value="Tanzania">Tanzania</option> <option value="Thailand">Thailand</option> <option value="Togo">Togo</option> <option value="Tokelau">Tokelau</option> <option value="Tonga">Tonga</option> <option value="Trinidad and Tobago">Trinidad and Tobago</option> <option value="Tunisia">Tunisia</option> <option value="Turkey">Turkey</option> <option value="Turkmenistan">Turkmenistan</option> <option value="Turks and Caicos Islands">Turks and Caicos Islands</option> <option value="Tuvalu">Tuvalu</option> <option value="Uganda">Uganda</option> <option value="Ukraine">Ukraine</option> <option value="United Arab Emirates">United Arab Emirates</option> <option value="Uruguay">Uruguay</option> <option value="US">US</option> <option value="USA Minor Outlying Islands">USA Minor Outlying Islands</option> <option value="Uzbekistan">Uzbekistan</option> <option value="Vanuatu">Vanuatu</option> <option value="Vatican City">Vatican City</option> <option value="Venezuela">Venezuela</option> <option value="Vietnam">Vietnam</option> <option value="Virgin Islands (British)">Virgin Islands (British)</option> <option value="Virgin Islands (USA)">Virgin Islands (USA)</option> <option value="Wallis and Futuna Islands">Wallis and Futuna Islands</option> <option value="Western Sahara">Western Sahara</option> <option value="Yemen">Yemen</option> <option value="Yugoslavia">Yugoslavia</option> <option value="Zaire">Zaire</option> <option value="Zambia">Zambia</option> <option value="Zimbabwe">Zimbabwe</option> </select> </td> </tr> <tr> <td> Postcode:<font color=red>*</font> </td> <td> <input type=text name=zip size=9> </td> </tr> <tr> <td> Address:<font color=red>*</font> </td> <td> <input type=text name=address> </td> </tr> <tr> <td> Phone<font color=red>:*</font> </td> <td> <input type=text name=phone> </td> </tr> <tr> <td> Mobile:</td> <td> <input type=text name=phone2> </td> </tr> <tr> <td> Email:<font color=red>*</font> </td> <td> <input type=text name=job_seeker_email> </td> </tr> <tr> <td valign=top> Job Category:<font color=red>*</font> <br> </td> <td valign=top> <SELECT NAME="JobCategory"> <option value="Accounting/Auditing">Accounting/Auditing</option> <option value="Administrative and Support Services">Administrative and Support Services</option> <option value="Advertising/Public Relations">Advertising/Public Relations</option> <option value="Computers, Hardware">Computers, Hardware</option> <option value="Computers, Software">Computers, Software</option> <option value="Consulting Services">Consulting Services</option> <option value="Customer Service and Call Center">Customer Service and Call Center</option> <option value="Director">Director</option> <option value="Executive Management">Executive Management</option> <option value="Finance/Economics">Finance/Economics</option> <option value="Human Resources">Human Resources</option> <option value="Information Technology">Information Technology</option> <option value="Installation, Maintenance,Repairs">Installation, Maintenance,Repairs</option> <option value="Internet/E-Commerce">Internet/E-Commerce</option> <option value="Legal">Legal</option> <option value="Management">Management</option> <option value="Marketing">Marketing</option> <option value="Sales">Sales</option> <option value="Supervisor">Supervisor</option> <option value="Telecommunications">Telecommunications</option> <option value="Transportation and Warehousing">Transportation and Warehousing</option> <option value="Other">Other</option> </SELECT><br> </td> </tr> <tr> <td> Your career level:<font color=red>*</font> </td> <td> <select name="careerlevel"> <option value="1">Student</option> <option value="2">Student (undergraduate/graduate)</option> <option value="3">Entry Level (less than 2 years of experience)</option> <option value="4">Mid Career (2+ years of experience)</option> <option value="5">Management (Manager/Director of Staff)</option> <option value="6">Executive (SVP, EVP, VP)</option> <option value="7">Senior Executive (President, CEO)</option> </select> </td> </tr> <tr> <td> Target company: </td> <td> <select name="target_company"> <option value=""> </option> <option value="Small (up to 99 empl.)"> Small (up to 99 empl.) </option> <option value="Medium (100 - 500 empl.)"> Medium (100 - 500 empl.) </option> <option value="Large (over 500 empl.)"> Large (over 500 empl.) </option> </select> </td> </tr> <tr> <td valign=top> Willing to relocate? </td> <td> <input type=radio name=relocate value=Yes checked>Yes<br> <input type=radio name=relocate value=No>No </td> </tr> <tr> <td align=left>&nbsp; </td> <td align=center> <input class=s2 type=submit name=submit value="Register me" align=left> <input class=s2 type=reset name=reset value="Reset" align=right> </td> </tr> </table> </form> <? include_once('../foother.html'); ?><file_sep><? include_once "accesscontrol.php"; if(isset($submit) && $submit == 'Save changes') { $rTitle = strip_tags($_POST[rTitle]); $rPar = strip_tags($_POST[rPar]); $NC = strip_tags($_POST[NewCity]); $phone11 = strip_tags($_POST[NewPhone]); $phone22 = strip_tags($_POST[NewPhone2]); $NewAddr = strip_tags($_POST[NewAddress]); $NewMail = strip_tags($_POST[NewEmail]); if($_POST[NewState] == 'Not in US') { $ns = ""; } else { $ns = $_POST[NewState]; } $q1 = "update job_seeker_info set rTitle = \"$rTitle\", rPar = \"$rPar\", state = \"$ns\", zip = \"$_POST[NewZip]\", city = \"$NC\", phone = \"$phone11\", phone2 = \"$phone22\", address = \"$NewAddr\", job_seeker_email = \"$NewMail\" where uname = \"$uname\" "; $r1 = mysql_query($q1) or die(mysql_error()); include "ER3.php"; } elseif(isset($submit) && $submit == 'Go to Step 1 (Work experience)') { include "ER3.php"; } ?><file_sep><? include_once "accesscontrol.php"; $q1 = "select * from job_seeker_info where uname = \"$uname\" "; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); ?> <SCRIPT LANGUAGE="JavaScript"> function checkFields() { missinginfo = ""; if (document.form.rTitle.value == "") { missinginfo += "\n - Resume title"; document.form.rTitle.focus(); } if (document.form.NewEmail.value == "") { missinginfo += "\n - Your email address"; document.form.NewEmail.focus(); } if (document.form.NewAddress.value == "") { missinginfo += "\n - Your address"; document.form.NewAddress.focus(); } if (document.form.NewPhone.value == "") { missinginfo += "\n - Your new phone"; document.form.NewPhone.focus(); } if (document.form.NewCity.value == "") { missinginfo += "\n - Your City"; document.form.NewCity.focus(); } if (document.form.NewZip.value == "") { missinginfo += "\n - Zip code"; document.form.NewZip.focus(); } if (missinginfo != "") { missinginfo ="_____________________________\n" + "You failed to correctly fill in:\n" + missinginfo + "\n_____________________________" + "\nPlease re-enter and submit again!"; alert(missinginfo); return false; } else return true; } </script> <form action=ER2.php method=post name=form onSubmit="return checkFields();" style="background:none;"> <table align=center width="446" bgcolor="#FFFFFF"> <tr> <td class=RB align=center> <b>Title </b><br> <font size=1> choose a title for your resume </font><br> <input type=text name=rTitle size=45 value="<?=$a1[rTitle]?>"> </td> </tr> <tr> <td class=RB align=center> <b>Introduce yourself to the employers</b> <br> <font size=1> a short paragraph about you </font><br> <textarea cols=80 rows=6 name=rPar><?=$a1[rPar]?></textarea> </td> </tr> <tr> <td> <table align=center width=350> <tr> <td>Email: </td><td><input type=text name=NewEmail value="<?=$a1[job_seeker_email]?>"></td> </tr> <tr> <td>Address: </td><td><input type=text name=NewAddress value="<?=$a1[address]?>"></td> </tr> <tr> <td>Phone: </td><td><input type=text name=NewPhone value="<?=$a1[phone]?>"></td> </tr> <tr> <td>Phone 2: </td><td><input type=text name=NewPhone2 value="<?=$a1[phone2]?>"></td> </tr> <tr> <td>City: </td> <td><input type=text name=NewCity value="<?=$a1[city]?>"></td> </tr> <tr> <td>Zip: </td> <td><input size=10 type=text name=NewZip value="<?=$a1[zip]?>"></td> </tr> <tr> <td>State: </td> <td><select name=NewState> <? $state1 = array('Not in US', 'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'District of Columbia', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Puerto Rico', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virgin Islands', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'); for($i = 0; $i <= (count($state1) - 1); $i++) { if(empty($a1[state])) { echo "<option value=\"$state1[$i]\"> $state1[$i] </option>"; } elseif($state1[$i] == $a1[state]) { echo "<option selected value=\"$state1[$i]\"> $state1[$i] </option>"; } else { echo "<option value=\"$state1[$i]\"> $state1[$i] </option>"; } } ?> </select> </td> </tr> </table> </td> </tr> <tr> <td align=center> <input type=submit name=submit value="Save changes"> <b> OR </b> <input type=submit name=submit value="Go to Step 1 (Work experience)"> </td> </tr> </table> </form> </body> <? include_once('../foother.html'); ?><file_sep><?php require "../connect.php"; require "version.php"; if(!isset($_GET['upgrade'])) { // if the form has not been submitted $query = mysql_query("show tables") or die(mysql_error()); if(!$query) { echo '<h2>'._('Database connection failed.').'</h2>'; echo '<p>'._('Edit connect.php and set the mysql database connection information.').'</p>'; exit; } $num_results = mysql_num_rows($query); if($num_results == 0) { header('location: ./install.php'); exit; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Surreal ToDo <?php echo _('Upgrade'); ?></title> <link rel="stylesheet" type="text/css" href="../theme/base.css" /> </head> <body> <div id="upgrade"> <h1>Surreal ToDo <?php echo _('Upgrade'); ?></h1> <?php while($row = mysql_fetch_row($query)){ if ($row[0] == 'config') { // Check the current version // Examine the config table layout to see how to retrieve the version $queryConfig = mysql_query("SHOW columns FROM config"); while ($rowConfig = mysql_fetch_assoc($queryConfig)) { if ($rowConfig['Field'] == 'value') { // table is in new config format $query = mysql_query("SELECT value FROM config where name = 'version'"); $num_results = mysql_num_rows($query); if($num_results == 0) { $schema_version = "Undetermined"; break; } $row = mysql_fetch_assoc($query); $schema_version = $row['value']; break; } if ($rowConfig['Field'] == 'version') { // table is in old config format $query = mysql_query("SELECT version FROM config"); $num_results = mysql_num_rows($query); if($num_results == 0) { $schema_version = "Undetermined"; break; } $row = mysql_fetch_assoc($query); $schema_version = $row['version']; break; } } break; } if ($row[0] == 'projects') { $schema_version = "pre_v0.3"; break; } if ($row[0] == 'tabs') { $schema_version = "0.3"; break; } } switch ($schema_version){ case 'pre_v0.3': echo '<h2>'._('Unable to upgrade versions prior to v0.3').'<h2>'; break; case APP_VERSION : echo '<h2>'._('Upgrade is not needed.').'</h2>'; echo '<br /><br /><a href="./index.php">'._('Continue').'</a>'; break; case $schema_version : echo '<h2>'._('This script will upgrade your database from version').' '.$schema_version.' -> '.APP_VERSION.'.</h2>'; echo '<h2>'._('Please! Backup your database before updating.').'</h2>'; echo ' <form action="'.$_SERVER['PHP_SELF'].'" method="get" name="form_upgrade"> <input name="version" type="hidden" value="v'.$schema_version.'" /> <input name="upgrade" type="submit" value="'._('Upgrade').'" /> </form> '; break; default : echo '<h2>'._('Unable to upgrade.').'</h2'; if(version_compare(APP_VERSION, $schema_version) == -1){ echo '<h2>'._('Your database is at a higher revision than the application.').'</h2>'; } else { echo '<h2>'._('Unable to determine the version of your database.').'</h2>'; } break; } // close switch $status } // close if(!isset($_GET['upgrade'])) if(isset($_GET['version'])) { $version = $_GET['version']; switch($version) { case 'v0.3': echo '<h2>Starting upgrade...</h2>'; mysql_query("alter table todo change date_added date_created timestamp NOT NULL default CURRENT_TIMESTAMP"); mysql_query("alter table todo change date_closed date_completed datetime default NULL"); mysql_query("alter table lists add column column_id int(8) unsigned default '1'"); mysql_query("CREATE TABLE `config` ( `config_id` int(8) unsigned NOT NULL, `version` varchar(20) collate utf8_unicode_ci NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"); mysql_query("insert into config set config_id = 0, version = '0.3.1'"); $query = mysql_query("SELECT * FROM lists"); while($row = mysql_fetch_assoc($query)){ $listID = $row['list_id']; list($left,$top,$zindex) = explode('x',$row['position']); if($left < 300) mysql_query("update lists set column_id = 1, position = ".$top." where list_id = ".$listID); if($left > 600) mysql_query("update lists set column_id = 3, position = ".$top." where list_id = ".$listID); if(($left >= 300) && ($left <= 600)) mysql_query("update lists set column_id = 2, position = ".$top." where list_id = ".$listID); } mysql_query("alter table lists change position position int(8) unsigned"); $tabquery = mysql_query("SELECT * from tabs"); while($tabrow = mysql_fetch_assoc($tabquery)){ $tabID = $tabrow['tab_id']; $position = 1; for ($columnID = 1; $columnID <= 3; ++$columnID ) { $position = 1; $query = mysql_query("SELECT * FROM lists where column_id = ".$columnID." AND tab_id = ".$tabID." ORDER BY position"); while($row = mysql_fetch_assoc($query)){ $listID = $row['list_id']; mysql_query("update lists set position = ".$position." where list_id = ".$listID); $position = ++$position; } } // close FOR loop } // close while tabs case 'v0.3.1': // Select all the exiting tabs in order to create a default page for each mysql_query(" CREATE TABLE `pages` ( `page_id` int(8) unsigned NOT NULL auto_increment, `name` varchar(20) collate utf8_unicode_ci NOT NULL default 'New Page', `tab_id` int(8) unsigned NOT NULL default '0', `date_created` timestamp NOT NULL default CURRENT_TIMESTAMP, `position` int(8) unsigned default '1', PRIMARY KEY (`page_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; "); $query = mysql_query("SELECT * FROM tabs ORDER BY tab_id ASC"); // For each tab create a 'Main Page' and reassgn the lists to the 'Main Page' while($row = mysql_fetch_assoc($query)){ $tabID = $row['tab_id']; mysql_query("INSERT into pages set name = 'Main Page', tab_id = $tabID"); $pageID = mysql_insert_id(); mysql_query("UPDATE lists set tab_id = $pageID where tab_id = $tabID"); } mysql_query("alter table lists change tab_id `page_id` int(8) unsigned NOT NULL default '0'"); mysql_query("update config set version = '0.4'"); mysql_query("alter table config add PRIMARY KEY (`config_id`)"); case 'v0.4': $default_timezone = date_default_timezone_get(); mysql_query("drop table config"); mysql_query("CREATE TABLE `config` ( `name` varchar(128) NULL, `value` varchar(128) NULL, PRIMARY KEY (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"); mysql_query("insert into config set name = 'version', value = '0.4.1'"); mysql_query("insert into config set name = 'timezone', value = '".$default_timezone."'"); mysql_query("insert into config set name = 'default_site_name', value = 'Surreal ToDo'"); mysql_query("insert into config set name = 'default_tab_name', value = 'New Tab'"); mysql_query("insert into config set name = 'first_page_name', value = 'Main Page'"); mysql_query("insert into config set name = 'default_page_name', value = 'New Page'"); mysql_query("insert into config set name = 'default_list_name', value = 'New List'"); mysql_query("insert into config set name = 'default_item_name', value = 'Double-click to Edit.'"); case 'v0.4.1': mysql_query("update config set value = '0.5' where name = 'version'"); mysql_query("drop index todo_id on todo"); mysql_query("drop index list_id on lists"); mysql_query("rename table todo to items"); mysql_query("alter table tabs add column trash int(1) unsigned default '0'"); mysql_query("alter table pages add column trash int(1) unsigned default '0'"); mysql_query("alter table lists add column trash int(1) unsigned default '0'"); mysql_query("alter table items add column trash int(1) unsigned default '0'"); mysql_query("create index item on items (list_id, trash, position)"); mysql_query("create index list on lists (page_id, trash, column_id, position)"); mysql_query("create index page on pages (tab_id, trash , position)"); mysql_query("create index tab on tabs (trash, position)"); case 'v0.5': mysql_query("update config set value = '0.5.1' where name = 'version'"); mysql_query("alter table items add column link varchar(255) collate utf8_unicode_ci default '#'"); case 'v0.5.1': mysql_query("update config set value = '0.5.2' where name = 'version'"); mysql_query("insert into config set name = 'date_format', value = 'Y-m-d'"); mysql_query("insert into config set name = 'time_format', value = 'h:ia'"); mysql_query("insert into config set name = 'theme', value = 'default'"); case 'v0.5.2': mysql_query("update config set value = '0.6' where name = 'version'"); mysql_query("insert into config set name = 'locale', value = 'en_US.utf8'"); mysql_query("alter table pages add column columns int(1) unsigned default '3'"); mysql_query("insert into config set name = 'completed_item', value = '8'"); mysql_query("alter table items change text `text` mediumText collate utf8_unicode_ci NOT NULL"); mysql_query("alter table lists add column show_item_date int(1) unsigned default '0'"); mysql_query("update items set color = '' where color = '#d89c3a'"); $query = mysql_query("select * from items WHERE fontStyle <> '' OR fontWeight <> '' OR fontSize <> '' OR color <> '' OR indent <> '' OR link <> '#' "); while($row = mysql_fetch_assoc($query)){ if ($row['link'] != '#') $text = '<a href="'.$row['link'].'">'.$row['text'].'</a>'; else $text = $row['text']; $newItem = '<span style="font-style:'.$row['fontStyle'].'; font-weight:'.$row['fontWeight'].'; font-size:'.$row['fontSize'].'; color:'.$row['color'].'; margin-left:'.$row['indent'].';">'.$text.'</span>'; mysql_query("update items set text = '$newItem', fontStyle = '', fontWeight = '', fontSize = '', color = '', indent = '', link = '#' WHERE id = ".$row['id']); } mysql_query("alter table items drop column fontStyle"); mysql_query("alter table items drop column fontWeight"); mysql_query("alter table items drop column fontSize"); mysql_query("alter table items drop column color"); mysql_query("alter table items drop column indent"); mysql_query("alter table items drop column link"); case 'v0.6': // no schema updates mysql_query("update config set value = '0.6.1' where name = 'version'"); case 'v0.6.1': // no schema updates mysql_query("update config set value = '0.6.1.1' where name = 'version'"); case 'v0.6.1.1': // no schema updates mysql_query("update config set value = '0.6.1.2' where name = 'version'"); case 'v0.6.1.2': // current version break; default: echo "Unable to determine your version to perform upgrade."; } // close switch echo '<h2>'._('Upgrade Complete').'</h2>'; echo '<a href="../">'._('Continue').'</a>'; } ?> </div> </body> </html> <file_sep><? session_start(); include_once "../main.php"; ?> <script language="JavaScript"> function chk() { if (document.form.ename.value=='') { alert("Please enter name"); document.form.ename.focus(); return false; } if (document.form.epass.value=='') { alert("Please enter password"); document.form.epass.focus(); return false; } if (document.form.cpass.value=='') { alert("Please enter password"); document.form.cpass.focus(); return false; } if (document.form.epass.value != document.form.cpass.value) { alert("Passwords donot match"); document.form.epass.focus(); return false; } if (document.form.CompanyName.value=='') { alert("Please enter company name"); document.form.CompanyName.focus(); return false; } if (document.form.CompanyCountry.value=='') { alert("Please select country"); document.form.CompanyCountry.focus(); return false; } if (document.form.CompanyZip.value=='') { alert("Please enter zip code"); document.form.CompanyZip.focus(); return false; } if (document.form.CompanyCity.value=='') { alert("Please enter city name"); document.form.CompanyCity.focus(); return false; } if (document.form.CompanyAddress.value=='') { alert("Please enter address"); document.form.CompanyAddress.focus(); return false; } if (document.form.CompanyPhone.value=='') { alert("Please enter phone"); document.form.CompanyPhone.focus(); return false; } if (document.form.CompanyEmail.value=='') { alert("Please enter email addreess"); document.form.CompanyEmail.focus(); return false; } if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(form.CompanyEmail.value)) { return (true) } else { alert("Invalid E-mail Address! Please re-enter.") document.form.CompanyEmail.focus() return (false) } return true; } </script> <form action=employer_registration2.php method=post name="form" onSubmit="return chk();" style="background:none;"> <table align=center width=446 cellspacing=0 cellpadding="5" bgcolor="#FFFFFF"> <tr> <td valign=middle> Username:<font color=red>*</font> </td> <td> <input type=text name=ename maxlength=10><br> <font size=1>max. 10 symbols (letters and/or numbers) </font> </td> </tr> <tr> <td> Password:<font color=red>*</font> </td> <td> <input type=password name=epass maxlength=10><br> <font size=1>max. 10 symbols (letters and/or numbers) </font> </td> </tr> <tr> <td> Confirm password:<font color=red>*</font> </td> <td> <input type=password name=cpass maxlength=10> </td> </tr> <tr> <td> Company name:<font color=red>*</font> </td> <td> <input type=text name=CompanyName> </td> </tr> <tr> <td> Country:<font color=red>*</font> </td> <td> <select name=CompanyCountry> <option value="UK">UK</option> <option value="Afghanistan">Afghanistan</option> <option value="Albania">Albania</option> <option value="Algeria">Algeria</option> <option value="American Samoa">American Samoa</option> <option value="Andorra">Andorra</option> <option value="Angola">Angola</option> <option value="Anguilla">Anguilla</option> <option value="Antartica">Antartica</option> <option value="Antigua and Barbuda">Antigua and Barbuda</option> <option value="Argentina">Argentina</option> <option value="Armenia">Armenia</option> <option value="Aruba">Aruba</option> <option value="Australia">Australia</option> <option value="Austria">Austria</option> <option value="Azerbaidjan">Azerbaidjan</option> <option value="Bahamas">Bahamas</option> <option value="Bahrain">Bahrain</option> <option value="Bangladesh">Bangladesh</option> <option value="Barbados">Barbados</option> <option value="Belarus">Belarus</option> <option value="Belgium">Belgium</option> <option value="Belize">Belize</option> <option value="Benin">Benin</option> <option value="Bermuda">Bermuda</option> <option value="Bhutan">Bhutan</option> <option value="Bolivia">Bolivia</option> <option value="Bosnia-Herzegovina">Bosnia-Herzegovina</option> <option value="Botswana">Botswana</option> <option value="Bouvet Island">Bouvet Island</option> <option value="Brazil">Brazil</option> <option value="British Indian Ocean Territory">British Indian Ocean Territory</option> <option value="Brunei Darussalam">Brunei Darussalam</option> <option value="Bulgaria">Bulgaria</option> <option value="Burkina Faso">Burkina Faso</option> <option value="Burundi">Burundi</option> <option value="Cambodia">Cambodia</option> <option value="Cameroon">Cameroon</option> <option value="Canada">Canada</option> <option value="Cape Verde">Cape Verde</option> <option value="Cayman Islands">Cayman Islands</option> <option value="Central African Republic">Central African Republic</option> <option value="Chad">Chad</option> <option value="Chile">Chile</option> <option value="China">China</option> <option value="Christmas Island">Christmas Island</option> <option value="Cocos (Keeling) Islands">Cocos (Keeling) Islands</option> <option value="Colombia">Colombia</option> <option value="Comoros">Comoros</option> <option value="Congo">Congo</option> <option value="Cook Islands">Cook Islands</option> <option value="Costa Rica">Costa Rica</option> <option value="Croatia">Croatia</option> <option value="Cuba">Cuba</option> <option value="Cyprus">Cyprus</option> <option value="Czech Republic">Czech Republic</option> <option value="Denmark">Denmark</option> <option value="Djibouti">Djibouti</option> <option value="Dominica">Dominica</option> <option value="Dominican Republic">Dominican Republic</option> <option value="East Timor">East Timor</option> <option value="Ecuador">Ecuador</option> <option value="Egypt">Egypt</option> <option value="El Salvador">El Salvador</option> <option value="Equatorial Guinea">Equatorial Guinea</option> <option value="Eritrea">Eritrea</option> <option value="Estonia">Estonia</option> <option value="Ethiopia">Ethiopia</option> <option value="Falkland Islands">Falkland Islands</option> <option value="Faroe Islands">Faroe Islands</option> <option value="Fiji">Fiji</option> <option value="Finland">Finland</option> <option value="Former USSR">Former USSR</option> <option value="France">France</option> <option value="France (European Territory)">France (European Territory)</option> <option value="French Guyana">French Guyana</option> <option value="French Southern Territories">French Southern Territories</option> <option value="Gabon">Gabon</option> <option value="Gambia">Gambia</option> <option value="Georgia">Georgia</option> <option value="Germany">Germany</option> <option value="Ghana">Ghana</option> <option value="Gibraltar">Gibraltar</option> <option value="Greece">Greece</option> <option value="Greenland">Greenland</option> <option value="Grenada">Grenada</option> <option value="Guadeloupe (French)">Guadeloupe (French)</option> <option value="Guam">Guam</option> <option value="Guatemala">Guatemala</option> <option value="Guinea">Guinea</option> <option value="Guinea Bissau">Guinea Bissau</option> <option value="Guyana">Guyana</option> <option value="Haiti">Haiti</option> <option value="Heard and McDonald Islands">Heard and McDonald Islands</option> <option value="Honduras">Honduras</option> <option value="Hong Kong">Hong Kong</option> <option value="Hungary">Hungary</option> <option value="Iceland">Iceland</option> <option value="India">India</option> <option value="Indonesia">Indonesia</option> <option value="Iran">Iran</option> <option value="Iraq">Iraq</option> <option value="Ireland">Ireland</option> <option value="Israel">Israel</option> <option value="Italy">Italy</option> <option value="Ivory Coast">Ivory Coast</option> <option value="Jamaica">Jamaica</option> <option value="Japan">Japan</option> <option value="Jordan">Jordan</option> <option value="Kazakhstan">Kazakhstan</option> <option value="Kenya">Kenya</option> <option value="Kiribati">Kiribati</option> <option value="Kuwait">Kuwait</option> <option value="Kyrgyzstan">Kyrgyzstan</option> <option value="Laos">Laos</option> <option value="Latvia">Latvia</option> <option value="Lebanon">Lebanon</option> <option value="Lesotho">Lesotho</option> <option value="Liberia">Liberia</option> <option value="Libya">Libya</option> <option value="Liechtenstein">Liechtenstein</option> <option value="Lithuania">Lithuania</option> <option value="Luxembourg">Luxembourg</option> <option value="Macau">Macau</option> <option value="Macedonia">Macedonia</option> <option value="Madagascar">Madagascar</option> <option value="Malawi">Malawi</option> <option value="Malaysia">Malaysia</option> <option value="Maldives">Maldives</option> <option value="Mali">Mali</option> <option value="Malta">Malta</option> <option value="Marshall Islands">Marshall Islands</option> <option value="Martinique (French)">Martinique (French)</option> <option value="Mauritania">Mauritania</option> <option value="Mauritius">Mauritius</option> <option value="Mayotte">Mayotte</option> <option value="Mexico">Mexico</option> <option value="Micronesia">Micronesia</option> <option value="Moldavia">Moldavia</option> <option value="Monaco">Monaco</option> <option value="Mongolia">Mongolia</option> <option value="Montserrat">Montserrat</option> <option value="Morocco">Morocco</option> <option value="Mozambique">Mozambique</option> <option value="Myanmar, Union of (Burma)">Myanmar, Union of (Burma)</option> <option value="Namibia">Namibia</option> <option value="Nauru">Nauru</option> <option value="Nepal">Nepal</option> <option value="Netherlands">Netherlands</option> <option value="Netherlands Antilles">Netherlands Antilles</option> <option value="Neutral Zone">Neutral Zone</option> <option value="New Caledonia (French)">New Caledonia (French)</option> <option value="New Zealand">New Zealand</option> <option value="Nicaragua">Nicaragua</option> <option value="Niger">Niger</option> <option value="Nigeria">Nigeria</option> <option value="Niue">Niue</option> <option value="Norfolk Island">Norfolk Island</option> <option value="North Korea">North Korea</option> <option value="Northern Mariana Islands">Northern Mariana Islands</option> <option value="Norway">Norway</option> <option value="Oman">Oman</option> <option value="Pakistan">Pakistan</option> <option value="Palau">Palau</option> <option value="Panama">Panama</option> <option value="Papua New Guinea">Papua New Guinea</option> <option value="Paraguay">Paraguay</option> <option value="Peru">Peru</option> <option value="Philippines">Philippines</option> <option value="Pitcairn Island">Pitcairn Island</option> <option value="Poland">Poland</option> <option value="Polynesia (French)">Polynesia (French)</option> <option value="Portugal">Portugal</option> <option value="Qatar">Qatar</option> <option value="Reunion (French)">Reunion (French)</option> <option value="Romania">Romania</option> <option value="Russian Federation">Russian Federation</option> <option value="Rwanda">Rwanda</option> <option value="S. Georgia &amp; S. Sandwich Islands">S. Georgia &amp; S. Sandwich Islands</option> <option value="Saint Helena">Saint Helena</option> <option value="Saint Kitts &amp; Nevis Anguilla">Saint Kitts &amp; Nevis Anguilla</option> <option value="Saint Lucia">Saint Lucia</option> <option value="Saint Pierre and Miquelon">Saint Pierre and Miquelon</option> <option value="Saint Tome and Principe">Saint Tome and Principe</option> <option value="Saint Vincent &amp; Grenadines">Saint Vincent &amp; Grenadines</option> <option value="Samoa">Samoa</option> <option value="San Marino">San Marino</option> <option value="Saudi Arabia">Saudi Arabia</option> <option value="Senegal">Senegal</option> <option value="Seychelles">Seychelles</option> <option value="Sierra Leone">Sierra Leone</option> <option value="Singapore">Singapore</option> <option value="Slovakia">Slovakia</option> <option value="Slovenia">Slovenia</option> <option value="Solomon Islands">Solomon Islands</option> <option value="Somalia">Somalia</option> <option value="South Africa">South Africa</option> <option value="South Korea">South Korea</option> <option value="Spain">Spain</option> <option value="Sri Lanka">Sri Lanka</option> <option value="Sudan">Sudan</option> <option value="Suriname">Suriname</option> <option value="Svalbard and Jan Mayen Islands">Svalbard and Jan Mayen Islands</option> <option value="Swaziland">Swaziland</option> <option value="Sweden">Sweden</option> <option value="Switzerland">Switzerland</option> <option value="Syria">Syria</option> <option value="Tadjikistan">Tadjikistan</option> <option value="Taiwan">Taiwan</option> <option value="Tanzania">Tanzania</option> <option value="Thailand">Thailand</option> <option value="Togo">Togo</option> <option value="Tokelau">Tokelau</option> <option value="Tonga">Tonga</option> <option value="Trinidad and Tobago">Trinidad and Tobago</option> <option value="Tunisia">Tunisia</option> <option value="Turkey">Turkey</option> <option value="Turkmenistan">Turkmenistan</option> <option value="Turks and Caicos Islands">Turks and Caicos Islands</option> <option value="Tuvalu">Tuvalu</option> <option value="Uganda">Uganda</option> <option value="Ukraine">Ukraine</option> <option value="United Arab Emirates">United Arab Emirates</option> <option value="Uruguay">Uruguay</option> <option value="US">US</option> <option value="USA Minor Outlying Islands">USA Minor Outlying Islands</option> <option value="Uzbekistan">Uzbekistan</option> <option value="Vanuatu">Vanuatu</option> <option value="Vatican City">Vatican City</option> <option value="Venezuela">Venezuela</option> <option value="Vietnam">Vietnam</option> <option value="Virgin Islands (British)">Virgin Islands (British)</option> <option value="Virgin Islands (USA)">Virgin Islands (USA)</option> <option value="Wallis and Futuna Islands">Wallis and Futuna Islands</option> <option value="Western Sahara">Western Sahara</option> <option value="Yemen">Yemen</option> <option value="Yugoslavia">Yugoslavia</option> <option value="Zaire">Zaire</option> <option value="Zambia">Zambia</option> <option value="Zimbabwe">Zimbabwe</option> </select> </td> </tr> <tr> <td> State: </td> <td> <select name=CompanyState> <OPTION VALUE="Not in US">Not in US</OPTION> <OPTION VALUE="Alabama">Alabama</OPTION> <OPTION VALUE="Alaska">Alaska</OPTION> <OPTION VALUE="Arizona">Arizona</OPTION> <OPTION VALUE="Arkansas">Arkansas</OPTION> <OPTION VALUE="California">California</OPTION> <OPTION VALUE="Colorado">Colorado</OPTION> <OPTION VALUE="Connecticut">Connecticut</OPTION> <OPTION VALUE="Delaware">Delaware</OPTION> <OPTION VALUE="District of Columbia">District of Columbia</OPTION> <OPTION VALUE="Florida">Florida</OPTION> <OPTION VALUE="Georgia">Georgia</OPTION> <OPTION VALUE="Hawaii">Hawaii</OPTION> <OPTION VALUE="Idaho">Idaho</OPTION> <OPTION VALUE="Illinois">Illinois</OPTION> <OPTION VALUE="Indiana">Indiana</OPTION> <OPTION VALUE="Iowa">Iowa</OPTION> <OPTION VALUE="Kansas">Kansas</OPTION> <OPTION VALUE="Kentucky">Kentucky</OPTION> <OPTION VALUE="Louisiana">Louisiana</OPTION> <OPTION VALUE="Maine">Maine</OPTION> <OPTION VALUE="Maryland">Maryland</OPTION> <OPTION VALUE="Massachusetts">Massachusetts</OPTION> <OPTION VALUE="Michigan">Michigan</OPTION> <OPTION VALUE="Minnesota">Minnesota</OPTION> <OPTION VALUE="Mississippi">Mississippi</OPTION> <OPTION VALUE="Missouri">Missouri</OPTION> <OPTION VALUE="Montana">Montana</OPTION> <OPTION VALUE="Nebraska">Nebraska</OPTION> <OPTION VALUE="Nevada">Nevada</OPTION> <OPTION VALUE="New Hampshire">New Hampshire</OPTION> <OPTION VALUE="New Jersey">New Jersey</OPTION> <OPTION VALUE="New Mexico">New Mexico</OPTION> <OPTION VALUE="New York">New York</OPTION> <OPTION VALUE="North Carolina">North Carolina</OPTION> <OPTION VALUE="North Dakota">North Dakota</OPTION> <OPTION VALUE="Ohio">Ohio</OPTION> <OPTION VALUE="Oklahoma">Oklahoma</OPTION> <OPTION VALUE="Oregon">Oregon</OPTION> <OPTION VALUE="Pennsylvania">Pennsylvania</OPTION> <OPTION VALUE="Puerto Rico">Puerto Rico</OPTION> <OPTION VALUE="Rhode Island">Rhode Island</OPTION> <OPTION VALUE="South Carolina">South Carolina</OPTION> <OPTION VALUE="South Dakota">South Dakota</OPTION> <OPTION VALUE="Tennessee">Tennessee</OPTION> <OPTION VALUE="Texas">Texas</OPTION> <OPTION VALUE="Utah">Utah</OPTION> <OPTION VALUE="Vermont">Vermont</OPTION> <OPTION VALUE="Virgin Islands">Virgin Islands</OPTION> <OPTION VALUE="Virginia">Virginia</OPTION> <OPTION VALUE="Washington">Washington</OPTION> <OPTION VALUE="West Virginia">West Virginia</OPTION> <OPTION VALUE="Wisconsin">Wisconsin</OPTION> <OPTION VALUE="Wyoming">Wyoming</OPTION> </select> </td> </tr> <tr> <td> Post Code::<font color=red>*</font> </td> <td> <input type=text name=CompanyZip> </td> </tr> <tr> <td> City:<font color=red>*</font> </td> <td> <input type=text name=CompanyCity> </td> </tr> <tr> <td> Address:<font color=red>*</font> </td> <td> <input type=text name=CompanyAddress> </td> </tr> <tr> <td> Phone:<font color=red>*</font> </td> <td> <input type=text name=CompanyPhone> </td> </tr> <tr> <td>Mobile:</td> <td> <input type=text name=CompanyPhone2> </td> </tr> <tr> <td> E-mail:<font color=red>*</font> </td> <td> <input type=text name=CompanyEmail> </td> </tr> <tr> <td align=left>&nbsp; </td> <td align=left> <input type=submit name=submit value="Register me"> <input type=reset name=reset value="Reset"> </td> </tr> </table> </form> </body> </html> <? include_once('../foother.html'); ?><file_sep><? include_once "accesscontrol.php"; $q1 = "select * from job_aplicants t1, job_careerlevel t2 where t1.aplicant = t2.uname and t1.job_id = \"$_GET[job_id]\" order by t2.clnumber desc"; $r1 = mysql_query($q1) or die(mysql_error()); //number of offer rerviews $q22 = "select nv from job_post where job_id = \"$_GET[job_id]\" "; $r22 = mysql_query($q22) or die(mysql_error()); $a22 = mysql_fetch_array($r22); //number of offer aplicants $q33 = "select count(aplicant) from job_aplicants where job_id = \"$_GET[job_id]\" "; $r33 = mysql_query($q33) or die(mysql_error()); $a33 = mysql_fetch_array($r33); echo "<br><br><br><table align=center width=446 cellspacing=0> <caption align=center><b> Aplicants list for Job ID# $_GET[job_id] / position $position </b><br><font size=2> This offer was reviewed $a22[0] time(s) and there are $a33[0] aplicant(s). </font> </caption> <tr bgcolor=red style=\"font-family:arial; font-size:12; color:white; font-weight:bold\"><td width=150>Name </td><td>Career level </td></tr>"; $col = "cococo"; while ($a1 = mysql_fetch_array($r1)) { $q2 = "select fname, lname from job_seeker_info where uname = \"$a1[uname]\" "; $r2 = mysql_query($q2) or die(mysql_error()); $a2 = mysql_fetch_array($r2); if($col == "cococo") { $col = "dddddd"; } else { $col = "cococo"; } echo "<tr bgcolor=\"$col\"><td><a class=TN href=\"javascript:popUp('EmployerView2.php?uname=$a1[uname]&ename=$ename')\"> $a2[0] $a2[1] </a></td><td> $a1[clname] </td></tr>"; } echo "</table><center><br><a class=TN href=DeleteJob.php> << go back </a></center>"; ?> <? include_once('../foother.html'); ?><file_sep><? include_once "conn.php"; $sbs = "select * from job_banners_m"; $rsbs = mysql_query($sbs) or die(mysql_error()); $abs = mysql_fetch_array($rsbs); $bs = $abs[0]; if ($bs == 1) { $q1 = "select * from job_banners_t"; $r1 = mysql_query($q1) or die (mysql_error()); $a = mysql_num_rows($r1); if ($a > 1) { mt_srand((double)microtime() * 1000000); $ban_n = mt_rand(1,$a); $qsb = "select burl, fn, alt from job_banners_t where b_id = \"$ban_n\" "; $rsb = mysql_query($qsb) or die (mysql_error()); $asb = mysql_fetch_array($rsb); echo " <a href=\"$asb[burl]\" target=_blank alt=\"$asb[alt]\"><img src=\"../siteadmin/banners/$asb[fn]\" border=0></a> "; } elseif ($a == 1) { $qsb = "select burl, fn, alt from job_banners_t where b_id = \"1\" "; $rsb = mysql_query($qsb) or die (mysql_error()); $asb = mysql_fetch_array($rsb); echo " <a href=\"$asb[burl]\" target=_blank alt=\"$asb[alt]\"><img src=\"../siteadmin/banners/$asb[fn]\" border=0></a> "; } } elseif($bs == 2) { $bc = "select * from job_link_source"; $rbc = mysql_query($bc) or die(mysql_error()); $b = mysql_num_rows($rbc); if ($b > 1) { mt_srand((double)microtime() * 1000000); $link_id = mt_rand(1,$b); $sl = "select link_code from job_link_source where link_id = \"$link_id\" "; $rsl = mysql_query($sl) or die(mysql_error()); $asl = mysql_fetch_array($rsl); $link_code = $asl[0]; echo " $link_code "; } elseif($b == 1) { $sl = "select link_code from job_link_source where link_id = \"1\" "; $rsl = mysql_query($sl) or die(mysql_error()); $asl = mysql_fetch_array($rsl); $link_code = $asl[0]; echo " $link_code "; } } ?><file_sep><? include_once "accesscontrol2.php"; if ($_GET['d']==1 && $_GET['f'] != "") { mysql_query("update job_seeker_info set isupload=0, resume='0' where uname=\"$uname\" ") or die(mysql_error()); @unlink($_GET['f']); } if (isset($_POST['up'])) { $uploaddir = 'resumes/'; $uploadfile = $uploaddir . $uname . "_" . $_FILES['userfile']['name']; // echo $uploadfile; $pos1 = strpos(strtolower($uploadfile), ".pdf"); $pos2 = strpos(strtolower($uploadfile), ".doc"); $pos3 = strpos(strtolower($uploadfile), ".zip"); $pos4 = strpos(strtolower($uploadfile), ".rar"); if ($pos1 != 0 || $pos2 != 0 || $pos3 != 0 || $pos4 != 0) { if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { mysql_query("update job_seeker_info set isupload=1, resume='$uploadfile' where uname=\"$uname\" ") or die(mysql_error()); echo "<table width=446><tr><td><center><br><br>File is valid, and was successfully uploaded.<br><br></center></tr></td></table>"; include_once('../foother.html'); exit(); } else { print "<table width=446><tr><td><center><br><br>Possible file upload attack! Cannot upload\n</center></tr></td></table>"; include_once('../foother.html'); exit(); } } else { print "<table width=446><tr><td><center><br><br>Only files with following extensions are allowed: .PDF, .DOC, .ZIP, .RAR\n</center></tr></td></table>"; // include_once('../foother.html'); // exit(); } } $r=mysql_query("select isupload,resume from job_seeker_info where uname=\"$uname\" "); $r2=mysql_fetch_object($r); if ($r2->isupload==1) {?> <table width=446 bgcolor="#FFFFFF"> <tr><td><center><br><br>Resume already Uploaded</center></tr></td> <tr><td><center><br><a href="<?=$r2->resume?>">Download Resume</a>&nbsp;|&nbsp;<a href="<?=$PHP_SELF . "?d=1&f=" . $r2->resume?>">Delete Resume</a></center></tr></td> </table> <? include_once('../foother.html'); exit(); } ?> <br><br> <form action="<?=$PHP_SELF?>" method="post" enctype="multipart/form-data" style="background:none;"> <table align = center width="446" bgcolor="#FFFFFF"> <tr> <td colspan=2 align=center><b> Upload your Resume</b></td> </tr> <tr> <td width="127" height="26" align=center>Upload your resume</td> <td width="307" height="26"><input name="userfile" type="file" /> &nbsp;</td> <input type="hidden" value="1" name="up"> </tr> <tr> <td align=left><br><font size=1 face=verdana>&nbsp; </font></td> <td align=left><input name="submit" type="submit" style="border-width:1; border-color:black; font-family:verdana; font-weight:normal; color:#000000; background-color:#e0e7e9" value="Upload"> <br> </td> </tr> </table> </form> <? include_once('../foother.html'); ?><file_sep><? include_once "../conn.php"; $q1 = "select JS_number from job_employer_info where ename = \"$ename\" "; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); if($a1[0] > 0) { $aup = $a1[0] - 1; $qup = "update job_employer_info set JS_number = \"$aup\" where ename = \"$ename\" "; $rup = mysql_query($qup) or die(mysql_error()); include "ereview.php"; } else { echo "You resume view limit is depleted. "; include_once('../foother.html'); } ?><file_sep> <!-- Tab menu --> <ul id="menuTab" class="jeegoocontext cm_default"> <li id="edit" class="icon"><span class="icon edit"></span><?php echo _('Edit'); ?></li> <li class="separator"></li> <li id="delete" class="icon"><span class="icon delete"></span><?php echo _('Delete'); ?></li> <li class="separator"></li> <li id="duplicate" class="icon"><span class="icon duplicateTab"></span><?php echo _('Duplicate'); ?></li> <li class="separator"></li> <li id="tabCreated" class="detail"><div id="dateCreated"><?php echo _('Created'); ?>: </div> <ul> <li class="detail"><?php echo _('Set'); ?> <input name="date_created" type="text" value="" class="dateCreatedInput" /></li> </ul> </li> </ul> <!-- Page menu --> <ul id="menuPage" class="jeegoocontext cm_default"> <li id="edit" class="icon"><span class="icon edit"></span><?php echo _('Edit'); ?></li> <li id="columns"><?php echo _('Columns per Page'); ?> <ul> <li id="one-column">1 Column per Page</li> <li id="two-column">2 Columns per Page</li> <li id="three-column">3 Columns per Page</li> </ul> </li> <li class="separator"></li> <li id="delete" class="icon"><span class="icon delete"></span><?php echo _('Delete'); ?></li> <li class="separator"></li> <li id="duplicate" class="icon"><span class="icon duplicatePage"></span><?php echo _('Duplicate'); ?></li> <li class="separator"></li> <li id="pageCreated" class="detail"><div id="dateCreated"><?php echo _('Created'); ?>: </div> <ul> <li class="detail"><?php echo _('Set'); ?> <input name="date_created" type="text" value="" class="dateCreatedInput" /></li> </ul> </li> </ul> <!-- List menu --> <ul id="menuList" class="jeegoocontext cm_default"> <li id="edit" class="icon"><span class="icon edit"></span><?php echo _('Edit'); ?></li> <li class="separator"></li> <li id="delete" class="icon"><span class="icon delete"></span><?php echo _('Delete'); ?></li> <li class="separator"></li> <li id="duplicate" class="icon"><span class="icon duplicateList"></span><?php echo _('Duplicate'); ?></li> <li class="separator"></li> <li id="show_item_dates"><?php echo _('Show Item Dates'); ?></li> <li id="hide_item_dates"><?php echo _('Hide Item Dates'); ?></li> <li class="separator"></li> <li id="listCreated" class="detail"><div id="dateCreated"><?php echo _('Created'); ?>: </div> <ul> <li class="detail"><?php echo _('Set'); ?> <input name="date_created" type="text" value="" class="dateCreatedInput" /></li> </ul> </li> </ul> <!-- Item menu --> <ul id="menuItem" class="jeegoocontext cm_default"> <li id="edit" class="icon"><span class="icon edit"></span><?php echo _('Edit'); ?></li> <li id="advancedEdit" class="icon"><span class="icon edit"></span><?php echo _('Advanced Edit'); ?></li> <li class="separator"></li> <li id="markComplete" class="icon"><span class="icon complete"></span><?php echo _('Mark Complete'); ?></li> <li id="markIncomplete" class="icon"><span class="icon incomplete"></span><?php echo _('Mark Incomplete'); ?></li> <li class="separator"></li> <li id="delete" class="icon"><span class="icon delete"></span><?php echo _('Delete'); ?></li> <li class="separator"></li> <li id="itemCreated" class="detail"><div id="dateCreated"><?php echo _('Created'); ?>: </div> <ul> <li class="detail"><?php echo _('Set'); ?> <input name="date_created" type="text" value="" class="dateCreatedInput" /></li> </ul> </li> <li id="itemCompleted" class="detail"><div id="dateCompleted"><?php echo _('Completed'); ?>: </div> <ul> <li class="detail"><?php echo _('Set'); ?> <input name="date_completed" type="text" value="" class="dateCompletedInput" /></li> </ul> </li> </ul> <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"> <?php include_once("..\includes\documentHeader.php"); print_r(docHeader('../..')); ?> <script language="JavaScript1.2" type="text/javascript" src="popUpWindowForURL.js"></script> </head> <body> <?php if (stristr($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) == false) { $ar = splitStringToArray($_SERVER['SCRIPT_NAME']); redirectBrowser('/?linkname=' . $ar[count($ar) - 1]); } ?> <?php print(handleNoScript()); ?> <table width="590"> <tr> <td class="primaryContentContainerHeader"> <table width="100%"> <tr> <td align="left"> <p align="justify"><a href="/php/links/getContentForFlashComposer.php" target="_self">Flash Composer</a></p> </td> <td align="right"> </td> </tr> </table> </td> </tr> <tr> <td height="200" valign="middle"> <table width="100%"> <tr> <td width="80%" valign="top"> <p align="justify">Welcome to the Flash Composer Sample(s).</p> <p align="justify">Flash Composer is a concept that seeks to create a Flash-based Content Management System through the use of Flash.</p> <p align="justify">The first example of Flash Composer is a rather simple-looking Painter. The Painter allows you to make a freehand drawing you can dynamically redraw.</p> <p align="justify">Keep in mind the Painter stores all the mouse-strokes, color selections and other attributes such as line width selections and it plays them back at-will.</p> <p align="justify">Flash-based Electronic Whiteboard Apps have been around for a long time on the web, this is not a new idea but it can be a useful idea. It only took a few hours to make this sample come to life. It would be quite easy to enable ezPainter to do any number of functions with the stored mouse-strokes such as but not limited to communicating the drawing to someone else who happens to be connected to the same Media Server, for instance.</p> </td> <td width="*" valign="top"> <p align="justify"><NOBR><a href="" onClick="popUpWindowForURL('/app/flash/composer/ezpainter.html', 'ezpainter', 750, 520); return false;">Flash Composer - ezPainter Sample</a></NOBR></p> </td> </tr> </table> <!-- <h4>Under construction... Come on back a bit later-on...</h4> --> </td> </tr> </table> </body> </html> <file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <meta http-equiv="Content-Language" content="UTF-8" /> <meta http-equiv="Content-Type" content="text/xhtml; charset=UTF-8" /> <link rel="stylesheet" href="style/master.css" type="text/css" /> <link rel="Shortcut Icon" href="images/blueBox.bmp" /> <?php preg_match('/(\w+)\.php/',basename($_SERVER['PHP_SELF']),$pageTitle); print "<title>Workbench - " . ucwords($pageTitle[1]) . "</title>" ?> <body> <script type="text/javascript" src="script/wz_tooltip.js"></script> <?php if($_GET['autoLogin'] == 1 || 'login.php'==basename($_SERVER['PHP_SELF'])){ checkLatestVersion(); } ?> <div id='main_block'> <div id='setupMenu'> <?php global $mySforceConnection; if (isset($_SESSION['sessionId']) && $mySforceConnection && 'logout.php' != basename($_SERVER['PHP_SELF'])){ if(!$_SESSION['getUserInfo'] || !$_SESSION['config']['cacheGetUserInfo']){ try{ global $mySforceConnection; $_SESSION['getUserInfo'] = $mySforceConnection->getUserInfo(); } catch (Exception $e) { $errors[] = $e->getMessage(); session_unset(); session_destroy(); } } } $setupBar_items = array (); if(!isset($_SESSION['sessionId']) || 'logout.php' == basename($_SERVER['PHP_SELF'])){ $setupBar_items['login.php'] = array('Login','Logs into your Salesforce organization'); } else { $setupBar_items['logout.php'] = array('Logout','Logs out of your Salesforce organization'); } $setupBar_items['settings.php'] = array('Settings','Configure the Workbench'); $setupBar_items['help.php'] = array('Help','Get help about using the Workbench'); $setupBar_items['about.php'] = array('About','Learn about the Workbench'); foreach($setupBar_items as $href => $label){ print "<a href='$href'"; if (!strcmp($href,basename($_SERVER['PHP_SELF']))){ print " style='color: #0046ad;'"; } print " onmouseover=\"Tip('$label[1]')\">$label[0]</a>&nbsp;&nbsp;"; } ?> </div> <div style="clear: both; text-align: center"><p> <img src="images/workbench-2-squared.png" width="257" height="50" alt="Workbench 2 Logo" border="0" /></p> </div> <div id='navmenu' style="clear: both;"> <?php $navbar_items = array ( // 'login.php'=>array('Login','Logs into your Salesforce organization'), // 'select.php'=>array('Select','Selects an action to perform on an object'), 'describe.php'=>array('Describe','Describes the attributes, fields, record types, and child relationships of an object'), 'insert.php'=>array('Insert','Creates new records from a CSV file'), 'upsert.php'=>array('Upsert','Creates new records and/or updates existing records from a CSV file based on a unique External Id'), 'update.php'=>array('Update','Updates existing records from a CSV file'), 'delete.php'=>array('Delete','Moves records listed in a CSV file to the Recycle Bin. Note, some objects cannot be undeleted'), 'undelete.php'=>array('Undelete','Restores records listed in a CSV file from the Recycle Bin. Note, some objects cannot be undeleted.'), 'purge.php' =>array('Purge','Permenantly deletes records listed in a CSV file from your Recycle Bin.'), 'query.php'=>array('Query','Queries the data in your organization and displays on the screen or exports to a CSV file'), 'search.php'=>array('Search','Search the data in your organization across multiple objects'), 'execute.php'=>array('Execute','Execute Apex code as an anonymous block') // 'settings.php'=>array('Settings','Configure the Workbench'), // 'logout.php'=>array('Logout','Logs out of your Salesforce organization') ); print "| "; foreach($navbar_items as $href => $label){ print "<a href='$href'"; if (!strcmp($href,basename($_SERVER['PHP_SELF']))){ print " style='color: #0046ad;' "; } print " onmouseover=\"Tip('$label[1]')\">$label[0]</a> | "; } ?> </div> <p/> <?php if(isset($_SESSION['getUserInfo'])){ print "<p id='myuserinfo'>Logged in as " . $_SESSION['getUserInfo']->userFullName . " at " . $_SESSION['getUserInfo']->organizationName . "</p>\n"; } if(isset($errors)){ print "<p/>"; show_error($errors); include_once('footer.php'); exit; } ?><file_sep><?php $version = "2.2.15"; function show_error($errors){ print "<div class='show_errors'>\n"; print "<img src='images/error24.png' width='24' height='24' align='middle' border='0' alt='ERROR:' /> <p/>"; if(is_array($errors)){ $errorString = null; foreach($errors as $error){ $errorString .= "<p>" . htmlspecialchars($error) . "</p>"; $errorString = str_replace("\n","<br/>",$errorString); } } else { $errorString = htmlspecialchars($errors); $errorString = str_replace("\n","<br/>",$errorString); } print $errorString; print "</div>\n"; } function show_info($infos){ print "<div class='show_info'>\n"; print "<img src='images/info24.png' width='24' height='24' align='middle' border='0' alt='info:' /> <p/>"; if(is_array($infos)){ foreach($infos as $info){ $infoString .= "<p>" . htmlspecialchars($info) . "</p>"; } print $infoString; } else { print htmlspecialchars($infos); } print "</div>\n"; } function checkLatestVersion(){ global $version; try{ if(extension_loaded('curl')){ $ch = curl_init(); if(stristr($version,'beta')){ curl_setopt ($ch, CURLOPT_URL, 'http://forceworkbench.sourceforge.net/latestVersionAvailableBeta.txt'); } else { curl_setopt ($ch, CURLOPT_URL, 'http://forceworkbench.sourceforge.net/latestVersionAvailable.txt'); } curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $latestVersionAvailable = trim(curl_exec($ch)); curl_close($ch); if (preg_match('/^[0-9]+.[0-9]+/',$latestVersionAvailable) && !stristr($version,'alpha')){ if($latestVersionAvailable != $version){ print "<span style='font-size: 8pt; font-weight: bold;'><a href='http://code.google.com/p/forceworkbench/' target='_blank' style='color: #0046ad;'>A newer version of the Workbench is available for download</a></span><br/>"; } } } } catch (Exception $e){ //do nothing } } function printSelectOptions($valuesToLabelsArray,$defaultValue){ foreach($valuesToLabelsArray as $value => $label){ print "<option value=\"" . $value . "\""; if($defaultValue == $value){ print " selected=\"selected\""; } print ">" . $label . "</option>"; } } function myGlobalSelect($default_object=null, $nameId='default_object', $width=20, $extras=null){ print "<select id='$nameId' name='$nameId' style='width: " . $width. "em;' $extras>\n"; // print "<select id='myGlobalSelect' name='default_object' style='width: 20em;'>\n"; print "<option value=''></option>"; if (!$_SESSION['myGlobal'] || !$_SESSION['config']['cacheDescribeGlobal']){ try{ global $mySforceConnection; $_SESSION['myGlobal'] = $mySforceConnection->describeGlobal(); } catch (Exception $e) { $errors[] = $e->getMessage(); show_error($errors); exit; } } //Print the global object types in a dropdown select box foreach($_SESSION['myGlobal']->types as $type){ print " <option value='$type'"; if ($default_object == $type){ print " selected='true'"; } print " />$type</option> \n"; } print "</select>\n"; } function describeSObject($objectTypes){ // if a scalar is passed to this function, change it to an array if (!is_array($objectTypes)){ $objectTypeArray = array($objectTypes); } else { $objectTypeArray = $objectTypes; } // find which objects are already in the session cache to only retreive the // ones uncached ones. if caching is disabled, just retreive everything and // clear the cache. $objectTypesToRetreive = array(); if($_SESSION['config']['cacheDescribeSObject']){ foreach($objectTypeArray as $objectType){ if(!isset($_SESSION['describeSObjects_results'][$objectType])){ $objectTypesToRetreive[] = $objectType; } } } else { $objectTypesToRetreive = $objectTypeArray; $_SESSION['describeSObjects_results'] = null; } // retreive uncached object descriptions from the API and return as an array. if (count($objectTypesToRetreive) >= 1 && count($objectTypesToRetreive) <= 100){ try{ global $mySforceConnection; $describeSObjects_results = $mySforceConnection->describeSObjects($objectTypesToRetreive); } catch (Exception $e) { $errors[] = $e->getMessage(); show_error($errors); exit; } if (!is_array($objectTypes)){ $describeSObjects_results_array = array($describeSObjects_results->name => $describeSObjects_results); } else { foreach ($describeSObjects_results as $describeSObject_resultKey => $describeSObject_resultValue){ $describeSObjects_results_array[$describeSObject_resultValue->name] = $describeSObject_resultValue; } } } else if(count($objectTypesToRetreive) > 100) { show_error("Too many polymorphic object types: " . count($objectTypesToRetreive)); include_once("footer.php"); exit; } // move the describe results to the session cache and then copy all the requested object descriptions from the cache // if caching is disaled, the results will just be returned directly if($_SESSION['config']['cacheDescribeSObject']){ if(isset($describeSObjects_results_array)){ foreach ($describeSObjects_results_array as $describeSObject_resultKey => $describeSObject_result){ $_SESSION['describeSObjects_results'][$describeSObject_result->name] = $describeSObjects_results_array[$describeSObject_result->name]; } } foreach($objectTypeArray as $objectTypeKey => $objectTypeValue){ $describeSObjects_results_ToReturn[$objectTypeValue] = $_SESSION['describeSObjects_results'][$objectTypeValue]; } } else { $describeSObjects_results_ToReturn = $describeSObjects_results_array; } // if alphabetize fields is enabled, alphabetize the describe results if($_SESSION['config']['abcOrder']){ foreach ($describeSObjects_results_ToReturn as $describeSObject_resultKey => $describeSObject_result){ $describeSObjects_results_ToReturn[$describeSObject_resultKey] = alphaOrderFields($describeSObject_result); } } //finally, return the describe results if (!is_array($objectTypes)){ return $describeSObjects_results_ToReturn[$objectTypes]; } else { return $describeSObjects_results_ToReturn; } } function alphaOrderFields($describeSObject_result){ //move field name out to key name and then ksort based on key for field abc order if(isset($describeSObject_result->fields)){ foreach($describeSObject_result->fields as $field){ $fieldNames[] = $field->name; } $describeSObject_result->fields = array_combine($fieldNames, $describeSObject_result->fields); ksort($describeSObject_result->fields); } return $describeSObject_result; } function field_mapping_set($action,$csv_array){ if ($action == 'insert' || $action == 'upsert' || $action == 'update'){ if (isset($_SESSION['default_object'])){ $describeSObject_result = describeSObject($_SESSION['default_object']); } else { show_error("A default object is required to $action. Go to the Select page to choose a default object and try again."); } } print "<form method='POST' action='" . $_SERVER['PHP_SELF'] . "'>"; if ($action == 'upsert'){ print "<p><strong>Choose the Salesforce field to use as the External Id. Be sure to also map this field below:</strong></p>\n"; print "<table class='field_mapping'><tr>\n"; print "<td style='color: red;'>External Id</td>"; print "<td><select name='_ext_id' style='width: 100%;'>\n"; // print " <option value=''></option>\n"; foreach($describeSObject_result->fields as $fields => $field){ if($field->idLookup){ //limit the fields to only those with the idLookup property set to true. Corrected Issue #10 print " <option value='$field->name'"; if($field->name == 'Id') print " selected='true'"; print ">$field->name</option>\n"; } } print "</select></td></tr></table>\n"; } //end if upsert print "<p><strong>Map the Salesforce fields to the columns from the uploaded CSV:</strong></p>\n"; print "<table class='field_mapping'>\n"; print "<tr><th>Salesforce Field</th>"; print "<th>CSV Field</th>"; if ($_SESSION['config']['showReferenceBy'] && ($action == 'insert' || $action == 'update' || $action == 'upsert')) print "<th onmouseover=\"Tip('For fields that reference other objects, external ids from the foreign objects provided in the CSV file and can be automatically matched to their cooresponding primary ids. Use this column to select the object and field by which to perform the Smart Lookup. If left unselected, standard lookup using the primary id will be performed. If this field is disabled, only stardard lookup is available because the foreign object contains no external ids.')\">Smart Lookup &nbsp; <img align='absmiddle' src='images/help16.png'/></th>"; print "</tr>\n"; if ($action == 'insert'){ foreach($describeSObject_result->fields as $fields => $field){ if ($field->createable){ printPutFieldForMapping($field, $csv_array); } } } if ($action == 'update'){ field_mapping_idOnly_set($csv_array, true); foreach($describeSObject_result->fields as $fields => $field){ if ($field->updateable){ printPutFieldForMapping($field, $csv_array); } } } if ($action == 'upsert'){ field_mapping_idOnly_set($csv_array, true); foreach($describeSObject_result->fields as $fields => $field){ if ($field->updateable && $field->createable){ printPutFieldForMapping($field, $csv_array); } } } if ($action == 'delete' || $action == 'undelete' || $action == 'purge'){ field_mapping_idOnly_set($csv_array, false); } print "</table>\n"; print "<p><input type='submit' name='action' value='Map Fields' />\n"; print "<input type='button' value='Preview CSV' onClick='window.open(" . '"csv_preview.php"' . ")'></p>\n"; print "</form>\n"; } function printPutFieldForMapping($field, $csv_array){ print "<tr"; if (!$field->nillable && !$field->defaultedOnCreate) print " style='color: red;'"; print "><td>$field->name</td>"; print "<td><select name='$field->name' style='width: 100%;'>"; print " <option value=''></option>\n"; foreach($csv_array[0] as $col){ print "<option value='$col'"; if (strtolower($col) == strtolower($field->name)) print " selected='true' "; print ">$col</option>\n"; } print "</select></td>"; if($_SESSION['config']['showReferenceBy']){ if(isset($field->referenceTo) && isset($field->relationshipName)){ $describeRefObjResult = describeSObject($field->referenceTo); printRefField($field, $describeRefObjResult); } else { print "<td>&nbsp;</td>\n"; } } print "</tr>\n"; } function printRefField($field, $describeRefObjResult){ if(is_array($describeRefObjResult)){ $polyExtFields = array(); foreach($describeRefObjResult as $describeRefObjResultKey => $describeRefObjResult){ $extFields = null; if(isset($describeRefObjResult->fields)){ foreach($describeRefObjResult->fields as $extFieldKey => $extFieldVal){ if($extFieldVal->idLookup == true){ $extFields[$extFieldKey] = $extFieldVal; } } $polyExtFields[$describeRefObjResult->name] = $extFields; } } //check if the new array has any fields print "<td><select name='$field->name:$field->relationshipName' style='width: 100%;'"; $numOfExtFields = 0; foreach($polyExtFields as $extFields){ if(count($extFields) > 1){ $numOfExtFields = $numOfExtFields + count($extFields) - 1; } } if($numOfExtFields <= 0){ print " disabled='true' "; } print ">\n"; print " <option value='Id' selected='true'></option>\n"; foreach($polyExtFields as $objectType => $extFields){ if(count($extFields) > 0){ foreach($extFields as $extFieldKey => $extFieldVal){ if ($extFieldVal->name != 'Id'){ print " <option value='$field->name.$field->relationshipName.$objectType.$extFieldVal->name'>$objectType.$extFieldVal->name</option>\n"; } } } } print "</select></td>\n"; } else { //for scalar values //check to see if there are any IdLookup fields and if so move them to a new array $extFields = null; if(count($describeRefObjResult->fields) > 0){ foreach($describeRefObjResult->fields as $extFieldKey => $extFieldVal){ if($extFieldVal->idLookup == true){ $extFields[$extFieldKey] = $extFieldVal; } } } //check if the new array has any fields and if so if(count($extFields) > 0){ print "<td><select name='$field->name:$field->relationshipName' style='width: 100%;'"; if (count($extFields) == 1) print " disabled='true' "; //disable the selection if only one choice ('Id') is available print ">\n"; print " <option value='Id' selected='true'></option>\n"; foreach($extFields as $extFieldKey => $extFieldVal){ if ($extFieldVal->name != 'Id'){ print " <option value='$field->name.$field->relationshipName.$describeRefObjResult->name.$extFieldVal->name'>$describeRefObjResult->name.$extFieldVal->name</option>\n"; } } print "</select></td>\n"; } } } function field_mapping_idOnly_set($csv_array, $showRefCol){ print "<tr style='color: red;'><td>Id</td>"; print "<td><select name='Id' style='width: 100%;'>"; print " <option value=''></option>\n"; foreach($csv_array[0] as $col){ print "<option value='$col'"; if (strtolower($col) == 'id') print " selected='true' "; print ">$col</option>\n"; } print "</select></td>"; if ($showRefCol && $_SESSION['config']['showReferenceBy']) print "<td></td>"; print"</tr>\n"; } function field_map_to_array($field_map){ $field_map_array = array(); foreach($field_map as $fieldMapKey=>$fieldMapValue){ if(preg_match('/^(\w+):(\w+)$/',$fieldMapKey,$keyMatches)){ if(preg_match('/^(\w+).(\w+).(\w+).(\w+)$/',$fieldMapValue,$valueMatches)){ $field_map_array[$valueMatches[1]]["relationshipName"] = $valueMatches[2]; $field_map_array[$valueMatches[1]]["relatedObjectName"] = $valueMatches[3]; $field_map_array[$valueMatches[1]]["relatedFieldName"] = $valueMatches[4]; } } else if ($fieldMapValue){ $field_map_array[$fieldMapKey]["csvField"] = $fieldMapValue; } } return $field_map_array; } function field_mapping_show($field_map,$ext_id){ if ($ext_id){ print "<table class='field_mapping'>\n"; print "<tr><td>External Id</td> <td>$ext_id</td></tr>\n"; print "</table><p/>\n"; } print "<table class='field_mapping'>\n"; print "<tr><th>Salesforce Field</th>"; print "<th>CSV Field</th>"; if ($_SESSION['config']['showReferenceBy']) print "<th>Smart Lookup</th>"; print "</tr>\n"; foreach($field_map as $salesforce_field=>$fieldMapArray){ print "<tr><td>$salesforce_field</td>"; print "<td>" . $fieldMapArray['csvField'] . "</td>"; if ($_SESSION['config']['showReferenceBy']){ print "<td>"; if ($fieldMapArray['relatedObjectName'] && $fieldMapArray['relatedFieldName']){ print $fieldMapArray['relatedObjectName'] . "." . $fieldMapArray['relatedFieldName']; } print "</td>"; } print "</tr>\n"; } print "</table>\n"; } function field_mapping_idOnly_show($field_map){ print "<table class='field_mapping'>\n"; print "<tr><th>Salesforce Field</th>"; print "<th>CSV Field</th>"; print "</tr>\n"; foreach($field_map as $salesforce_field=>$csv_field){ print "<tr><td>$salesforce_field</td>"; print "<td>$csv_field</td></tr>\n"; } print "</table>\n"; } function field_mapping_confirm($action,$field_map,$csv_array,$ext_id){ if (!($field_map && $csv_array)){ show_error("CSV file and field mapping not initialized successfully. Upload a new file and map fields."); } else { if (($action == 'Confirm Update') || ($action == 'Confirm Delete') || ($action == 'Confirm Undelete') || ($action == 'Confirm Purge')){ if (!isset($field_map['Id'])){ show_error("Salesforce ID not selected. Please try again."); include_once('footer.php'); exit(); } else { ob_start(); if(($action == 'Confirm Delete') || ($action == 'Confirm Undelete') || ($action == 'Confirm Purge')){ field_mapping_idOnly_show($field_map); } else { field_mapping_show($field_map,null); } $id_col = array_search($field_map['Id'],$csv_array[0]); for($row=1,$id_count = 0; $row < count($csv_array); $row++){ if ($csv_array[$row][$id_col]){ $id_count++; } } $field_mapping_table = ob_get_clean(); show_info ("The file uploaded contains $id_count records with Salesforce IDs with the field mapping below."); print "<p><strong>Confirm the mappings below:</strong></p>"; print "<p>$field_mapping_table</p>"; } } else { $record_count = count($csv_array) - 1; show_info ("The file uploaded contains $record_count records to be added to " . $_SESSION['default_object']); print "<p><strong>Confirm the mappings below:</strong></p>"; field_mapping_show($field_map,$ext_id); } print "<form method='POST' action='" . $_SERVER['PHP_SELF'] . "'>"; print "<p><input type='submit' name='action' value='$action' /></p>\n"; print "</form>\n"; } } function form_upload_objectSelect_show($file_input_name,$showObjectSelect = FALSE){ print "<form enctype='multipart/form-data' method='post' action='" . $_SERVER['PHP_SELF'] . "'>\n"; print "<input type='hidden' name='MAX_FILE_SIZE' value='" . $_SESSION['config']['maxFileSize'] . "' />\n"; print "<p><input type='file' name='$file_input_name' size=44 /></p>\n"; if ($showObjectSelect){ myGlobalSelect($_SESSION['default_object']); $submitLabel = 'Upload & Select Object'; } else { $submitLabel = 'Upload'; } print "<p><input type='submit' name='action' value='$submitLabel' /></p>\n"; print "</form>\n"; } function csv_upload_valid_check($file){ if($file['error'] !== 0){ $upload_error_codes = array( 0=>"There is no error, the file uploaded with success", 1=>"The file uploaded is too large. Please try again. (Error 1)", //as per PHP config 2=>"The file uploaded is too large. Please try again. (Error 2)", //as per form config 3=>"The file uploaded was only partially uploaded. Please try again. (Error 3)", 4=>"No file was uploaded. Please try again. (Error 4)", 6=>"Missing a temporary folder. Please try again. (Error 6)", 7=>"Failed to write file to disk. Please try again. (Error 7)", 8=>"File upload stopped by extension. Please try again. (Error 8)" ); if($_SESSION['config']['maxFileSize']['overrideable']){ $upload_error_codes[2] = "The file uploaded is too large. Please try again or adjust in Settings. (Error 2)"; } return($upload_error_codes[$file['error']]); } elseif(!is_uploaded_file($file['tmp_name'])){ return("The file was not uploaded from your computer. Please try again."); } elseif((!stristr($file['type'],'csv') || $file['type'] !== "application//vnd.ms-excel") && !stristr($file['name'],'.csv')){ return("The file uploaded is not a valid CSV file. Please try again."); } elseif($file['size'] == 0){ return("The file uploaded contains no data. Please try again."); } else{ return(0); } } function csv_file_to_array($file){ $csv_array = array(); $handle = fopen($file, "r"); for ($row=0; ($data = fgetcsv($handle)) !== FALSE; $row++) { for ($col=0; $col < count($data); $col++) { $csv_array[$row][$col] = $data[$col]; } } fclose($handle); if ($csv_array !== NULL){ return($csv_array); } else { echo("There were errors parsing your CSV file. Please try again."); exit; } } function csv_array_show($csv_array){ print "<table class='data_table'>\n"; print "<tr>"; for($col=0; $col < count($csv_array[0]); $col++){ print "<th>"; print htmlspecialchars($csv_array[0][$col],ENT_QUOTES,'UTF-8'); print "</th>"; } print "</tr>\n"; for($row=1; $row < count($csv_array); $row++){ print "<tr>"; for($col=0; $col < count($csv_array[0]); $col++){ print "<td>"; if ($csv_array[$row][$col]){ print htmlspecialchars($csv_array[$row][$col],ENT_QUOTES,'UTF-8'); } else { print "&nbsp;"; } print "</td>"; } print "</tr>\n"; } print "</table>\n"; } function idOnlyCallIds($api_call,$field_map,$csv_array,$show_results){ if (!($field_map && $csv_array)){ show_error("CSV file and field mapping not initialized successfully. Upload a new file and map fields."); } else { $id_array = array(); $id_col = array_search($field_map['Id'],$csv_array[0]); for($row=1; $row < count($csv_array); $row++){ if ($csv_array[$row][$id_col]){ $id_array[] = $csv_array[$row][$id_col]; } } $results = array(); $id_array_all = $id_array; while($id_array){ $id_arrayBatch = array_splice($id_array,0,$_SESSION['config']['batchSize']); try{ global $mySforceConnection; if($api_call == 'purge') $api_call = 'emptyRecycleBin'; $results_more = $mySforceConnection->$api_call($id_arrayBatch); if(!$results){ $results = $results_more; } else { $results = array_merge($results,$results_more); } } catch (Exception $e) { $errors = null; $errors = $e->getMessage(); show_error($errors); include_once("footer.php"); exit; } } if($show_results) show_idOnlyCall_results($results,$id_array_all); } } function putSObjects($api_call,$ext_id,$field_map,$csv_array,$show_results){ if (!($field_map && $csv_array && $_SESSION['default_object'])){ show_error("CSV file and field mapping not initialized. Upload a new file and map fields."); } else { $csv_header = array_shift($csv_array); $results = array(); while($csv_array){ $sObjects = array(); $csv_arrayBatch = array_splice($csv_array,0,$_SESSION['config']['batchSize']); for($row=0; $row < count($csv_arrayBatch); $row++){ $sObject = new SObject; $sObject->type = $_SESSION['default_object']; if($_SESSION['config']['fieldsToNull']) $sObject->fieldsToNull = array(); $fields = array(); foreach($field_map as $salesforce_field=>$fieldMapArray){ if(isset($fieldMapArray['relatedObjectName']) && isset($fieldMapArray['relatedFieldName']) && isset($fieldMapArray['csvField'])){ $refSObject = new SObject; $refSObject->type = $fieldMapArray['relatedObjectName']; $col = array_search($fieldMapArray['csvField'],$csv_header); if($csv_arrayBatch[$row][$col] != ""){ $refSObject->fields = array($fieldMapArray['relatedFieldName'] => htmlspecialchars($csv_arrayBatch[$row][$col],ENT_QUOTES,'UTF-8')); } $field = array($fieldMapArray['relationshipName'] => $refSObject); } else if(isset($salesforce_field) && isset($fieldMapArray['csvField'])){ $col = array_search($fieldMapArray['csvField'],$csv_header); if($csv_arrayBatch[$row][$col] != ""){ $field = array($salesforce_field => htmlspecialchars($csv_arrayBatch[$row][$col],ENT_QUOTES,'UTF-8')); } elseif($_SESSION['config']['fieldsToNull']){ $sObject->fieldsToNull[] = $salesforce_field; } } if (!$fields){ $fields = $field; } else { $fields = array_merge($fields,$field); } } $sObject->fields = $fields; array_push($sObjects, $sObject); unset($sObject); } //print "<pre>"; //print_r($sObjects); //print "</pre>"; //exit; try{ global $mySforceConnection; if ($api_call == 'upsert'){ $results_more = $mySforceConnection->$api_call($ext_id,$sObjects); unset($sObjects); } else { $results_more = $mySforceConnection->$api_call($sObjects); unset($sObjects); } } catch (Exception $e) { $errors = null; $errors = $e->getMessage(); show_error($errors); include_once("footer.php"); exit; } if(!$results){ $results = $results_more; } else { $results = array_merge($results,$results_more); } } if($show_results) show_put_results($results,$api_call); } } function show_put_results($results,$api_call){ //check if only result is returned if(!is_array($results)) $results = array($results); $success_count = 0; $error_count = 0; ob_start(); for($row=0; $row < count($results); $row++){ $excel_row = $row + 1; if ($results[$row]->success){ $success_count++; print "<tr>"; print "<td>" . $excel_row . "</td>"; print "<td>" . $results[$row]->id . "</td>"; print "<td>Success</td>"; if (($api_call == 'upsert' && $results[$row]->created) || $api_call == 'create'){ print "<td>Created</td>"; } else { print "<td>Updated</td>"; } print "</tr>\n"; } else { $error_count++; print "<tr style='color: red;'>"; print "<td>" . $excel_row . "</td>"; print "<td>" . $results[$row]->id . "</td>"; print "<td>" . ucwords($results[$row]->errors->message) . "</td>"; print "<td>" . $results[$row]->errors->statusCode . "</td>"; //print "<td>" . $results[$row]->errors->fields . "</td>"; //APIDOC: Reserved for future use. Array of one or more field names. Identifies which fields in the object, if any, affected the error condition. print "</tr>\n"; } } print "</table><br/>"; $results_table = ob_get_clean(); show_info("There were $success_count successes and $error_count errors."); print "<br/>\n<table class='field_mapping'>\n"; print "<td>&nbsp;</td> <th>ID</th> <th>Result</th> <th>Status</th>\n"; print "<p>$results_table</p>"; } function show_idOnlyCall_results($results,$id_array){ //check if only result is returned if(!is_array($results)) $results = array($results); $success_count = 0; $error_count = 0; ob_start(); for($row=0; $row < count($id_array); $row++){ $excel_row = $row + 1; if ($results[$row]->success){ $success_count++; print "<tr>"; print "<td>" . $excel_row . "</td>"; print "<td>" . $id_array[$row] . "</td>"; print "<td>Success</td><td></td>"; print "</tr>"; } else { $error_count++; print "<tr style='color: red;'>"; print "<td>" . $excel_row . "</td>"; print "<td>" . $id_array[$row] . "</td>"; print "<td>" . ucwords($results[$row]->errors->message) . "</td>"; print "<td>" . $results[$row]->errors->statusCode . "</td>"; //print "<td>" . $results[$row]->errors->fields . "</td>"; //APIDOC: Reserved for future use. Array of one or more field names. Identifies which fields in the object, if any, affected the error condition. print "</tr>"; } } print "</table><br/>"; $results_table = ob_get_clean(); show_info("There were $success_count successes and $error_count errors."); print "<p></p><table class='data_table'>\n"; print "<td>&nbsp;</td><th>ID</th><th>Result</th><th>Error Code</th>\n"; print "<p>$results_table</p>"; } function put($action){ $confirm_action = 'Confirm ' . ucwords($action); if(isset($_POST['action']) && $_POST['action'] == $confirm_action){ require_once('header.php'); print "<h1>" . ucwords($action) . " Results</h1>"; if ($action == 'insert') $api_call = 'create'; else $api_call = $action; if ($action == 'upsert') $ext_id = $_SESSION['_ext_id']; else $ext_id = NULL; putSObjects($api_call,$ext_id,$_SESSION['field_map'],$_SESSION['csv_array'],true); include_once('footer.php'); unset($_SESSION['field_map'],$_SESSION['csv_array'],$_SESSION['_ext_id'],$_SESSION['file_tmp_name']); } elseif(isset($_POST['action']) && $_POST['action'] == 'Map Fields'){ require_once('header.php'); array_pop($_POST); //remove header row if ($_POST['_ext_id']){ $_SESSION['_ext_id'] = $_POST['_ext_id']; $_POST['_ext_id'] = NULL; } $_SESSION['field_map'] = field_map_to_array($_POST); field_mapping_confirm($confirm_action,$_SESSION['field_map'],$_SESSION['csv_array'],$_SESSION['_ext_id']); include_once('footer.php'); } elseif (isset($_FILES['file']) && isset($_POST['default_object'])){ require_once('header.php'); if (csv_upload_valid_check($_FILES['file'])){ form_upload_objectSelect_show('file',TRUE); show_error(csv_upload_valid_check($_FILES['file'])); } else { $csv_file_name = basename($_FILES['file']['name']); $_SESSION['file_tmp_name'] = $_FILES['file']['tmp_name']; $_SESSION['csv_array'] = csv_file_to_array($_SESSION['file_tmp_name']); $csv_array_count = count($_SESSION['csv_array']) - 1; if (!$csv_array_count) { show_error("The file uploaded contains no records. Please try again."); include_once('footer.php'); exit(); } elseif($csv_array_count > $_SESSION['config']['maxFileLengthRows']){ show_error ("The file uploaded contains more than " . $_SESSION['config']['maxFileLengthRows'] . " records. Please try again."); include_once('footer.php'); exit(); } $info = "The file $csv_file_name was uploaded successfully and contains $csv_array_count row"; if ($csv_array_count !== 1) $info .= 's'; show_info($info); print "<br/>"; field_mapping_set($action,$_SESSION['csv_array']); } include_once('footer.php'); } else { require_once ('header.php'); print "<p><strong>Select an object and upload a CSV file to $action:</strong></p>\n"; form_upload_objectSelect_show('file',TRUE); include_once('footer.php'); } } function idOnlyCall($action){ if($_POST['action'] == 'Confirm ' . ucfirst($action)){ require_once('header.php'); print "<h1>" . ucfirst($action) . " Results</h1>"; idOnlyCallIds($action,$_SESSION['field_map'],$_SESSION['csv_array'],true); unset($_SESSION['field_map'],$_SESSION['csv_array'],$_SESSION['update_file_tmp_name']); include_once('footer.php'); } elseif($_POST['action'] == 'Map Fields'){ require_once('header.php'); array_pop($_POST); //remove header row $_SESSION['field_map'] = $_POST; field_mapping_confirm('Confirm ' . ucfirst($action),$_SESSION['field_map'],$_SESSION['csv_array'],null); include_once('footer.php'); } elseif ($_FILES['file']){ require_once('header.php'); if (csv_upload_valid_check($_FILES['file'])){ form_upload_objectSelect_show('file',FALSE); show_error(csv_upload_valid_check($_FILES['file'])); include_once('footer.php'); } else { $csv_file_name = basename($_FILES['file']['name']); $_SESSION['file_tmp_name'] = $_FILES['file']['tmp_name']; $_SESSION['csv_array'] = csv_file_to_array($_SESSION['file_tmp_name']); $csv_array_count = count($_SESSION['csv_array']) - 1; if (!$csv_array_count) { show_error("The file uploaded contains no records. Please try again."); include_once('footer.php'); exit(); } elseif ($csv_array_count > $_SESSION['config']['maxFileLengthRows']) { show_error("The file uploaded contains more than " . $_SESSION['config']['maxFileLengthRows'] . " records. Please try again."); include_once('footer.php'); exit(); } $info = "The file $csv_file_name was uploaded successfully and contains $csv_array_count row"; if ($csv_array_count !== 1) $info .= 's'; show_info($info); print "<br/>"; field_mapping_set($action,$_SESSION['csv_array']); } } else { require_once ('header.php'); print "<p><strong>Upload a CSV file with Salesforce IDs to $action:</strong></p>\n"; form_upload_objectSelect_show('file',FALSE); include_once('footer.php'); } } function debug($showSuperVars = true, $showSoap = true, $customName = null, $customValue = null){ if($_SESSION['config']['debug'] == true){ print "<script> function toggleDebugSection(title, sectionId){ var section = document.getElementById(sectionId); if(section.style.display == 'inline'){ section.style.display = 'none'; title.childNodes[0].nodeValue = title.childNodes[0].nodeValue.replace('-','+'); } else { title.childNodes[0].nodeValue = title.childNodes[0].nodeValue.replace('+','-'); section.style.display = 'inline'; } } </script>"; print "<div style='text-align: left;'>"; if($customValue){ if($customName){ print "<h1>$customName</h1>\n"; } else { print "<h1>CUSTOM</h1>\n"; } var_dump($customValue); print "<hr/>"; } if($showSuperVars){ print "<h1 onclick=\"toggleDebugSection(this,'container_globals')\" class=\"debugHeader\">+ SUPERGLOBAL VARIABLES</h1>\n"; print "<div id='container_globals' class='debugContainer'>"; print "<strong onclick=\"toggleDebugSection(this,'container_globals_cookie')\" class=\"debugHeader\">+ COOKIE SUPERGLOBAL VARIABLE</strong>\n"; print "<div id='container_globals_cookie' class='debugContainer'>"; var_dump ($_COOKIE); print "<hr/>"; print "</div>"; print "<strong onclick=\"toggleDebugSection(this,'container_globals_session')\" class=\"debugHeader\">+ SESSION SUPERGLOBAL VARIABLE</strong>\n"; print "<div id='container_globals_session' class='debugContainer'>"; var_dump ($_SESSION); print "<hr/>"; print "</div>"; print "<strong onclick=\"toggleDebugSection(this,'container_globals_post')\" class=\"debugHeader\">+ POST SUPERGLOBAL VARIABLE</strong>\n"; print "<div id='container_globals_post' class='debugContainer'>"; var_dump ($_POST); print "<hr/>"; print "</div>"; print "<strong onclick=\"toggleDebugSection(this,'container_globals_get')\" class=\"debugHeader\">+ GET SUPERGLOBAL VARIABLE</strong>\n"; print "<div id='container_globals_get' class='debugContainer'>"; var_dump ($_GET); print "<hr/>"; print "</div>"; print "<strong onclick=\"toggleDebugSection(this,'container_globals_files')\" class=\"debugHeader\">+ FILES SUPERGLOBAL VARIABLE</strong>\n"; print "<div id='container_globals_files' class='debugContainer'>"; var_dump ($_FILES); print "<hr/>"; print "</div>"; print "<strong onclick=\"toggleDebugSection(this,'container_globals_env')\" class=\"debugHeader\">+ ENVIRONMENT SUPERGLOBAL VARIABLE</strong>\n"; print "<div id='container_globals_env' class='debugContainer'>"; var_dump ($_ENV); print "<hr/>"; print "</div>"; print "</div>"; } global $mySforceConnection; if($showSoap && isset($mySforceConnection)){ try{ print "<h1 onclick=\"toggleDebugSection(this,'partner_soap_container')\" class=\"debugHeader\">+ PARTNER SOAP MESSAGES</h1>\n"; print "<div id='partner_soap_container' class='debugContainer'>"; print "<strong>LAST REQUEST HEADER</strong>\n"; print htmlspecialchars($mySforceConnection->getLastRequestHeaders(),ENT_QUOTES,'UTF-8'); print "<hr/>"; print "<strong>LAST REQUEST</strong>\n"; print htmlspecialchars($mySforceConnection->getLastRequest(),ENT_QUOTES,'UTF-8'); print "<hr/>"; print "<strong>LAST RESPONSE HEADER</strong>\n"; print htmlspecialchars($mySforceConnection->getLastResponseHeaders(),ENT_QUOTES,'UTF-8'); print "<hr/>"; print "<strong>LAST RESPONSE</strong>\n"; print htmlspecialchars($mySforceConnection->getLastResponse(),ENT_QUOTES,'UTF-8'); print "<hr/>"; print "</div>"; } catch (Exception $e) { print "<strong>SOAP Error</strong>\n"; print_r ($e); } } global $apexBinding; if($showSoap && isset($apexBinding)){ try{ print "<h1 onclick=\"toggleDebugSection(this,'apex_soap_container')\" class=\"debugHeader\">+ APEX SOAP MESSAGES</h1>\n"; print "<div id='apex_soap_container' class='debugContainer'>"; print "<strong>LAST REQUEST HEADER</strong>\n"; print htmlspecialchars($apexBinding->getLastRequestHeaders(),ENT_QUOTES,'UTF-8'); print "<hr/>"; print "<strong>LAST REQUEST</strong>\n"; print htmlspecialchars($apexBinding->getLastRequest(),ENT_QUOTES,'UTF-8'); print "<hr/>"; print "<strong>LAST RESPONSE HEADER</strong>\n"; print htmlspecialchars($apexBinding->getLastResponseHeaders(),ENT_QUOTES,'UTF-8'); print "<hr/>"; print "<strong>LAST RESPONSE</strong>\n"; print htmlspecialchars($apexBinding->getLastResponse(),ENT_QUOTES,'UTF-8'); print "<hr/>"; print "</div>"; } catch (Exception $e) { print "<strong>SOAP Error</strong>\n"; print_r ($e); } } print "</div>"; } } ?> <file_sep><? include "accesscontrol.php"; include_once "navigation2.htm"; if(isset($submit) && $submit == 'Save changes') { if (is_array($JobCategory2)) { $JobStr = implode("," , $JobCategory2); } $position = strip_tags($position); $description = strip_tags($description); $q3 = "update job_post set position = \"$position\", JobCategory = \"$JobStr\", description = \"$description2\", j_target = \"$j_target2\", salary = \"$salary2\", s_period = \"$s_period2\" where job_id = \"$job_id22\" "; $r3 = mysql_query($q3) or die(mysql_error()); echo "<table width=446><tr><td><br><br><center>The position $position was updated.</center></td></tr></table>"; include("../foother.html"); exit; } $q1 = "select * from job_post where job_id = \"$_GET[job_id]\" "; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); ?> <br><br> <table align=center> <tr><td colspan=2 align=center> To edit a job, use the form below:</td></tr><br><br> <form method=post style="background:none;"> <tr><td>Position:</td> <td> <input type=text name=position value="<?=$a1[position]?>"> </td> </tr> <tr> <td valign=top> Job Category: </td> <td valign=top> <SELECT NAME="JobCategory2[]" multiple size=5 style=width:300> <OPTION VALUE="Accounting/Auditing" >Accounting/Auditing</OPTION> <OPTION VALUE="Administrative and Support Services" >Administrative and Support Services</OPTION> <OPTION VALUE="Advertising/Public Relations" >Advertising/Public Relations</OPTION> <OPTION VALUE="Agriculture/Forestry/Fishing" >Agriculture/Forestry/Fishing</OPTION> <OPTION VALUE="Architectural Services" >Architectural Services</OPTION> <OPTION VALUE="Arts, Entertainment, and Media" >Arts, Entertainment, and Media</OPTION> <OPTION VALUE="Banking" >Banking</OPTION> <OPTION VALUE="Biotechnology and Pharmaceutical" >Biotechnology and Pharmaceutical</OPTION> <OPTION VALUE="Community, Social Services, and Nonprofit" >Community, Social Services, and Nonprofit</OPTION> <OPTION VALUE="Computers, Hardware" >Computers, Hardware</OPTION> <OPTION VALUE="Computers, Software" >Computers, Software</OPTION> <OPTION VALUE="Construction, Mining and Trades" >Construction, Mining and Trades</OPTION> <OPTION VALUE="Consulting Services" >Consulting Services</OPTION> <OPTION VALUE="Customer Service and Call Center" >Customer Service and Call Center</OPTION> <OPTION VALUE="Education, Training, and Library" >Education, Training, and Library</OPTION> <OPTION VALUE="Employment Placement Agencies" >Employment Placement Agencies</OPTION> <OPTION VALUE="Engineering" >Engineering</OPTION> <OPTION VALUE="Executive Management" >Executive Management</OPTION> <OPTION VALUE="Finance/Economics" >Finance/Economics</OPTION> <OPTION VALUE="Financial Services" >Financial Services</OPTION> <OPTION VALUE="Government and Policy" >Government and Policy</OPTION> <OPTION VALUE="Healthcare, Other" >Healthcare, Other</OPTION> <OPTION VALUE="Healthcare, Practitioner, and Technician" >Healthcare, Practitioner, and Technician</OPTION> <OPTION VALUE="Hospitality, Tourism" >Hospitality, Tourism</OPTION> <OPTION VALUE="Human Resources" >Human Resources</OPTION> <OPTION VALUE="Information Technology" >Information Technology</OPTION> <OPTION VALUE="Installation, Maintenance and Repair" >Installation, Maintenance and Repair</OPTION> <OPTION VALUE="Insurance" >Insurance</OPTION> <OPTION VALUE="Internet/E-Commerce" >Internet/E-Commerce</OPTION> <OPTION VALUE="Law Enforcement and Security" >Law Enforcement and Security</OPTION> <OPTION VALUE="Legal" >Legal</OPTION> <OPTION VALUE="Manufacturing and Production" >Manufacturing and Production</OPTION> <OPTION VALUE="Marketing" >Marketing</OPTION> <OPTION VALUE="Military" >Military</OPTION> <OPTION VALUE="Other" >Other</OPTION> <OPTION VALUE="Personal Care and Services" >Personal Care and Services</OPTION> <OPTION VALUE="Real Estate" >Real Estate</OPTION> <OPTION VALUE="Restaurant and Food Service" >Restaurant and Food Service</OPTION> <OPTION VALUE="Retail/Wholesale" >Retail/Wholesale</OPTION> <OPTION VALUE="Sales" >Sales</OPTION> <OPTION VALUE="Science" >Science</OPTION> <OPTION VALUE="Sports/Recreation" >Sports/Recreation</OPTION> <OPTION VALUE="Telecommunications" >Telecommunications</OPTION> <OPTION VALUE="Transportation and Warehousing" >Transportation and Warehousing</OPTION> </SELECT><br> </td> </tr> <tr><td>Description:</td> <td><textarea rows=6 cols=35 name=description2><?=$a1[description]?></textarea></td> </tr> <tr> <td>Target: </td> <td> <select name="j_target2" style=width:303> <option value="">Select </option> <? $jt = array('Student (High School)', 'Student (undergraduate/graduate)', 'Entry Level (less than 2 years of experience)', 'Mid Career (2+ years of experience)', 'Management (Manager/Director of Staff)', 'Executive (SVP, EVP, VP)', 'Senior Executive (President, CEO)'); for($j = 0; $j <= (count($jt) - 1); $j++) { $j2 = $j + 1; if($j2 == $a1[j_target]) { echo "<option value=\"$j2\" selected>$jt[$j] </option>"; } else { echo "<option value=\"$j2\">$jt[$j] </option>"; } } ?> </select> </td> </tr> <tr><td>Salary: </td> <td> <input size=10 type=text name=salary2 value=<?=$a1[salary]?>> <select name=s_period2> <? $sp = array('Yearly', 'Monthly'); echo "$sp[0] <br> $sp[1] <br> $sp[2]"; for($i = 0; $i <= (count($sp) - 1); $i++) { if($sp[$i] == $a1[s_period]) { echo "<option value=$sp[$i] selected> $sp[$i] </option>"; } else { echo "<option value=$sp[$i]> $sp[$i] </option>"; } } ?> </select> </td></tr> <tr> <td align=left> <input type=hidden name=job_id22 value=<?=$_GET[job_id]?>> <input type=submit name=submit value="Save changes"> </td> </tr> </table> </form> <? //} ?> <? include_once('../foother.html'); ?><file_sep><? include_once "accesscontrol.php"; if(isset($submit)) { if(empty($_POST[NewName])) { echo "<center><font color=red><b> Company name filed is blank. </b></font></center>"; exit(); } if(empty($_POST[NewCountry])) { echo "<center><font color=red><b> Choose your country, please. </b></font></center>"; exit(); } if(empty($_POST[NewState])) { echo "<center><font color=red><b> Choose your state, please. </b></font></center>"; exit(); } if(empty($_POST[NewZip])) { echo "<center><font color=red><b> Zip code filed is blank. </b></font></center>"; exit(); } if(empty($_POST[NewCity])) { echo "<center><font color=red><b> City filed is blank. </b></font></center>"; exit(); } if(empty($_POST[NewAddress])) { echo "<center><font color=red><b> Address filed is blank. </b></font></center>"; exit(); } if(empty($_POST[NewPhone])) { echo "<center><font color=red><b> Phone filed is blank. </b></font></center>"; exit(); } if(empty($_POST[NewEmail])) { echo "<center><font color=red><b> Email filed is blank. </b></font></center>"; exit(); } $q2 = "update job_employer_info set CompanyName = \"$_POST[NewName]\", CompanyCountry = \"$_POST[NewCountry]\", CompanyState = \"$_POST[NewState]\", CompanyZip = \"$_POST[NewZip]\", CompanyCity = \"$_POST[NewCity]\", CompanyAddress = \"$_POST[NewAddress]\", CompanyPhone = \"$_POST[NewPhone]\", CompanyPhone2 = \"$_POST[NewPhone2]\", CompanyEmail = \"$_POST[NewEmail]\" where ename = \"$_SESSION[ename]\" "; $r2 = mysql_query($q2) or die(mysql_error()); echo "<center> Your acount information was updated successfull. </center>"; } $q1 = "select * from job_employer_info where ename = \"$_SESSION[ename]\""; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); ?> <form method=post style="background:none;"> <table align=center> <tr> <td> Company name: </td> <td><input type=text name=NewName value="<?=$a1[CompanyName]?>"></td> </tr> <tr> <td> Country: </td> <td> <select name=NewCountry> <OPTION VALUE="">Select</OPTION> <OPTION VALUE="Afghanistan">Afghanistan</OPTION> <OPTION VALUE="Albania">Albania</OPTION> <OPTION VALUE="Algeria">Algeria</OPTION> <OPTION VALUE="American Samoa">American Samoa</OPTION> <OPTION VALUE="Andorra">Andorra</OPTION> <OPTION VALUE="Angola">Angola</OPTION> <OPTION VALUE="Anguilla">Anguilla</OPTION> <OPTION VALUE="Antartica">Antartica</OPTION> <OPTION VALUE="Antigua and Barbuda">Antigua and Barbuda</OPTION> <OPTION VALUE="Argentina">Argentina</OPTION> <OPTION VALUE="Armenia">Armenia</OPTION> <OPTION VALUE="Aruba">Aruba</OPTION> <OPTION VALUE="Australia">Australia</OPTION> <OPTION VALUE="Austria">Austria</OPTION> <OPTION VALUE="Azerbaidjan">Azerbaidjan</OPTION> <OPTION VALUE="Bahamas">Bahamas</OPTION> <OPTION VALUE="Bahrain">Bahrain</OPTION> <OPTION VALUE="Bangladesh">Bangladesh</OPTION> <OPTION VALUE="Barbados">Barbados</OPTION> <OPTION VALUE="Belarus">Belarus</OPTION> <OPTION VALUE="Belgium">Belgium</OPTION> <OPTION VALUE="Belize">Belize</OPTION> <OPTION VALUE="Benin">Benin</OPTION> <OPTION VALUE="Bermuda">Bermuda</OPTION> <OPTION VALUE="Bhutan">Bhutan</OPTION> <OPTION VALUE="Bolivia">Bolivia</OPTION> <OPTION VALUE="Bosnia-Herzegovina">Bosnia-Herzegovina</OPTION> <OPTION VALUE="Botswana">Botswana</OPTION> <OPTION VALUE="Bouvet Island">Bouvet Island</OPTION> <OPTION VALUE="Brazil">Brazil</OPTION> <OPTION VALUE="British Indian Ocean Territory">British Indian Ocean Territory</OPTION> <OPTION VALUE="Brunei Darussalam">Brunei Darussalam</OPTION> <OPTION VALUE="Bulgaria">Bulgaria</OPTION> <OPTION VALUE="Burkina Faso">Burkina Faso</OPTION> <OPTION VALUE="Burundi">Burundi</OPTION> <OPTION VALUE="Cambodia">Cambodia</OPTION> <OPTION VALUE="Cameroon">Cameroon</OPTION> <OPTION VALUE="Canada">Canada</OPTION> <OPTION VALUE="Cape Verde">Cape Verde</OPTION> <OPTION VALUE="Cayman Islands">Cayman Islands</OPTION> <OPTION VALUE="Central African Republic">Central African Republic</OPTION> <OPTION VALUE="Chad">Chad</OPTION> <OPTION VALUE="Chile">Chile</OPTION> <OPTION VALUE="China">China</OPTION> <OPTION VALUE="Christmas Island">Christmas Island</OPTION> <OPTION VALUE="Cocos (Keeling) Islands">Cocos (Keeling) Islands</OPTION> <OPTION VALUE="Colombia">Colombia</OPTION> <OPTION VALUE="Comoros">Comoros</OPTION> <OPTION VALUE="Congo">Congo</OPTION> <OPTION VALUE="Cook Islands">Cook Islands</OPTION> <OPTION VALUE="Costa Rica">Costa Rica</OPTION> <OPTION VALUE="Croatia">Croatia</OPTION> <OPTION VALUE="Cuba">Cuba</OPTION> <OPTION VALUE="Cyprus">Cyprus</OPTION> <OPTION VALUE="Czech Republic">Czech Republic</OPTION> <OPTION VALUE="Denmark">Denmark</OPTION> <OPTION VALUE="Djibouti">Djibouti</OPTION> <OPTION VALUE="Dominica">Dominica</OPTION> <OPTION VALUE="Dominican Republic">Dominican Republic</OPTION> <OPTION VALUE="East Timor">East Timor</OPTION> <OPTION VALUE="Ecuador">Ecuador</OPTION> <OPTION VALUE="Egypt">Egypt</OPTION> <OPTION VALUE="El Salvador">El Salvador</OPTION> <OPTION VALUE="Equatorial Guinea">Equatorial Guinea</OPTION> <OPTION VALUE="Eritrea">Eritrea</OPTION> <OPTION VALUE="Estonia">Estonia</OPTION> <OPTION VALUE="Ethiopia">Ethiopia</OPTION> <OPTION VALUE="Falkland Islands">Falkland Islands</OPTION> <OPTION VALUE="Faroe Islands">Faroe Islands</OPTION> <OPTION VALUE="Fiji">Fiji</OPTION> <OPTION VALUE="Finland">Finland</OPTION> <OPTION VALUE="Former USSR">Former USSR</OPTION> <OPTION VALUE="France">France</OPTION> <OPTION VALUE="France (European Territory)">France (European Territory)</OPTION> <OPTION VALUE="French Guyana">French Guyana</OPTION> <OPTION VALUE="French Southern Territories">French Southern Territories</OPTION> <OPTION VALUE="Gabon">Gabon</OPTION> <OPTION VALUE="Gambia">Gambia</OPTION> <OPTION VALUE="Georgia">Georgia</OPTION> <OPTION VALUE="Germany">Germany</OPTION> <OPTION VALUE="Ghana">Ghana</OPTION> <OPTION VALUE="Gibraltar">Gibraltar</OPTION> <OPTION VALUE="Greece">Greece</OPTION> <OPTION VALUE="Greenland">Greenland</OPTION> <OPTION VALUE="Grenada">Grenada</OPTION> <OPTION VALUE="Guadeloupe (French)">Guadeloupe (French)</OPTION> <OPTION VALUE="Guam">Guam</OPTION> <OPTION VALUE="Guatemala">Guatemala</OPTION> <OPTION VALUE="Guinea">Guinea</OPTION> <OPTION VALUE="Guinea Bissau">Guinea Bissau</OPTION> <OPTION VALUE="Guyana">Guyana</OPTION> <OPTION VALUE="Haiti">Haiti</OPTION> <OPTION VALUE="Heard and McDonald Islands">Heard and McDonald Islands</OPTION> <OPTION VALUE="Honduras">Honduras</OPTION> <OPTION VALUE="Hong Kong">Hong Kong</OPTION> <OPTION VALUE="Hungary">Hungary</OPTION> <OPTION VALUE="Iceland">Iceland</OPTION> <OPTION VALUE="India">India</OPTION> <OPTION VALUE="Indonesia">Indonesia</OPTION> <OPTION VALUE="Iran">Iran</OPTION> <OPTION VALUE="Iraq">Iraq</OPTION> <OPTION VALUE="Ireland">Ireland</OPTION> <OPTION VALUE="Israel">Israel</OPTION> <OPTION VALUE="Italy">Italy</OPTION> <OPTION VALUE="Ivory Coast">Ivory Coast</OPTION> <OPTION VALUE="Jamaica">Jamaica</OPTION> <OPTION VALUE="Japan">Japan</OPTION> <OPTION VALUE="Jordan">Jordan</OPTION> <OPTION VALUE="Kazakhstan">Kazakhstan</OPTION> <OPTION VALUE="Kenya">Kenya</OPTION> <OPTION VALUE="Kiribati">Kiribati</OPTION> <OPTION VALUE="Kuwait">Kuwait</OPTION> <OPTION VALUE="Kyrgyzstan">Kyrgyzstan</OPTION> <OPTION VALUE="Laos">Laos</OPTION> <OPTION VALUE="Latvia">Latvia</OPTION> <OPTION VALUE="Lebanon">Lebanon</OPTION> <OPTION VALUE="Lesotho">Lesotho</OPTION> <OPTION VALUE="Liberia">Liberia</OPTION> <OPTION VALUE="Libya">Libya</OPTION> <OPTION VALUE="Liechtenstein">Liechtenstein</OPTION> <OPTION VALUE="Lithuania">Lithuania</OPTION> <OPTION VALUE="Luxembourg">Luxembourg</OPTION> <OPTION VALUE="Macau">Macau</OPTION> <OPTION VALUE="Macedonia">Macedonia</OPTION> <OPTION VALUE="Madagascar">Madagascar</OPTION> <OPTION VALUE="Malawi">Malawi</OPTION> <OPTION VALUE="Malaysia">Malaysia</OPTION> <OPTION VALUE="Maldives">Maldives</OPTION> <OPTION VALUE="Mali">Mali</OPTION> <OPTION VALUE="Malta">Malta</OPTION> <OPTION VALUE="Marshall Islands">Marshall Islands</OPTION> <OPTION VALUE="Martinique (French)">Martinique (French)</OPTION> <OPTION VALUE="Mauritania">Mauritania</OPTION> <OPTION VALUE="Mauritius">Mauritius</OPTION> <OPTION VALUE="Mayotte">Mayotte</OPTION> <OPTION VALUE="Mexico">Mexico</OPTION> <OPTION VALUE="Micronesia">Micronesia</OPTION> <OPTION VALUE="Moldavia">Moldavia</OPTION> <OPTION VALUE="Monaco">Monaco</OPTION> <OPTION VALUE="Mongolia">Mongolia</OPTION> <OPTION VALUE="Montserrat">Montserrat</OPTION> <OPTION VALUE="Morocco">Morocco</OPTION> <OPTION VALUE="Mozambique">Mozambique</OPTION> <OPTION VALUE="Myanmar, Union of (Burma)">Myanmar, Union of (Burma)</OPTION> <OPTION VALUE="Namibia">Namibia</OPTION> <OPTION VALUE="Nauru">Nauru</OPTION> <OPTION VALUE="Nepal">Nepal</OPTION> <OPTION VALUE="Netherlands">Netherlands</OPTION> <OPTION VALUE="Netherlands Antilles">Netherlands Antilles</OPTION> <OPTION VALUE="Neutral Zone">Neutral Zone</OPTION> <OPTION VALUE="New Caledonia (French)">New Caledonia (French)</OPTION> <OPTION VALUE="New Zealand">New Zealand</OPTION> <OPTION VALUE="Nicaragua">Nicaragua</OPTION> <OPTION VALUE="Niger">Niger</OPTION> <OPTION VALUE="Nigeria">Nigeria</OPTION> <OPTION VALUE="Niue">Niue</OPTION> <OPTION VALUE="Norfolk Island">Norfolk Island</OPTION> <OPTION VALUE="North Korea">North Korea</OPTION> <OPTION VALUE="Northern Mariana Islands">Northern Mariana Islands</OPTION> <OPTION VALUE="Norway">Norway</OPTION> <OPTION VALUE="Oman">Oman</OPTION> <OPTION VALUE="Pakistan">Pakistan</OPTION> <OPTION VALUE="Palau">Palau</OPTION> <OPTION VALUE="Panama">Panama</OPTION> <OPTION VALUE="Papua New Guinea">Papua New Guinea</OPTION> <OPTION VALUE="Paraguay">Paraguay</OPTION> <OPTION VALUE="Peru">Peru</OPTION> <OPTION VALUE="Philippines">Philippines</OPTION> <OPTION VALUE="Pitcairn Island">Pitcairn Island</OPTION> <OPTION VALUE="Poland">Poland</OPTION> <OPTION VALUE="Polynesia (French)">Polynesia (French)</OPTION> <OPTION VALUE="Portugal">Portugal</OPTION> <OPTION VALUE="Qatar">Qatar</OPTION> <OPTION VALUE="Reunion (French)">Reunion (French)</OPTION> <OPTION VALUE="Romania">Romania</OPTION> <OPTION VALUE="Russian Federation">Russian Federation</OPTION> <OPTION VALUE="Rwanda">Rwanda</OPTION> <OPTION VALUE="S. Georgia &amp; S. Sandwich Islands">S. Georgia &amp; S. Sandwich Islands</OPTION> <OPTION VALUE="Saint Helena">Saint Helena</OPTION> <OPTION VALUE="Saint Kitts &amp; Nevis Anguilla">Saint Kitts &amp; Nevis Anguilla</OPTION> <OPTION VALUE="Saint Lucia">Saint Lucia</OPTION> <OPTION VALUE="Saint Pierre and Miquelon">Saint Pierre and Miquelon</OPTION> <OPTION VALUE="Saint Tome and Principe">Saint Tome and Principe</OPTION> <OPTION VALUE="Saint Vincent &amp; Grenadines">Saint Vincent &amp; Grenadines</OPTION> <OPTION VALUE="Samoa">Samoa</OPTION> <OPTION VALUE="San Marino">San Marino</OPTION> <OPTION VALUE="Saudi Arabia">Saudi Arabia</OPTION> <OPTION VALUE="Senegal">Senegal</OPTION> <OPTION VALUE="Seychelles">Seychelles</OPTION> <OPTION VALUE="Sierra Leone">Sierra Leone</OPTION> <OPTION VALUE="Singapore">Singapore</OPTION> <OPTION VALUE="Slovakia">Slovakia</OPTION> <OPTION VALUE="Slovenia">Slovenia</OPTION> <OPTION VALUE="Solomon Islands">Solomon Islands</OPTION> <OPTION VALUE="Somalia">Somalia</OPTION> <OPTION VALUE="South Africa">South Africa</OPTION> <OPTION VALUE="South Korea">South Korea</OPTION> <OPTION VALUE="Spain">Spain</OPTION> <OPTION VALUE="Sri Lanka">Sri Lanka</OPTION> <OPTION VALUE="Sudan">Sudan</OPTION> <OPTION VALUE="Suriname">Suriname</OPTION> <OPTION VALUE="Svalbard and Jan Mayen Islands">Svalbard and Jan Mayen Islands</OPTION> <OPTION VALUE="Swaziland">Swaziland</OPTION> <OPTION VALUE="Sweden">Sweden</OPTION> <OPTION VALUE="Switzerland">Switzerland</OPTION> <OPTION VALUE="Syria">Syria</OPTION> <OPTION VALUE="Tadjikistan">Tadjikistan</OPTION> <OPTION VALUE="Taiwan">Taiwan</OPTION> <OPTION VALUE="Tanzania">Tanzania</OPTION> <OPTION VALUE="Thailand">Thailand</OPTION> <OPTION VALUE="Togo">Togo</OPTION> <OPTION VALUE="Tokelau">Tokelau</OPTION> <OPTION VALUE="Tonga">Tonga</OPTION> <OPTION VALUE="Trinidad and Tobago">Trinidad and Tobago</OPTION> <OPTION VALUE="Tunisia">Tunisia</OPTION> <OPTION VALUE="Turkey">Turkey</OPTION> <OPTION VALUE="Turkmenistan">Turkmenistan</OPTION> <OPTION VALUE="Turks and Caicos Islands">Turks and Caicos Islands</OPTION> <OPTION VALUE="Tuvalu">Tuvalu</OPTION> <OPTION VALUE="Uganda">Uganda</OPTION> <OPTION VALUE="UK">UK</OPTION> <OPTION VALUE="Ukraine">Ukraine</OPTION> <OPTION VALUE="United Arab Emirates">United Arab Emirates</OPTION> <OPTION VALUE="Uruguay">Uruguay</OPTION> <OPTION VALUE="US">US</OPTION> <OPTION VALUE="USA Minor Outlying Islands">USA Minor Outlying Islands</OPTION> <OPTION VALUE="Uzbekistan">Uzbekistan</OPTION> <OPTION VALUE="Vanuatu">Vanuatu</OPTION> <OPTION VALUE="Vatican City">Vatican City</OPTION> <OPTION VALUE="Venezuela">Venezuela</OPTION> <OPTION VALUE="Vietnam">Vietnam</OPTION> <OPTION VALUE="Virgin Islands (British)">Virgin Islands (British)</OPTION> <OPTION VALUE="Virgin Islands (USA)">Virgin Islands (USA)</OPTION> <OPTION VALUE="Wallis and Futuna Islands">Wallis and Futuna Islands</OPTION> <OPTION VALUE="Western Sahara">Western Sahara</OPTION> <OPTION VALUE="Yemen">Yemen</OPTION> <OPTION VALUE="Yugoslavia">Yugoslavia</OPTION> <OPTION VALUE="Zaire">Zaire</OPTION> <OPTION VALUE="Zambia">Zambia</OPTION> <OPTION VALUE="Zimbabwe">Zimbabwe</OPTION> </select> </td> </tr> <tr> <td>State: </td> <td> <select name=NewState> <option value="">Select </option> <OPTION VALUE="Not in US">Not in US</OPTION> <OPTION VALUE="Alabama">Alabama</OPTION> <OPTION VALUE="Alaska">Alaska</OPTION> <OPTION VALUE="Arizona">Arizona</OPTION> <OPTION VALUE="Arkansas">Arkansas</OPTION> <OPTION VALUE="California">California</OPTION> <OPTION VALUE="Colorado">Colorado</OPTION> <OPTION VALUE="Connecticut">Connecticut</OPTION> <OPTION VALUE="Delaware">Delaware</OPTION> <OPTION VALUE="District of Columbia">District of Columbia</OPTION> <OPTION VALUE="Florida">Florida</OPTION> <OPTION VALUE="Georgia">Georgia</OPTION> <OPTION VALUE="Hawaii">Hawaii</OPTION> <OPTION VALUE="Idaho">Idaho</OPTION> <OPTION VALUE="Illinois">Illinois</OPTION> <OPTION VALUE="Indiana">Indiana</OPTION> <OPTION VALUE="Iowa">Iowa</OPTION> <OPTION VALUE="Kansas">Kansas</OPTION> <OPTION VALUE="Kentucky">Kentucky</OPTION> <OPTION VALUE="Louisiana">Louisiana</OPTION> <OPTION VALUE="Maine">Maine</OPTION> <OPTION VALUE="Maryland">Maryland</OPTION> <OPTION VALUE="Massachusetts">Massachusetts</OPTION> <OPTION VALUE="Michigan">Michigan</OPTION> <OPTION VALUE="Minnesota">Minnesota</OPTION> <OPTION VALUE="Mississippi">Mississippi</OPTION> <OPTION VALUE="Missouri">Missouri</OPTION> <OPTION VALUE="Montana">Montana</OPTION> <OPTION VALUE="Nebraska">Nebraska</OPTION> <OPTION VALUE="Nevada">Nevada</OPTION> <OPTION VALUE="New Hampshire">New Hampshire</OPTION> <OPTION VALUE="New Jersey">New Jersey</OPTION> <OPTION VALUE="New Mexico">New Mexico</OPTION> <OPTION VALUE="New York">New York</OPTION> <OPTION VALUE="North Carolina">North Carolina</OPTION> <OPTION VALUE="North Dakota">North Dakota</OPTION> <OPTION VALUE="Ohio">Ohio</OPTION> <OPTION VALUE="Oklahoma">Oklahoma</OPTION> <OPTION VALUE="Oregon">Oregon</OPTION> <OPTION VALUE="Pennsylvania">Pennsylvania</OPTION> <OPTION VALUE="Puerto Rico">Puerto Rico</OPTION> <OPTION VALUE="Rhode Island">Rhode Island</OPTION> <OPTION VALUE="South Carolina">South Carolina</OPTION> <OPTION VALUE="South Dakota">South Dakota</OPTION> <OPTION VALUE="Tennessee">Tennessee</OPTION> <OPTION VALUE="Texas">Texas</OPTION> <OPTION VALUE="Utah">Utah</OPTION> <OPTION VALUE="Vermont">Vermont</OPTION> <OPTION VALUE="Virgin Islands">Virgin Islands</OPTION> <OPTION VALUE="Virginia">Virginia</OPTION> <OPTION VALUE="Washington">Washington</OPTION> <OPTION VALUE="West Virginia">West Virginia</OPTION> <OPTION VALUE="Wisconsin">Wisconsin</OPTION> <OPTION VALUE="Wyoming">Wyoming</OPTION> </select> </td> </tr> <tr> <td>Zip </td> <td><input type=text name=NewZip value="<?=$a1[CompanyZip]?>"></td> </tr> <tr> <td>City </td> <td><input type=text name=NewCity value="<?=$a1[CompanyCity]?>"></td> </tr> <tr> <td>Address </td> <td><input type=text name=NewAddress value="<?=$a1[CompanyAddress]?>"></td> </tr> <tr> <td>Phone </td> <td><input type=text name=NewPhone value="<?=$a1[CompanyPhone]?>"></td> </tr> <tr> <td>Phone 2 </td> <td><input type=text name=NewPhone2 value="<?=$a1[CompanyPhone2]?>"></td> </tr> <tr> <td>Email </td> <td><input type=text name=NewEmail value="<?=$a1[CompanyEmail]?>"></td> </tr> <tr> <td colspan=2 align=center> <input type=submit value=submit name=submit> </td> </tr> </table> </form> <? include_once('../foother.html'); ?><file_sep><? include_once "../conn.php"; $q = "select * from job_seeker_info where uname = \"$uname\""; $r = mysql_query($q) or die(mysql_error()); $a = mysql_fetch_array($r); $q1 = "select * from job_work_experience where uname = \"$uname\" order by WEn desc "; $r2 = mysql_query($q1) or die(mysql_error()); ?> <html> <head> <title> <? echo "$a[fname] $a[lname]'s Resume"; ?> </title> <style> body {font-family:verdana} </style> </head> <body> <a href="javascript:close()">close window</a> <table width=550 align=center> <caption align=center><b><? echo "$a[rTitle] <br><p align=left><font size=2 style=\"font-weight:normal\"> $a[rPar] </font></p>"; ?> </b> </caption> <tr> <td valign=top> <b>Name:</b> </td> <td width=175 valign=top> <? echo "$a[fname] $a[lname]"; ?> </td> <td valign=top> <b>Address: </b> </td> <td valign=top> <? echo "$a[address] \n $a[city] - $a[zip]"; if ($a[state] != 'Not in US') {echo $a[state];} ?> </tr> <tr> <td valign=top> <b>Age: </b> </td> <td valign=top> <? if((date(m) > $a[bmonth]) || (date(m) == $a[bmonth] && date(d) < $a[bday])) { echo date(Y) - $a[byear]; } else { echo date(Y) - $a[byear] - 1; } ?> </td> <td valign=top> <b>Country: </b> </td> <td valign=top> <?=$a[country]?> </td> </tr> <tr> <td valign=top> <b>Phone:</b> </td> <td valign=top> <? echo "$a[phone] \n $a[phone2]"; ?> </td> <td valign=top> <b>E-mail: </b> </td> <td valign=top> <?= $a[job_seeker_email]?> </td> </tr> <tr> <td valign=top> <b> Job category: </b> </td> <td valign=top> <?=$a[job_category]?> </td> <td> <b>Career level:</b> </td> <td > <?=$a[careerlevel]?> </td> </tr> <tr> <td colspan=2> <b>Willing to relocate?</b> <?=$a[relocate]?> </td> </tr> </table> <? while ($a1 = mysql_fetch_array($r2)) { echo " <table align=center width=550 border=1 bordercolor=black cellspacing=0 cellpadding=0> <caption>Work experience# $a1[WEn] </caption> <tr> <td colspan=4><b><sup>Position: </b></sup> $a1[WE_p] </td> </tr> <tr> <td width=80><b><sup>From date: </b></sup></td><td width=150> $a1[WE_Start] </td> <td rowspan=2 > <table cellspacing=0 width=100%> <tr> <td valign=top bgcolor=white> <b><sup>Description: </b></sup </td> </tr> <tr> <td > $a1[WE_d] </td> </tr> </table> </td> </tr> <tr> <td><b><sup>To date: </b></sup></td><td > $a1[WE_End] </td> </tr> </table> "; } $q3 = "select * from job_education where uname = \"$uname\" order by En asc"; $r3 = mysql_query($q3) or die(mysql_error()); while ($a2 = mysql_fetch_array($r3)) { echo " <table align=center width=550 border=1 bordercolor=black cellspacing=0> <caption>Education# $a2[En] </caption> <tr> <td width=120><b><sup>Institution: </b></sup></td><td width=190 > $a2[E_i] </td> <td rowspan=4 valign=top> <table width=100% cellspacing=0> <tr> <td bgcolor=white> <b><sup> Description: </b></sup> </td> </tr> <tr> <td > $a2[E_d] </td> </tr> </table> </td> </tr> <tr> <td><b><sup>From date: </b></sup></td><td > $a2[E_Start] </td> </tr> <tr> <td><b><sup>To date: </b></sup> </td><td > $a2[E_End] </td> </tr> <tr><td><b><sup> Graduate level: </b></sup></td><td > $a2[E_gr]</td></tr> </table> "; } $q4 = "select * from job_skills where uname = \"$uname\" "; $r4 = mysql_query($q4) or die(mysql_error()); while($a4 = mysql_fetch_array($r4)) { echo " <table align=center width=550 border=1 bordercolor=black cellspacing=0> <caption><b>Skills </b></caption> <tr> <td colspan=2><b>My additional skills: </b> $a4[SK_d] </td> </tr> </table> "; } ?> <? include_once('../foother.html'); ?><file_sep>msgfmt locale/$1/LC_MESSAGES/$1.po -o locale/$1/LC_MESSAGES/$1.mo<file_sep><? include_once "../main.php"; ?> <table width="446"><tr><td> <? if ($_POST['submit'] == "Register me") { $q1 = "insert into job_employer_info set ename = \"". $_POST["ename"] . "\", epass = \"$epass\", CompanyName = \"$CompanyName\", CompanyCountry = \"$CompanyCountry\", CompanyState = \"$CompanyState\", CompanyZip = \"$CompanyZip\", CompanyCity = \"$CompanyCity\", CompanyAddress = \"$CompanyAddress\", CompanyPhone = \"$CompanyPhone\", CompanyPhone2 = \"$CompanyPhone2\", CompanyEmail = \"$CompanyEmail\" "; $r1 = mysql_query($q1); if (!$r1) { echo '<table width=440><tr><td> <br><br><center>This username is already in use. Please choose another. </center></td></tr></table></td></tr></table>'; include ("../foother.html"); exit; } $to = $CompanyEmail; $subject = "Your account at $site_name"; $message = "This is your account information at $site_name\n\n username: " . $_POST["ename"] . "\n password: <PASSWORD> Keep this information in a secure place. \n\n Thanks for your registration. We believe you will find the staff you need at <a href=http://www.lhrjobs.co.uk>LHR Jobs.co.uk</a>"; $from = "From: <$email_address>"; echo "<br><br>You have successfully completed the registration process <br> <a href=PostJob.php>Click here </a> to post jobs."; mail($to, $subject, $message, $from); // include_once "pay10.php"; } ?> </td></tr></table> <? include ("../foother.html"); ?> <file_sep><? ini_set("register_globals","On"); ?> <html><head><title>Install </title> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body bgcolor="#ffffff" style="text-align: center" background="images/bg_b.jpg" topmargin="20"> <table width="664" border="0" cellpadding="0" cellspacing="0" align="center" bgcolor="#D6E742"> <tr> <td height="25" colspan="0" valign="top" style="padding:10px;"> <br> <br> <strong>Welcome to Installation. Please note the following things.</strong><br> <strong>Database Host</strong> - Please enter your database host name here. This hostname can be a URL or a IP. <br> <strong>Database Name</strong> - Please enter your database name here. First make a MySql database from your hosting panel then use its name here. Please note that the databse should be empty. <br> <strong>Username</strong> - This Username is the database user name. Place your database user name here. <br> <strong>Password</strong> - This is mysql database password. <br> <strong>Site Name</strong> - Place your site name here not the site url. This site name will be used in this website, including il all outgoing emails.<br> <strong>Email Addres</strong> - Enter your email address here.<br> <strong>Site Address</strong> - Enter your site address here without http:// or www format, please note that give full url without any trailing slash and including folder name in which you are installing this script. For example, <strong>mydomain.com</strong> or <strong>mydomain.com/foldername</strong> <strong>PayPal ID</strong> - Enter your paypal id here., if you dont have any left it empty.<br> <strong>2Checkout Vendor ID</strong> - Enter your 2Checkout Vendor id here., if you dont have any left it empty.<br> <strong>Active Account</strong> - Select your preferred payment gateway to be used. <br> <center> <em>All these setting can be changed after installation from Admin panel.</em> </center> </td> </table> <div align="center"> <TABLE WIDTH=550 BORDER=0 CELLPADDING=0 CELLSPACING=0 bgcolor="#E0B837"> <TR> <TD ROWSPAN=2 background="images/body_01.gif">&nbsp;</TD> <TD valign="top" bgcolor="D6E742" colspan="2"> &nbsp;</TD> <TD width="446" valign="top" bgcolor="#D6E742"> <? if ($_POST['submit']=="Submit") { $str ="<?\n\n// 'server' 'database_username' 'database_password' \n\$connection = mysql_connect(\"$_POST[database_host]\", \"$_POST[database_username]\", \"$_POST[database_password]\")\n or die (mysql_error());\n\n // 'database_name' \n \$db = mysql_select_db(\"$_POST[database_name]\", \$connection) or die (mysql_error());\n?>"; print $str; $fp=fopen("conn.php","w"); fwrite($fp,$str); fclose($fp); $fp=fopen("employers/conn.php","w"); fwrite($fp,$str); fclose($fp); $fp=fopen("jobseekers/conn.php","w"); fwrite($fp,$str); fclose($fp); $fp=fopen("siteadmin/conn.php","w"); fwrite($fp,$str); fclose($fp); //print "Database values have been altered"; include ("conn.php"); //creating tables $jal_qry=array("DROP TABLE IF EXISTS `job_admin_login`","CREATE TABLE job_admin_login ( aid varchar(50) NOT NULL default '', apass varchar(50) NOT NULL default '', name varchar(100) NOT NULL default '', email varchar(100) NOT NULL default '', PRIMARY KEY (aid) ) TYPE=MyISAM;"); for($i=0;$i<count($jal_qry);$i++) { if (!mysql_query($jal_qry[$i])) { echo $jal_qry; echo "Could not create table...!!!"; exit; } } $jal_qry=array("DROP TABLE IF EXISTS `configuration`","CREATE TABLE `configuration` ( `conf_id` int(11) NOT NULL auto_increment, `paypal_email` varchar(100) NOT NULL default '', `vendorid` varchar(12) NOT NULL default '', `site_name` varchar(150) NOT NULL default '', `email` varchar(150) NOT NULL default '', `address` varchar(150) NOT NULL default '', `active_account` char(6) NOT NULL default '', PRIMARY KEY (`conf_id`) ) TYPE=MyISAM;"); for($i=0;$i<count($jal_qry);$i++) { if (!mysql_query($jal_qry[$i])) { echo $jal_qry; echo "Could not create table...!!!"; exit; } } // "Table --job_admin_login-- created"; $ja_qry=array("DROP TABLE IF EXISTS `job_aplicants`","CREATE TABLE job_aplicants ( job_id int(10) NOT NULL default '0', aplicant varchar(20) NOT NULL default '') TYPE=MyISAM;"); for($i=0;$i<count($ja_qry);$i++) { if (!mysql_query($ja_qry[$i])) { echo $ja_qry; echo "Could not create table...!!!"; exit; } } // "Table --job_applicants-- created"; $jbm_qry=array("DROP TABLE IF EXISTS `job_banners_m`","CREATE TABLE job_banners_m ( bc char(1) NOT NULL default '' ) TYPE=MyISAM;"); for($i=0;$i<count($jbm_qry);$i++) { if (!mysql_query($jbm_qry[$i])) { echo $jbm_qry; echo "Could not create table...!!!"; exit; } } //"Table --job_banners_m-- created"; $jbt_qry=array("DROP TABLE IF EXISTS `job_banners_t`","CREATE TABLE job_banners_t ( b_id varchar(10) NOT NULL default '', fn varchar(100) NOT NULL default '', burl varchar(100) NOT NULL default '', alt varchar(255) default NULL ) TYPE=MyISAM;"); for($i=0;$i<count($jbt_qry);$i++) { if (!mysql_query($jbt_qry[$i])) { echo $jbt_qry; echo "Could not create table...!!!"; exit; } } //"Table --job_banners_t-- created"; $jc_qry=array("DROP TABLE IF EXISTS `job_careerlevel`","CREATE TABLE job_careerlevel ( uname varchar(10) NOT NULL default '', clnumber int(2) NOT NULL default '0', clname varchar(60) NOT NULL default '' ) TYPE=MyISAM;"); for($i=0;$i<count($jc_qry);$i++) { if (!mysql_query($jc_qry[$i])) { echo $jc_qry; echo "Could not create table...!!!"; exit; } } //"Table --job_careerlevel-- created"; $je_qry=array("DROP TABLE IF EXISTS `job_education`","CREATE TABLE job_education ( uname varchar(10) NOT NULL default '', En char(3) NOT NULL default '', E_i varchar(200) NOT NULL default '', E_Start varchar(20) NOT NULL default '', E_End varchar(20) NOT NULL default '', E_gr varchar(100) NOT NULL default '', E_d text ) TYPE=MyISAM;"); for($i=0;$i<count($je_qry);$i++) { if (!mysql_query($je_qry[$i])) { echo $je_qry; echo "Could not create table...!!!"; exit; } } //"Table --job_education-- created"; $jei_qry=array("DROP TABLE IF EXISTS `job_employer_info`","CREATE TABLE `job_employer_info` ( `ename` varchar(10) NOT NULL default '', `epass` varchar(10) NOT NULL default '', `CompanyName` varchar(100) NOT NULL default '', `CompanyCountry` varchar(200) NOT NULL default '', `CompanyState` varchar(50) NOT NULL default '', `CompanyZip` varchar(10) NOT NULL default '', `CompanyCity` varchar(100) NOT NULL default '', `CompanyAddress` varchar(255) NOT NULL default '', `CompanyPhone` varchar(30) NOT NULL default '', `CompanyPhone2` varchar(30) NOT NULL default '', `CompanyEmail` varchar(200) NOT NULL default '', `plan` varchar(100) NOT NULL default '', `JS_number` char(3) NOT NULL default '', `JP_number` char(3) NOT NULL default '', `JS_accessed` char(3) NOT NULL default '', `JP_accessed` char(3) NOT NULL default '', `CompanyType` varchar(50) NOT NULL default '', `turnover` int(20) NOT NULL default '0', `nempl` int(10) NOT NULL default '0', `free` char(1) NOT NULL default '0', `expiryplan` date NOT NULL default '0000-00-00', PRIMARY KEY (`ename`)) TYPE=MyISAM;"); for($i=0;$i<count($jei_qry);$i++) { if (!mysql_query($jei_qry[$i])) { echo $jei_qry; echo "Could not create table...!!!"; exit; } } //"Table --job_employer_info-- created"; $jls_qry=array("DROP TABLE IF EXISTS `job_link_source`","CREATE TABLE job_link_source (link_id varchar(50) NOT NULL default '',link_code text) TYPE=MyISAM;"); for($i=0;$i<count($jls_qry);$i++) { if (!mysql_query($jls_qry[$i])) { echo $jls_qry; echo "Could not create table...!!!"; exit; } } //"Table --job_link_source-- created"; $jp_qry=array("DROP TABLE IF EXISTS `job_plan`","CREATE TABLE `job_plan` (`PlanName` varchar(50) NOT NULL default '', `price` float default NULL, `numdays` int(11) NOT NULL default '0' ,`reviews` int(11) NOT NULL default '0' , `postings` int(11) NOT NULL default '0') TYPE=MyISAM;"); for($i=0;$i<count($jp_qry);$i++) { if (!mysql_query($jp_qry[$i])) { echo $jp_qry; echo "Could not create table...!!!"; exit; } } //"Table --job_plan-- created"; $jp_qry=array("DROP TABLE IF EXISTS `job_post`","CREATE TABLE job_post ( job_id int(10) default NULL, ename varchar(10) NOT NULL default '', Company varchar(100) NOT NULL default '', CompanyCountry varchar(200) NOT NULL default '', position varchar(100) NOT NULL default '', JobCategory varchar(150) NOT NULL default '', description text NOT NULL, j_target int(3) NOT NULL default '0', salary int(10) NOT NULL default '0', s_period varchar(10) NOT NULL default '', EXmonth char(2) NOT NULL default '', EXday char(2) NOT NULL default '', EXyear varchar(4) NOT NULL default '', nv int(5) NOT NULL default '0', CompanyState varchar(100) NOT NULL default '' ) TYPE=MyISAM;"); for($i=0;$i<count($jp_qry);$i++) { if (!mysql_query($jp_qry[$i])) { echo $jp_qry; echo "Could not create table...!!!"; exit; } } //"Table --job_post-- created"; $jsi_qry=array("DROP TABLE IF EXISTS `job_seeker_info`","CREATE TABLE `job_seeker_info` ( `uname` varchar(10) NOT NULL default '', `upass` varchar(10) NOT NULL default '', `title` char(3) NOT NULL default '', `fname` varchar(100) NOT NULL default '', `lname` varchar(100) NOT NULL default '', `bmonth` varchar(15) NOT NULL default '', `bday` char(2) NOT NULL default '', `byear` varchar(4) NOT NULL default '', `maritalstatus` varchar(20) NOT NULL default '', `income` varchar(20) NOT NULL default '', `city` varchar(100) NOT NULL default '', `state` varchar(30) NOT NULL default '', `country` varchar(60) NOT NULL default '', `zip` varchar(10) NOT NULL default '', `address` varchar(255) NOT NULL default '', `phone` varchar(50) NOT NULL default '', `phone2` varchar(50) NOT NULL default '', `job_seeker_email` varchar(100) NOT NULL default '', `job_seeker_web` varchar(200) NOT NULL default '', `job_category` varchar(150) NOT NULL default '', `careerlevel` varchar(60) NOT NULL default '', `target_company` varchar(60) NOT NULL default '', `relocate` char(3) NOT NULL default '', `rTitle` varchar(100) NOT NULL default '', `rPar` text NOT NULL, `isupload` tinyint(4) NOT NULL default '0', `resume` varchar(255) NOT NULL default '', PRIMARY KEY (`uname`)) TYPE=MyISAM;"); for($i=0;$i<count($jsi_qry);$i++) { if (!mysql_query($jsi_qry[$i])) { echo $jsi_qry; echo "Could not create table...!!!"; exit; } } //"Table --job_seeker_info-- created"; $js_qry=array("DROP TABLE IF EXISTS `job_skills`","CREATE TABLE job_skills ( uname varchar(10) NOT NULL default '', SK_d text ) TYPE=MyISAM;"); for($i=0;$i<count($js_qry);$i++) { if (!mysql_query($js_qry[$i])) { echo $js_qry; echo "Could not create table...!!!"; exit; } } //"Table --job_skills-- created"; $js_qry=array("DROP TABLE IF EXISTS `job_story`","CREATE TABLE job_story ( story_id int(5) NOT NULL default '0', story text ) TYPE=MyISAM;"); for($i=0;$i<count($js_qry);$i++) { if (!mysql_query($js_qry[$i])) { echo $js_qry; echo "Could not create table...!!!"; exit; } } $ins_qry1 = mysql_query("INSERT INTO job_story VALUES (1, 'Testing the system.')"); //"Table --job_story-- created"; $jsw_qry=array("DROP TABLE IF EXISTS `job_story_waiting`","CREATE TABLE job_story_waiting ( WS_id int(5) NOT NULL default '0', story text ) TYPE=MyISAM;"); for($i=0;$i<count($jsw_qry);$i++) { if (!mysql_query($jsw_qry[$i])) { echo $jsw_qry; echo "Could not create table...!!!"; exit; } } //"Table --job_story_waiting-- created"; $ins_qry1 = mysql_query("INSERT INTO job_story_waiting VALUES (1, 'Testing the system.')"); $jwe_qry=array("DROP TABLE IF EXISTS `job_work_experience`","CREATE TABLE job_work_experience ( uname varchar(10) NOT NULL default '', WEn int(2) NOT NULL default '0', WE_Start varchar(30) NOT NULL default '', WE_End varchar(30) NOT NULL default '', WE_p varchar(50) NOT NULL default '', WE_d text NOT NULL ) TYPE=MyISAM;"); for($i=0;$i<count($jwe_qry);$i++) { if (!mysql_query($jwe_qry[$i])) { echo $jwe_qry; echo "Could not create table...!!!"; exit; } } $ins_data = array("INSERT INTO job_admin_login VALUES ('admin', 'admin', '<NAME>', 'my email address')","INSERT INTO job_story VALUES (1, 'Testing the system.')","INSERT INTO `configuration` (`conf_id`, `paypal_email`, `site_name`, `email`, `address`,`vendorid`,`active_account`) VALUES (1, '". $_POST["paypal_id"] . "', '" . $_POST["site_name"] . "', '" . $_POST["email_address"] . "', '" . $_POST["site_address"] . "' , '" . $_POST["vendor_id"] . "', '" . $_POST["active_account"] . "' )"); for($i=0;$i<count($ins_data);$i++) { if (!mysql_query($ins_data[$i])) { echo "Problem in inserting data...!!!"; exit; } } //"Table --job_work_experience-- created"; $jta_qry=array("DROP TABLE IF EXISTS `job_tempacc`","CREATE TABLE job_tempacc ( id bigint(20) DEFAULT '0' NOT NULL auto_increment, date_added date DEFAULT '0000-00-00' NOT NULL, ip varchar(20) NOT NULL, user_id varchar(20) NOT NULL, txn_id varchar(50) NOT NULL, payer_email varchar(150) NOT NULL, payment_date varchar(30) NOT NULL, payment_fee double(50,5) DEFAULT '0.00000' NOT NULL, payment_gross double(50,5) DEFAULT '0.00000' NOT NULL, payment_status varchar(20) NOT NULL, memo text NOT NULL, paypal_response varchar(20) NOT NULL, paypal_post_vars text NOT NULL, plan_name varchar(100) NOT NULL, receiver_email varchar(100) NOT NULL, error_no tinyint(4) DEFAULT '0' NOT NULL, PRIMARY KEY (id) ) TYPE=MyISAM;"); for($i=0;$i<count($jta_qry);$i++) { if (!mysql_query($jta_qry[$i])) { echo $jta_qry; echo "Could not create table...!!!"; exit; } } //"Table --job_tempacc-- created"; $ins_qry1 = mysql_query("INSERT INTO job_tempacc VALUES (test, 'Testing the system.','test')"); //tables created ?> <table width="446" bgcolor="#D6E742"><tr><td><CENTER><br> <B>All Tables created successfully</B><BR><BR> </CENTER></td></tr></table> <? // unlink("install.php"); } else { ?> <script language="JavaScript"> function validate() { if (document.frm.database_name.value=='') { alert("Please enter database name"); document.frm.database_name.focus(); return false; } if (document.frm.database_username.value=='') { alert("Please enter database user name"); document.frm.database_username.focus(); return false; } if (document.frm.site_name.value=='') { alert("Please enter your site name"); document.frm.site_name.focus(); return false; } if (document.frm.email_address.value=='') { alert("Please enter email address"); document.frm.email_address.focus(); return false; } if (document.frm.site_address.value=='') { alert("Please enter site address"); document.frm.site_address.focus(); return false; } if (document.frm.paypal_id.value=='' || document.frm.vendor_id.value=='' ) { alert("Please enter PayPal ID or Vendor ID"); document.frm.paypal_id.focus(); return false; } return true; } </script> <center> <h3>Installation </h3> <table border="0" cellpadding="0" cellspacing="8" width="446" align="center" bgcolor="#D6E742"> <form name = frm method = post action = "install.php" onSubmit="return validate();"> <tr> <td width="50%" align="left"><strong>Database Host</strong></td> <td width="50%"><input type = text name = database_host value = "" ></td> </tr> <tr> <td width="50%" align="left"><strong>Database Name</strong></td> <td width="50%"><input type = text name = database_name value = "" ></td> </tr> <tr> <td width="50%" align="left"><strong>Username</strong></td> <td width="50%"><input type = text name = database_username value = "" ></td> </tr> <tr> <td width="50%" align="left"><strong>Password</strong></td> <td width="50%"><input type = text name = database_password value = "" ></td> </tr> <tr> <td width="50%" align="left"><strong>Site Name</strong></td> <td width="50%"><input name = site_name type = text id="site_name" value = "" ></td> </tr> <tr> <td width="50%" align="left"><strong>Email Address</strong></td> <td width="50%"><input name = email_address type = text id="email_address" value = "" ></td> </tr> <tr> <td width="50%" align="left"><strong>Site Address</strong></td> <td width="50%"><input name = site_address type = text id="site_address" value = "" ></td> </tr> <tr> <td width="50%" align="left"><strong>Paypal Id</strong></td> <td width="50%"><input name = paypal_id type = text id="paypal_id" value = "" ></td> </tr> <tr> <td width="50%" align="left"><strong>2Checkout Vendor Id</strong></td> <td width="50%"><input name = vendor_id type = text id="vendor_id" value = "" ></td> </tr> <tr> <td width="50%" align="left"><strong>Active Account</strong></td> <td width="50%"><select name="active_account"> <option value="pptc" selected>Use Both (PayPal & 2Checkout)</option><option value="tc">2Checkout</option><option value="pp">PayPal</option></select></td> </tr> <tr> <td width="50%" align="left">&nbsp;</td> <td width="50%"> <input type = "submit" name = "submit" value = "Submit" > <input type = "reset" name = "reset" value = "Reset" ></td> </tr> </form> </table> </center> <? } ?> </TD> <TD ROWSPAN=2 background="images/body_05.jpg"> <IMG SRC="images/body_05.jpg" WIDTH=7 HEIGHT=329 ALT=""></TD> </TR> <TR> <TD> <IMG SRC="images/body_06.gif" WIDTH=11 HEIGHT=4 ALT=""></TD> <TD> <IMG SRC="images/body_07.gif" WIDTH=193 HEIGHT=4 ALT=""></TD> <TD bgcolor="#D6E742"></TD> </TR> <TR bgcolor="#E0B837"> <TD> <IMG SRC="images/body_09.gif" WIDTH=7 HEIGHT=42 ALT=""></TD> <TD COLSPAN=3 align="center">POWERED BY <strong>PREPROJECTS.COM</strong></TD> <TD> <IMG SRC="images/body_11.gif" WIDTH=7 HEIGHT=42 ALT=""></TD> </TR> </TABLE></div> </td><br> </tr> </table> </body> </html><file_sep><? include_once "includes/documentHeader.php"; include_once "conn.php"; include_once "main.php"; $q1 = "select story_id from job_story"; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_num_rows($r1); if($a1 != '0') { mt_srand((double)microtime() * 1000000); $number = mt_rand(1, $a1); $q2 = "select story from job_story where story_id = \"$number\""; $r2 = mysql_query($q2) or die(mysql_error()); $a2 = mysql_fetch_array($r2); $st = $a2[0]; } ?> <table width="100%"> <tr> <td width="100%"> $_SERVER=(<?=var_dump_array($_SERVER)?>) </td> </tr> </table> <table width="446" border="0" align="center" cellpadding="5" cellspacing="0" bgcolor="#FFFFFF"> <tr valign="top"> <td width="100%" valign="top"><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/title_welcome.gif" width="260" height="15" alt="" border="0"> <br><br> <font size="2" face="Tahoma, Arial, sans-serif" color="#000000">Whether you’re an individual looking for a new job or a company searching for a new employee. Try us here at <em><?=$site_name?></em><br><br> <div align="center"><img src="images/logo_Electron.gif" alt="pay VISA Electron" width="37" height="23"><img src="images/logo_MC.gif" alt="pay MasterCard" width="37" height="23"> <img src="images/logo_Solo.gif" alt="pay Solo" width="37" height="23"><img src="images/logo_Switch.gif" alt="pay Switch" width="72" height="23"><img src="images/logo_Visa.gif" alt="pay Visa" width="37" height="23"></div> <br> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td width="50%" style="padding-right:10px;"><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/title_jobseekers1.gif" width="92" height="12" alt="" border="0" vspace="5"> <br> <font class="job"><a href="http://<?=$_SERVER[HTTP_HOST]?>/jobseekers/JobSearch.php">Search jobs</a></font> <br> Browse all the jobs for free <br> <br> <font class="job"><a href="http://<?=$_SERVER[HTTP_HOST]?>/jobseekers/jobseeker_registration.php">Join for free</a></font> <br> Register to access all the information <br> <br> <font class="job"><a href="http://<?=$_SERVER[HTTP_HOST]?>/jobseekers/jobseeker_registration.php">Post your resume</a></font> <br> Describe yourself - education, jobs, ect.</td> <td width="50%" style="padding-right:10px;"><img src="http://<?=$_SERVER[HTTP_HOST]?>/images/title_employers1.gif" width="84" height="12" alt="" border="0" vspace="5"> <br> <font class="job"><a href="http://<?=$_SERVER[HTTP_HOST]?>/employers/EmployerSearch.php">Search for staff</a></font> <br> Need more employees? <br> <br> <font class="job"><a href="http://<?=$_SERVER[HTTP_HOST]?>/employers/employer_registration.php">Register here</a></font> <br> Register to access the staff you need. <br> <br> <font class="job"><a href="http://<?=$_SERVER[HTTP_HOST]?>/employers/PostJob.php">Post a job</a></font> <br> First step to find your employees</td> </tr> </table> <br> <img src="http://<?=$_SERVER[HTTP_HOST]?>/images/title_successstory.gif" width="116" height="12" alt="" border="0" vspace="5"> <br> <br> <img src="http://<?=$_SERVER[HTTP_HOST]?>/images/clear.gif" width="1" height="1" alt="" border="0"> &nbsp;</td> </tr> </table> <? if($a1 != '0') { ?> <script language="JavaScript1.2"> var it=0 function initialize(){ mytext=typing.innerText var myheight=typing.offsetHeight typing.innerText='' document.all.typing.style.height=myheight document.all.typing.style.visibility="visible" typeit() } function typeit(){ typing.insertAdjacentText("beforeEnd",mytext.charAt(it)) if (it<mytext.length-1){ it++ setTimeout("typeit()",100) } else return } if (document.all) document.body.onload=initialize </script> <small><span id="typing" style="visibility:hidden" align="left"> <?=$st?> </span></small> <br> <? } ?> <hr size="1" noshade> <div align="center"><? include_once "banners.php";?></div> <? include_once('foother.html'); ?><file_sep><?php include_once("../includes/documentHeader.php"); $errors = array(); $debug = array(); $data = ""; $success = "false"; function echo_errors($errors) { $errorsStream = ""; $errorsStream = $errorsStream . "<error>"; for($i = 0; $i < count($errors); $i++) { $errorsStream = $errorsStream . "<msg>" . cdataEscape($errors[$i]) . "</msg>"; } $errorsStream = $errorsStream . "</error>"; return $errorsStream; } function echo_debug($debug) { $debugStream = ""; $debugStream = $debugStream . "<debug>"; for($i = 0; $i < count($debug); $i++) { $debugStream = $debugStream . "<msg>" . cdataEscape($debug[$i]) . "</msg>"; } $debugStream = $debugStream . "</debug>"; return $debugStream; } $cmd = getValueFromGetOrPostArray("cmd"); array_push($debug,"cmd=" . $cmd); $t = getdate(); $today = date('m-d-y', $t[0]); $file_path = $_SERVER['DOCUMENT_ROOT']."/#myUploads/" . $today . "/" . $_SERVER['REMOTE_ADDR']; array_push($debug,"\$file_path=" . $file_path); switch($cmd) { case "verifyUpload": $filename = getValueFromGetOrPostArray("filename"); $fname = $file_path . "/" . $filename; array_push($debug,"\$filename=" . $fname); $success = "true"; $_bool = file_exists ( $fname); $data = $data . "<verification>" . (($_bool) ? "1" : "0") . "</verification>"; break; case "SendEmailMessage": $fromAddr = getValueFromGetOrPostArray("fromAddr"); array_push($debug,"\$fromAddr=" . $fromAddr); $toAddr = getValueFromGetOrPostArray("toAddr"); array_push($debug,"\$toAddr=" . $toAddr); $subj = getValueFromGetOrPostArray("subj"); array_push($debug,"\$subj=" . $subj); $msg = getValueFromGetOrPostArray("msg"); array_push($debug,"\$msg=" . $msg); $msg = wordwrap($msg, 70); $smtp=new SMTPMAIL; array_push($debug,"\$smtp=" . var_print_r($smtp)); if(!$smtp->send_smtp_mail($toAddr,$subj,$msg,"",$fromAddr)) { $success = "false"; array_push($errors,"SMTP Failed to send the requested email."); } else { $success = "true"; } break; default: $success = "false"; array_push($errors,"No action was requested."); } ?> <?php $success = cdataEscape($success); $errStr = echo_errors($errors); $debugStr = echo_debug($debug); $xmlstr = <<<XML <?xml version="1.0" encoding="iso-8859-1"?> <results> <success>$success</success> $data $errStr $debugStr </results> XML; echo $xmlstr; ?> <file_sep><?php /** * Tweetr Proxy Class * @author <NAME> [swfjunkie.com, Switzerland] */ class Tweetr { //-------------------------------------------------------------------------- // // Class variables // //-------------------------------------------------------------------------- const USER_AGENT = 'TweetrProxy 1.0b2'; const USER_AGENT_LINK = 'http://tweetr.swfjunkie.com/'; const BASEURL = '/proxy'; const DEBUGMODE = false; const GHOST_DEFAULT = 'ghost'; const CACHE_ENABLED = false; const CACHE_TIME = 120; // 2 minutes const CACHE_DIRECTORY = 'cache'; const UPLOAD_DIRECTORY = 'tmp'; //-------------------------------------------------------------------------- // // Initialization // //-------------------------------------------------------------------------- /** * Creates a Tweetr Proxy Instance * @param (array) $options Associative Array containing optional values see http://code.google.com/p/tweetr/wiki/PHPProxyUsage */ public function Tweetr($options = null) { // set the options $this->baseURL = (isset($options['baseURL'])) ? $options['baseURL'] : self::BASEURL; $this->userAgent = (isset($options['userAgent'])) ? $options['userAgent'] : self::USER_AGENT; $this->userAgentLink = (isset($options['userAgentLink'])) ? $options['userAgentLink'] : self::USER_AGENT_LINK; $this->indexContent = (isset($options['indexContent'])) ? $options['indexContent'] : '<html><head><title>'.$this->userAgent.'</title></head><body><a href="'.$this->userAgentLink.'" title="Go to Website">'.$this->userAgent.'</a></body></html>'; $this->debug = (isset($options['debugMode'])) ? $options['debugMode'] : self::DEBUGMODE; $this->ghostName = (isset($options['ghostName'])) ? $options['ghostName'] : self::GHOST_DEFAULT; $this->ghostPass = (isset($options['ghostPass'])) ? $options['ghostPass'] : self::GHOST_DEFAULT; $this->userName = (isset($options['userName'])) ? $options['userName'] : null; $this->userPass = (isset($options['userPass'])) ? $options['userPass'] : null; $this->cacheEnabled = (isset($options['cache_enabled'])) ? $options['cache_enabled'] : self::CACHE_ENABLED; $this->cacheTime = (isset($options['cache_time'])) ? $options['cache_time'] : self::CACHE_TIME; $this->cacheDirectory = "./".((isset($options['cache_directory'])) ? $options['cache_directory'] : self::CACHE_DIRECTORY)."/"; $this->uploadDirectory = "./".((isset($options['upload_directory'])) ? $options['upload_directory'] : self::UPLOAD_DIRECTORY)."/"; // set the current url and parse it $this->url = parse_url($_SERVER['REQUEST_URI']); $this->parseRequest(); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- private $url; private $debug; private $baseURL; private $userAgent; private $userAgentLink; private $indexContent; private $userName; private $userPass; private $ghostName; private $ghostPass; private $cacheEnabled; private $cacheTime; private $cacheDirectory; private $uploadDirectory; //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * Pre-Parses the received request to see if we need authentication or not */ private function parseRequest() { if($_SERVER['REQUEST_METHOD'] == 'POST') { $this->checkCredentials(); } else { if($this->url['path'] == $this->baseURL.'/') die(urldecode($this->indexContent)); else $this->checkCredentials(); } } /** * Makes a request to twitter with the data provided and returns the result to the screen */ private function twitterRequest($authentication = false) { /* caching - begin */ if($_SERVER['REQUEST_METHOD'] != 'POST' && $this->cacheEnabled && $this->cacheExists() && !$this->isOAuthRegCall()) { header('Content-type: text/xml; charset=utf-8'); echo $this->cacheRead(); return; } /* caching - end */ if($this->isOAuthRegCall()) $twitterURL = 'http://twitter.com'.str_replace($this->baseURL,'',$this->url['path']); else $twitterURL = 'https://api.twitter.com/1'.str_replace($this->baseURL,'',$this->url['path']); if($_SERVER['REQUEST_METHOD'] == 'GET') $twitterURL .= '?'.$this->url['query']; $opt[CURLOPT_URL] = $twitterURL; $opt[CURLOPT_USERAGENT] = $this->userAgent; $opt[CURLOPT_RETURNTRANSFER] = true; $opt[CURLOPT_TIMEOUT] = 60; if($authentication) { $opt[CURLOPT_HTTPAUTH] = CURLAUTH_BASIC; $creds = (isset($_GET['hash'])) ? $_GET['hash'] : $_POST['hash']; $credsArr = explode(':', base64_decode($creds)); $credUser = $credsArr[0]; $credPass = $credsArr[1]; if( isset($this->ghostName) && isset($this->ghostPass) && isset($this->userName) && isset($this->userPass) && $this->ghostName == $credUser && $this->ghostPass == $credPass) { $opt[CURLOPT_USERPWD] = $this->userName .':'. $this->userPass; } else { $opt[CURLOPT_USERPWD] = $credUser .':'. $credPass; } } if($_SERVER['REQUEST_METHOD'] == 'POST') { $oauthArgs = array(); $postFields = array(); if (isset($_FILES['image'])) { $imagePath = $this->uploadDirectory.$_FILES['image']['name']; if (move_uploaded_file($_FILES['image']['tmp_name'], $imagePath)) { $imageInfo = getimagesize($imagePath); $postFields['image'] = "@".realpath($imagePath).";type=".$imageInfo['mime']; } else { die('Upload failed, check upload directory permissions/path...'); } } foreach($_POST as $key => $val) { if (isset($imagePath)) { if (strpos($key, "oauth_") === false) $postFields[$key] = $val; } else { if ($key == "oauth_signature") $oauthsig = $val; else if ($key == "_method") $_method = $val; else $postFields[$key] = $val; } } if (isset($imagePath)) { if (isset($_POST['oauth_version'])) { $oauthHeader = 'Authorization: OAuth realm="'.$twitterURL.'", oauth_consumer_key="'.rawurlencode($_POST['oauth_consumer_key']).'", oauth_token="'.rawurlencode($_POST['oauth_token']).'", oauth_nonce="'.rawurlencode($_POST['oauth_nonce']).'", oauth_timestamp="'.rawurlencode($_POST['oauth_timestamp']).'", oauth_signature_method="HMAC-SHA1", oauth_version="1.0",oauth_signature="'.rawurlencode($_POST['oauth_signature']).'"'; $opt[CURLOPT_HTTPHEADER] = array($oauthHeader, 'Expect:', ); } else { $opt[CURLOPT_HTTPHEADER] = array('Expect:', ); } $opt[CURLOPT_POST] = true; $opt[CURLOPT_POSTFIELDS] = $postFields; } else { if (isset($oauthsig)) { ksort($postFields); $postFields = array_merge($postFields, array('oauth_signature' => $oauthsig)); } $opt[CURLOPT_HTTPHEADER] = array('Expect:'); if (isset($_method)) $opt[CURLOPT_CUSTOMREQUEST] = strtoupper($_method); else $opt[CURLOPT_POST] = TRUE; $opt[CURLOPT_SSL_VERIFYPEER] = FALSE; $opt[CURLOPT_POSTFIELDS] = http_build_query($postFields); } } //do the request $curl = curl_init(); curl_setopt_array($curl, $opt); ob_start(); $response = curl_exec($curl); if(strlen(''.$response) < 2 ) $response = ob_get_contents(); ob_end_clean(); if (isset($imagePath)) unlink($imagePath); if($this->debug) { $headers = curl_getinfo($curl); $errorNumber = curl_errno($curl); $errorMessage = curl_error($curl); } curl_close($curl); if($this->debug) { $this->log($headers); $this->log($errorNumber); $this->log($errorMessage); } if (!$this->isOAuthRegCall()) header('Content-type: text/xml; charset=utf-8'); /* caching - begin */ if ($this->cacheEnabled) $this->cacheInit(); echo $response; if ($this->cacheEnabled) $this->cacheEnd(); } /** * Requests Basic Authentication */ private function checkCredentials() { if (!isset($_GET['hash']) && !isset($_POST['hash'])) $this->twitterRequest(); else $this->twitterRequest(true); } /** * Checks if the received call is a oauth token/authorization request */ private function isOAuthRegCall() { if( strpos($this->url['path'], "oauth/request_token") != false || strpos($this->url['path'], "oauth/authorize") != false || strpos($this->url['path'], "oauth/access_token") != false) return true; return false; } /** * Log Method that you can overwrite with your own logging stuff. * FirePHP is my personal recommendation though ;) * @param $obj Whatever you are trying to log */ private function log($obj) { //require_once('fire/fb.php'); //FB::log($obj); } //------------------------------- // Caching //------------------------------- /** * Start Caching Process */ private function cacheInit() { if($this->cacheExists()) { echo $this->cacheRead(); exit(); } else { ob_start(); } } /** * End Caching Process */ private function cacheEnd() { $data = ob_get_clean(); $this->cacheSave($data); echo $data; } /** * Create cache key */ private function cacheKey() { foreach($_POST as $key => $value) $keys[] = $key . '=' . urlencode($value) ; foreach($_GET as $key => $value) $keys[] = $key . '=' . urlencode($value) ; $keys[] = 'app=tweetr'; $keys[] = 'requrl='.urlencode($this->url['path']); sort($keys); return md5(implode('&', $keys)); } /** * Returns filename */ private function cacheFilename() { return $this->cacheDirectory. $this->cacheKey() . '.cache'; } /** * Checks if a specific cached file exists */ private function cacheExists() { if(@file_exists($this->cacheFilename()) && (time() - $this->cacheTime) < @filemtime($this->cacheFilename())) return true; else return false; } /** * Reads the Cache */ private function cacheRead() { return file_get_contents($this->cacheFilename()); } /** * Destroy uneccessary cache files */ private function cachePurge() { $dir_handle = @opendir($this->cacheDirectory) or die('Unable to open '.$this->cacheDirectory); while ($file = readdir($dir_handle)) { if ($file!='.' && $file!='..' && (time() - $this->cacheTime) > @filemtime($this->cacheDirectory.$file)) unlink($this->cacheDirectory.$file) or die('Error. Could not erase file : '.$file); } } /** * Save a cache file */ private function cacheSave($value) { $this->cachePurge(); $fp = @fopen($this->cacheFilename(), 'w') or die('Error opening file: '.$this->cacheFilename()); @fwrite($fp, $value) or die('Error writing file.'); @fclose($fp); } } ?><file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; $q1 = "select * from job_story_waiting where WS_id = \"$_GET[story_id]\""; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); $q2 = "select count(*) from job_story"; $r2 = mysql_query($q2) or die(mysql_error()); $a2 = mysql_fetch_array($r2); $NewID = $a2[0] + 1; $NewStory = addslashes($a1[story]); $q3 = "insert into job_story set story_id = \"$NewID\", story = \"$NewStory\""; $r3 = mysql_query($q3) or die(mysql_error()); $q4 = "delete from job_story_waiting where WS_id = \"$_GET[story_id]\" "; $r4 = mysql_query($q4) or die(mysql_error()); $q5 = "select * from job_story_waiting order by WS_id"; $r5 = mysql_query($q5) or die(mysql_error()); while($a5 = mysql_fetch_array($r5)) { $i = $i + 1; $add = addslashes($a5[story]); $q6 = "update job_story_waiting set WS_id = \"$i\" where story = \"$add\" "; $r6 = mysql_query($q6) or die(mysql_error()); } echo "<br><center> The approval was successfull.</center><br>"; include_once("stories.php"); ?> <? include_once('../foother.html'); ?><file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; include_once "navigation.html"; $nb = "select count(b_id) from job_banners_t"; $rnb = mysql_query($nb) or die; $anb = mysql_fetch_array($rnb); echo "<br><br>"; for ($bb = 1; $bb <= $anb[0]; $bb++) { $sb = "select * from job_banners_t where b_id = \"$bb\" "; $rsb = mysql_query($sb) or die(mysql_error()); $ab = mysql_fetch_array($rsb); echo "<table align=center width=446 border=0 cellpadding=3 cellspacing=0 bordercolor=black>"; echo "<tr><td width= 100 class=TD_links>Banner ID: $ab[b_id] <br><br> File name: $ab[fn] <br><br><a href=del_ban.php?b_id=$ab[b_id]&fn=$ab[fn]>delete </a></td><td align=center> <img src=banners/$ab[fn] alt=\"$ab[alt]\"> </td></tr>"; echo "</table><br>"; } ?><file_sep><?php define('BASE_DIR', dirname(__FILE__)); define('BASE_URL', str_replace("/index.php","",$_SERVER['SCRIPT_NAME'])); require BASE_DIR."/content/version.php"; require BASE_DIR."/connect.php"; if (!empty($_GET["content"])) { $content = $_GET["content"]; } else { $content = "content/notebook.php"; } if (isset($_GET['search'])) $content = "content/search.php"; // Check to make sure we are running PHP 5.2 or greater if (version_compare(PHP_VERSION, '5.2.0') < 0) { echo 'Surreal ToDo '._('requires PHP 5.2 or greater. Your version is') . ' ' . PHP_VERSION . "\n"; break; } // Load all the application config settings $query = mysql_query("SELECT name, value FROM config"); if (!$query) header('location: ./content/install.php'); while($row = mysql_fetch_array($query)){ $GLOBALS["config"][ $row["name"] ] = $row["value"]; } // Set the language $locale = $GLOBALS["config"]["locale"]; bindtextdomain($locale, './locale'); bind_textdomain_codeset($locale, 'UTF-8'); textdomain($locale); setlocale(LC_ALL,$locale); $localeFile = '/locale/'.$locale.'/LC_MESSAGES/'.$locale; // Verify the database version coincides with the application version // If not attempt to upgrade if ($GLOBALS["config"]["version"] != APP_VERSION) header('location: ./content/upgrade.php'); // Set the user defined timezone date_default_timezone_set($GLOBALS["config"]["timezone"]); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-quiv="Cache-Control" content="<?php if ($_SERVER['HTTP_HOST'] == 'webapps') echo 'no-cache'; else echo 'public';?>"> <meta http-quiv="Expires" content="<?php echo date('D, d M Y H:i:s \G\M\T', time() + 2592000); ?>"> <title><?php echo $GLOBALS["config"]["default_site_name"]; ?></title> <?php echo '<link rel="stylesheet" type="text/css" href="min/?f=theme/base.css,theme/'.$GLOBALS["config"]["theme"].'/styles.css,theme/'.$GLOBALS["config"]["theme"].'/jquery/jquery-ui.css" />'; if (file_exists(BASE_DIR.$localeFile.".po")) { echo '<link rel="gettext" type="application/x-po" href=".'.$localeFile.'.po" />'; } ?> </head> <body> <div id="container"> <div id="header"> <h1><a href="<?php echo BASE_URL; ?>"><?php echo $GLOBALS["config"]["default_site_name"]; ?></a></h1> <ul class="headerMenu"> <li><a href="<?php echo BASE_URL; ?>"><?php echo _('Notebook'); ?></a></li> <li><a href="<?php echo BASE_URL; ?>/index.php?content=content/trash.php"><?php echo _('Trash'); ?></a></li> <li><a href="<?php echo BASE_URL; ?>/index.php?content=content/settings.php"><?php echo _('Settings'); ?></a></li> <li class="search"> <form> <input name="search" type="text" value="<?php echo _('Search'); ?>..." onclick="this.select()" /> </form> </li> </ul> </div> <!-- close header --> <?php require BASE_DIR.'/'.$content; ?> </div> <!-- close container --> </body> </html><file_sep><?php $database_name="resume_del"; $database_username=""; $database_password="";?><file_sep><? include_once "accesscontrol.php"; $qs = "select rTitle from job_seeker_info where uname = \"$uname\" "; $rs = mysql_query($qs) or die(mysql_error()); $as = mysql_fetch_array($rs); if(!empty($as[0])) { echo "<table width=446><tr><td><br><br><center> You already had posted your resume.<br>If you want to edit it, click <a href=ER1.php>here </a></center></td></tr></table>"; } else { ?> <html> <head> <title> <?=$site_name?> </title> <SCRIPT LANGUAGE="JavaScript"> function checkFields() { missinginfo = ""; if (document.form.rTitle.value == "") { missinginfo += "\n - Resume titie"; document.form.rTitle.focus(); } if (missinginfo != "") { missinginfo ="Choose a title for your resume."; alert(missinginfo); return false; } else return true; } </script> <br> <table align=center width=446> <tr> <td> There are only three easy steps to build your powerfull resume: <ul> <li><b> Work experience. </b> Enter all your jobs - previous and presents. Let the employers know what you already done before and let they estimate your experience.</li> <li><b> Education. </b> Enter the information about your education. Start from Highschool and finish with the university. You may choose as many education instittution as you need.</li> <li><b> Skills. </b> You have some additional skills? They help you to work most successfull and easy to comunicate with people? You must be proud. Let the employers know this. </li> </ul> </td> </td> <tr> <td> Start building your resume now. Choose the resume title and write a short paragraph about you. </td> </tr> <tr> <form action=1.php method=post name=form onSubmit="return checkFields();" style="background:none;"> <td align=center> <b>Title </b><font size=1> (choose a title for your resume, 2 - 3 words)</font><br> <input type=text name=rTitle size=35> </td> </tr> <tr> <td align=center> Introduce yourself to the employers <font size=1> (a short paragraph about you) </font><br> <textarea cols=46 rows=4 name=rPar></textarea> </td> </tr> <tr><td align=center><input type=submit value="Go to Step 1 (Work experience)"></td></tr> </form> </table> <? } ?> <? include_once('../foother.html'); ?><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"> <?php include_once("..\includes\documentHeader.php"); print_r(docHeader('../..')); ?> </head> <body> <?php if (stristr($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) == false) { $ar = splitStringToArray($_SERVER['SCRIPT_NAME']); redirectBrowser('/?linkname=' . $ar[count($ar) - 1]); } ?> <table width="590"> <tr> <td class="primaryContentContainerHeader"> <p align="justify"><a href="/php/links/getContentForFlashTowersOfHanoi.php" target="_self">Flash Towers Of Hanoi :: Classic Computer Science Project</a></p> </td> </tr> <tr> <td valign="top"> <p align="justify">The Towers of Hanoi is a Classic Computer Science problem. Almost every single Computer Science textbook on the planet has this problem fully explained along with the pseudo-code for the solution set. These Flash Clips simply allow the Towers of Hanoi problem to be solved for up to 10 discs.</p> <p align="justify">The Towers of Hanoi would be a far more interesting problem to code if the problem domain required the discs to be randomly shuffled and the solution set required for an AI (Artificial Intelligence) approach to reach a solution within a reasonable timeframe. Coding the variation of the Towers of Hanoi I would personally find interesting would require far more programming skill than the version that is presented here however it would be a fun problem to study assuming one had the time to write the code and fully develop the programmatic solution set.</p> <p align="justify"><a href="/php/links/getContentForFlashTowersOfHanoiV1.php" target="_self">Flash Towers Of Hanoi Version 1 :: The original version.</a></p> <p align="justify"><a href="/php/links/getContentForFlashTowersOfHanoiV2.php" target="_self">Flash Towers Of Hanoi Version 2 :: with Variable Runtime Speed.</a></p> </td> </tr> </table> </body> </html> <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"> <?php include_once("..\includes\documentHeader.php"); print_r(docHeader('../..')); ?> <script language="JavaScript1.2" type="text/javascript" src="popUpWindowForURL.js"></script> </head> <body> <?php if (stristr($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) == false) { $ar = splitStringToArray($_SERVER['SCRIPT_NAME']); redirectBrowser('/?linkname=' . $ar[count($ar) - 1]); } ?> <?php print(handleNoScript()); ?> <table width="590"> <tr> <td class="primaryContentContainerHeader"> <table width="100%"> <tr> <td align="left"> <p align="justify"><a href="/php/links/getContentForFlashFlex2.php" target="_self">Flex 2.0.1</a></p> </td> <td align="right"> </td> </tr> </table> </td> </tr> <tr> <td height="200" valign="middle"> <table width="100%"> <tr> <td width="80%" valign="top"> <p align="justify">Welcome to the Flex 2 Sample(s).</p> <p align="justify">ezPainter was my first Flex 2 Sample Applet. This sort of App is always fun to code but then who doesn't enjoy some recreational doodling anyway ?!?</p> <p align="justify">This rendition of ezPainter is a very small 3 Kb Flash Movie. Compare this with the 45 Kb Composer rendition that was created using a different development platform. This bodes quite well for Flex 2 assuming this level of optimization is any indication as to the quality of the Flex 2 Flash Development platform. In all fairness, the larger Composer rendition for ezPainter does have more functionality but it was also created using the more traditional timeline Flash programming model one might use when creating an animated movie clip for a Cartoon or the like.</p> <p align="justify">Flex 2 provides a programming model for Flash that is about as far away from the original Flash programming model as can be achived. Flex 2 allows programmers to ignore the fact that Flash is the end-product and focus instead on the task of writing the code. Flex 2 programmers do not need to know anything about Flash timelines or frame rates.</p> <p align="justify">The Flex 2 programming model is similar to the C#.Net Programming model but Flex 2 provides a better development platform in terms of what can be done with the language out-of-the-box.</p> <p align="justify">Someday, time-permitting, the ezPainter Sample may even be empowered to interact with a database to allow people to share their drawings.</p> </td> <td width="*" valign="top"> <p align="justify"><NOBR><a href="" onClick="popUpWindowForURL('/app/flash/flex2/ezPainterSample/ezPainterSample.html', 'ezPainterSample', 750, 520); return false;">ezPainter</a></NOBR></p> </td> </tr> </table> <!-- <h4>Under construction... Come on back a bit later-on...</h4> --> </td> </tr> </table> </body> </html> <file_sep><?php # ---------------------------------------------------- # ----- AUTO EMAIL ME PASSWORD AND DOWNLOAD # ----- Version 1.7 # ----- Created on: 01/30/07 # ----- Designed by: American Financing # ---------------------------------------------------- // Receiving variables @$First_Name = addslashes($_POST['First_Name']); @$Last_Name = addslashes($_POST['Last_Name']); @$email = addslashes($_POST['email']); // Validation if (strlen($First_Name) == 0 ) { header("Location: error.html"); exit; } if (strlen($Last_Name) == 0 ) { header("Location: error.html"); exit; } if (! ereg('[A-Za-z0-9_-]+\@[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+', $email)) { header("Location: error.html"); exit; } //Sending Email to form owner # Email to Owner $pfw_header = "From: $email"; $pfw_subject = "USER: Auto eMail me Password and Download"; $pfw_email_to = "<EMAIL>"; $pfw_message = "First_Name: $First_Name\n" . "Last_Name: $Last_Name\n" . "email: $email\n"; @mail($pfw_email_to, $pfw_subject ,$pfw_message ,$pfw_header ) ; //Sending auto respond Email to user # Email to Owner $pfw_header = "From: <EMAIL>"; $pfw_subject = "Auto eMail me Password and Download"; $pfw_email_to = "$email"; $pfw_message = "Thank You for Trying out Auto eMail me Password and Download.\n" . "\n" . "Hello $First_Name $Last_Name,\n" . "\n" . "You can download the file at:\n" . "http://www.americanfinancing.net\n" . "\n" . "The Password to unzip the file is: americanfinancing\n" . "\n" . "All in lower case.\n" . "\n" . "Please visit us at http://www.americanfinancing.net\n" . "and apply for a Home Loan Today."; @mail($pfw_email_to, $pfw_subject ,$pfw_message ,$pfw_header ) ; //saving record in a text file $pfw_file_name = "data.csv"; $pfw_first_raw = "First_Name,Last_Name,email\r\n"; $pfw_values = "$First_Name,$Last_Name,$email\r\n"; $pfw_is_first_row = false; if(!file_exists($pfw_file_name)) { $pfw_is_first_row = true ; } if (!$pfw_handle = fopen($pfw_file_name, 'a+')) { die("Cannot open file ($pfw_file_name)"); exit; } if ($pfw_is_first_row) { if (fwrite($pfw_handle, $pfw_first_raw ) === FALSE) { die("Cannot write to file ($pfw_filename)"); exit; } } if (fwrite($pfw_handle, $pfw_values) === FALSE) { die("Cannot write to file ($pfw_filename)"); exit; } fclose($pfw_handle); header("Location: thank_you.html"); ?> <file_sep><? include_once "accesscontrol.php"; $SK_d = strip_tags($SK_d, "<br>"); $SK_d = addslashes($SK_d); if ( $submit == 'Save and finish') { $q1 = "update job_skills set SK_d = \"$SK_d\" where uname = \"$uname\" "; $r2 = mysql_query($q1) or die(mysql_error()); $q12 = "select * from job_skills where uname = \"$uname\" "; $r12 = mysql_query($q12) or die(mysql_error()); $a12 = mysql_fetch_array($r12); $a111 = stripslashes($a12[SK_d]); echo "<table width=446 bgcolor=#FFFFFF><tr><td><br><br><br><center>Your resume has been updated successfully.</center></td></tr></table>"; unset($submit); include_once('../foother.html'); } else { include "EditSkills.php"; } ?> <file_sep><?php require_once ('session.php'); require_once ('shared.php'); require_once ('header.php'); ?> <h1>About</h1> <p> The Workbench is a web-based application that gives administrators on-demand access to useful tools to manage their salesforce.com organization. Combining the power of both the Apex Data Loader with the Force.com Explorer, the Workbench can insert, upsert, update, export, delete, undelete, and purge data as well as describe any object in your salesforce.com organization. These functions build on the strengths of both the existing products to create an even more powerful and easier-to-use on-demand application. Not only can the Workbench be used as a standalone application in your browser, but it can also be integrated within Salesforce as a single-sign-on web tab for more convenient access. </p> <p> <strong> Workbench v<?php echo $GLOBALS['version']; ?><br/> </strong> Distributed under the Open Source BSD License.<br/> Developed by <NAME><br/> </p> <p> <img src='images/open_source_logo.png' width='119' height='96' alt='Open Source Logo' align='center' />&nbsp;&nbsp; <img src='images/php-med-trans-light.gif' width='95' height='51' alt='PHP Logo' align='center' /> </p> <p> <strong>The Workbench is NOT a product of or supported by salesforce.com, inc. For support from the Open Source community, please visit the recources below:</strong> <ul> <li><a href="http://code.google.com/p/forceworkbench/">Main Page</a></li> <li><a href="http://groups.google.com/group/forceworkbench">Feedback &amp; Discussion</a></li> <li><a href="http://wiki.apexdevnet.com/index.php/Workbench">Wiki</a></li> <li><a href="http://wiki.apexdevnet.com/index.php/Workbench#FAQ">FAQ</a></li> <li><a href="http://code.google.com/p/forceworkbench/issues/list">Issue Tracking</a></li> <li><a href="http://code.google.com/p/forceworkbench/source/browse">Source Code</a></li> <li><a href="http://code.google.com/p/forceworkbench/downloads/list">Download</a></li> </ul> </p> <strong><p> THIS APPLICATION IS STILL IN ACTIVE DEVELOPMENT AND HAS NOT UNDERGONE QUALITY ASSURANCE TESTING. DO NOT USE WITH PRODUCTION DATA. THIS APPLICATION IS PROVIDED 'AS IS' AND THE USER ASSUMES ALL RISKS ASSOCIATED WITH ITS USE.</p> </strong> <hr/> <p>This application is based on the salesforce.com PHP Toolkit and calls against the Force.com Web Services API, but is not itself a product of salesforce.com, inc. and not supported by salesforce.com, inc or its contributors. Below is the copyright and license for the PHP Toolkit:</p> <p> Copyright (c) 2008, salesforce.com, inc.<br/> All rights reserved. </p> <p> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: <ul> <li>Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.</li> <li>Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.</li> <li>Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.</li> </ul> </p> <p> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. </p> <hr/> <p> Collapsible tree on Describe page is built on <a href="http://www.dynamicdrive.com/dynamicindex1/navigate1.htm">Simple Tree Menu</a> framework from <a href="http://www.dynamicdrive.com">Dynamic Drive DHTML code library</a> </p> <hr/> <p> Code for menu bar tool tips is built on <a href="http://www.walterzorn.com/tooltip/tooltip_e.htm">JavaScript, DHTML Tooltips </a> framework from <a href="http://www.walterzorn.com/"><NAME></a> </p> </div> <?php include_once ('footer.php'); ?> <file_sep>Surreal ToDo Download from SourceForge at http://www.sourceforge.net/projects/surrealtodo/ Project home and demo located at http://www.getsurreal.com/surrealtodo/ Author: <NAME> What's New v0.6.1.2 Updated install and upgrade scripts Added Danish translation Added German translation v0.6.1 Fixed bug with Advanced Edit Save Added French Translation (user contributed) v0.6 Added advanced text editing (hyperlinks, images, font styles, font colors, lists, tables, etc) Improved performance for enabling browser caching of non dynamic data Improved performance by combining images into sprites Improved performance by minifying javascript and CSS files Added ability to choose format of completed items (strikethrough, gray, italic, check mark) Added ability to be translated to any language Added Russian Translation (user contributed) Added Traditional Chinese Translation (user contributed) Added Simplified Chinese Translation (user contributed) Added Japanese Translation (google translation needs user review) Added ability to choose 1, 2 or 3 columns per page v0.5.2 Added ability for user to set date and time format Added ability to edit dates Added theme capability Added Dusk to Dawn theme contributed by Alexufo v0.5.1 Added ability to set hyperlink for list items Added ability to duplicate a tab, page or list allowing template functionality v0.5 Added trashcan feature to allow restoring deleted objects Added search feature v0.4.1 Disable custom context menu when editing in order to restore default contextmenu with cut, copy, paste, etc. options Fix - do not allow saving empty text Fix - clicking on active tab cleared page contents Added settings configuration to set default text for new Tabs, Pages, Lists and Items Added check if new version is available Fix - edit multiple tasks only able to save or cancel on last one edited spellcheck - use browsers built-in spell check removed 'new page' and 'settings' as sortable Added CSS to install script Added CSS to update script Fix - new tasks are not sortable in new lists Cleaned up some undefined php variables v0.4 Multiple Pages per Tab Move Lists to different Pages via drag and drop Move Lists to different Tabs via drag and drop Move Pages to different Tabs via drag and drop v0.3.1 Front end changes: -lists organized into 3 columns -list expand and collapse changed to accordion Fixes: -fix "ESC" doesn't work to cancel edit with Google Chrome and Safari -on tab edit set that tab to be active Additions: -added install script -added upgrade script Installation Copy files to your website folder. Edit connect.php to supply your database connection settings. Browse to your site and the install script will setup your database. Upgrade If you are running a version prior to v0.3 you must first upgrade to v0.3 manually. Backup your database. Document your database connection settings. Delete or rename the folder containing the older version. Extract or copy files to your website folder. Edit connect.php with your database connection settings. Browse to your site and the upgrade script will update your database. <file_sep><? include_once "accesscontrol.php"; $q1 = "select * from job_post where job_id = \"$job_ed\" "; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); ?> <br><br> <table align=center width="446"> <tr><td colspan=2 align=center> To edit a job, use the form below:</td></tr><br><br> <form action=EditJob2.php method=post style="background:none;"> <tr><td>Position:</td> <td> <input type=text name=position value="<?=$a1[position]?>"> </td> </tr> <tr> <td valign=top> Job Category: </td> <td valign=top> <SELECT NAME="JobCategory2[]" multiple size=5 style=width:300> <OPTION VALUE="Accounting/Auditing" >Accounting/Auditing</OPTION> <OPTION VALUE="Administrative and Support Services" >Administrative and Support Services</OPTION> <OPTION VALUE="Advertising/Public Relations" >Advertising/Public Relations</OPTION> <OPTION VALUE="Agriculture/Forestry/Fishing" >Agriculture/Forestry/Fishing</OPTION> <OPTION VALUE="Architectural Services" >Architectural Services</OPTION> <OPTION VALUE="Arts, Entertainment, and Media" >Arts, Entertainment, and Media</OPTION> <OPTION VALUE="Banking" >Banking</OPTION> <OPTION VALUE="Biotechnology and Pharmaceutical" >Biotechnology and Pharmaceutical</OPTION> <OPTION VALUE="Community, Social Services, and Nonprofit" >Community, Social Services, and Nonprofit</OPTION> <OPTION VALUE="Computers, Hardware" >Computers, Hardware</OPTION> <OPTION VALUE="Computers, Software" >Computers, Software</OPTION> <OPTION VALUE="Construction, Mining and Trades" >Construction, Mining and Trades</OPTION> <OPTION VALUE="Consulting Services" >Consulting Services</OPTION> <OPTION VALUE="Customer Service and Call Center" >Customer Service and Call Center</OPTION> <OPTION VALUE="Education, Training, and Library" >Education, Training, and Library</OPTION> <OPTION VALUE="Employment Placement Agencies" >Employment Placement Agencies</OPTION> <OPTION VALUE="Engineering" >Engineering</OPTION> <OPTION VALUE="Executive Management" >Executive Management</OPTION> <OPTION VALUE="Finance/Economics" >Finance/Economics</OPTION> <OPTION VALUE="Financial Services" >Financial Services</OPTION> <OPTION VALUE="Government and Policy" >Government and Policy</OPTION> <OPTION VALUE="Healthcare, Other" >Healthcare, Other</OPTION> <OPTION VALUE="Healthcare, Practitioner, and Technician" >Healthcare, Practitioner, and Technician</OPTION> <OPTION VALUE="Hospitality, Tourism" >Hospitality, Tourism</OPTION> <OPTION VALUE="Human Resources" >Human Resources</OPTION> <OPTION VALUE="Information Technology" >Information Technology</OPTION> <OPTION VALUE="Installation, Maintenance and Repair" >Installation, Maintenance and Repair</OPTION> <OPTION VALUE="Insurance" >Insurance</OPTION> <OPTION VALUE="Internet/E-Commerce" >Internet/E-Commerce</OPTION> <OPTION VALUE="Law Enforcement and Security" >Law Enforcement and Security</OPTION> <OPTION VALUE="Legal" >Legal</OPTION> <OPTION VALUE="Manufacturing and Production" >Manufacturing and Production</OPTION> <OPTION VALUE="Marketing" >Marketing</OPTION> <OPTION VALUE="Military" >Military</OPTION> <OPTION VALUE="Other" >Other</OPTION> <OPTION VALUE="Personal Care and Services" >Personal Care and Services</OPTION> <OPTION VALUE="Real Estate" >Real Estate</OPTION> <OPTION VALUE="Restaurant and Food Service" >Restaurant and Food Service</OPTION> <OPTION VALUE="Retail/Wholesale" >Retail/Wholesale</OPTION> <OPTION VALUE="Sales" >Sales</OPTION> <OPTION VALUE="Science" >Science</OPTION> <OPTION VALUE="Sports/Recreation" >Sports/Recreation</OPTION> <OPTION VALUE="Telecommunications" >Telecommunications</OPTION> <OPTION VALUE="Transportation and Warehousing" >Transportation and Warehousing</OPTION> </SELECT><br> </td> </tr> <tr><td>Description:</td> <td><textarea rows=6 cols=35 name=description2><?=$a1[description]?></textarea></td> </tr> <tr> <td>Target: </td> <td> <select name="j_target2" style=width:303> <option value=""> </option> <OPTION VALUE="1">Student (High School)</OPTION> <OPTION VALUE="2">Student (undergraduate/graduate)</OPTION> <OPTION VALUE="3">Entry Level (less than 2 years of experience)</OPTION> <OPTION VALUE="4">Mid Career (2+ years of experience)</OPTION> <OPTION VALUE="5">Management (Manager/Director of Staff)</OPTION> <OPTION VALUE="6">Executive (SVP, EVP, VP)</OPTION> <OPTION VALUE="7">Senior Executive (President, CEO)</OPTION> </select> </td> </tr> <tr><td>Salary: </td> <td> <input size=10 type=text name=salary2 value=<?=$a1[salary]?>> <select name=s_period2> <option value=Yearly> Yearly </option> <option value=Monthly>Monthly </option> </select> </td></tr> <tr> <td align=right> </td><td> <input type=hidden name=job_id22 value=<?=$job_ed?>> <input type=submit name=submit value="Save changes"> </td> </tr> </table> </form> <? include_once('../foother.html'); ?><file_sep><? include "accesscontrol.php"; include_once "navigation2.htm"; $q1 = "delete from job_careerlevel where uname = \"$uname\" "; $r1 = mysql_query($q1) or die(mysql_error()); $q2 = "delete from job_education where uname = \"$uname\" "; $r2 = mysql_query($q2) or die(mysql_error()); $q3 = "delete from job_work_experience where uname = \"$uname\" "; $r3 = mysql_query($q3) or die(mysql_error()); $q4 = "delete from job_skills where uname = \"$uname\" "; $r4 = mysql_query($q4) or die(mysql_error()); $q5 = "update job_seeker_info set rTitle=\"\", rPar = \"\" where uname = \"$uname\" "; $r5 = mysql_query($q5) or die(mysql_error()); ?> <table width="446"><tr><td> <center> <br><br><br> The <?=$uname?>'s resume was deleted successfully. </center></td></tr></table> <? include_once('../foother.html'); ?><file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" xml:lang="en" lang="en"><head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title> ©GithubManager v1.0, All Rights Reserved.</title> <?php date_default_timezone_set('America/Chicago'); require_once 'vendor/autoload.php'; $client = new Github\Client(); $client->authenticate("raychorn", "peekab00", Github\Client::AUTH_HTTP_PASSWORD); ?> <?php $__uri__ = (isset($_SERVER['HTTPS']) ? 'https://' : 'http://').$_SERVER["SERVER_NAME"].(($_SERVER['SERVER_PORT'] != '80') ? ':'.$_SERVER['SERVER_PORT'] : '').$_SERVER["REQUEST_URI"]; ?> <link rel="icon" type="image/png" href="index_files/VyperLogixCorp-icon60x57.png"> <script src="index_files/ga.js" async="" type="text/javascript"></script><script type="text/javascript" src="index_files/dynamic.js"></script> <script type="text/javascript" src="index_files/jquery.js"></script> <script type="text/javascript" src="index_files/jquery-ui.js"></script> <script type="text/javascript" src="index_files/jquery_003.js"></script> <script type="text/javascript" src="index_files/jquery_002.js"></script> <script type="text/javascript" src="index_files/jquery_005.js"></script> <script type="text/javascript" src="index_files/additional-methods.js"></script> <script type="text/javascript" src="index_files/jquery_004.js"></script> <script type="text/javascript" src="index_files/00_constants.js"></script> <script type="text/javascript" src="index_files/01_objectExplainer.js"></script> <script type="text/javascript" src="index_files/02_AnchorPosition.js"></script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-9863220-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <script type="text/javascript"> var __default_options__ = {html:'',options:{minWidth:700,minHeight:500,width:700,height:500,modal:true}}; var ___options___ = { '/':__default_options__ }; var ___pageSelector___ = null; $(document).ready(function() { include_css('http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/start/jquery-ui.css'); function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } function sameOrigin(url) { // test that a given url is a same-origin URL // url could be relative or scheme relative or absolute var host = document.location.host; // host + port var protocol = document.location.protocol; var sr_origin = '//' + host; var origin = protocol + sr_origin; // Allow absolute or scheme relative URLs to same origin return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') || // or any other URL that isn't scheme relative or absolute i.e relative. !(/^(\/\/|http:|https:).*/.test(url)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) { // Send the token to same-origin, relative URLs only. // Send the token only if the method warrants CSRF protection // Using the CSRFToken value acquired earlier xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); try { include_css('static/main.css'); } catch (e) {} var href_tokens = window.location.href.split('/'); ___pageSelector___ = href_tokens[href_tokens.length-1]; ___pageSelector___ = (___pageSelector___.length == 0) ? '/' : ___pageSelector___; var __icons__ = [ '<a href="http://www.vyperlogix.com" target="_top"><img src="/static/images/VyperLogixCorp-icon(60x57).png" height="101" /></a>', '<a href="http://github.com" target="_top"><img src="/static/images/github_icon.png" height="101" /></a>' ]; var __iconNum__ = __icons__.length-1; var __iconElement__ = $("#logo"); function change_site_icon() { if (__iconElement__) { __iconElement__.html(__icons__[__iconNum__]); __iconNum__++; if (__iconNum__ > __icons__.length-1) { __iconNum__ = 0; } setTimeout(function(){change_site_icon();},5000); } } $("#logo").hide(); $("#popUpDialog").hide(); $("#popUpDialog").dialog({ autoOpen: false, minWidth:600, minHeight:200, width:600, height:500 }); $('#ajaxBusy').css({ display:"none", margin:"0px", paddingLeft:"0px", paddingRight:"0px", paddingTop:"0px", paddingBottom:"0px", position: "absolute", top: "40px", left: "0px", width:"auto" }); $(document).ajaxStart(function(){ var pos = $('#btn_logout').position(); $('#ajaxBusy').css({"left":(pos.left-70)+"px"}); $('#ajaxBusy').show(); }).ajaxStop(function(){ $('#ajaxBusy').hide(); }); }); function not_yet_implemented() { alert('Not Yet Implemented !!!\nCheck back again for more...'); } </script> </head> <body> <header> <div> <table id="navigation_content_holder" align="center" border="0" cellpadding="0" cellspacing="0" width="1000"> <tbody><tr> <td align="left" valign="top"> <div style="display: none;" id="logo"> <a href="http://www.vyperlogix.com/" target="_top"><img src="index_files/VyperLogixCorp-icon60x57.png" height="101"></a> </div> <!--start of navigation_holder--> <div style="padding-left:0px;"> <div id="navigation"> <span class="navigation"><a id="anchor_navbar_home" href="<?php echo($__uri__); ?>" target="_top">HOME</a> </span> </div> </div> </td> <td align="right" valign="top" width="*"> <div> </div> </td> </tr> <tr> <td bgcolor="white"> <div id="div_ERROR" style="color:#F00;"></div> <div style="display: none; margin: 0px; padding: 0px; position: absolute; top: 40px; left: 0px; width: auto;" id="ajaxBusy"><img src="index_files/ajax-loader.gif" border="0"></div> </td> </tr> </tbody></table> </div> <div style="clear: both"></div> </header> <div> <table id="container" align="center" border="0" cellpadding="0" cellspacing="0" width="1000"> <tbody><tr> <td id="main_content_holder" align="left" valign="top"> <table width="100%"> <tbody><tr> <td id="main_background" width="80%"> </td> <td align="right" valign="top" width="*"> <div id="main_sign_in_holder" style="display:none;"> </div> <div id="main_sign_in_holder2"> GithubManager™ is the fastest way to get your Zip File that contains a Project or blob of code into your Github Repo. </div> </td> </tr> </tbody></table> <div style="clear: both">&nbsp;</div> <div style="clear: both; padding-top:0px;">&nbsp;</div> <div id="shipment_container"> <div class="bubble"> <div class="rectangle"><div class="header_font">Want Code in YOUR Github Repo Now ?</div></div> <div class="triangle-l">&nbsp;</div> <div class="info"> <p> </p><div class="right_box"><img src="index_files/github-logo-social-coding.jpg" width="200"></div> <p></p> <br> <ul id="django_cloud_info" style="list-style-type:square"> <li><nobr>Instant Results !!!</nobr></li> <li><nobr>Instant Graficiation !!!</nobr></li> <li><nobr>Instant Repo !!!</nobr></li> <li><nobr>Just one mouse click away...</nobr></li> <li><nobr>Reduce your development cost !!!</nobr></li> <li><nobr>Reduce your time to market !!!</nobr></li> </ul> <br> </div> </div> </div> <div id="django_rightside_container"> <div class="bubble"> <div class="rectangle"><div class="header_font">Need Github Support?</div></div> <div class="triangle-l"></div> <div class="infoRight"> <table style="display:inline; padding-left: -20px;" width="100%"> <tbody><tr> <td align="left"> <ul id="django_programmer_info" style="list-style-type:square"> <li><nobr>Github Guru's for Hire !!!</nobr></li> <li>Let our Github Gurus do all the work for you !!!</li> <li>We push your code into your Repos !!!</li> </ul> </td> <td align="right"><img src="index_files/programmer206x240.jpg" width="190"></td> </tr> </tbody></table> </div> </div> </div> </td> </tr> </tbody></table> </div> <div style="clear: both;"></div> <table id="footer_content_holder" align="center" border="0" cellpadding="0" cellspacing="0" width="100%"> <tbody><tr> <td> <div class="footer_left_box"> <div class="footer_font">©&nbsp;2013 GitHubManager™&nbsp;<a href="http://www.vyperlogix.com/" target="_top">VyperLogix.Com</a>, All rights reserved.<br>All References to GitHub are Copyrighted/Trademarks by and of <a href="http://github.com/" target="_top">Github</a>.</div> </div> <div class="footer_right_box"> <div class="footer_font"> </div> </div></td> </tr> </tbody></table> <div aria-labelledby="ui-dialog-title-popUpDialog" role="dialog" tabindex="-1" class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-draggable ui-resizable" style="display: none; position: absolute; overflow: hidden; z-index: 1000; outline: 0px none;"><div style="-moz-user-select: none;" unselectable="on" class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix"><span style="-moz-user-select: none;" unselectable="on" id="ui-dialog-title-popUpDialog" class="ui-dialog-title">???</span><a style="-moz-user-select: none;" unselectable="on" role="button" class="ui-dialog-titlebar-close ui-corner-all" href="#"><span style="-moz-user-select: none;" unselectable="on" class="ui-icon ui-icon-closethick">close</span></a></div><div class="ui-dialog-content ui-widget-content" id="popUpDialog" style=""> <p id="popup_dialog_content"></p> </div><div style="-moz-user-select: none;" unselectable="on" class="ui-resizable-handle ui-resizable-n"></div><div style="-moz-user-select: none;" unselectable="on" class="ui-resizable-handle ui-resizable-e"></div><div style="-moz-user-select: none;" unselectable="on" class="ui-resizable-handle ui-resizable-s"></div><div style="-moz-user-select: none;" unselectable="on" class="ui-resizable-handle ui-resizable-w"></div><div unselectable="on" style="z-index: 1001; -moz-user-select: none;" class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se ui-icon-grip-diagonal-se"></div><div unselectable="on" style="z-index: 1002; -moz-user-select: none;" class="ui-resizable-handle ui-resizable-sw"></div><div unselectable="on" style="z-index: 1003; -moz-user-select: none;" class="ui-resizable-handle ui-resizable-ne"></div><div unselectable="on" style="z-index: 1004; -moz-user-select: none;" class="ui-resizable-handle ui-resizable-nw"></div></div></body></html><file_sep><?php $db = new MSSQLDB('FlashContent', 'SQL2005', 'sa', 'sisko@7660$boo'); ?> <file_sep><? include_once "accesscontrol.php"; if($submit == 'Delete') { $q = "delete from job_education where uname = \"$uname\" and En = \"$En\" "; $r = mysql_query($q) or die(mysql_error()); $q3 = "select * from job_education where uname = \"$uname\" order by En asc "; $r3 = mysql_query($q3) or die(mysql_error()); $q4 = "delete from job_education where uname = \"$uname\" "; $r4 = mysql_query($q4) or die(mysql_error()); while($a3 = mysql_fetch_array($r3)) { $vn = $vn + 1; $q5 = "insert into job_education set uname = \"$a3[uname]\", En = \"$vn\", E_i = \"$E_i\", E_Start = \"$a3[E_Start]\", E_End = \"$a3[E_End]\", E_gr = \"$a3[E_gr]\", E_d = \"$a3[E_d]\" "; $r5 = mysql_query($q5) or die(mysql_error()); } include_once "ER4.php"; } elseif($submit == 'Edit') { $qe1 = "select * from job_education where uname = \"$uname\" and En = \"$En\" "; $re2 = mysql_query($qe1) or die(mysql_error()); $ae2 = mysql_fetch_array($re2); ?> <SCRIPT LANGUAGE="JavaScript"> function checkFields() { missinginfo = ""; if (document.form.E_i.value == "") { missinginfo += "\n - Institution name"; } if (document.form.ESmonth.value == "") { missinginfo += "\n - Start date / Month"; } if (document.form.ESyear.value == "") { missinginfo += "\n - Start date / Year"; } if (document.form.EEmonth.value == "") { missinginfo += "\n - End date / Month"; } if (document.form.EEyear.value == "") { missinginfo += "\n - End date / Year"; } if (document.form.E_gr.value == "") { missinginfo += "\n - Education level"; } if (document.form.E_d.value == "") { missinginfo += "\n - Description"; } if (missinginfo != "") { missinginfo ="_____________________________\n" + "You failed to correctly fill in your:\n" + missinginfo + "\n_____________________________" + "\nPlease re-enter and submit again!"; alert(missinginfo); return false; } else return true; } </script> <form method=post action=EditEE2.php name=form onSubmit="return checkFields();" style="background:none;"> <table align=center width="446"> <tr> <td colspan=2 align=center> <b>Education #<?=$En?></b> </td> </tr> <tr> <td> <b>Institution name: </b> </td> <td> <input type=text name=E_i size=27 value="<? $ae2[E_i] = stripslashes($ae2[E_i]); echo $ae2[E_i]; ?>"> </td> </tr> <tr> <td> <b>Start date: </b> </td> <td> <select name=ESmonth> <option value=""> Month </option> <option value=January> January </option> <option value=February> February </option> <option value=March> March </option> <option value=April> April </option> <option value=May> May </option> <option value=June> June </option> <option value=July> July </option> <option value=August> August </option> <option value=September> September </option> <option value=October> October </option> <option value=November> November </option> <option value=December> December </option> </select> <select name=ESyear style=width:74> <option value=""> Year &nbsp;&nbsp;&nbsp;&nbsp;</option> <? for ($i = 2005; $i >= 1932; $i--) { echo " <option value=$i> $i </option>"; } ?> </select> </td> </tr> <tr> <td> <b> End date: </b> </td> <td> <select name=EEmonth> <option value=""> Month </option> <option value=Present class=Pres> Present </option> <option value=January> January </option> <option value=February> February </option> <option value=March> March </option> <option value=April> April </option> <option value=May> May </option> <option value=June> June </option> <option value=July> July </option> <option value=August> August </option> <option value=September> September </option> <option value=October> October </option> <option value=November> November </option> <option value=December> December </option> </select> <select name=EEyear style=width:75> <option value=""> Year </option> <option value=Present class=Pres>Present </option> <? for ($i = 2005; $i >= 1932; $i--) { echo " <option value=$i> $i </option>"; } ?> </select> </td> </tr> <tr> <td> <b>Education level: </b> </td> <td> <select name="E_gr" style=width:174> <option value=""> Select </option> <OPTION VALUE="Student (High School)">Student (High School)</OPTION> <OPTION VALUE="Collage">Collage</OPTION> <OPTION VALUE="Bachelor"> Bachelor </OPTION> <OPTION VALUE="Master"> Master </OPTION> <OPTION VALUE="Ph D">Ph D</OPTION> </select> </td> </tr> <tr> <td valign=top> <b>Description: </b><br><font size=1>(do not use HTML, please </font>) </td> <td> <textarea name=E_d rows=6 cols=32><?=$ae2[E_d]?> </textarea> </td> </tr> <tr> <td align=left>&nbsp; </td> <td align=left> <input type=submit name=submit value="Save this and go to Step 3 (Skills)"><br> <input type=submit name=submit2 value="Save this and add another one"> <input type=hidden name=En2 value=<?=$En?>> <input type=hidden name=En value=<?=$En?>> </table> </form> <? } ?> <? include_once('../foother.html'); ?><file_sep><? include_once "conn.php"; $day = date(d); $month = date(m); $year = date(Y); $del = "delete from job_post where EXday = \"$day\" and EXmonth = \"$month\" and EXyear = \"$year\" "; $rdel = mysql_query($del) or die(mysql_error()); ?><file_sep><?php require_once ('session.php'); require_once ('shared.php'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <meta http-equiv="Content-Language" content="UTF-8" /> <meta http-equiv="Content-Type" content="text/xhtml; charset=UTF-8" /> <link rel="stylesheet" href="style/master.css" type="text/css" /> <title>Workbench CSV Preview</title> </head> <body> <?php csv_array_show($_SESSION[csv_array]); include_once ('footer.php'); ?> <file_sep><? include_once "../conn.php"; $q1 = "select * from job_plan order by price"; $r1 = mysql_query($q1) or die(mysql_error()); if ($active_account=="pp") { ?> <table align=center width=446 bgcolor="#FFFFFF"> <tr> <td colspan=2> To access all the features we offer, choose your Employer Plan </td> </tr> <? while($a1 = mysql_fetch_array($r1)) { if($a1[price] > 0) { echo " <tr> <td> <b>$a1[PlanName]</b> <ul> <li>Valid for $a1[numdays] days; </li> <li>$a1[postings] job postings; </li> <li>$a1[reviews] resume reviews; </li> <li><b>price: <font color=#000000>$ $a1[price] </font</b></li> </ul> </td> <td> <form action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\" style=\"background:none;\"> <input type=\"hidden\" name=\"cmd\" value=\"_xclick\"> <input type=\"hidden\" name=\"business\" value=\"$paypal_email_address\"> <input type=\"hidden\" name=\"receiver_email\" value=\"$paypal_email_address\"> <input type=\"hidden\" name=\"item_name\" value=\"$a1[PlanName]\"> <input type=\"hidden\" name=\"item_number\" value=\"$ename\"> <input type=\"hidden\" name=\"amount\" value=\"$a1[price]\"> <input type=\"hidden\" name=\"no_note\" value=\"1\"> <input type=\"hidden\" name=\"currency_code\" value=\"USD\"> <input type=\"hidden\" name=\"return\" value=\"http://$_SERVER[HTTP_HOST]/employers/pay22.php?plan=$a1[PlanName]&price=$a1[price]&epayname=$ename&act=success\"> <input type=\"hidden\" name=\"notify_url\" value=\"http://$_SERVER[HTTP_HOST]/employers/pay222.php\"> <INPUT type=\"hidden\" name=\"on0\" value=\"ADV_ID\"> <INPUT type=\"hidden\" name=\"os0\" value=\"$a1[PlanName]\"> <input type=\"hidden\" name=\"cancel_return\" value=\"http://$_SERVER[HTTP_HOST]/employers/cancel.php\"> <input type=\"image\" src=\"http://$_SERVER[HTTP_HOST]/images/x-click-but01.gif\" border=\"0\" name=\"submit\" alt=\"Make payments with PayPal - it's fast, free and secure!\"> </form> </td> </tr>"; } else { echo " <tr> <td> <b>$a1[PlanName]</b> <ul> <li>Valid for $a1[numdays] days; </li> <li>$a1[postings] job postings; </li> <li>$a1[reviews] resume reviews; </li> <li><b>price: <font color=#000000>$ $a1[price] </font</b></li> </ul> </td> <td> <form action=pay2.php method=post style=\"background:none;\"> <input type=hidden name=ename value=\"$ename\"> <input type=hidden name=epass value=\"$epass\"> <input type=hidden name=plan value=\"$a1[PlanName]\"> <input type=hidden name=numdays value=\"$a1[numdays]\"> <input type=hidden name=price value=\"$a1[price]\"> <input type=submit value=\"Get if free\"> </form> </td>"; } } ?> </table> <? } if ($active_account=="tc") { ?> <table align=center width=446> <tr> <td colspan=2> To access all the features we offer, choose your Employer Plan: </td> </tr> <? while($a1 = mysql_fetch_array($r1)) { if($a1[price] > 0) { $crt_id=substr(md5($ename),0,12); $_SESSION["crt_id"]=$crt_id; echo " <tr> <td> <b>$a1[PlanName]</b> <ul> <li>Valid for $a1[numdays] days; </li> <li>$a1[postings] job postings; </li> <li>$a1[reviews] resume reviews; </li> <li><b>price: <font color=#000000>$$a1[price] </font</b></li> </ul> </td> <td> <form action=\"https://www2.2checkout.com/2co/buyer/purchase\" method=\"post\" style=\"background:none;\"> <input type=\"hidden\" name=\"cart_order_id\" value=\"$crt_id\" /> <input type=\"hidden\" name=\"PlanName\" value=\"$a1[PlanName]\" /> <input type=\"hidden\" value=\"$vendor_id\" name=\"sid\" /> <input type=\"hidden\" name=\"total\" value=\"$a1[price]\" /> <input type=\"hidden\" name=\"id_type\" value=\"1\" /> <input type=\"hidden\" name=\"c_prod\" value=\"$a1[PlanName],1\" /> <input type=\"hidden\" name=\"c_name\" value=\"$a1[PlanName]\" /> <input type=\"hidden\" name=\"c_description\" value=\"$a1[PlanName]\" /> <input type=\"hidden\" name=\"c_price\" value=\"$a1[price]\" /> <input type=\"hidden\" name=\"x_Receipt_Link_URL\" value=\"http://".$_SERVER[HTTP_HOST]."/employers/thanks.php\"> <input type=\"hidden\" name=\"return_url\" value=\"http://".$_SERVER[HTTP_HOST]."/employers/cancel.php\"> <input type=\"image\" border=0 src=\"http://$_SERVER[HTTP_HOST]/images/2checkout.gif\" name=\"submit\" alt=\"Make payments with 2Checkout - it's fast,free and secure!\"> </form> </td> </tr>"; } else { echo " <tr> <td> <b>$a1[PlanName]</b> <ul> <li>Valid for $a1[numdays] days; </li> <li>$a1[postings] job postings; </li> <li>$a1[reviews] resume reviews; </li> <li><b>price: <font color=#000000>$$a1[price] </font</b></li> </ul> </td> <td> <form action=pay2.php method=post style=\"background:none;\"> <input type=hidden name=ename value=\"$ename\"> <input type=hidden name=epass value=\"$epass\"> <input type=hidden name=plan value=\"$a1[PlanName]\"> <input type=hidden name=reviews value=\"$a1[reviews]\"> <input type=hidden name=postings value=\"$a1[postings]\"> <input type=hidden name=price value=\"$a1[price]\"> <input type=submit value=\"Get it free\"> </form> </td>"; } } ?> </table> <? } ?> <? if ($active_account=="pptc") { ?> <table align=center width=446 border="0"> <tr> <td colspan=2> To access all the features we offer, choose your Employer Plan: </td> </tr> <? while($a1 = mysql_fetch_array($r1)) { if($a1[price] > 0) { $crt_id=substr(md5($ename),0,12); $_SESSION["crt_id"]=$crt_id; echo " <tr> <td> <b>$a1[PlanName]</b> <ul> <li>Valid for $a1[numdays] days; </li> <li>$a1[postings] job postings; </li> <li>$a1[reviews] resume reviews; </li> <li><b>price: <font color=#000000>$$a1[price] </font</b></li> </ul> </td> <td> <form action=\"https://www2.2checkout.com/2co/buyer/purchase\" method=\"post\" style=\"background:none;\"> <input type=\"hidden\" name=\"cart_order_id\" value=\"$crt_id\" /> <input type=\"hidden\" name=\"PlanName\" value=\"$a1[PlanName]\" /> <input type=\"hidden\" value=\"$vendor_id\" name=\"sid\" /> <input type=\"hidden\" name=\"total\" value=\"$a1[price]\" /> <input type=\"hidden\" name=\"id_type\" value=\"1\" /> <input type=\"hidden\" name=\"c_prod\" value=\"$a1[PlanName],1\" /> <input type=\"hidden\" name=\"c_name\" value=\"$a1[PlanName]\" /> <input type=\"hidden\" name=\"c_description\" value=\"$a1[PlanName]\" /> <input type=\"hidden\" name=\"c_price\" value=\"$a1[price]\" /> <input type=\"hidden\" name=\"x_Receipt_Link_URL\" value=\"http://".$_SERVER[HTTP_HOST]."/employers/thanks.php\"> <input type=\"hidden\" name=\"return_url\" value=\"http://".$_SERVER[HTTP_HOST]."/employers/cancel.php\"> <input type=\"image\" border=0 src=\"http://$_SERVER[HTTP_HOST]/images/2checkout.gif\" name=\"submit\" alt=\"Make payments with 2Checkout - it's fast,free and secure!\"> </form> "; echo "<br> <form action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\" style=\"background:none;\"> <input type=\"hidden\" name=\"cmd\" value=\"_xclick\"> <input type=\"hidden\" name=\"business\" value=\"$paypal_email_address\"> <input type=\"hidden\" name=\"receiver_email\" value=\"$paypal_email_address\"> <input type=\"hidden\" name=\"item_name\" value=\"$a1[PlanName]\"> <input type=\"hidden\" name=\"item_number\" value=\"$ename\"> <input type=\"hidden\" name=\"amount\" value=\"$a1[price]\"> <input type=\"hidden\" name=\"no_note\" value=\"1\"> <input type=\"hidden\" name=\"currency_code\" value=\"USD\"> <input type=\"hidden\" name=\"return\" value=\"http://$_SERVER[HTTP_HOST]/employers/pay22.php?plan=$a1[PlanName]&price=$a1[price]&epayname=$ename&act=success\"> <input type=\"hidden\" name=\"notify_url\" value=\"http://$_SERVER[HTTP_HOST]/employers/pay222.php\"> <INPUT type=\"hidden\" name=\"on0\" value=\"ADV_ID\"> <INPUT type=\"hidden\" name=\"os0\" value=\"$a1[PlanName]\"> <input type=\"hidden\" name=\"cancel_return\" value=\"http://$_SERVER[HTTP_HOST]/employers/cancel.php\"> <input type=\"image\" src=\"http://$_SERVER[HTTP_HOST]/images/x-click-but01.gif\" border=\"0\" name=\"submit\" alt=\"Make payments with PayPal - it's fast, free and secure!\"> </form> </td> </tr>"; } else { echo " <tr> <td> <b>$a1[PlanName]</b> <ul> <li>Valid for $a1[numdays] days; </li> <li>$a1[postings] job postings; </li> <li>$a1[reviews] resume reviews; </li> <li><b>price: <font color=#000000>$$a1[price] </font</b></li> </ul> </td> <td> <form action=pay2.php method=post style=\"background:none;\"> <input type=hidden name=ename value=\"$ename\"> <input type=hidden name=epass value=\"$epass\"> <input type=hidden name=plan value=\"$a1[PlanName]\"> <input type=hidden name=reviews value=\"$a1[reviews]\"> <input type=hidden name=postings value=\"$a1[postings]\"> <input type=hidden name=price value=\"$a1[price]\"> <input type=submit value=\"Get it free\"> </form> </td>"; } } ?> </table> <? } ?> <? include_once('../foother.html'); ?><file_sep><?php require_once('session.php'); require_once('shared.php'); if($_SESSION){ require_once('header.php'); if($_SESSION['config']['invalidateSessionOnLogout']){ try{ $mySforceConnection->logout(); $sessionInvatidated = true; } catch(Exception $e){ $sessionInvatidated = false; } } else { $sessionInvatidated = false; } session_unset(); session_destroy(); if($sessionInvatidated == true){ show_info('You have been successfully logged out of the Workbench and Salesforce.'); } else { show_info('You have been successfully logged out of the Workbench.'); } include_once('footer.php'); } else { session_unset(); session_destroy(); header('Location: login.php'); } ?> <file_sep> <div id="notebook"> <div id="tabs"> <ul id="tabRow"> <!-- The jQuery generated tabs go here --> </ul> <!-- close tabRow --> <div id=icons_TabRow> <abbr title="<?php echo _('New Tab'); ?>" class="notebookIcons newTab"></abbr> <abbr title="<?php echo _('New List'); ?>" class="notebookIcons newList"></abbr> </div> </div> <!-- close tabs --> <div class="clear"></div> <div id="tabContent"> <div id="contentHolder"> <!-- The AJAX fetched content goes here --> </div> <!-- close contentHolder --> </div> <!-- close tabContent --> </div> <!-- close notebook --> <div id="pages"> <ul id="pageList"> <!-- The jQuery generated pages go here --> </ul> <!-- close pageList --> </div> <!-- close pages --> <!-- These divs are used as the base for the confirmation jQuery UI POPUP. Hidden by CSS. --> <div id="dialog-confirm-delete-list" class="dialog" title="<?php echo _('Delete Entire List?'); ?>"><?php echo _('All Items in this List will be deleted.'); ?></div> <div id="dialog-confirm-delete-page" class="dialog" title="<?php echo _('Delete Entire Page?'); ?>"><?php echo _('All Lists and Items on this Page will be deleted.'); ?></div> <div id="dialog-confirm-delete-tab" class="dialog" title="<?php echo _('Delete Entire Tab?'); ?>"><?php echo _('All Pages, Lists and Items on this Tab will be deleted.'); ?></div> <?php /* Look for a tab and page to be specified in the url and generate javascript needed to click the tab or page. If the tab or page is not specified generate javascript to click on the first tab or page in the list. */ if (isset($_GET['tab'])){ $tabID = $_GET['tab'] ?> <script type="text/javascript"> function clickTab(){ $(document).find("#Tab-<?php echo $tabID; ?>").find("a.tab").click(); } </script> <?php if (isset($_GET['page'])){ $pageID = $_GET['page'] /* The below script is only loaded if a specific page was listed in the url. In order for subsequent tab changes to properly load the page for that tab, a counter is started so that it only uses the page from the url for the first time. */ ?> <script type="text/javascript"> var pageCount = 0; function clickPage(){ pageCount++; if (pageCount >1) $(document).find('.page').eq(0).click(); else $(document).find("a#Page-<?php echo $pageID; ?>").click(); } </script> <?php } else { ?> <script type="text/javascript"> function clickPage(){ $(document).find('.page').eq(0).click(); } </script> <?php } } else { ?> <script type="text/javascript"> function clickTab(){ $(document).find('.tab').eq(0).click(); } function clickPage(){ $(document).find('.page').eq(0).click(); } </script> <?php } require "./content/menus.php"; /* Check for newer version ** Needs to be rewritten to account for installations behind a firewall $webVersion = file_get_contents('http://www.getsurreal.com/surrealtodo/version.php?version='.APP_VERSION); if ($webVersion !== false) { if ($webVersion == "2") { echo '<div id="newVersion"><a href="http://sourceforge.net/projects/surrealtodo">New version available.</a></div>'; } } */ ?> <script type="text/javascript" src="min/?f=lib/jquery/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="min/?f=lib/jquery/jquery-ui-1.8.5.min.js"></script> <script type="text/javascript" src="min/?f=lib/jquery/jquery.livequery.js"></script> <script type="text/javascript" src="min/?f=lib/jquery/plugin/jquery.jeegoocontext.min.js"></script> <script type="text/javascript" src="min/?f=lib/tabs-script.js"></script> <script type="text/javascript" src="min/?f=lib/script.js"></script> <script type="text/javascript" src="min/?f=lib/gettext.js"></script> <script type="text/javascript" src="min/?f=lib/context-menu.js"></script> <script type="text/javascript" src="lib/tiny_mce/tiny_mce.js"></script><file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; if(isset($submit)) { if(empty($who)) { echo "<table width=446><tr><td><center><br><br><br> Error.<br> Go <a class=TN href=mail.php> back </a> and make your choice. </center></td></tr></table>"; include ("../foother.html"); exit; } if(empty($message)) { echo "<table width=446><tr><td><center><br><br><br> You are trying to send blank email. <br> Go <a class=TN href=mail.php> back </a> and write some text. </center></td></tr></table>"; include ("../foother.html"); exit; } if($_POST[who] == 'jobseekers') { $q1 = "select job_seeker_email from job_seeker_info "; $r1 = mysql_query($q1) or die(mysql_error()); } elseif($_POST[who] == 'employers') { $q1 = "select CompanyEmail from job_employer_info "; $r1 = mysql_query($q1) or die(mysql_error()); } while($a1 = mysql_fetch_array($r1)) { $from = "From: $email_address"; mail($a1[0], $subject, $message, $from); } echo "<table width=446><tr><td><center><br><br><br>The mail was sent successfully. </center></td></tr></table>"; unset($who); include ("../foother.html"); exit; } ?> <br><br><br> <form action=<?=$PHP_SELF?> method=post style="background:none;"> <table align=center width=446> <tr> <td><b> Send email to all: </b></td> <td> <select name=who> <option value="">Select </option> <option value="jobseekers">Jobseekers </option> <option value="employers">Employers </option> </select> </td> </tr> <tr> <td><b>Subject: </b></td> <td><input type=text name=subject></td> </tr> <tr> <td valign=top><b> Message: </td> <td><textarea rows=6 cols=45 name=message></textarea></td> </tr> <tr> <td colspan=2 align=center> <input type=submit name=submit value=Send> </td> </tr> </table> </form> <? include_once('../foother.html'); ?><file_sep>function popUpDocumentForFlash4ProjectPlanDemo2() { var aURL = '/app/flash/IssueTrack-Project-Plan/IssueTrack-Project-PlanA.html?nocache=#RandRange(1, 65535, 'SHA1PRNG')#'; try {popUpWindowForURL(aURL, 'IssueTrackProjectPlan2'); } catch(e) { ezAlertError(ezErrorExplainer(e)); }; } <file_sep><? include_once "accesscontrol.php"; ?> <SCRIPT LANGUAGE="JavaScript"> function checkFields() { missinginfo = ""; if (document.form.WE_p.value == "") { missinginfo += "\n - Position"; } if (document.form.WSmonth.value == "") { missinginfo += "\n - Start date / Month"; } if (document.form.WSyear.value == "") { missinginfo += "\n - Start date / Year"; } if (document.form.WEmonth.value == "") { missinginfo += "\n - End date / Month"; } if (document.form.WEyear.value == "") { missinginfo += "\n - End date / Year"; } if (document.form.WE_d.value == "") { missinginfo += "\n - Description"; } if (missinginfo != "") { missinginfo ="_____________________________\n" + "You failed to correctly fill in your:\n" + missinginfo + "\n_____________________________" + "\nPlease re-enter and submit again!"; alert(missinginfo); return false; } else return true; } </script> <form method=post action=EWAdd2.php name=form onSubmit="return checkFields();" style="background:none;"> <table align=center width="446"> <tr> <td colspan=2 align=center> <b>Work experience #<?=$WEn?></b> </td> </tr> <tr> <td> <b>Position: </b> </td> <td> <input type=text name=WE_p size=27> </td> </tr> <tr> <td> <b>Start date: </b> </td> <td> <select name=WSmonth> <option value=""> Month </option> <option value=January> January </option> <option value=February> February </option> <option value=March> March </option> <option value=April> April </option> <option value=May> May </option> <option value=June> June </option> <option value=July> July </option> <option value=August> August </option> <option value=September> September </option> <option value=October> October </option> <option value=November> November </option> <option value=December> December </option> </select> <select name=WSyear> <option value=""> Year &nbsp;&nbsp;&nbsp;&nbsp;</option> <option value=2002> 2005 </option> <option value=2002> 2004 </option> <option value=2002> 2003 </option> <option value=2002> 2002 </option> <option value=2001> 2001 </option> <option value=2000> 2000 </option> <option value=1999> 1999 </option> <option value=1998> 1998 </option> <option value=1997> 1997 </option> <option value=1996> 1996 </option> <option value=1995> 1995 </option> <option value=1994> 1994 </option> <option value=1993> 1993 </option> <option value=1992> 1992 </option> <option value=1991> 1991 </option> <option value=1990> 1990 </option> <option value=1989> 1989 </option> <option value=1988> 1988 </option> <option value=1987> 1987 </option> <option value=1986> 1986 </option> <option value=1985> 1985 </option> <option value=1984> 1984 </option> <option value=1983> 1983 </option> <option value=1982> 1982 </option> <option value=1981> 1981 </option> <option value=1980> 1980 </option> <option value=1979> 1979 </option> <option value=1978> 1978 </option> <option value=1977> 1977 </option> <option value=1976> 1976 </option> <option value=1975> 1975 </option> <option value=1974> 1974 </option> <option value=1973> 1973 </option> <option value=1972> 1972 </option> <option value=1971> 1971 </option> <option value=1970> 1970 </option> <option value=1969> 1969 </option> <option value=1968> 1968 </option> <option value=1967> 1967 </option> <option value=1966> 1966 </option> <option value=1965> 1965 </option> <option value=1964> 1964 </option> <option value=1963> 1963 </option> <option value=1962> 1962 </option> <option value=1961> 1961 </option> <option value=1960> 1960 </option> <option value=1959> 1959 </option> <option value=1958> 1958 </option> <option value=1957> 1957 </option> <option value=1956> 1956 </option> <option value=1955> 1955 </option> <option value=1954> 1954 </option> <option value=1953> 1953 </option> <option value=1952> 1952 </option> <option value=1951> 1951 </option> <option value=1950> 1950 </option> <option value=1949> 1949 </option> <option value=1948> 1948 </option> <option value=1947> 1947 </option> <option value=1946> 1946 </option> <option value=1945> 1945 </option> <option value=1943> 1943 </option> <option value=1942> 1942 </option> <option value=1941> 1941 </option> <option value=1940> 1940 </option> <option value=1939> 1939 </option> <option value=1938> 1938 </option> <option value=1937> 1937 </option> <option value=1936> 1936 </option> <option value=1935> 1935 </option> <option value=1934> 1934 </option> <option value=1933> 1933 </option> <option value=1932> 1932 </option> </select> </td> </tr> <tr> <td> <b> End date: </b> </td> <td> <select name=WEmonth> <option value=""> Month </option> <option value=Present class=Pres> Present </option> <option value=January> January </option> <option value=February> February </option> <option value=March> March </option> <option value=April> April </option> <option value=May> May </option> <option value=June> June </option> <option value=July> July </option> <option value=August> August </option> <option value=September> September </option> <option value=October> October </option> <option value=November> November </option> <option value=December> December </option> </select> <select name=WEyear> <option value=""> Year </option> <option value=Present class=Pres>Present </option> <option value=2002> 2005 </option> <option value=2002> 2004 </option> <option value=2002> 2003 </option> <option value=2002> 2002 </option> <option value=2001> 2001 </option> <option value=2000> 2000 </option> <option value=1999> 1999 </option> <option value=1998> 1998 </option> <option value=1997> 1997 </option> <option value=1996> 1996 </option> <option value=1995> 1995 </option> <option value=1994> 1994 </option> <option value=1993> 1993 </option> <option value=1992> 1992 </option> <option value=1991> 1991 </option> <option value=1990> 1990 </option> <option value=1989> 1989 </option> <option value=1988> 1988 </option> <option value=1987> 1987 </option> <option value=1986> 1986 </option> <option value=1985> 1985 </option> <option value=1984> 1984 </option> <option value=1983> 1983 </option> <option value=1982> 1982 </option> <option value=1981> 1981 </option> <option value=1980> 1980 </option> <option value=1979> 1979 </option> <option value=1978> 1978 </option> <option value=1977> 1977 </option> <option value=1976> 1976 </option> <option value=1975> 1975 </option> <option value=1974> 1974 </option> <option value=1973> 1973 </option> <option value=1972> 1972 </option> <option value=1971> 1971 </option> <option value=1970> 1970 </option> <option value=1969> 1969 </option> <option value=1968> 1968 </option> <option value=1967> 1967 </option> <option value=1966> 1966 </option> <option value=1965> 1965 </option> <option value=1964> 1964 </option> <option value=1963> 1963 </option> <option value=1962> 1962 </option> <option value=1961> 1961 </option> <option value=1960> 1960 </option> <option value=1959> 1959 </option> <option value=1958> 1958 </option> <option value=1957> 1957 </option> <option value=1956> 1956 </option> <option value=1955> 1955 </option> <option value=1954> 1954 </option> <option value=1953> 1953 </option> <option value=1952> 1952 </option> <option value=1951> 1951 </option> <option value=1950> 1950 </option> <option value=1949> 1949 </option> <option value=1948> 1948 </option> <option value=1947> 1947 </option> <option value=1946> 1946 </option> <option value=1945> 1945 </option> <option value=1943> 1943 </option> <option value=1942> 1942 </option> <option value=1941> 1941 </option> <option value=1940> 1940 </option> <option value=1939> 1939 </option> <option value=1938> 1938 </option> <option value=1937> 1937 </option> <option value=1936> 1936 </option> <option value=1935> 1935 </option> <option value=1934> 1934 </option> <option value=1933> 1933 </option> <option value=1932> 1932 </option> </select> </td> </tr> <tr> <td valign=top> <b>Description: </b><br><font size=1>(do not use HTML, please) </font> </td> <td> <textarea name=WE_d rows=6 cols=32></textarea> </td> </tr> <tr> <td>&nbsp; </td> <td> <input type=submit name=submit value="Save and go to Step 2 (Education)"> <input type=hidden name=WEn value=<?=$WEn?>> <br> <br> <input type=submit name=submit2 value="Save changes and add another"> <input type=hidden name=WEn2 value=<?=$WEn?>> </td> </table> </form> <? include_once('../foother.html'); ?><file_sep><? php $__cache_files__ = array(); $__cache_dirs__ = array(); $classesDir = array ( 'lib' ); function scandir_through($dir,$ftype) { global $__cache_files__; global $__cache_dirs__; $files = array(); $directories = new RecursiveIteratorIterator( new ParentIterator(new RecursiveDirectoryIterator($dir)), RecursiveIteratorIterator::SELF_FIRST); $count_dirs = 0; $count_files = 0; foreach ($directories as $directory) { $dirname = $directory.'/*'.((strlen($ftype) > 0) ? '.'.$ftype : ''); if (!array_key_exists($directory.'', $__cache_dirs__)) { //echo('scandir_through.3 --> '.$directory.'<BR/>'); $__cache_dirs__[$directory.''] = $count_dirs; ++$count_dirs; foreach (glob($dirname) as $filename) { if (!array_key_exists($filename, $__cache_files__)) { //echo('scandir_through.4 --> '.$filename.'<BR/>'); $__cache_files__[$filename] = $count_files; ++$count_files; } } } } echo('scandir_through.5 --> count_dirs='.$count_dirs.'<BR/>'); echo('scandir_through.6 --> count_files='.$count_files.'<BR/>'); $files = array_keys($__cache_files__); sort($files); echo('1.1 --> '.var_dump($files).'<BR/>'); return $files; } function __autoload($args) { global $classesDir; foreach ($classesDir as $directory) { //echo('1 --> '.$directory.'<BR/>'); $files = scandir_through($directory,'php'); //echo('1.1 --> '.var_dump($files).'<BR/>'); foreach ($files as $filename) { $fname = $filename; echo('2 --> '.$fname.'<BR/>'); if ( (is_file($fname)) && (file_exists($fname)) ) { echo('3 --> '.$fname.'<BR/>'); require_once ($fname); } } } } //__autoload(1); ?> <file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; include_once "navigation.html"; $nb = "select count(link_id) from job_link_source"; $rnb = mysql_query($nb) or die; $anb = mysql_fetch_array($rnb); echo "<br><br>"; for ($bb = 1; $bb <= $anb[0]; $bb++) { $sb = "select * from job_link_source where link_id = \"$bb\" "; $rsb = mysql_query($sb) or die(mysql_error()); $ab = mysql_fetch_array($rsb); echo "<table align=center width=446 border=0 cellpadding=3 cellspacing=0 bordercolor=black>"; echo "<tr><td width= 100 class=TD_links>Link ID: $ab[link_id] <br><br> <a href=del_link.php?link_id=$ab[link_id]>delete </a></td><td align=center> $ab[link_code] </td></tr>"; echo "</table><br>"; } ?> <file_sep>/* (c).Copyright_VyperLogixCorp.js - copyright 2008, Vyper Logix Corp. */ <file_sep><? include_once "../main.php"; if(isset($fu)) { $q1 = "select epass, CompanyEmail from job_employer_info where ename = \"$_POST[ename]\""; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); if(empty($a1[0]) || empty($a1[1])) { echo "<table width=446><tr><td><br><br><br><center> There is no registered user with username: <b> $_POST[ename] </b></center></td></tr></table>"; } else { $to = $a1[CompanyEmail]; $subject = "Your username/password for $site_name"; $message = "Hello,\n here is your login information for http://$_SERVER[HTTP_HOST] \n\n Username: $_POST[ename] \n Password: <PASSWORD>]"; $from = "From: $email_address"; mail($to, $subject, $message, $from); echo "<table width=446><tr><td><br><br><br><center> Your login information was sent to $to </center></td></tr></table>"; } } elseif(isset($fm)) { $q2 = "select ename, epass from job_employer_info where CompanyEmail = \"$_POST[EEmail]\""; $r2 = mysql_query($q2) or die(mysql_error()); $a2 = mysql_fetch_array($r2); if(empty($a2[0]) || empty($a2[1])) { echo "<table width=446><tr><td><br><br><br><center> There is no registered user with email: <b> $_POST[EEmail] </b></center></td></tr></table>"; } else { $to = $_POST[EEmail]; $subject = "Your username/password for $site_name"; $message = "Hello,\n here is your login information for http://$_SERVER[HTTP_HOST] \n\n Username: $a2[ename] \n Password: <PASSWORD>]"; $from = "From: $email_address"; mail($to, $subject, $message, $from); echo "<table width=446><tr><td><br><br><br><center> Your login information was sent to $to </center></td></tr></table>"; } } else { ?> <br> <br> <form action="<?=$PHP_SELF?>" method="post" style="background:none;"> <table align=center width=446> <tr> <td>If you remember your username, but have forgot your password enter your username and in a few second will receive your password directly into the email you used at our site registration form.</td> </tr> <tr> <td>Username: <br> <input type=text name=ename> </td> </tr> <tr> <td><input type=submit name=fu value=Submit> </tr> </table> </form> <form action=<?=$PHP_SELF?> method=post style="background:none;"> <table align=center width=446> <tr> <td>If you have forgot all your login information (username & password) but still remember the email you used at our site registration form, just enter it into the box and in a few seconds you will receive your login information. </td> </tr> <tr> <td>Email: <br> <input type=text name=EEmail> </td> </tr> <tr> <td><input type=submit name=fm value=Submit> </tr> </table> </form> <? } ?> <? include_once('../foother.html'); ?><file_sep><? include_once('main.php'); ?> <table border="0" cellpadding="0" cellspacing="0" width="446" align="center" bgcolor="#FFFFFF"> <tr valign="top"> <td class="w" style="padding-left:10px;padding-top:10px;"> <p><font face="Tahoma, Arial, sans-serif" size="4"><b><i><font color="#000000">Search and Post Jobs Online!</font></i></b></font></p> <p><font size="2" face="Tahoma, Arial, sans-serif" color="#000000"> <u><strong>About us</strong></u><br> <br> </font><font face="Tahoma, Arial, sans-serif" size="2"><b>PHP Job Website</b> is an Extensive and Powerful script written in PHP to launch your own jobs portal with quality features (upload resume, resume search, pound sterling payments and much much more). It has a very high potential to generate very heavy online revenues for you. Script is built with a focus on increases ease of users and profits of webmasters. <br> <br> PHP Job Website is the most comprehensive and advanced job script package available online. Looking for the right job script to launch your professional Job Website? Look no further!PHP Job Website is an Extensive and Powerful script written in PHP to launch your own jobs portal with quality features (upload resume, resume search, pound sterling payments and much much more). It has a very high potential to generate very heavy online revenues for you. Script is built with a focus on increases ease of users and profits of webmasters. <br> <br> PHP Job Website is the most comprehensive and advanced job script package available online. Looking for the right job script to launch your professional Job Website? Look no further!</font></p> <p align="center"><strong><font size="2" face="Arial, Helvetica, sans-serif" color="#333399">Cost effective and targated</font></strong></p> </td> </tr> </table> <? include_once('foother.html'); ?><file_sep><?php class SforceApexClient { public $sforce; protected $sessionId; protected $location; protected $namespace = 'http://soap.sforce.com/2006/08/apex'; public function __construct($wsdl, $apexServerUrl, $LogCategory, $LogCategoryLevel) { $_SERVER['HTTP_USER_AGENT'] = 'Salesforce/PHPToolkit/1.0'; $soapClientArray = array(); $soapClientArray['trace'] = 1; $soapClientArray['encoding'] = 'utf-8'; //set compression settings if ($_SESSION['config']['enableGzip'] && phpversion() > '5.1.2') { $soapClientArray['compression'] = SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP | 1; } //set proxy settings if ($_SESSION['config']['proxyEnabled'] == true) { $proxySettings = array(); $proxySettings['proxy_host'] = $_SESSION['config']['proxyHost']; $proxySettings['proxy_port'] = (int)$_SESSION['config']['proxyPort']; // Use an integer, not a string $proxySettings['proxy_login'] = $_SESSION['config']['proxyUsername']; $proxySettings['proxy_password'] = $_SESSION['config']['proxyPassword']; $soapClientArray = array_merge($soapClientArray, $proxySettings); } $this->sforce = new SoapClient($wsdl,$soapClientArray); //start to set headers $header_array = array(); //set session header $sessionVar = array('sessionId' => new SoapVar($_SESSION['sessionId'], XSD_STRING)); $headerBody = new SoapVar($sessionVar, SOAP_ENC_OBJECT); $header_array[] = new SoapHeader($this->namespace, 'SessionHeader', $headerBody, false); //set debugging header $logInfoComp = array( 'category' => new SoapVar($LogCategory, XSD_STRING), 'level' => new SoapVar($LogCategoryLevel, XSD_STRING) ); $logInfoVar = array( 'categories' => new SoapVar($logInfoComp, SOAP_ENC_OBJECT) ); $debugBody = new SoapVar($logInfoVar, SOAP_ENC_OBJECT); $header_array[] = new SoapHeader($this->namespace, 'DebuggingHeader', $debugBody, false); //set call options header if(isset($_SESSION['config']['callOptions_client'])){ $clientBody = array('client' => new SoapVar($_SESSION['config']['callOptions_client'], XSD_STRING)); $callOptions_header = new SoapHeader($this->namespace, 'CallOptions', $clientBody, false); $header_array[] = $callOptions_header; } //set allowFieldTruncationHeader header if(isset($_SESSION['config']['allowFieldTruncationHeader_allowFieldTruncation'])){ $allowFieldTruncationBody = array('allowFieldTruncation' => new SoapVar($_SESSION['config']['allowFieldTruncationHeader_allowFieldTruncation'], XSD_BOOLEAN)); $allowFieldTruncationHeader = new SoapHeader($this->namespace, 'AllowFieldTruncationHeader', $allowFieldTruncationBody, false); $header_array[] = $allowFieldTruncationHeader; } $this->sforce->__setSoapHeaders($header_array); $this->sforce->__setLocation($apexServerUrl); return $this->sforce; } public function executeAnonymous($executeAnonymousBlock) { $executeAnonymousRequest = new stdClass; $executeAnonymousRequest->String = $executeAnonymousBlock; $executeAnonymousResult = $this->sforce->__soapCall("executeAnonymous",array($executeAnonymousRequest),null,null,$outputHeaders); $executeAnonymousResultWithDebugLog = new stdClass; $executeAnonymousResultWithDebugLog->executeAnonymousResult = $executeAnonymousResult->result; foreach($outputHeaders as $outputHeader){ $executeAnonymousResultWithDebugLog->debugLog .= $outputHeader->debugLog; } return $executeAnonymousResultWithDebugLog; } public function getLastRequest() { return $this->sforce->__getLastRequest(); } public function getLastRequestHeaders() { return $this->sforce->__getLastRequestHeaders(); } public function getLastResponse() { return $this->sforce->__getLastResponse(); } public function getLastResponseHeaders() { return $this->sforce->__getLastResponseHeaders(); } } ?> <file_sep>function clickTabsForPage(pg) { pg = ((pg == null) ? -1 : pg); var i = -1; var oDiv = -1; var oTab = -1; var oSpan = -1; for (i = 1; i <= 10; i++) { oDiv = document.getElementById('div_contentPage' + i); if (!!oDiv) { oTab = document.getElementById('tabSelected'); oSpan = document.getElementById('spanTabSelected'); if ( (!!oTab) && (!!oSpan) ) { oTab.id = oTab.name; oTab.name = null; oSpan.id = oSpan.name; oSpan.name = null; } oDiv.style.display = 'none'; } } oDiv = document.getElementById('div_contentPage' + pg); if (!!oDiv) { oTab = document.getElementById('tab_' + pg); oSpan = document.getElementById('span_tab_' + pg); if ( (!!oTab) && (!!oSpan) ) { oTab.name = oTab.id; oTab.id = 'tabSelected'; oSpan.name = oSpan.id; oSpan.id = 'spanTabSelected'; } oDiv.style.display = 'inline'; } } <file_sep><? include_once "accesscontrol2.php"; //jobseeker view his resume $q = "select * from job_seeker_info where uname = \"$uname\""; $r = mysql_query($q) or die(mysql_error()); $a = mysql_fetch_array($r); $q1 = "select * from job_work_experience where uname = \"$uname\" order by WEn desc "; $r2 = mysql_query($q1) or die(mysql_error()); $q3 = "select * from job_careerlevel where uname = \"$uname\" "; $r3 = mysql_query($q3) or die(mysql_error()); $a3 = mysql_fetch_array($r3); ?> <table width=446 align=center cellpadding=0 bgcolor="#FFFFFF"> <caption align=center><b><? echo "$a[rTitle] <br><p align=left><font size=2 style=\"font-weight:normal\"> $a[rPar] </font></p>"; ?> </b> </caption> <tr> <td valign=top> <div align="center"> <table width=100% cellspacing=0 bordercolor=black> <tr> <td> <b>Name:</b> </td> <td width=175 valign=top> <? echo "$a[fname] $a[lname]"; ?> </td> </tr> <tr> <td> <b>Age: </b> </td> <td valign=top> <? if((date(m) > $a[bmonth]) || (date(m) == $a[bmonth] && date(d) < $a[bday])) { echo date(Y) - $a[byear]; } else { echo date(Y) - $a[byear] - 1; } ?> </td> </tr> <tr> <td> <b>Phone:</b> </td> <td valign=top> <? echo "$a[phone] \n $a[phone2]"; ?> </td> </tr> <tr> <td> <b>E-mail: </b> </td> <td> <?=$a[job_seeker_email]?> </td> </tr> </table> </div> </td></tr><tr> <td valign=top><br> <div align="center"> <table width=100% cellpadding=0 cellspacing=0 bordercolor=black> <tr> <td colspan=2><b> Address: </b></td> </tr> <tr> <td colspan=2> <?=$a[address]?> </td> </tr> <tr> <td><b> Country: </b></td> <td> <?=$a[country]?> </td> </tr> <tr> <td><b>City/Zip <? if(!empty($a[state])) { echo "/State"; } ?> </b></td> <td> <?=$a[city]?>/<?=$a[zip]?> <? if(!empty($a[state])) { echo "/$a[state]"; } ?> </td> </td> </tr> </table></div> <br> <table align=center width=100% border = 0 bordercolor=black cellspacing=0> <tr> <td><strong>Career level</strong> </td> <td> <?=$a3[clname]?> </td> </tr> </table> </td> </tr> </table> </body> </html> <? echo "<br><br><br>"; while ($a1 = mysql_fetch_array($r2)) { echo " <form action=EditWorkExperience.php method=post style=\"background:none;\"> <table align=center width=446 bordercolor=black cellspacing=0 cellpadding=0> <caption> <font size=2> <strong>Work experience# $a1[WEn]</strong> </font> </caption> </form> <tr> <td colspan=4><b>&nbsp; Position: </b> $a1[WE_p] </td> </tr> <tr> <td><b>&nbsp; From date</b></td> <td><b>&nbsp; To date</b></td> </tr> <tr> <td>&nbsp;$a1[WE_Start]</td> <td>&nbsp;$a1[WE_End]</td> </tr> <tr> <td colspan=4> <table cellspacing=0 width=100%> <tr> <td valign=top> <b>&nbsp; Description: </b> </td> </tr> <tr> <td> $a1[WE_d] </td> </tr> </table> </td> </td> </tr> </table><br> "; } $q1 = "select * from job_education where uname = \"$uname\" order by En asc "; $r2 = mysql_query($q1) or die(mysql_error()); echo "<br><br><br>"; while ($a1 = mysql_fetch_array($r2)) { echo " <form action=EditEducation.php method=post style=\"background:none;\"> <table align=center width=446 bordercolor=black cellspacing=0 cellpadding=0> <caption> <font size=2> <strong>Education# $a1[En]</strong> </font> </caption> </form> <tr> <td colspan=4><b>&nbsp; Education Institution: </b>"; echo stripslashes($a1[E_i]); echo "</td> </tr> <tr> <td>&nbsp; Graduate Level </td> <td width=100><b>&nbsp; From date </b></td><td width=185 >&nbsp; $a1[E_Start] </td> </tr> <tr> <td > &nbsp; $a1[E_gr] </td> <td width=100><b>&nbsp; To date </b></td><td width=185 >&nbsp; $a1[E_End] </td> </tr> <tr> <td colspan=4> <table cellspacing=0 width=100%> <tr> <td valign=top> <b>&nbsp; Description: </b> </td> </tr> <tr> <td > $a1[E_d] </td> </tr> </table> </td> </td> </tr> </table><br> "; } $q4 = "select * from job_skills where uname = \"$uname\" "; $r4 = mysql_query($q4) or die(mysql_error()); while($a4 = mysql_fetch_array($r4)) { $aaa = stripslashes($a4[SK_d]); echo " <table align=center width=446 bordercolor=black cellspacing=0> <caption><b>My additional skills </b></caption> <tr> <td colspan=2> $aaa </td> </tr> </table> "; } ?> <? include_once('../foother.html'); ?><file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; $q1 = "select * from job_admin_login order by binary aid"; $r1 = mysql_query($q1) or die(mysql_error()); echo "<table align=center width=446 border=1 cellspacing=0 bordercolor=e0e7e9>"; echo "<tr style=\"background-color:e0e7e9; font-family:arial; color:maroon; font-weight:normal;font-size:11px;\"><td> Admin ID </td><td> Admin pass </td> <td>Name </td> <td>Email </td> <td align=center> Manage</td></tr>"; while($a1 = mysql_fetch_array($r1)) { echo " <tr> <td> $a1[aid] </td> <td> $a1[apass] </td> <td> $a1[name]</td> <td> $a1[email]</td> <td align=center> <a class=TN href=\"delete_admin.php?daid=$a1[aid]\">Delete </a></td> </tr>"; } echo "</table>"; ?> <br><center> To add a new admin at your level, <a class=TN href=add_admin.php> click here </a></center> <? include_once('../foother.html'); ?><file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; $q1 = "select * from job_story order by story_id"; $r1 = mysql_query($q1) or die(mysql_error()); if(mysql_num_rows($r1) > '0') { echo "<table align=center width=400><tr><td>"; while($a1 = mysql_fetch_array($r1)) { echo " <table align=center width=400 border=0 style=\"border:1px Solid #e0e7e9;\" cellspacing=0 bordercolor=black> <tr> <td>Story ID# $a1[story_id] </td> <td><a class=TN href=EditStory.php?story_id=$a1[story_id]>Edit </a> this story </td> <td><a class=TN href=DeleteStory.php?story_id=$a1[story_id]> Delete </a> this story </td> </tr> <tr> <td colspan=3>$a1[story] </td> </tr> </table> <br>"; } //echo "</td></tr></table><br><br>"; } else { echo "<br><br><br><center> There are not approved success stories, yet.</center><br><br>"; } $q2 = "select * from job_story_waiting order by WS_id"; $r2 = mysql_query($q2) or die(mysql_error()); if(mysql_num_rows($r2) > '0') { echo "<table align=center width=400><caption align=center><b> Stories, waiting for approval.</b></caption><tr><td>"; while($a2 = mysql_fetch_array($r2)) { echo " <table align=center width=400 border=0 style=\"border:1px Solid #e0e7e9;\" cellspacing=0 bordercolor=black> <tr> <td>Waiting Story ID# $a2[WS_id] </td> <td><a class=TN href=EditWStory.php?story_id=$a2[WS_id]>Edit </a> this story </td> <td><a class=TN href=DeleteWStory.php?story_id=$a2[WS_id]> Delete </a> this story </td> <td><a class=TN href=ApprovalWStory.php?story_id=$a2[WS_id]> Approve </a> this story </td> </tr> <tr> <td colspan=4>$a2[story] </td> </tr> </table> <br>"; } echo "</td></tr></table>"; } else { echo "<br><center> There are no success stories, waiting to be approved.</center>"; } echo "</td></tr></table><br>"; ?> <? include_once('../foother.html'); ?><file_sep><?php require_once("class_PayPalIPN.php"); class Advertiser { function addMoney($user_id,$plan) { // echo "I am calleddddddddddddddddddddddddddddddddddddddd"; $q = "select * from job_plan where PlanName = '$plan'"; $r = mysql_query($q) or die(mysql_error()); $a = mysql_fetch_array($r); $expireon = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+$a[numdays], date("Y"))); $expireond=date("d M Y",$expireon); $q1 = "update job_employer_info set plan = '$plan', expiryplan='$expireon', JS_number = '$a[reviews]', JP_number = '$a[postings]',JS_accessed=0,JP_accessed=0 where ename = '$user_id'"; // echo $q1; $r1 = mysql_query($q1) or die(mysql_error()); }/*---addMoney()-----*/ }/*------------class Advertiser-------------*/ $paypal_ipn = new PayPalIPN($_POST); $adv = new Advertiser(); $Email=$paypal_email_address; // echo $Email; $paypal_ipn->setPayPalReceiverEmail($Email); $paypal_ipn->postResponse2PayPal(); //Post back our response to PayPal $paypal_ipn->validateTransaction(); $user_id = $paypal_ipn->paypal_post_arr['item_number']; $plan = $paypal_ipn->paypal_post_arr['item_name']; if ($paypal_ipn->isTransactionOk()) { //ok. process payment $adv->addMoney($paypal_ipn->paypal_post_arr['item_number'],$paypal_ipn->paypal_post_arr['item_name']); $invalidtxn="false"; } else { echo "<center><strong>Invalid Transaction .. Please try again</strong></center> "; $invalidtxn="true"; } $paypal_ipn->logTransactions($user_id); //log valid & invalid transactions ?><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"> <?php include_once("..\includes\documentHeader.php"); // print_r(docHeader('../..')); ?> </head> <body bgcolor="#53a9ff"> <table width="100%"> <tr> <td valign="top"> <?php $cn = tomcatServerDomain("/my-apps/laszlo.ez-ajax.com/index-tabs.lzx?lzt=swf&debug=false&lzr=swf8&nocache=" . rand(1, 32767)); print_r(flashContent("OpenLaszloDemo", 770, 590, $cn, "#53a9ff")); ?> </td> </tr> </table> </body> </html> <file_sep><? include_once "accesscontrol.php"; $q1 = "select fname, job_seeker_email from job_seeker_info where uname = \"$uname\" "; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); $from = "From:$a1[0] <$a1[1]>"; $subject = "Job offer"; $message = strip_tags($fmessage); $to = strip_tags($femail); mail($to, $subject, $message, $from); echo "<table width=446><tr><td><br><br><br><center>The message was sent to $to </center></td></tr></table>"; ?> <? include_once('../foother.html'); ?><file_sep><?php require_once ('session.php'); require_once ('shared.php'); put('update'); ?> <file_sep><?php require_once ('session.php'); require_once ('shared.php'); put('insert'); ?> <file_sep><? include "accesscontrol.php"; include "navigation2.htm"; if(isset($submit)) { $from = "From: $email_address"; mail($email, $subject, $message, $from); echo "<table width=446><tr><td><br><br><br><center><font face=verdana size=2>The message to $email was send successfully.<br><br></td></tr></table>"; include("../foother.html"); exit; } ?> <html> <head> <title>Send email to <?=$email?> </title> </head> <body><font face=verdana size=2> <br><br><br><br> <form method=post style="background:none;"> <table align=center width=400> <tr> <td> <b> To: </b></td> <td> <?=$email?> </td> </tr> <tr> <td><b> Subject: </b></td> <td> <input type=text name=subject size=35></td> </tr> <tr> <td valign=top><b>Message: </b></td> <td><textarea name=message rows=6 cols=30></textarea></td> </tr> <tr> <td align=left> <input type=hidden name=email value=<?=$email?>> <input type=submit name=submit value=Send></td> <td align=right><input type=reset></td> </tr> </table> </form> </body> </html> <? include_once('../foother.html'); ?><file_sep><?php session_start(); require_once('shared.php'); if($_GET['serverUrl'] && $_GET['sid']){ //simulate adv login from url query params for web tab use $_POST['serverUrl'] = $_GET['serverUrl']; $_POST['sessionId'] = $_GET['sid']; $_POST[login_type] = "adv"; $_POST[actionJumpAdv] = "select.php"; } if ($_POST['login_type']=='std'){ process_login($_POST['usernameStd'], $_POST['passwordStd'], null, null, $_POST['actionJumpStd']); } elseif ($_POST['login_type']=='adv'){ process_login($_POST['usernameAdv'], $_POST['passwordAdv'], $_POST['serverUrl'], $_POST['sessionId'], $_POST['actionJumpAdv']); } else { checkLatestVersion(); display_login(null); } function display_login($errors){ require_once ('header.php'); //Displays errors if there are any if (isset($errors)) { show_error($errors); } if ($_COOKIE['user']){ $user = $_COOKIE['user']; $isRemembered = "checked='checked'"; print "<body onLoad='givePassFocus();' />"; } else { $user = $_POST['user']; $isRemembered = NULL; print "<body onLoad='giveUserFocus();' />"; } //Display main login form body print <<<LOGIN_FORM <script type='text/javascript' language='JavaScript'> function toggleUsernamePasswordSessionDisabled(){ if(document.getElementById('sessionId').value){ document.getElementById('usernameAdv').disabled = true; document.getElementById('passwordAdv').disabled = true; } else { document.getElementById('usernameAdv').disabled = false; document.getElementById('passwordAdv').disabled = false; } if(document.getElementById('usernameAdv').value || document.getElementById('passwordAdv').value){ document.getElementById('sessionId').disabled = true; } else { document.getElementById('sessionId').disabled = false; } } function form_become_adv() { document.getElementById('login_std').style.display='none'; //document.getElementById('apexLogo').style.display='none'; document.getElementById('login_adv').style.display='inline'; } function form_become_std() { document.getElementById('login_std').style.display='inline'; //document.getElementById('apexLogo').style.display='inline' document.getElementById('login_adv').style.display='none'; } function build_location(){ var inst = document.getElementById('inst').value; var endp = document.getElementById('endp').value; document.getElementById('serverUrl').value = 'https://' + inst + '.salesforce.com/services/Soap/u/' + endp; } function giveUserFocus(){ document.getElementById('username').focus(); } function givePassFocus(){ document.getElementById('password').focus(); } </script> <div id='intro_text'> <p>Use the standard login to login with your salesforce.com username and password or use the advanced login to login with a valid salesforce.com session ID or to a specific API version:</p> </div> <div id='logo_block'> <!--<img id='apexLogo' src='images/appex_x_rgb.png' width='200' height='171' border='0' alt='Apex X Logo' />--> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </div> <div id='login_block'> <form id='login_form' action='$_SERVER[PHP_SELF]' method='post'> <div id='login_become_select' style='text-align: right;'> <input type='radio' id='login_become_std' name='login_type' value='std' onClick='form_become_std();' checked='true' /><label for='login_become_std'>Standard</label> <input type='radio' id='login_become_adv' name='login_type' value='adv' onClick='form_become_adv();' /><label for='login_become_adv'>Advanced</label> </div> <div id='login_std'> <p><strong>Username: </strong><input type='text' name='usernameStd' id='username' size='45' value='$user' /></p> <p><strong>Password: </strong><input type='password' name='passwordStd' id='password' size='45' /></p> <p><strong>Jump to: </strong> <select name='actionJumpStd' style='width: 24em;'> <option value='select.php'></option> <option value='describe.php'>Describe</option> <option value='insert.php'>Insert</option> <option value='upsert.php'>Upsert</option> <option value='update.php'>Update</option> <option value='delete.php'>Delete</option> <option value='undelete.php'>Undelete</option> <option value='purge.php'>Purge</option> <option value='query.php'>Query</option> <option value='search.php'>Search</option> <option value='settings.php'>Settings</option> </select></p> <p style='text-align: right;'><label><input type='checkbox' name='rememberUser' $isRemembered />Remember username</label></p> </div> <div id='login_adv' style='display: none;'> <p><strong>Username: </strong><input type='text' name='usernameAdv' id='usernameAdv' size='65' value='$user' onkeyup='toggleUsernamePasswordSessionDisabled();' /></p> <p><strong>Password: </strong><input type='<PASSWORD>' name='passwordAdv' id='passwordAdv' size='65' onkeyup='toggleUsernamePasswordSessionDisabled();' /></p> <p>-OR-</p> <p><strong>Session ID: </strong><input type='text' name='sessionId' id='sessionId' size='65' onkeyup='toggleUsernamePasswordSessionDisabled();' /></p> <p>&nbsp;</p> <p><strong>Server URL: </strong><input type='text' name='serverUrl' id='serverUrl' size='65' value='https://www.salesforce.com/services/Soap/u/13.0' /></p> <p><strong>QuickSelect: </strong> <select name='inst' id='inst' onChange='build_location();'> <option value='www'>www</option> <option value='na0-api'>NA0 (SSL)</option> <option value='na1-api'>NA1</option> <option value='na2-api'>NA2</option> <option value='na3-api'>NA3</option> <option value='na4-api'>NA4</option> <option value='na5-api'>NA5</option> <option value='na6-api'>NA6</option> <option value='ap0'>AP</option> <option value='emea'>EMEA</option> <option value='test'>test</option> <option value='tapp0-api'>Sandbox CS0</option> <option value='cs1-api'>Sandbox CS1</option> <option value='cs2-api'>Sandbox CS2</option> <option value='prerelna1.pre'>Pre-Release</option> </select> <select name='endp' id='endp' onChange='build_location();'> <option value='13.0' selected='true'>13.0</option> <option value='12.0'>12.0</option> <option value='11.1'>11.1</option> <option value='11.0'>11.0</option> <option value='10.0'>10.0</option> <option value='9.0'>9.0</option> <option value='8.0'>8.0</option> <option value='7.0'>7.0</option> <option value='6.0'>6.0</option> </select></p> <p><strong>Jump to: </strong> <select name='actionJumpAdv' style='width: 14em;'> <option value='select.php'></option> <option value='describe.php'>Describe</option> <option value='insert.php'>Insert</option> <option value='upsert.php'>Upsert</option> <option value='update.php'>Update</option> <option value='delete.php'>Delete</option> <option value='undelete.php'>Undelete</option> <option value='purge.php'>Purge</option> <option value='query.php'>Query</option> <option value='search.php'>Search</option> <option value='settings.php'>Settings</option> </select></p> </div> <div id='login_submit' style='text-align: right;'> <input type='submit' name='loginClick' value='Login'> </div> </form> </div> LOGIN_FORM; include_once ('footer.php'); } //end display_form() //connects to Apex API and validates login function process_login_old($username, $password, $actionJump){ if($_POST['rememberUser'] !== 'on') setcookie(user,NULL,time()-3600); try{ require_once ('soapclient/SforcePartnerClient.php'); require_once ('soapclient/SforceHeaderOptions.php'); $username = htmlspecialchars(trim($username)); $password = htmlspecialchars(trim($password)); $wsdl = 'soapclient/sforce.130.partner.wsdl'; $mySforceConnection = new SforcePartnerClient(); $mySforceConnection->createConnection($wsdl); $mySforceConnection->login($username, $password); session_unset(); session_destroy(); session_start(); $_SESSION['location'] = $mySforceConnection->getLocation(); $_SESSION['sessionId'] = $mySforceConnection->getSessionId(); $_SESSION['wsdl'] = $wsdl; if($_POST['rememberUser'] == 'on'){ setcookie(user,$username,time()+60*60*24*7,'','','',TRUE); } else { setcookie(user,NULL,time()-3600); } session_write_close(); header("Location: $actionJump"); } catch (Exception $e) { $errors = null; $errors = $e->getMessage(); display_login($errors); exit; } } //end process_login function process_Login($username, $password, $serverUrl, $sessionId, $actionJump){ $username = htmlspecialchars(trim($username)); $password = htmlspecialchars(trim($password)); $serverUrl = htmlspecialchars(trim($serverUrl)); $sessionId = htmlspecialchars(trim($sessionId)); $actionJump = htmlspecialchars(trim($actionJump)); if($_POST['rememberUser'] !== 'on') setcookie(user,NULL,time()-3600); if ($username && $password && $sessionId){ $errors = null; $errors = 'Provide only username and password OR session id, but not all three.'; display_login($errors); exit; } try{ require_once ('soapclient/SforcePartnerClient.php'); require_once ('soapclient/SforceHeaderOptions.php'); $wsdl = 'soapclient/sforce.130.partner.wsdl'; $mySforceConnection = new SforcePartnerClient(); $mySforceConnection->createConnection($wsdl); if($_SESSION['config']['callOptions_client'] || $_SESSION['config']['callOptions_defaultNamespace']){ $header = new CallOptions($_SESSION['config']['callOptions_client'], $_SESSION['config']['callOptions_defaultNamespace']); $mySforceConnection->setCallOptions($header); } if($username && $password && !$sessionId){ if($serverUrl){ $mySforceConnection->setEndpoint($serverUrl); } else { $mySforceConnection->setEndpoint("https://www.salesforce.com/services/Soap/u/13.0"); } $mySforceConnection->login($username, $password); } elseif ($sessionId && $serverUrl && !($username && $password)){ if (stristr($serverUrl,'www') || stristr($serverUrl,'test') || stristr($serverUrl,'prerellogin')) { $errors = null; $errors = 'Must not connect to login server (www, test, or prerellogin) if providing a session id. Choose your specific Salesforce instance on the QuickSelect menu when using a session id; otherwise, provide a username and password and choose the appropriate a login server.'; display_login($errors); exit; } $mySforceConnection->setEndpoint($serverUrl); $mySforceConnection->setSessionHeader($sessionId); } session_unset(); session_destroy(); session_start(); $_SESSION['location'] = $mySforceConnection->getLocation(); $_SESSION['sessionId'] = $mySforceConnection->getSessionId(); $_SESSION['wsdl'] = $wsdl; if($_POST['rememberUser'] == 'on'){ setcookie(user,$username,time()+60*60*24*7,'','','',TRUE); } else { setcookie(user,NULL,time()-3600); } session_write_close(); header("Location: $actionJump"); } catch (Exception $e) { $errors = null; $errors = $e->getMessage(); display_login($errors); exit; } } function checkLatestVersion(){ global $version; try{ if(extension_loaded('curl')){ $ch = curl_init(); if(stristr($version,'beta')){ curl_setopt ($ch, CURLOPT_URL, 'http://forceworkbench.sourceforge.net/latestVersionAvailableBeta.txt'); } else { curl_setopt ($ch, CURLOPT_URL, 'http://forceworkbench.sourceforge.net/latestVersionAvailable.txt'); } curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $latestVersionAvailable = trim(curl_exec($ch)); curl_close($ch); if (preg_match('/^[0-9]+.[0-9]+/',$latestVersionAvailable) && !stristr($version,'alpha')){ if($latestVersionAvailable != $version){ print "<span style='font-size: 8pt; font-weight: bold;'><a href='http://code.google.com/p/forceworkbench/'>A newer version of the Workbench is available for download</a></span><br/>"; } } } } catch (Exception $e){ //do nothing } } ?> <file_sep><? include "conn.php"; if (isset($submit) && !empty($email)) { $message1 = "$message"." \n\n You can reply to the Employer, by clicking here: \n\n http://<?=$_SERVER[HTTP_HOST]?>/MessageJ.php?Employer=$Employer "; $from = "From: $email_address"; mail($email, $subject, $message1, $from); echo "<br><br><br><center><font face=verdana> Your message was send successfull.<br> The jobseeker can not view your email, but can reply to you<br> using our message system. </font><br><br> <a href=javascript:close()> close the window</a></center>"; } else { echo " <html> <head> <title>Send email</title> <style> a {font-size:11} body {font-family:verdana} input {border-color:black} textarea {border-color:black} </style> <form action=$PHP_SELF method=post style=\"background:none;\"> <table align=center width=470> <tr> <td colspan=2><b>Send email</b></td> </tr> <tr> <td width=200>To: </td> <td>"; if (!empty($email)) { echo "<input type=text name=email value=\"$email\" size=35>"; } else { $q1 = "select job_seeker_email from job_seeker_info where uname = \"$Jobseeker\" "; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); $email = $a1[0]; echo "<input type=text name=email value=\"$email\" size=35>"; } echo "</td> </tr> <tr> <td>Employer's username: </td> <td><input type=text name=Employer size=15></td> </tr> <tr> <td>Subject: </td> <td><input type=text name=subject size=35></td> </tr> <tr> <td valign=top>Message: </td> <td><textarea rows=4 cols=30 name=message></textarea></td> </tr> <tr> <td></td><td><input type=submit value=send name=submit style=\"background-color:white\"> <input type=reset value=cancel style=\"background-color:white\"></td> </tr> <tr><td colspan=2><font size=1><br> * The jobseeker can not view your contact information, but can reply to you using $site_name Message services.<br> <br>In this case, we will forward to your email address all the messages from the jobseeker.</td></tr> </table>"; } ?> <? include_once('foother.html'); ?><file_sep><? include_once('main.php'); ?> <table border="0" cellpadding="0" cellspacing="0" width="446" align="center"> <tr valign="top"> <td class="w" style="padding-left:10px;padding-top:10px;"> <p><em><strong><font face="Tahoma, Arial, sans-serif" size="4"><font color="#000000">Link to us</font></font></strong></em></p> <p align="left"><font size="2" face="Arial, Helvetica, sans-serif" color="#000000">You are welcome to link from another site to <?=$site_name?> content. Links may include text content or our button:<br><br> <strong>Text:</strong><br><br> <br><br> <strong>Buttons:</strong><br><br> <br><br> <br><br> <br><br> <br> </font> </td> </tr> </table> <? include_once('foother.html'); ?><file_sep><? session_start(); session_unset("ename"); session_unset("epass"); session_unregister("ename"); session_unregister("epass"); session_destroy(); setcookie("ename","", "0", "/", "", ""); setcookie("epass","", "0", "/", "", ""); ?> <html> <head> <META HTTP-EQUIV="REFRESH" CONTENT="0;URL=../index.php"> </head> </html><file_sep><? include "main.php"; if (isset($submit) && !empty($Jobseeker)) { $q1 = "select CompanyEmail from job_employer_info where ename = \"$Employer\""; $r1 = mysql_query($q1) or die(mysql_error()); $email = mysql_fetch_array($r1); $message1 = "$message"." \n\n You can reply to the Jobseeker, by clicking here:\n\n http://<?=$_SERVER[HTTP_HOST]?>/MessageE.php?Jobseeker=$Jobseeker "; $from = "From: $email_address"; mail($email, $subject, $message1, $from); echo "<br><br><br><center> Your message was send successfull.<br> The employer can reply to you using our message system.</center>"; } else { echo " <html> <head> <title>Send email</title> <style> a {font-size:11} body {font-family:verdana} input {border-color:black} textarea {border-color:black} </style> <form action=$PHP_SELF method=post style=\"background:none;\"> <table align=center> <tr> <td colspan=2><b>Send message</b></td> </tr> <tr> <td>Jobseeker's username: </td> <td><input type=text name=Jobseeker size=15></td> </tr> <tr> <td>Subject: </td> <td><input type=text name=subject size=35></td> </tr> <tr> <td valign=top>Message: </td> <td><textarea rows=4 cols=30 name=message></textarea></td> </tr> <tr> <td> <input type=hidden name=Employer value=\"$Employer\"> <input type=submit value=send name=submit style=\"background-color:white\"></td> <td align=right><input type=reset value=cancel style=\"background-color:white\"></td> </tr> </table>"; } ?> <? include_once('foother.html'); ?><file_sep><? include_once "../conn.php"; ?> <html> <head> <title> <?=$site_name?> </title> <style> caption {font-family:verdana; font-size:16; color:#000000; font-weight:bold} body {font-family:verdana; font-size:12} select {font-family:verdana; font-size:12} input {font-size:11; border-color:black} input.s2 {font-size:11; border-color:black; background-color:white; color:051dba; font-weight:bold} a.NavCol {font-family:verdana; font-size:11; color:white; text-decoration:none} a.NavCol:hover {text-decoration:underline} .Nav {text-align:center} a.ERR {font-family:verdana; font-size:15; color:black; text-decoration:none} a.ERR:hover {text-decoration:underline} a {font-family:verdana; font-size:11; font-weight:bold; color:000000; text-decoration:none} a:hover {text-decoration:underline} .BRes {font-family:verdana; font-size:10; font-weight:bold; color:white; text-decoration:none} a.BRes:hover {text-decoration:none; color:orange} .Pres {color:red} </style> <SCRIPT LANGUAGE="JavaScript"> function popUp(URL) { day = new Date(); id = day.getTime(); eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=yes,location=0,statusbar=0,menubar=0,resizable=yes,width=600,height=400,left = 100,top = 50');"); } </script> </head> <body> <table align=center bgcolor=#000000 width=500> <caption align=center> <?=$_SERVER[HTTP_HOST]?> </caption> <tr> <td class=Nav><a class=NavCol href=employer_registration.php> Registration </a></td> <td class=Nav><a class=NavCol href=PostJob.php> Post a job </a> </td> <td class=Nav><a class=NavCol href=DeleteJob.php> Manage jobs </a> </td> <td class=Nav><a class=NavCol href=EmployerSearch.php> Search </a></td> <td class=Nav><a class=NavCol href=logout.php> Logout </a></td> </tr> </table> <file_sep><? unset($step); $step = '1'; include_once "accesscontrol.php"; $WE_d = strip_tags($WE_d); if ($submit2 == 'Add Aonother') { $d1 = array(); $d1[0] = $WSmonth; $d1[1] = $WSyear; if (is_array($d1)) { $WE_Start = implode("/" , $d1); } $d2 = array(); $d2[0] = $WEmonth; $d2[1] = $WEyear; if (is_array($d2)) { $WE_End = implode("/" , $d2); } $qs1 = "insert into job_work_experience set uname = \"$uname\", WEn = \"$n\", WE_Start = \"$WE_Start\", WE_End = \"$WE_End\", WE_p = \"$WE_p\", WE_d = \"$WE_d\" "; $rs1 = mysql_query($qs1) or die(mysql_error()); include "1s.php"; } elseif ( $submit == 'Save and go to Step 2 (Education)') { $d1 = array(); $d1[0] = $WSmonth; $d1[1] = $WSyear; if (is_array($d1)) { $WE_Start = implode("/" , $d1); } $d2 = array(); $d2[0] = $WEmonth; $d2[1] = $WEyear; if (is_array($d2)) { $WE_End = implode("/" , $d2); } $qs1 = "insert into job_work_experience set uname = \"$uname\", WEn = \"$n\", WE_Start = \"$WE_Start\", WE_End = \"$WE_End\", WE_p = \"$WE_p\", WE_d = \"$WE_d\" "; echo $qs1; $rs1 = mysql_query($qs1) or die(mysql_error()); ?><script language="JavaScript">location.href='2.php';</script> <? } elseif(!empty($rTitle) && !empty($rPar)) { $q1 = "update job_seeker_info set rTitle = \"$rTitle\", rPar = \"$rPar\" where uname = \"$uname\" "; $r1 = mysql_query($q1) or die(mysql_error()); include "1s.php"; } ?> <file_sep><? include_once "../main.php"; if(isset($fu)) { $q1 = "select apass, email from job_admin_login where aid = \"$_POST[adname]\""; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); if(!empty($a1)) { $to = $a1[email]; $subject = "Your Admin info for $site_name"; $message = "Hello,\n here is your login information for $_SERVER[HTTP_HOST]\n\n Admin ID: \t $_POST[adname] \n Password: \t $a1[<PASSWORD>]"; $from = "From: $email_address"; mail($to, $subject, $message, $from); echo "<table align=center width=446><tr><td><br><br><br><center> Your login information was sent to $to </center></td></tr></table>"; } else { echo "<table align=center width=446><tr><td><br><br><br><center> There is no one registered admin with username $_POST[adname] </center></td></tr></table>"; } } elseif(isset($fm)) { $q2 = "select aid, apass from job_admin_login where email = \"$_POST[EEmail]\""; $r2 = mysql_query($q2) or die(mysql_error()); $a2 = mysql_fetch_array($r2); if(!empty($a2)) { $to = $_POST[EEmail]; $subject = "Your username/password for $site_name"; $message = "Hello,\n here is your login information for $_SERVER[HTTP_HOST] \n\n AdminID:\t $a2[aid] \n Password: \t $<PASSWORD>]"; $from = "From: $email_address"; mail($to, $subject, $message, $from); echo "<table align=center width=446><tr><td><br><br><br><center> Your login information was sent to $to </center></td></tr></table>"; } else { echo "<table align=center width=446><tr><td><br><br><br><center> There is no one registered admin with email $_POST[EEmail]</center></td></tr></table>"; } } else { ?> <form action=<?=$PHP_SELF?> method=post style="background:none;"> <table align=center width=446> <tr> <td>If you remember your username, but have forgot your password enter your username and in a few second will receive your password directly into the email you used for our site registration.</td> </tr> <tr> <td>Username: <br> <input type=text name=adname> </td> </tr> <tr> <td><input type=submit name=fu value=Submit> </tr> </table> </form> <form action=<?=$PHP_SELF?> method=post style="background:none;"> <table align=center width=446> <tr> <td>If you have forgot all your login information (username & password) but still remember the email you used for our site registration, just enter it into the box and in a few seconds you will receive your login informstion. </td> </tr> <tr> <td>Email: <br> <input type=text name=EEmail> </td> </tr> <tr> <td><input type=submit name=fm value=Submit> </tr> </table> </form> <? } ?> <? include_once('../foother.html'); ?><file_sep>[PCM] Language=ENU CountryCode=1 Model=Presario VGA_VENDORID=32902 VGA_DEVICEID=10146 Location=USA InstallPath=C:\Program Files\HP\QuickPlay <file_sep><?php $list = explode(',','1,2,3,0,4,0,0,-1,1,-2,2'); $results = array(); for ($item = 0; $item < count($list)-1; $item++) { $val = $list[$item] + $list[$item+1]; if ($val == 0) { $new_ar = array(); array_push($new_ar,$list[$item]); array_push($new_ar,$list[$item+1]); array_push($results,$new_ar); print 'PASSES: '.$list[$item].' and '.$list[$item+1].' == '.$val.'<br/>'; } else { print 'FAILS: '.$list[$item].' and '.$list[$item+1].' == '.$val.'<br/>'; } } ?><file_sep><?php require_once('class.phpgmailer.php'); require_once "documentHeader.php"; require_once 'JSON.php'; $crlf = "\r\n"; $resp = array(); $json = new Services_JSON(); $username = "<EMAIL>"; $password = "<PASSWORD>"; $time_start = microtime_float(); $_is_method_post = false; $resp['DEBUG.1'] = var_dump_ret($_SERVER); $REQUEST_METHOD = "GET"; if (isset($_SERVER['REQUEST_METHOD'])) { $REQUEST_METHOD = strtoupper($_SERVER['REQUEST_METHOD']); } $_is_method_post = strcmp($REQUEST_METHOD,"POST") == 0; $resp['DEBUG.2'] = var_dump_ret($_is_method_post); if ($_is_method_post) { $resp['DEBUG.3'] = var_dump_ret($_POST); try { $to = ''; if (isset($_POST["to"])) { $_to_ = $_POST["to"]; if (strlen($_to_) > 0) { $to = $_to_; } } } catch (Exception $e) { $resp['ERROR.1'] = 'Exception caught: '.$e->getMessage()."\n"; } try { $_subject_ = ''; if (isset($_POST["subject"])) { $_subject_ = $_POST["subject"]; if ( ($_subject_) && (strlen($_subject_) > 0) ) { $subject = $_subject_; } } } catch (Exception $e) { $resp['ERROR.2'] = 'Exception caught: '.$e->getMessage()."\n"; } try { $body = ''; if (isset($_POST["body"])) { $_body_ = $_POST["body"]; if ( ($_body_) && (strlen($_body_) > 0) ) { $body = $_body_; } } } catch (Exception $e) { $resp['ERROR.3'] = 'Exception caught: '.$e->getMessage()."\n"; } try { $altbody = ''; if (isset($_POST["altbody"])) { $_altbody_ = $_POST["altbody"]; if ( ($_altbody_) && (strlen($_altbody_) > 0) ) { $altbody = $_altbody_; } } } catch (Exception $e) { $resp['ERROR.4'] = 'Exception caught: '.$e->getMessage()."\n"; } } else { $from = $username; $to = "<EMAIL>"; $subject = "Hi!"; $body = "<p>Hi,<BR/><BR/>How <u>are</u> you?</p>"; $altbody = "Hi,\n\nHow are you?\n"; } $mail = new PHPGMailer(); $mail->Username = $username; $mail->Password = <PASSWORD>; $mail->From = $from; $mail->FromName = 'Vyper Logix Web Team'; $mail->Subject = $subject; $mail->AddAddress($to); if (strlen($altbody) > 0) { $resp['DEBUG.4'] = 'IsHTML(true)'; $mail->Body = stripslashes($altbody); $mail->IsHTML(true); } else { $resp['DEBUG.5'] = 'IsHTML(false)'; $mail->Body = stripslashes($body); $mail->AltBody = stripslashes($altbody); $mail->IsHTML(false); } $mail->Send(); $resp['STATUS'] = $mail->ErrorInfo; $time_end = microtime_float(); $resp['ELAPSED_TIME'] = $time_end - $time_start; echo($json->encode($resp)); ?><file_sep><HTML> <HEAD> <TITLE>simpleNavBar</TITLE> </HEAD> <BODY bgcolor="#FFFFFF"> <noscript>Please enable JavaScript and try again ! Thanks.&nbsp; <a href="http://flash.ex-ajax.com">Click HERE to continue...</a> </noscript> <script language="JavaScript1.2" type="text/javascript"> document.writeln(parent.getFlashContent('simpleNavBar', '/app/flash/simpleNavBar/simpleNavBar.swf', 150, 800, '#ffffff', 'high')); </script> </OBJECT> </BODY> </HTML> <file_sep><? include_once "accesscontrol.php"; $day = date(d); $month = date(m); $year = date(Y); $del = "delete from job_post where EXday = \"$day\" and EXmonth = \"$month\" and EXyear = \"$year\" "; $rdel = mysql_query($del) or die(mysql_error()); if(!empty($job_del)) { $q1 = "delete from job_post where job_id = \"$job_del\" and ename = \"$ename\" "; $r1 = mysql_query($q1) or die(mysql_error()); echo "<table width=446><tr><td><br><br><br><center> The job was deleted successfull.</center></td></tr></table>"; } else { $qm = "select * from job_post where ename = \"$ename\" order by job_id"; $rqm = mysql_query($qm) or die(mysql_error()); echo "<br><br><table align=center border=0 cellspacing=5 width=446>\n<tr><td colspan=3>Your current job offers:</td>"; while($aqm = mysql_fetch_array($rqm)) { $day = date(d); $month = date(m); $year = date(Y); $EXdate = "$aqm[EXyear]"."-"."$aqm[EXmonth]"."-"."$aqm[EXday]"; $dnes = "$year"."-"."$month"."-"."$day"; $qd = "select to_days('$EXdate') - to_days('$dnes')"; $rqd = mysql_query($qd) or die(mysql_error()); $adate = mysql_fetch_array($rqd); $qempl = "select CompanyName, CompanyCountry, CompanyCity from job_employer_info where ename = \"$ename\" "; $rempl = mysql_query($qempl) or die(mysql_error()); $ae = mysql_fetch_array($rempl); if($aqm[j_target] == '1') { $clname = 'Student (High School)'; } elseif($aqm[j_target] == '2') { $clname = 'Student (undergraduate/graduate)'; } elseif($aqm[j_target] == '3') { $clname = 'Entry Level (less than 2 years of experience)'; } elseif($aqm[j_target] == '4') { $clname = 'Mid Career (2+ years of experience)'; } elseif($aqm[j_target] == '5') { $clname = 'Management (Manager/Director of Staff)'; } elseif($aqm[j_target] == '6') { $clname = 'Executive (SVP, EVP, VP)'; } elseif($aqm[j_target] == '7') { $clname = 'Senior Executive (President, CEO)'; } echo "<tr> <td> <b>Job ID: </b> $aqm[job_id] <br> <b>Position:</b> $aqm[position] <br> <b>Deascription: </b> $aqm[description] <br> <b>Salary: </b> $aqm[salary] / $aqm[s_period]<br> <b>Job category: </b> $aqm[JobCategory] <br> <b>Target: </b> $clname <br> <b>The job expire after: </b> $adate[0] day(s)<br> <b>Country & City </b> $ae[CompanyCountry] - $ae[CompanyCity]<br> view <a href=\"ManageAplicants.php?job_id=$aqm[job_id]&job_id=$aqm[job_id]&position=$aqm[position]\" class=TN> aplicants list </a> for this position </font></td></tr> <tr><td align=center><a href=\"DeleteJob.php?job_del=$aqm[job_id]\">Delete</a>&nbsp;&nbsp;<a href=\"EditJob.php?job_ed=$aqm[job_id]\">Edit</a></td> </tr>"; } } ?> </table> <? include_once('../foother.html'); ?><file_sep><? include_once "accesscontrol.php"; $q1 = "select plan, JS_number, JP_number from job_employer_info where ename = \"$ename\" "; $r1 = mysql_query($q1) or die(mysql_error()); $a1 = mysql_fetch_array($r1); if(!empty($a1[plan])) { $a11 = $a1[JP_number]; if(isset($submit) && $submit == 'Post this job') { $q2 = "select * from job_employer_info where ename = \"$ename\" "; $r2 = mysql_query($q2) or die(mysql_error()); $a2 = mysql_fetch_array($r2); if (is_array($JobCategory)) { $JobStr = implode("," , $JobCategory); } $qc = "select job_id from job_post order by job_id desc"; $rc = mysql_query($qc) or die(mysql_error()); $ac = mysql_fetch_array($rc); $job_id = $ac[0] + 1; $position = strip_tags($position); $description = strip_tags($description); $EXday = date('d', mktime(0,0,0,0, date(d) + $_POST[exdays1], 0)); $EXmonth = date('m', mktime(0,0,0, date(m), date(d) + $_POST[exdays1], 0)); $EXyear = date('Y', mktime(0,0,0,date(m) ,date(d) + $_POST[exdays1], date(Y))); $q3 = "insert into job_post set job_id = \"$job_id\", ename = \"$ename\", CompanyCountry = \"$a2[CompanyCountry]\", CompanyState = \"$a2[CompanyState]\", Company = \"$a2[CompanyName]\", position = \"$position\", JobCategory = \"$JobStr\", description = \"$description\", j_target = \"$j_target\", salary = \"$salary\", s_period = \"$s_period\", EXmonth = \"$EXmonth\", EXday = \"$EXday\", EXyear = \"$EXyear\" "; $r3 = mysql_query($q3) or die(mysql_error()); $a11 = $a11 - 1; $q4 = "update job_employer_info set JP_number = \"$a11\" where ename = \"$ename\" "; $r4 = mysql_query($q4) or die(mysql_error()); $to = $a2[CompanyEmail]; $subject = "Your Job post at $site_name"; $message = "This is an automate sent copy of your Job post.\n\n Details:\n Job ID# $job_id \n Position: $position \n Category: $JobStr \n Description: $description \n Target: $clname \n Salary: $salary/$s_period \n Expire date: $EXmonth/$EXday/$EXyear\n\n\n To edit or delete this job, click here: http://$_SERVER[HTTP_HOST]/employers/DeleteJob.php "; $from = "From: $email_address"; mail($to, $subject, $message, $from); echo "<br><br><center> The job offer was posted successfully. <br><br><br> </center>"; } if ($a11 < 1) { echo "<center><br><br><br>You can not post jobs. <br>To do this, you must buy one of our Employer's Plans:</center>"; include_once "pay10.php"; } else { echo ""; ?> <SCRIPT LANGUAGE="JavaScript"> function checkFields() { missinginfo = ""; if (document.form.position.value == "") { missinginfo += "\n - Position"; } if (document.form.description.value == "") { missinginfo += "\n - Description"; } if (document.form.salary.value == "") { missinginfo += "\n - Salary"; } if (document.form.exdays1.value == "") { missinginfo += "\n - Expire date/Day"; } if (missinginfo != "") { missinginfo ="_____________________________\n" + "You failed to correctly fill in your:\n" + missinginfo + "\n_____________________________" + "\nPlease re-enter and submit again!"; alert(missinginfo); return false; } else return true; } </script> <form action="<?=$PHP_SELF?>" method=post name=form onSubmit="return checkFields();" style="background:none;"> <table width=446> <tr> <td colspan=2> <b>You are using <?=$a1[plan]?>. <br>Your account status is positive - you can:</b> <ul> <li>post <?=$a11?> jobs; </li> <li>review <?=$a1[JS_number]?> resumes; </li> </ul> </td> <tr> <tr><td colspan=2 align=center> To post a job, use the form below:</td></tr> <tr><td>Position:</td> <td> <input type=text name=position> </td> </tr> <tr> <td valign=top> Job Category: <br> </td> <td valign=top> <SELECT NAME="JobCategory[]" multiple size=5> <option value="Accounting/Auditing">Accounting/Auditing</option> <option value="Administrative and Support Services">Administrative and Support Services</option> <option value="Advertising/Public Relations">Advertising/Public Relations</option> <option value="Computers, Hardware">Computers, Hardware</option> <option value="Computers, Software">Computers, Software</option> <option value="Consulting Services">Consulting Services</option> <option value="Customer Service and Call Center">Customer Service and Call Center</option> <option value="Director">Director</option> <option value="Executive Management">Executive Management</option> <option value="Finance/Economics">Finance/Economics</option> <option value="Human Resources">Human Resources</option> <option value="Information Technology">Information Technology</option> <option value="Installation, Maintenance and Repair">Installation, Maintenance and Repair</option> <option value="Internet/E-Commerce">Internet/E-Commerce</option> <option value="Legal">Legal</option> <option value="Marketing">Marketing</option> <option value="Sales">Sales</option> <option value="Supervisor">Supervisor</option> <option value="Telecommunications">Telecommunications</option> <option value="Transportation and Warehousing">Transportation and Warehousing</option> <option value="Other">Other</option> </SELECT><br> </td> <tr><td valign=top>Description:</td> <td><textarea rows=6 cols=35 name=description></textarea></td> </tr> <tr> <td>Target: </td> <td> <select name="j_target"> <option value="1">Student (School Leaver)</option> <option value="2">Student (undergraduate/graduate)</option> <option value="3">Entry Level (less than 2 years of experience)</option> <option value="4">Mid Career (2+ years of experience)</option> <option value="5">Management (Manager/Director of Staff)</option> <option value="6">Executive </option> <option value="7">Senior Executive (President, CEO)</option> </select> </td> </tr> <tr><td>Salary: </td> <td> <input type=text name=salary size=11> <select name=s_period> <option value="Yearly">Yearly </option> <option value="Monthly">Monthly </option> </select> </td></tr> <tr> <td> This offer expire after: </td> <td> <select name=exdays1> <option value="7">7</option> <option value="14">14</option> <option value="21">21</option> <option value="28">28</option> </select> days. </td> </tr> <tr> <td align=left>&nbsp; </td> <td align=left> <input type=submit name=submit value="Post this job"> <input type=submit name=reset2 value="Reset"> </td> </tr> </table> </form> <? } } else { include "pay10.php"; } ?> <? include_once('../foother.html'); ?><file_sep><? include "accesscontrol.php"; include_once "navigation2.htm"; $ename=$_GET[ename]; $q = "select * from job_post where ename = '$ename' order by job_id"; $r = mysql_query($q) or die(mysql_error()); echo "<br>"; $aa = mysql_num_rows($r); if($aa > '0') { while($a = mysql_fetch_array($r)) { ?> <br> <table align=center width=446> <tr> <td colspan=2 align=center> <b> Details about Job ID# <?=$a[job_id]?> </b> <br> <a class=TN href=AEO.php?job_id=<?=$a[job_id]?>> edit </a> / <a class=TN href=ADO.php?job_id=<?=$a[job_id]?>> delete </a></td> </tr> <tr> <td><b> Position: </b></td> <td> <?=$a[position]?> </td> </tr> <tr> <td><b>Employer: </b></td> <td> <?=$a[Company]?> </td> </tr> <tr> <td width=100><b> Job category: </b></td> <td> <?=$a[JobCategory]?> </td> </tr> <tr> <td><b> Target: </b></td> <td> <? if($a[j_target] == '1') { echo 'Student (High School)'; } elseif($a[j_target] == '2') { echo 'Student (undergraduate/graduate)'; } elseif($a[j_target] == '3') { echo 'Entry Level (less than 2 years of experience)'; } elseif($a[j_target] == '4') { echo 'Mid Career (2+ years of experience)'; } elseif($a[j_target] == '5') { echo 'Management (Manager/Director of Staff)'; } elseif($a[j_target] == '6') { echo 'Executive (SVP, EVP, VP)'; } elseif($a[j_target] == '7') { echo 'Senior Executive (President, CEO)'; } ?> </td> </tr> <tr> <td><b> Salary: </b> </td> <td> <?=$a[salary]?> / <?=$a[s_period]?> </td> </tr> <tr> <td valign=top><b> Description: </b></td> <td> <?=$a[description]?> </td> </tr> <tr><td colspan=2></td></tr> </table> <? } } else { echo "<br><br><br><center>There are no one job offer from this employer. </center>"; } ?> <? include_once('../foother.html'); ?><file_sep><?php session_start(); require_once "../conn.php"; include_once "../main.php"; if(!isset($uname) && !isset($upass)) { ?> <body bgcolor="#FFFFFF"> <h1><font face=arial color=#000000>JobSeekers Login </h1> <p>You must log in to access this area of the site.<br> If you are not a registered user, <a href="jobseeker_registration.php" style="text-decoration:none; color:#000000"><b>click here</b></a> to sign up.</p> <p><form name=jsl method="post" action="<?=$PHP_SELF?>" style="background:none;"> <table width="446" cellpadding="5" cellspacing="0" border="0" align="center" bgcolor="#FFFFFF"> <tr> <td width="103">Username:</td> <td width="323" align=left> <input type="text" name="uname" size="8" style="border-color:black"></td> </tr> <tr> <td width="103">Password:</td> <td align=left><input type="password" name="upass" SIZE="8" style="border-color:black"></td> </tr> <tr align="center"> <td width="103">&nbsp;</td> <td align="left"> <input type=hidden name=job_id value="<?=$job_id?>"> <input type="submit" value=" Login " style="border-width:1; border-color:black; font-family:verdana; font-weight:normal; color:#000000; background-color: #e0e7e9"></td> </tr> <tr><td colspan=2 align=center> <a class=TN href=forgot.php> Forgot your username/password? </a></td></tr> </table> </form></p> </center> <?php include ("../foother.html"); exit; } session_register("uname"); session_register("upass"); $sql = "SELECT * FROM job_seeker_info WHERE uname = '$uname' AND upass = '$upass'"; $result = mysql_query($sql); if (!$result) { error("A database error occurred while checking your ". "login details.\\nIf this error persists, please ". "contact $email_address"); } elseif (mysql_num_rows($result) == 0) { session_unregister("uname"); session_unregister("upass"); ?> <table width="446"><tr><td> <font face=verdana> <h1> Access Denied </h1> <p>Your user ID or password is incorrect, or you are not a registered user on this site.<br><br> To try logging in again, click <a href="<?=$PHP_SELF?>">here</a>. <br><br>To register for instant access, click <a href="jobseeker_registration.php">here</a>.</p> </td></tr></td></table> <?php include ("../foother.html"); exit; } ?><file_sep><? include_once "accesscontrol.php"; include_once "navigation2.htm"; include_once "navigation.html"; ?> <html> <head> <title>Admin area > Banners Management</title> </head> <body> <br><br><br> <table align=center width=400 valign=middle> <tr> <td class=TD_links> Make your choice: <ul> <li> <a href=upload_banners.php> upload a banner </a></li> <li> <a href=linkexchange.php> paste a code for some linkexchange program </a></li> </ul> </td> </tr> </table> </body> </html> <? include_once('../foother.html'); ?><file_sep><? include_once "../main.php"; ?> <br><br> <form action=JobSearch3.php method=post style="background:none;"> <table align = center width="446" bgcolor="#FFFFFF"> <tr> <td colspan=2 align=center><b> Search for a job </b></td> </tr> <tr> <td><b>Position: </b></td> <td><input type=text name=position></td> </tr> <tr> <td><b>Country: </b></td> <td> <select name=country style="width:290"> <option value="UK">UK</option> <option value="Afghanistan">Afghanistan</option> <option value="Albania">Albania</option> <option value="Algeria">Algeria</option> <option value="American Samoa">American Samoa</option> <option value="Andorra">Andorra</option> <option value="Angola">Angola</option> <option value="Anguilla">Anguilla</option> <option value="Antartica">Antartica</option> <option value="Antigua and Barbuda">Antigua and Barbuda</option> <option value="Argentina">Argentina</option> <option value="Armenia">Armenia</option> <option value="Aruba">Aruba</option> <option value="Australia">Australia</option> <option value="Austria">Austria</option> <option value="Azerbaidjan">Azerbaidjan</option> <option value="Bahamas">Bahamas</option> <option value="Bahrain">Bahrain</option> <option value="Bangladesh">Bangladesh</option> <option value="Barbados">Barbados</option> <option value="Belarus">Belarus</option> <option value="Belgium">Belgium</option> <option value="Belize">Belize</option> <option value="Benin">Benin</option> <option value="Bermuda">Bermuda</option> <option value="Bhutan">Bhutan</option> <option value="Bolivia">Bolivia</option> <option value="Bosnia-Herzegovina">Bosnia-Herzegovina</option> <option value="Botswana">Botswana</option> <option value="Bouvet Island">Bouvet Island</option> <option value="Brazil">Brazil</option> <option value="British Indian Ocean Territory">British Indian Ocean Territory</option> <option value="Brunei Darussalam">Brunei Darussalam</option> <option value="Bulgaria">Bulgaria</option> <option value="Burkina Faso">Burkina Faso</option> <option value="Burundi">Burundi</option> <option value="Cambodia">Cambodia</option> <option value="Cameroon">Cameroon</option> <option value="Canada">Canada</option> <option value="Cape Verde">Cape Verde</option> <option value="Cayman Islands">Cayman Islands</option> <option value="Central African Republic">Central African Republic</option> <option value="Chad">Chad</option> <option value="Chile">Chile</option> <option value="China">China</option> <option value="Christmas Island">Christmas Island</option> <option value="Cocos (Keeling) Islands">Cocos (Keeling) Islands</option> <option value="Colombia">Colombia</option> <option value="Comoros">Comoros</option> <option value="Congo">Congo</option> <option value="Cook Islands">Cook Islands</option> <option value="Costa Rica">Costa Rica</option> <option value="Croatia">Croatia</option> <option value="Cuba">Cuba</option> <option value="Cyprus">Cyprus</option> <option value="Czech Republic">Czech Republic</option> <option value="Denmark">Denmark</option> <option value="Djibouti">Djibouti</option> <option value="Dominica">Dominica</option> <option value="Dominican Republic">Dominican Republic</option> <option value="East Timor">East Timor</option> <option value="Ecuador">Ecuador</option> <option value="Egypt">Egypt</option> <option value="El Salvador">El Salvador</option> <option value="Equatorial Guinea">Equatorial Guinea</option> <option value="Eritrea">Eritrea</option> <option value="Estonia">Estonia</option> <option value="Ethiopia">Ethiopia</option> <option value="Falkland Islands">Falkland Islands</option> <option value="Faroe Islands">Faroe Islands</option> <option value="Fiji">Fiji</option> <option value="Finland">Finland</option> <option value="Former USSR">Former USSR</option> <option value="France">France</option> <option value="France (European Territory)">France (European Territory)</option> <option value="French Guyana">French Guyana</option> <option value="French Southern Territories">French Southern Territories</option> <option value="Gabon">Gabon</option> <option value="Gambia">Gambia</option> <option value="Georgia">Georgia</option> <option value="Germany">Germany</option> <option value="Ghana">Ghana</option> <option value="Gibraltar">Gibraltar</option> <option value="Greece">Greece</option> <option value="Greenland">Greenland</option> <option value="Grenada">Grenada</option> <option value="Guadeloupe (French)">Guadeloupe (French)</option> <option value="Guam">Guam</option> <option value="Guatemala">Guatemala</option> <option value="Guinea">Guinea</option> <option value="Guinea Bissau">Guinea Bissau</option> <option value="Guyana">Guyana</option> <option value="Haiti">Haiti</option> <option value="Heard and McDonald Islands">Heard and McDonald Islands</option> <option value="Honduras">Honduras</option> <option value="Hong Kong">Hong Kong</option> <option value="Hungary">Hungary</option> <option value="Iceland">Iceland</option> <option value="India">India</option> <option value="Indonesia">Indonesia</option> <option value="Iran">Iran</option> <option value="Iraq">Iraq</option> <option value="Ireland">Ireland</option> <option value="Israel">Israel</option> <option value="Italy">Italy</option> <option value="Ivory Coast">Ivory Coast</option> <option value="Jamaica">Jamaica</option> <option value="Japan">Japan</option> <option value="Jordan">Jordan</option> <option value="Kazakhstan">Kazakhstan</option> <option value="Kenya">Kenya</option> <option value="Kiribati">Kiribati</option> <option value="Kuwait">Kuwait</option> <option value="Kyrgyzstan">Kyrgyzstan</option> <option value="Laos">Laos</option> <option value="Latvia">Latvia</option> <option value="Lebanon">Lebanon</option> <option value="Lesotho">Lesotho</option> <option value="Liberia">Liberia</option> <option value="Libya">Libya</option> <option value="Liechtenstein">Liechtenstein</option> <option value="Lithuania">Lithuania</option> <option value="Luxembourg">Luxembourg</option> <option value="Macau">Macau</option> <option value="Macedonia">Macedonia</option> <option value="Madagascar">Madagascar</option> <option value="Malawi">Malawi</option> <option value="Malaysia">Malaysia</option> <option value="Maldives">Maldives</option> <option value="Mali">Mali</option> <option value="Malta">Malta</option> <option value="Marshall Islands">Marshall Islands</option> <option value="Martinique (French)">Martinique (French)</option> <option value="Mauritania">Mauritania</option> <option value="Mauritius">Mauritius</option> <option value="Mayotte">Mayotte</option> <option value="Mexico">Mexico</option> <option value="Micronesia">Micronesia</option> <option value="Moldavia">Moldavia</option> <option value="Monaco">Monaco</option> <option value="Mongolia">Mongolia</option> <option value="Montserrat">Montserrat</option> <option value="Morocco">Morocco</option> <option value="Mozambique">Mozambique</option> <option value="Myanmar, Union of (Burma)">Myanmar, Union of (Burma)</option> <option value="Namibia">Namibia</option> <option value="Nauru">Nauru</option> <option value="Nepal">Nepal</option> <option value="Netherlands">Netherlands</option> <option value="Netherlands Antilles">Netherlands Antilles</option> <option value="Neutral Zone">Neutral Zone</option> <option value="New Caledonia (French)">New Caledonia (French)</option> <option value="New Zealand">New Zealand</option> <option value="Nicaragua">Nicaragua</option> <option value="Niger">Niger</option> <option value="Nigeria">Nigeria</option> <option value="Niue">Niue</option> <option value="Norfolk Island">Norfolk Island</option> <option value="North Korea">North Korea</option> <option value="Northern Mariana Islands">Northern Mariana Islands</option> <option value="Norway">Norway</option> <option value="Oman">Oman</option> <option value="Pakistan">Pakistan</option> <option value="Palau">Palau</option> <option value="Panama">Panama</option> <option value="Papua New Guinea">Papua New Guinea</option> <option value="Paraguay">Paraguay</option> <option value="Peru">Peru</option> <option value="Philippines">Philippines</option> <option value="Pitcairn Island">Pitcairn Island</option> <option value="Poland">Poland</option> <option value="Polynesia (French)">Polynesia (French)</option> <option value="Portugal">Portugal</option> <option value="Qatar">Qatar</option> <option value="Reunion (French)">Reunion (French)</option> <option value="Romania">Romania</option> <option value="Russian Federation">Russian Federation</option> <option value="Rwanda">Rwanda</option> <option value="S. Georgia &amp; S. Sandwich Islands">S. Georgia &amp; S. Sandwich Islands</option> <option value="Saint Helena">Saint Helena</option> <option value="Saint Kitts &amp; Nevis Anguilla">Saint Kitts &amp; Nevis Anguilla</option> <option value="Saint Lucia">Saint Lucia</option> <option value="Saint Pierre and Miquelon">Saint Pierre and Miquelon</option> <option value="Saint Tome and Principe">Saint Tome and Principe</option> <option value="Saint Vincent &amp; Grenadines">Saint Vincent &amp; Grenadines</option> <option value="Samoa">Samoa</option> <option value="San Marino">San Marino</option> <option value="Saudi Arabia">Saudi Arabia</option> <option value="Senegal">Senegal</option> <option value="Seychelles">Seychelles</option> <option value="Sierra Leone">Sierra Leone</option> <option value="Singapore">Singapore</option> <option value="Slovakia">Slovakia</option> <option value="Slovenia">Slovenia</option> <option value="Solomon Islands">Solomon Islands</option> <option value="Somalia">Somalia</option> <option value="South Africa">South Africa</option> <option value="South Korea">South Korea</option> <option value="Spain">Spain</option> <option value="Sri Lanka">Sri Lanka</option> <option value="Sudan">Sudan</option> <option value="Suriname">Suriname</option> <option value="Svalbard and Jan Mayen Islands">Svalbard and Jan Mayen Islands</option> <option value="Swaziland">Swaziland</option> <option value="Sweden">Sweden</option> <option value="Switzerland">Switzerland</option> <option value="Syria">Syria</option> <option value="Tadjikistan">Tadjikistan</option> <option value="Taiwan">Taiwan</option> <option value="Tanzania">Tanzania</option> <option value="Thailand">Thailand</option> <option value="Togo">Togo</option> <option value="Tokelau">Tokelau</option> <option value="Tonga">Tonga</option> <option value="Trinidad and Tobago">Trinidad and Tobago</option> <option value="Tunisia">Tunisia</option> <option value="Turkey">Turkey</option> <option value="Turkmenistan">Turkmenistan</option> <option value="Turks and Caicos Islands">Turks and Caicos Islands</option> <option value="Tuvalu">Tuvalu</option> <option value="Uganda">Uganda</option> <option value="Ukraine">Ukraine</option> <option value="United Arab Emirates">United Arab Emirates</option> <option value="Uruguay">Uruguay</option> <option value="US">US</option> <option value="USA Minor Outlying Islands">USA Minor Outlying Islands</option> <option value="Uzbekistan">Uzbekistan</option> <option value="Vanuatu">Vanuatu</option> <option value="Vatican City">Vatican City</option> <option value="Venezuela">Venezuela</option> <option value="Vietnam">Vietnam</option> <option value="Virgin Islands (British)">Virgin Islands (British)</option> <option value="Virgin Islands (USA)">Virgin Islands (USA)</option> <option value="Wallis and Futuna Islands">Wallis and Futuna Islands</option> <option value="Western Sahara">Western Sahara</option> <option value="Yemen">Yemen</option> <option value="Yugoslavia">Yugoslavia</option> <option value="Zaire">Zaire</option> <option value="Zambia">Zambia</option> <option value="Zimbabwe">Zimbabwe</option> </select> </td> </tr> <tr> <td><b>City: </b></td> <td><input type=text name=city></td> </tr> <tr> <td><b>State: </b></td> <td> <select name=state style=width:154> <option value="Not in US">Not in US</option> <option value="Alabama">Alabama</option> <option value="Alaska">Alaska</option> <option value="Arizona">Arizona</option> <option value="Arkansas">Arkansas</option> <option value="California">California</option> <option value="Colorado">Colorado</option> <option value="Connecticut">Connecticut</option> <option value="Delaware">Delaware</option> <option value="District of Columbia">District of Columbia</option> <option value="Florida">Florida</option> <option value="Georgia">Georgia</option> <option value="Hawaii">Hawaii</option> <option value="Idaho">Idaho</option> <option value="Illinois">Illinois</option> <option value="Indiana">Indiana</option> <option value="Iowa">Iowa</option> <option value="Kansas">Kansas</option> <option value="Kentucky">Kentucky</option> <option value="Louisiana">Louisiana</option> <option value="Maine">Maine</option> <option value="Maryland">Maryland</option> <option value="Massachusetts">Massachusetts</option> <option value="Michigan">Michigan</option> <option value="Minnesota">Minnesota</option> <option value="Mississippi">Mississippi</option> <option value="Missouri">Missouri</option> <option value="Montana">Montana</option> <option value="Nebraska">Nebraska</option> <option value="Nevada">Nevada</option> <option value="New Hampshire">New Hampshire</option> <option value="New Jersey">New Jersey</option> <option value="New Mexico">New Mexico</option> <option value="New York">New York</option> <option value="North Carolina">North Carolina</option> <option value="North Dakota">North Dakota</option> <option value="Ohio">Ohio</option> <option value="Oklahoma">Oklahoma</option> <option value="Oregon">Oregon</option> <option value="Pennsylvania">Pennsylvania</option> <option value="Puerto Rico">Puerto Rico</option> <option value="Rhode Island">Rhode Island</option> <option value="South Carolina">South Carolina</option> <option value="South Dakota">South Dakota</option> <option value="Tennessee">Tennessee</option> <option value="Texas">Texas</option> <option value="Utah">Utah</option> <option value="Vermont">Vermont</option> <option value="Virgin Islands">Virgin Islands</option> <option value="Virginia">Virginia</option> <option value="Washington">Washington</option> <option value="West Virginia">West Virginia</option> <option value="Wisconsin">Wisconsin</option> <option value="Wyoming">Wyoming</option> </select> </td> </tr> <tr> <td><b>Keyword: </b></td> <td><input type=text name=kw></td> </tr> <tr> <td valign=top><b>Job Category: </b><br> </td> <td valign=top> <SELECT NAME="JobCategory" size="1" style="width:290"> <option value="Accounting/Auditing">Accounting/Auditing</option> <option value="Administrative and Support Services">Administrative and Support Services</option> <option value="Advertising/Public Relations">Advertising/Public Relations</option> <option value="Computers, Hardware">Computers, Hardware</option> <option value="Computers, Software">Computers, Software</option> <option value="Consulting Services">Consulting Services</option> <option value="Customer Service and Call Center">Customer Service and Call Center</option> <option value="Director">Director</option> <option value="Executive Management">Executive Management</option> <option value="Finance/Economics">Finance/Economics</option> <option value="Human Resources">Human Resources</option> <option value="Information Technology">Information Technology</option> <option value="Installation, Maintenance and Repair">Installation, Maintenance and Repair</option> <option value="Internet/E-Commerce">Internet/E-Commerce</option> <option value="Legal">Legal</option> <option value="Management">Management</option> <option value="Marketing">Marketing</option> <option value="Sales">Sales</option> <option value="Supervisor">Supervisor</option> <option value="Telecommunications">Telecommunications</option> <option value="Transportation and Warehousing">Transportation and Warehousing</option> <option value="Other">Other</option> </SELECT><br> </td> </tr> <tr> <td><b>Job's Target: </b></td> <td> <select name="careerlevel" style="width:290"> <option value="">Select </option> <option value="1">Student (High School)</option> <option value="2">Student (undergraduate/graduate)</option> <option value="3">Entry Level (less than 2 years of experience)</option> <option value="4">Mid Career (2+ years of experience)</option> <option value="5">Management (Manager/Director of Staff)</option> <option value="6">Executive (SVP, EVP, VP)</option> <option value="7">Senior Executive (President, CEO)</option> </select> </td> </tr> <tr> <td><b>Search method: </b></td> <td><input type=radio name=sm value=or>or &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type=radio name=sm value=and checked>and </td> </tr> <tr> <td colspan=2 align=center> <input type=submit name=submit value=Search style="border-color:black; background-color:#e0e7e9; font-family:arial; font-weight:bold; color:#000000"> <br><br> <font size=1 face=verdana> *If you leave blank some fields, they will not take part in the LHR Jobs search process.</font> </td> </tr> </table> </form> <? include_once('../foother.html'); ?><file_sep><?php require_once ('session.php'); require_once ('shared.php'); if(isset($_POST['soql_query'])){ //correction for dynamic magic quotes if(get_magic_quotes_gpc()){ $_POST['soql_query'] = stripslashes($_POST['soql_query']); } $_SESSION['soql_query'] = $_POST['soql_query']; $_SESSION['QB_field_sel'] = $_POST['QB_field_sel']; $_SESSION['QB_filter_field_sel'] = $_POST['QB_filter_field_sel']; $_SESSION['QB_oper_sel'] = $_POST['QB_oper_sel']; $_SESSION['QB_filter_txt'] = $_POST['QB_filter_txt']; $_SESSION['QB_filter_field_sel2'] = $_POST['QB_filter_field_sel2']; $_SESSION['QB_oper_sel2'] = $_POST['QB_oper_sel2']; $_SESSION['QB_filter_txt2'] = $_POST['QB_filter_txt2']; $_SESSION['QB_nulls'] = $_POST['QB_nulls']; $_SESSION['QB_orderby_sort'] = $_POST['QB_orderby_sort']; $_SESSION['QB_orderby_field'] = $_POST['QB_orderby_field']; $_SESSION['QB_limit_txt'] = $_POST['QB_limit_txt']; } $_POST['QB_field_sel'] = $_SESSION['QB_field_sel']; $_POST['QB_filter_field_sel'] = $_SESSION['QB_filter_field_sel']; $_POST['QB_oper_sel'] = $_SESSION['QB_oper_sel']; $_POST['QB_filter_txt'] = $_SESSION['QB_filter_txt']; $_POST['QB_filter_field_sel2'] = $_SESSION['QB_filter_field_sel2']; $_POST['QB_oper_sel2'] = $_SESSION['QB_oper_sel2']; $_POST['QB_filter_txt2'] = $_SESSION['QB_filter_txt2']; $_POST['QB_nulls'] = $_SESSION['QB_nulls']; $_POST['QB_orderby_sort'] = $_SESSION['QB_orderby_sort']; $_POST['QB_orderby_field'] = $_SESSION['QB_orderby_field']; $_POST['QB_limit_txt'] = $_SESSION['QB_limit_txt']; if (isset($_POST['justUpdate']) && $_POST['justUpdate'] == true){ if (isset($_POST['default_object'])) $_SESSION['default_object'] = $_POST['default_object']; unset($_POST['QB_field_sel']); unset($_POST['QB_filter_field_sel']); unset($_POST['QB_oper_sel']); unset($_POST['QB_filter_txt']); unset($_POST['QB_filter_field_sel2']); unset($_POST['QB_oper_sel2']); unset($_POST['QB_filter_txt2']); unset($_POST['QB_nulls']); unset($_POST['QB_orderby_sort']); unset($_POST['QB_orderby_field']); unset($_POST['QB_limit_txt']); } //Main form logic: When the user first enters the page, display form defaulted to //show the query results with default object selected on a previous page, otherwise // just display the blank form. When the user selects the SCREEN or CSV options, the //query is processed by the correct function if(isset($_POST['queryMore']) && isset($_SESSION['queryLocator'])){ print "<body onLoad='toggleFieldDisabled();'>"; require_once ('header.php'); show_query_form($_POST['soql_query'],'screen',$_POST['query_action']); $queryTimeStart = microtime(true); $records = query(null,'QueryMore',$_SESSION['queryLocator']); $queryTimeEnd = microtime(true); $queryTimeElapsed = $queryTimeEnd - $queryTimeStart; show_query_result($records,$queryTimeElapsed); include_once('footer.php'); } else if (isset($_POST['querySubmit']) && $_POST['querySubmit']=='Query' && isset($_POST['soql_query']) && $_POST['export_action'] == 'screen') { print "<body onLoad='toggleFieldDisabled();'>"; require_once ('header.php'); show_query_form($_POST['soql_query'],'screen',$_POST['query_action']); $queryTimeStart = microtime(true); $records = query($_POST['soql_query'],$_POST['query_action']); $queryTimeEnd = microtime(true); $queryTimeElapsed = $queryTimeEnd - $queryTimeStart; show_query_result($records,$queryTimeElapsed); include_once('footer.php'); } elseif (isset($_POST['querySubmit']) && $_POST[querySubmit]=='Query' && $_POST[soql_query] && $_POST[export_action] == 'csv') { if (!substr_count($_POST['soql_query'],"count()")){ $records = query($_POST['soql_query'],$_POST['query_action'],null,true); export_query_csv($records,$_POST['query_action']); } else { print "<body onLoad='toggleFieldDisabled();'>"; require_once ('header.php'); show_query_form($_POST['soql_query'],'csv',$_POST['query_action']); print "</form>"; //could include inside because if IE page loading bug print "<p>&nbsp;</p>"; show_error("count() is not supported for CSV file export. Change export to Browser or choose fields and try again."); include_once('footer.php'); } } else { print "<body onLoad='toggleFieldDisabled();'>"; require_once ('header.php'); show_query_form($_SESSION['soql_query'],'screen','Query'); print "</form>"; //could include inside because if IE page loading bug include_once('footer.php'); } //Show the main SOQL query form with default query or last submitted query and export action (screen or CSV) function show_query_form($soql_query,$export_action,$query_action){ if ($_SESSION['default_object']){ $describeSObject_result = describeSObject($_SESSION['default_object'], true); } else { show_info('First choose an object to use the SOQL builder wizard.'); } print "<script>\n"; print "var field_type_array = new Array()\n"; if(isset($describeSObject_result)){ foreach($describeSObject_result->fields as $fields => $field){ print " field_type_array[\"$field->name\"]=[\"$field->type\"];\n"; } } print <<<QUERY_BUILDER_SCRIPT function parentChildRelationshipQueryBlocker(){ var soql = document.getElementById('soql_query_textarea').value.toUpperCase(); if(soql.indexOf('(SELECT') != -1 && soql.indexOf('IN (SELECT') == -1){ return confirm ("Parent-to-child relationship queries are not yet supported by the Workbench and may display unexpected results. Are you sure you wish to continue?"); } } function toggleFieldDisabled(){ var QB_field_sel = document.getElementById('QB_field_sel'); if(document.getElementById('myGlobalSelect').value){ QB_field_sel.disabled = false; } else { QB_field_sel.disabled = true; } var isFieldSelected = false; for (var i = 0; i < QB_field_sel.options.length; i++) if (QB_field_sel.options[i].selected) isFieldSelected = true; if(isFieldSelected){ document.getElementById('QB_filter_field_sel').disabled = false; document.getElementById('QB_orderby_field').disabled = false; document.getElementById('QB_orderby_sort').disabled = false; document.getElementById('QB_nulls').disabled = false; document.getElementById('QB_limit_txt').disabled = false; if(document.getElementById('QB_filter_field_sel').value){ document.getElementById('QB_filter_txt').disabled = false; document.getElementById('QB_oper_sel').disabled = false; } else { document.getElementById('QB_filter_txt').disabled = true; document.getElementById('QB_oper_sel').disabled = true; } } else{ document.getElementById('QB_filter_field_sel').disabled = true; document.getElementById('QB_oper_sel').disabled = true; document.getElementById('QB_filter_txt').disabled = true; document.getElementById('QB_orderby_field').disabled = true; document.getElementById('QB_orderby_sort').disabled = true; document.getElementById('QB_nulls').disabled = true; document.getElementById('QB_limit_txt').disabled = true; } if (isFieldSelected && document.getElementById('QB_filter_field_sel').value && document.getElementById('QB_oper_sel').value && document.getElementById('QB_filter_txt').value){ document.getElementById('QB_filter_field_sel2').disabled = false; if(document.getElementById('QB_filter_field_sel2').value){ document.getElementById('QB_filter_txt2').disabled = false; document.getElementById('QB_oper_sel2').disabled = false; } else { document.getElementById('QB_filter_txt2').disabled = true; document.getElementById('QB_oper_sel2').disabled = true; } } else { document.getElementById('QB_filter_field_sel2').disabled = true; document.getElementById('QB_oper_sel2').disabled = true; document.getElementById('QB_filter_txt2').disabled = true; } } function updateObject(){ document.query_form.justUpdate.value = 1; document.query_form.submit(); } function build_query(){ toggleFieldDisabled(); var myGlobalSelect = document.getElementById('myGlobalSelect').value; var QB_field_sel = document.getElementById('QB_field_sel'); QB_fields_selected = new Array(); for (var i = 0; i < QB_field_sel.options.length; i++){ if (QB_field_sel.options[i].selected){ QB_fields_selected.push(QB_field_sel.options[i].value); } } var soql_select = ''; if(QB_fields_selected.toString().indexOf('count()') != -1 && QB_fields_selected.length > 1){ alert('Warning: Choosing count() with other fields will result in a malformed query. Unselect either count() or the other fields to continue.'); } else if (QB_fields_selected.length > 0){ var soql_select = 'SELECT ' + QB_fields_selected + ' FROM ' + myGlobalSelect; } var QB_filter_field_sel = document.getElementById('QB_filter_field_sel').value; var QB_oper_sel = document.getElementById('QB_oper_sel').value; var QB_filter_txt = document.getElementById('QB_filter_txt').value; if (QB_filter_field_sel && QB_oper_sel && QB_filter_txt){ if (QB_oper_sel == 'starts'){ QB_oper_sel = 'LIKE' QB_filter_txt = QB_filter_txt + '%'; } else if (QB_oper_sel == 'ends'){ QB_oper_sel = 'LIKE' QB_filter_txt = '%' + QB_filter_txt; } else if (QB_oper_sel == 'contains'){ QB_oper_sel = 'LIKE' QB_filter_txt = '%' + QB_filter_txt + '%'; } if (QB_oper_sel == 'IN' || QB_oper_sel == 'NOT IN' || QB_oper_sel == 'INCLUDES' || QB_oper_sel == 'EXCLUDES'){ QB_filter_txt_q = '(' + QB_filter_txt + ')'; } else if ((QB_filter_txt == 'null') || (field_type_array[QB_filter_field_sel] == "datetime") || (field_type_array[QB_filter_field_sel] == "date") || (field_type_array[QB_filter_field_sel] == "currency") || (field_type_array[QB_filter_field_sel] == "percent") || (field_type_array[QB_filter_field_sel] == "double") || (field_type_array[QB_filter_field_sel] == "int") || (field_type_array[QB_filter_field_sel] == "boolean")){ QB_filter_txt_q = QB_filter_txt; } else { QB_filter_txt_q = '\'' + QB_filter_txt + '\''; } var soql_where = ' WHERE ' + QB_filter_field_sel + ' ' + QB_oper_sel + ' ' + QB_filter_txt_q; } else { var soql_where = ''; } var QB_filter_field_sel2 = document.getElementById('QB_filter_field_sel2').value; var QB_oper_sel2 = document.getElementById('QB_oper_sel2').value; var QB_filter_txt2 = document.getElementById('QB_filter_txt2').value; if (QB_filter_field_sel2 && QB_oper_sel2 && QB_filter_txt2){ if (QB_oper_sel2 == 'starts'){ QB_oper_sel2 = 'LIKE' QB_filter_txt2 = QB_filter_txt2 + '%'; } else if (QB_oper_sel2 == 'ends'){ QB_oper_sel2 = 'LIKE' QB_filter_txt2 = '%' + QB_filter_txt2; } else if (QB_oper_sel2 == 'contains'){ QB_oper_sel2 = 'LIKE' QB_filter_txt2 = '%' + QB_filter_txt2 + '%'; } if (QB_oper_sel2 == 'IN' || QB_oper_sel2 == 'NOT IN' || QB_oper_sel2 == 'INCLUDES' || QB_oper_sel2 == 'EXCLUDES'){ QB_filter_txt_q2 = '(' + QB_filter_txt2 + ')'; } else if ((QB_filter_txt2 == 'null') || (field_type_array[QB_filter_field_sel2] == "datetime") || (field_type_array[QB_filter_field_sel2] == "date") || (field_type_array[QB_filter_field_sel2] == "currency") || (field_type_array[QB_filter_field_sel2] == "percent") || (field_type_array[QB_filter_field_sel2] == "double") || (field_type_array[QB_filter_field_sel2] == "int") || (field_type_array[QB_filter_field_sel2] == "boolean")){ QB_filter_txt_q2 = QB_filter_txt2; } else { QB_filter_txt_q2 = '\'' + QB_filter_txt2 + '\''; } var soql_where2 = ' AND ' + QB_filter_field_sel2 + ' ' + QB_oper_sel2 + ' ' + QB_filter_txt_q2; } else { var soql_where2 = ''; } if(soql_where && soql_where2){ soql_where = soql_where + soql_where2; } var QB_orderby_field = document.getElementById('QB_orderby_field').value; var QB_orderby_sort = document.getElementById('QB_orderby_sort').value; var QB_nulls = document.getElementById('QB_nulls').value; if (QB_orderby_field){ var soql_orderby = ' ORDER BY ' + QB_orderby_field + ' ' + QB_orderby_sort; if (QB_nulls) soql_orderby = soql_orderby + ' NULLS ' + QB_nulls; } else var soql_orderby = ''; var QB_limit_txt = document.getElementById('QB_limit_txt').value; if (QB_limit_txt) var soql_limit = ' LIMIT ' + QB_limit_txt; else var soql_limit = ''; if (soql_select) document.getElementById('soql_query_textarea').value = soql_select + soql_where + soql_orderby + soql_limit ; } </script> QUERY_BUILDER_SCRIPT; if($_SESSION['config']['autoJumpToQueryResults']){ print "<form method='POST' name='query_form' action='$_SERVER[PHP_SELF]#qr'>\n"; } else { print "<form method='POST' name='query_form' action='$_SERVER[PHP_SELF]'>\n"; } print "<input type='hidden' name='justUpdate' value='0' />"; print "<p><strong>Choose the object, fields, and critera to build a SOQL query below:</strong></p>\n"; print "<table border='0' width=1>\n"; print "<tr><td valign='top' width='1'>"; //extracted myGlobalSelect Function print "Object:\n<select id='myGlobalSelect' name='default_object' style='width: 16em;' onChange='updateObject();'>\n"; print "<option value=''></option>"; if (!$_SESSION['myGlobal']){ try{ global $mySforceConnection; $_SESSION['myGlobal'] = $mySforceConnection->describeGlobal(); } catch (Exception $e) { $errors = null; $errors = $e->getMessage(); show_error($errors); exit; } } //Print the global object types in a dropdown select box foreach($_SESSION['myGlobal']->types as $type){ print " <option value='$type'"; if (isset($_SESSION['default_object']) && $_SESSION['default_object'] == $type){ print " selected='true'"; } print " />$type</option> \n"; } print "</select><p/>\n"; print "Fields:<select id='QB_field_sel' name='QB_field_sel[]' multiple='mutliple' size='10' style='width: 16em;' onChange='build_query();'>\n"; if(isset($describeSObject_result)){ print " <option value='count()'"; if(isset($_POST['QB_field_sel'])){ //check to make sure something is selected; otherwise warnings will display foreach ($_POST['QB_field_sel'] as $selected_field){ if ('count()' == $selected_field) print " selected='selected' "; } } print ">count()</option>\n"; print ">$field->name</option>\n"; foreach($describeSObject_result->fields as $fields => $field){ print " <option value='$field->name'"; if(isset($_POST['QB_field_sel'])){ //check to make sure something is selected; otherwise warnings will display foreach ($_POST['QB_field_sel'] as $selected_field){ if ($field->name == $selected_field) print " selected='selected' "; } } print ">$field->name</option>\n"; } } print "</select></td>\n"; print "<td valign='top'>"; print "<table border='0' align='right'>\n"; print "<tr><td valign='top' colspan=2>Export to:<br/>" . "<label><input type='radio' name='export_action' value='screen' "; if ($export_action == 'screen') print "checked='true'"; print " >Browser</label>&nbsp;"; print "<label><input type='radio' name='export_action' value='csv' "; if ($export_action == 'csv') print "checked='true'"; print " >CSV File</label>"; print "<td valign='top' colspan=2>Deleted and archived records:<br/>" . "<label><input type='radio' name='query_action' value='Query' "; if ($query_action == 'Query') print "checked='true'"; print " >Exclude</label>&nbsp;"; print "<label><input type='radio' name='query_action' value='QueryAll' "; if ($query_action == 'QueryAll') print "checked='true'"; print " >Include</label></td></tr>\n"; print "<tr><td><br/>Sort results by:</td> <td><br/>&nbsp;</td> <td><br/>&nbsp;</td> <td><br/>Max Records:</td></tr>\n"; print "<tr>"; print "<td><select id='QB_orderby_field' name='QB_orderby_field' style='width: 16em;' onChange='build_query();'>\n"; print "<option value=''></option>\n"; if(isset($describeSObject_result)){ foreach($describeSObject_result->fields as $fields => $field){ print " <option value='$field->name'"; if (isset($_POST['QB_orderby_field']) && $field->name == $_POST['QB_orderby_field']) print " selected='selected' "; print ">$field->name</option>\n"; } } print "</select></td>\n"; $QB_orderby_sort_options = array( 'ASC' => 'A to Z', 'DESC' => 'Z to A' ); print "<td><select id='QB_orderby_sort' name='QB_orderby_sort' style='width: 10em;' onChange='build_query();'>\n"; foreach ($QB_orderby_sort_options as $op_key => $op){ print "<option value='$op_key'"; if (isset($_POST['QB_orderby_sort']) && $op_key == $_POST['QB_orderby_sort']) print " selected='selected' "; print ">$op</option>\n"; } print "</select></td>\n"; $QB_nulls_options = array( 'FIRST' => 'Nulls First', 'LAST' => 'Nulls Last' ); print "<td><select id='QB_nulls' name='QB_nulls' style='width: 10em;' onChange='build_query();'>\n"; foreach ($QB_nulls_options as $op_key => $op){ print "<option value='$op_key'"; if (isset($_POST['QB_nulls']) && $op_key == $_POST['QB_nulls']) print " selected='selected' "; print ">$op</option>\n"; } print "</select></td>\n"; print "<td><input type='text' id='QB_limit_txt' size='11' name='QB_limit_txt' value='" . htmlspecialchars($_POST['QB_limit_txt'],ENT_QUOTES,'UTF-8') . "' onkeyup='build_query();' /></td>\n"; print "</tr>\n"; print "<tr><td valign='top' colspan=4 nowrap>\n"; print "<br/>Filter results by:<br/>\n"; print "<select id='QB_filter_field_sel' name='QB_filter_field_sel' style='width: 16em;' onChange='build_query();'>\n"; print "<option value=''></option>"; if(isset($describeSObject_result)){ foreach($describeSObject_result->fields as $fields => $field){ print " <option value='$field->name'"; if (isset($_POST['QB_filter_field_sel']) && $field->name == $_POST['QB_filter_field_sel']) print " selected='selected' "; print ">$field->name</option>\n"; } } print "</select>\n"; $ops = array( '=' => '=', '!=' => '&ne;', '<' => '&lt;', '<=' => '&le;', '>' => '&gt;', '>=' => '&ge;', 'starts' => 'starts with', 'ends' => 'ends with', 'contains' => 'contains', 'IN' => 'in', 'NOT IN' => 'not in', 'INCLUDES' => 'includes', 'EXCLUDES' => 'excludes' ); print "<select id='QB_oper_sel' name='QB_oper_sel' style='width: 10em;' onChange='build_query();'>\n"; foreach ($ops as $op_key => $op){ print "<option value='$op_key'"; if (isset($_POST['QB_oper_sel']) && $op_key == $_POST['QB_oper_sel']) print " selected='selected' "; print ">$op</option>\n"; } print "</select>\n"; print "<input type='text' id='QB_filter_txt' size='31' name='QB_filter_txt' value=\"" . htmlspecialchars($_POST['QB_filter_txt'],ENT_QUOTES,'UTF-8') . "\" onkeyup='build_query();' />"; print "</td></tr>\n"; print "<tr><td valign='top' colspan=4 nowrap>\n"; print "<br/>Then filter results by:<br/>\n"; print "<select id='QB_filter_field_sel2' name='QB_filter_field_sel2' style='width: 16em;' onChange='build_query();'>\n"; print "<option value=''></option>\n"; if(isset($describeSObject_result)){ foreach($describeSObject_result->fields as $fields => $field){ print " <option value='$field->name'"; if (isset($_POST['QB_filter_field_sel2']) && $field->name == $_POST['QB_filter_field_sel2']) print " selected='selected' "; print ">$field->name</option>\n"; } } print "</select> \n"; $ops = array( '=' => '=', '!=' => '&ne;', '<' => '&lt;', '<=' => '&le;', '>' => '&gt;', '>=' => '&ge;', 'starts' => 'starts with', 'ends' => 'ends with', 'contains' => 'contains', 'IN' => 'in', 'NOT IN' => 'not in', 'INCLUDES' => 'includes', 'EXCLUDES' => 'excludes' ); print "<select id='QB_oper_sel2' name='QB_oper_sel2' style='width: 10em;' onChange='build_query();'>"; foreach ($ops as $op_key => $op){ print "<option value='$op_key'"; if (isset($_POST['QB_oper_sel2']) && $op_key == $_POST['QB_oper_sel2']) print " selected='selected' "; print ">$op</option>"; } print "</select>\n"; print "<input type='text' id='QB_filter_txt2' size='31' name='QB_filter_txt2' value=\"" . htmlspecialchars($_POST['QB_filter_txt2'],ENT_QUOTES,'UTF-8') . "\" onkeyup='build_query();' />\n"; print "</td></tr>\n"; print "</table>\n"; print "</td></tr>\n"; print "<tr><td valign='top' colspan=5><br/>Enter or modify a SOQL query below:\n" . "<br/><textarea id='soql_query_textarea' type='text' name='soql_query' cols='108' rows='4' style='overflow: auto; font-family: monospace, courier;'>" . htmlspecialchars($soql_query,ENT_QUOTES,'UTF-8') . "</textarea>\n" . "</td></tr>\n"; print "<tr><td colspan=5><input type='submit' name='querySubmit' value='Query' onclick='return parentChildRelationshipQueryBlocker();' />\n"; print "<input type='reset' value='Reset' />\n"; print "</td></tr></table><p/>\n"; } function query($soql_query,$query_action,$query_locator = null,$suppressScreenOutput=false){ try{ global $mySforceConnection; if ($query_action == 'Query') $query_response = $mySforceConnection->query($soql_query); if ($query_action == 'QueryAll') $query_response = $mySforceConnection->queryAll($soql_query); if ($query_action == 'QueryMore' && isset($query_locator)) $query_response = $mySforceConnection->queryMore($query_locator); if (substr_count($soql_query,"count()") && $suppressScreenOutput == false){ $countString = "Query would return " . $query_response->size . " record"; $countString .= ($query_response->size == 1) ? "." : "s."; show_info($countString); $records = $query_response->size; include_once('footer.php'); exit; } if(isset($query_response->records)){ $records = $query_response->records; } else { $records = null; } $_SESSION['totalQuerySize'] = $query_response->size; if(!$query_response->done){ $_SESSION['queryLocator'] = $query_response->queryLocator; } else { $_SESSION['queryLocator'] = null; } while(($suppressScreenOutput || $_SESSION['config']['autoRunQueryMore']) && !$query_response->done){ $query_response = $mySforceConnection->queryMore($query_response->queryLocator); $records = array_merge($records,$query_response->records); } return $records; } catch (Exception $e){ $errors = null; $errors = $e->getMessage(); print "<p><a name='qr'>&nbsp;</a></p>"; show_error($errors); include_once('footer.php'); exit; } } function getQueryResultHeaders($sobject, $tail=""){ if(!isset($headerBufferArray)){ $headerBufferArray = array(); } if ($sobject->Id){ $headerBufferArray[] = $tail . "Id"; } if ($sobject->fields){ foreach($sobject->fields->children() as $field){ $headerBufferArray[] = $tail . htmlspecialchars($field->getName(),ENT_QUOTES,'UTF-8'); } } if($sobject->sobjects){ foreach($sobject->sobjects as $sobjects){ $recurse = getQueryResultHeaders($sobjects, $tail . htmlspecialchars($sobjects->type,ENT_QUOTES,'UTF-8') . "."); $headerBufferArray = array_merge($headerBufferArray, $recurse); } } return $headerBufferArray; } function getQueryResultRow($sobject){ if(!isset($rowBuffer)){ $rowBuffer = array(); } if ($sobject->Id){ $rowBuffer[] = htmlspecialchars($sobject->Id,ENT_QUOTES,'UTF-8'); } if ($sobject->fields){ foreach($sobject->fields as $datum){ $rowBuffer[] = htmlspecialchars($datum,ENT_QUOTES,'UTF-8'); } } if($sobject->sobjects){ foreach($sobject->sobjects as $sobjects){ $rowBuffer = array_merge($rowBuffer, getQueryResultRow($sobjects)); } } return $rowBuffer; } //If the user selects to display the form on screen, they are routed to this function function show_query_result($records, $queryTimeElapsed){ //Check if records were returned if ($records) { try { $rowNum = 0; print "<a name='qr'></a><div style='clear: both;'><br/><h2>Query Results</h2>\n"; if(isset($_SESSION['queryLocator']) && !$_SESSION['config']['autoRunQueryMore']){ preg_match("/-(\d+)/",$_SESSION['queryLocator'],$lastRecord); $rowNum = ($lastRecord[1] - count($records) + 1); print "<p>Returned records $rowNum - " . $lastRecord[1] . " of "; } else if (!$_SESSION['config']['autoRunQueryMore']){ $rowNum = ($_SESSION['totalQuerySize'] - count($records) + 1); print "<p>Returned records $rowNum - " . $_SESSION['totalQuerySize'] . " of "; } else { $rowNum = 1; print "<p>Returned "; } print $_SESSION['totalQuerySize'] . " total record"; if ($_SESSION['totalQuerySize'] !== 1) print 's'; print " in "; printf ("%01.3f", $queryTimeElapsed); print " seconds:</p>\n"; if (!$_SESSION['config']['autoRunQueryMore'] && $_SESSION['queryLocator']){ print "<p><input type='submit' name='queryMore' id='queryMoreButtonTop' value='More...' /></p>\n"; } print "<table class='data_table'>\n"; //call shared recusive function above for header printing and then strip off the extra <th> print "<tr><td>&nbsp;</td><th>" . implode("</th><th>", getQueryResultHeaders(new SObject($records[0]))) . "</th></tr>\n"; if($_SESSION['config']['linkIdToUi']){ preg_match("@//(.*)\.salesforce@", $_SESSION['location'], $instUIDomain); } //Print the remaining rows in the body foreach ($records as $record){ //call shared recusive function above for row printing and then strip off the extra <td> $queryTableRow = "<tr><td>" . $rowNum++ . "</td><td>" . implode("</td><td>", getQueryResultRow(new SObject($record))) . "</td></tr>\n"; if($_SESSION['config']['linkIdToUi']){ //$queryTableRow = preg_replace("/[A-Za-z0-9]{18}/","<a href='https://$instUIDomain[1].salesforce.com/$0' target='sfdcUi'>$0</a>",$queryTableRow); $queryTableRow = preg_replace("@<td>([A-Za-z0-9]{4}0000[A-Za-z0-9]{10})</td>@","<td><a href='https://$instUIDomain[1].salesforce.com/secur/frontdoor.jsp?sid=". $_SESSION['sessionId'] . "&retURL=%2F$1' target='sfdcUi'>$1</a></td>",$queryTableRow); } print $queryTableRow; } print "</table>"; if (!$_SESSION['config']['autoRunQueryMore'] && $_SESSION['queryLocator']){ print "<p><input type='submit' name='queryMore' id='queryMoreButtonBottom' value='More...' /></p>"; } print "</form></div>\n"; } catch (Exception $e) { $errors = null; $errors = $e->getMessage(); print "<p />"; show_error($errors); include_once('footer.php'); exit; } } else { print "<p><a name='qr'>&nbsp;</a></p>"; show_error("Sorry, no records returned."); } include_once('footer.php'); } //Export the above query to a CSV file function export_query_csv($records,$query_action){ if ($records) { try { $csv_file = fopen('php://output','w') or die("Error opening php://output"); $csv_filename = "export" . date(YmdHis) . ".csv"; header("Content-Type: application/csv"); header("Content-Disposition: attachment; filename=$csv_filename"); //Write first row to CSV and unset variable fputcsv($csv_file,getQueryResultHeaders(new SObject($records[0]))); //Export remaining rows and write to CSV line-by-line foreach ($records as $record) { fputcsv($csv_file, getQueryResultRow(new SObject($record))); } fclose($csv_file) or die("Error closing php://output"); } catch (Exception $e) { require_once("header.php"); $errors = $e->getMessage(); show_query_form($_POST['soql_query'],'csv',$query_action); print "<p />"; show_error($errors); include_once('footer.php'); exit; } } else { require_once("header.php"); $errors = "No records returned for CSV output."; show_query_form($_POST['soql_query'],'csv',$query_action); print "<p />"; show_error($errors); include_once('footer.php'); exit; } } ?> <file_sep><? include_once "main.php"; if(isset($submit)) { ?> <body bgcolor="#FFFFFF"> <table width="446" bgcolor="#FFFFFF"><tr><td> <? if(!empty($_POST[name])) { $name1 = strip_tags($_POST[name]); } else { echo "<center> You forgot to enter your name.</center>"; } if(!empty($_POST[email])) { $email1 = strip_tags($_POST[email]); } else { echo "<center> You forgot to enter your email.</center>"; } if(!empty($_POST[status])) { $status1 = $_POST[status]; } else { echo "<center> You forgot to select your status.</center>"; } if(!empty($_POST[subject])) { $subject1 = strip_tags($_POST[subject]); } else { echo "<center> The subject field is empty.</center>"; } if(!empty($_POST[message])) { $message1 = strip_tags($_POST[message]); } else { echo "<center> You forgot to write the messgae.</center>"; } if(!empty($name1) && !empty($email1) && !empty($status1) && !empty($subject1) && !empty($message1)) { //I use the email for official corespondence $to = "$email_address"; //display the message author and his email $from = "From: $name1 <$email1>"; //this subject will be visible only for you $sub = "Contact form message"; //fit together all the post information into one message $message = "$subject1 \n\n"."$message1 \n\n"."$name1\n$status1"; //if a user has insert some html/javascript/php tags //we will remove them for security reasons $message = stripslashes($message); //now send the message to $email_address mail($to, $sub, $message, $from); //display "thank you" message. You can edit it and write what you want. //if you want to use quotes at this message, use this format: \"text here\" //you can use any html tags echo "<br><br><br><center> Thanks for your message. <br>We will contact you as soon as possible.</center>"; // exit(); } ?> </td></tr></table> <? } ?> <br><br><br> <form method=post style="background:none;"> <table align=center width="446" bgcolor="#FFFFFF"> <tr> <td colspan=2>Use this form to send us a message</td> </tr> <tr> <td>Your name:</td> <td><input type=text name=name></td> </tr> <tr> <td>Your email:</td> <td><input type=text name=email></td> </tr> <tr> <td>Your status:</td> <td> <select name=status> <option value="">select</option> <option value="Jobseeker">Jobseeker </option> <option value="Employer">Employer </option> <option value="Visitor">Visitor </option> </select> </td> </tr> <tr> <td>Subject: </td> <td><input type=text name=subject></td> </tr> <tr> <td valign=top>Message: </td> <td><textarea name=message rows=4 cols=30></textarea></td> </tr> <tr> <td colspan=2 align=center> <input type=submit name=submit class=SRT value=Send> &nbsp;&nbsp;&nbsp; <input type=reset class=SRT> </td> </tr> </table> </form> <? include_once('foother.html'); ?><file_sep><? include_once "accesscontrol.php"; $sql = "SELECT plan,JS_number,JP_number,expiryplan FROM job_employer_info WHERE ename = '$ename' AND epass = '$epass'"; $result = mysql_query($sql); $res=mysql_fetch_array($result); $plan=$res[0]; if ($plan != "") { $expiryon=mktime(0,0,0,substr($res['expiryplan'],5,2),substr($res['expiryplan'],8,2),substr($res['expiryplan'],0,4)); $today=mktime(0,0,0,substr(date("Y.m.d"),5,2),substr(date("Y.m.d"),8,2),substr(date("Y.m.d"),0,4)); if ($today > $expiryon) { ?> <br> <table width="446" bgcolor="#FFFFFF"><tr><td> <font face=verdana> <h1> Access Denied </h1> <p><h5>Your package has expired, please renew your Employer Plan to view the resumes <br><br>To register for instant access, click <a href="pay1.php">here</a>.</h5></p> </td></tr></table> <?php include("../foother.html"); exit; } } else { ?> <br> <h3>Access Denied2</h1> <table width="446"><tr><td> <font face=verdana> <h1> Access Denied </h1> <p><h5>To access this feature we offer, choose your Employer Plan: <br><br>To register for instant access, click <a href="pay1.php">here</a>.</h5></p> </td></tr></table> <?php include("../foother.html"); exit; } $day = date(d); $month = date(m); $year = date(Y); $del = "delete from job_post where EXday = \"$day\" and EXmonth = \"$month\" and EXyear = \"$year\" "; $rdel = mysql_query($del) or die(mysql_error()); $sch = array(); if (!empty($_POST[JobCategory])) { $sch[] = "job_category like '%$_POST[JobCategory]%'"; } if (!empty($_POST[careerlevel])) { $sch[] = "careerlevel = \"$_POST[careerlevel]\" "; } if (!empty($_POST[target_company])) { $sch[] = "target_company = \"$_POST[target_company]\" "; } if (!empty($_POST[relocate])) { $sch[] = "relocate = \"$_POST[relocate]\" "; } if (!empty($_POST[country])) { $sch[] = "country = \"$_POST[country]\" "; } if (!empty($_POST[city])) { $sch[] = "city like '%$_POST[city]%'"; } if (!empty($_POST[state])) { $sch[] = "state = \"$_POST[state]\" "; } if (!empty($_POST[kw])) { $sch[] = "rTitle like '%$_POST[kw]%' or rPar like '%$_POST[kw]%' "; } if (!$ByPage) $ByPage=5; if (!$Start) $Start=0; if($_POST[sm] == 'or') { $qs = "select * from job_seeker_info ".(($sch)?"where ".join(" or ", $sch):"")." limit $Start,$ByPage"; $qss = "select * from job_seeker_info ".(($sch)?"where ".join(" or ", $sch):""); } elseif($_POST[sm] == 'and') { $qs = "select * from job_seeker_info ".(($sch)?"where ".join(" and ", $sch):"")." limit $Start,$ByPage"; $qss = "select * from job_seeker_info ".(($sch)?"where ".join(" and ", $sch):""); } $rqs = mysql_query($qs) or die(mysql_error()); $rqss = mysql_query($qss) or die(mysql_error()); $rr = mysql_num_rows($rqss); echo "<table align=center border=0 width=446><tr><td>"; if($rr == '0') { echo "<br><br><center> No results found.</center>"; } elseif($rr == '1') { echo "<br><br><center> Your search return one result. </center>"; } elseif($rr > '1') { echo "<br><br><center> Your search return $rr results. </center>"; } while($as = mysql_fetch_array($rqs)) { $q3 = "select * from job_careerlevel where uname = \"$as[uname]\" "; $r3 = mysql_query($q3) or die(mysql_error()); $a3 = mysql_fetch_array($r3); if($as[careerlevel] == '0') { $clname = 'N/A'; } if($as[careerlevel] == '1') { $clname = 'Student (High School)'; } elseif($as[careerlevel] == '2') { $clname = 'Student (undergraduate/graduate)'; } elseif($as[careerlevel] == '3') { $clname = 'Entry Level (less than 2 years of experience)'; } elseif($as[careerlevel] == '4') { $clname = 'Mid Career (2+ years of experience)'; } elseif($as[careerlevel] == '5') { $clname = 'Management (Manager/Director of Staff)'; } elseif($as[careerlevel] == '6') { $clname = 'Executive (SVP, EVP, VP)'; } elseif($as[careerlevel] == '7') { $clname = 'Senior Executive (President, CEO)'; } echo "<br><table align=center width=420 cellspacing=0 border=0 bordercolor=e0e7e9> <tr> <td><strong>Name</strong>:</td><td bgcolor=ffffff><a class=TN href=\"EmployerView2.php?uname=$as[uname]&ename=$ename\"> $as[fname] $as[lname] </a></td> </tr> <tr><td><strong>Career level</strong>: </td> <td bgcolor=ffffff> $as[careerlevel] </td></tr> <tr> <td width=100 valign=top><strong>Prefered jobs</strong>:</td> <td bgcolor=ffffff> $as[job_category] </td> </tr>"; if ($as["isupload"]==1) { echo "<tr> <td width=100 valign=top>Download Resume</td> <td bgcolor=ffffff><a href=\"http://$_SERVER[HTTP_HOST]/jobseekers/$as[resume]\">Download Now</a></td> </tr>"; } echo "</table>"; } if($_POST[sm] == 'or') { $qs2 = "select * from job_seeker_info ".(($sch)?"where ".join(" or ", $sch):""); } elseif($_POST[sm] == 'and') { $qs2 = "select * from job_seeker_info ".(($sch)?"where ".join(" and ", $sch):""); } $rqs2 = mysql_query($qs2) or die(mysql_error()); $rr2 = mysql_num_rows($rqs2); echo "<table align=center width=400><tr>"; if ($rr2 <= $ByPage && $Start == '0') { } if ( $Start > 0 ) { $nom1 = $Start - $ByPage; echo "<td align=left><a class=TN href=\"Search2.php?sm=$sm&JobCategory=$JobCategory&careerlevel=$careerlevel&target_company=$target_company&relocate=$relocate&country=$country&city=$city&kw=$kw&Start=$nom1\">previous</a></td>"; } if ($rr2 > $Start + $ByPage || ($Start == 0 && $rr2 > $ByPage)) { $nom = $Start + $ByPage; echo "<td align=right><a class=TN href=\"Search2.php?sm=$sm&JobCategory=$JobCategory&careerlevel=$careerlevel&target_company=$target_company&relocate=$relocate&country=$country&city=$city&kw=$kw&Start=$nom\">next</a></td>"; } echo "</tr></table>"; echo "</td></tr></table>"; ?> <? include_once('../foother.html'); ?><file_sep><?php require_once('session.php'); require_once('shared.php'); $errors = null; if(isset($_POST['submitConfigSetter'])){ //find errors foreach($config as $configKey => $configValue){ if(!isset($configValue['isHeader']) && isset($_POST[$configKey])){ if(isset($configValue['maxValue']) && $configValue['maxValue'] < $_POST[$configKey]){ $errors[] = $configValue[label] . " must not be greater than " . $configValue['maxValue']; } else if(isset($configValue['minValue']) && $configValue['minValue'] > $_POST[$configKey]){ $errors[] = $configValue[label] . " must not be less than " . $configValue['minValue']; } } } if (isset($_POST['assignmentRuleHeader_useDefaultRule']) && isset($_POST['assignmentRuleHeader_assignmentRuleId'])){ $errors[] = "Can not set both 'Use Default Assignment Rule' and 'Assignment Rule Id'"; } } if(isset($_POST['submitConfigSetter']) || isset($_POST['restoreDefaults'])){ if(!isset($errors)){ foreach($config as $configKey => $configValue){ if (isset($_POST['restoreDefaults'])){ setcookie($configKey,NULL,time()-3600); //clear all config cookies if restoreDefaults selected } else if(isset($_POST[$configKey]) && $configValue['dataType'] == "boolean"){ //for boolean trues setcookie($configKey,1,time()+60*60*24*365*10); } else if(isset($configValue['dataType']) && $configValue['dataType'] == "boolean"){ //for boolean falses setcookie($configKey,0,time()+60*60*24*365*10); } else if(isset($_POST[$configKey])){ setcookie($configKey,$_POST[$configKey],time()+60*60*24*365*10); //for non-null strings and numbers } else { setcookie($configKey,NULL,time()-3600); //for null strings and numbers (remove cookie) } } header("Location: $_SERVER[PHP_SELF]"); } } require_once('header.php'); if(isset($errors)){ show_error($errors); } print "<form method='post' action='$_SERVER[PHP_SELF]'>\n"; print "<table border='0' cellspacing='5' style='border-width-top: 1'>\n"; foreach($config as $configKey => $configValue){ if(isset($configValue['isHeader']) && $configValue['display']){ print "\t<tr><th align='left' colspan='3'><br/>" . htmlspecialchars($configValue['label'],ENT_QUOTES,'UTF-8') . "</th></tr>\n"; } else if($configValue['overrideable']){ print "\t<tr onmouseover=\"Tip('" . htmlspecialchars(addslashes($configValue['description']),ENT_NOQUOTES,'UTF-8') . "')\">\n"; print "\t\t<td align='right'><label for='$configKey'>" . htmlspecialchars($configValue['label'],ENT_QUOTES,'UTF-8') . "</label></td><td>&nbsp;&nbsp;</td>\n"; print "\t\t<td align='left'>"; if($configValue['dataType'] == "boolean"){ print "<input name='$configKey' id='$configKey' type='checkbox' "; if($_SESSION['config'][$configKey]) print " checked='true'"; print "/></td>\n"; } else if ($configValue['dataType'] == "string" || $configValue['dataType'] == "int"){ print "<input name='$configKey' id='$configKey' type='text' value='". $_SESSION['config'][$configKey] . "' size='30'/></td>\n"; } else if ($configValue['dataType'] == "password"){ print "<input name='$configKey' id='$configKey' type='password' value='". $_SESSION['config'][$configKey] . "' size='30'/></td>\n"; } else { print "</td>\n"; } print "\t</tr>\n"; } } print "<tr> <td></td> <td></td> <td></td> </tr>"; print "<tr> <td colspan='3' align='left'><input type='submit' name='submitConfigSetter' value='Apply Settings'/>&nbsp;<input type='submit' name='restoreDefaults' value='Restore Defaults'/>&nbsp;<input type='reset' value='Cancel'/></td> </tr>"; print "<table>\n"; print "</form>"; require_once('footer.php'); ?> <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"> <?php include_once("includes\documentHeader.php"); print_r(docHeader('', 'flashx.ez-ajax.com')); ?> <script language="JavaScript1.2" type="text/javascript" src="js/00_constants.js"></script> <script language="javascript1.2" type="text/javascript" src="js/01_clientWid$.js"></script> <script language="JavaScript1.2" type="text/javascript" src="js/01_clientHt$.js"></script> <script language="JavaScript1.2" type="text/javascript" src="js/01_getViewportWidth.js"></script> <script language="JavaScript1.2" type="text/javascript" src="js/01_getViewportHeight.js"></script> <script language="javascript1.2" type="text/javascript"> function resizeFlash() { try { var oTD = document.getElementById('table_td_movie'); if (!!oTD) { oTD.width = ezGetViewportWidth(); oTD.height = ezGetViewportHeight(); // alert('oTD.width = [' + oTD.width + ']' + ', oTD.height = [' + oTD.height + ']'); } } catch (e) { alert(222); }; } window.onresize = function() { resizeFlash() }; </script> </head> <body> <noscript>You must enable JavaScript to use this site.<br>Please adjust your browser's settings to enable JavaScript or use a browser that supports JavaScript.<br> <a href="http://flashx.ez-ajax.com" target="_blank">flashx.ez-ajax.com</a> </noscript> <script language="javascript1.2" type="text/javascript"> var version = deconcept.SWFObjectUtil.getPlayerVersion(); if (document.getElementById && (version['major'] > 0)) { document.write('<?php print_r(flashContent('ContentContainer', '100%', '100%', '/flash/main/ContentContainer.swf?flashroot=/flash/main/', '#164f9f')); ?>'); resizeFlash(); } else { document.write('<div id="flashcontent" style="position: absolute; width: 100%; height: 100%; z-index: 200;">'); document.write('<strong>You need to upgrade your Flash Player</strong>'); document.write('This is replaced by the Flash content. '); document.write('Place your alternate content here and users without the Flash plugin or with '); document.write('Javascript turned off will see this. Content here allows you to leave out <code>noscript</code> '); document.write('tags. Include a link to <a href="/flash/main/ContentContainer.html">bypass the detection</a> if you wish.'); document.write('</div>'); } </script> </body> </html> <file_sep><?php session_start(); include_once 'Tweetr.php'; error_reporting(E_ERROR); $steps = 8; /** ---------------------------- * HTML Snippets *-----------------------------*/ $header = "<html> <head> <title>TweetrProxy Installation Script</title> <style type='text/css'> body { background-color: #B2B28F; margin: 0; padding: 0; color: #444; font-size: 10px; margin: 5px; font-family: \"Lucida Grande\", Verdana, Helvetica, Arial, sans-serif; font-size: 11px; line-height: 20px;} #contentBox {position: absolute; z-index: 2; top: 50%; left: 50%; margin: -250px 0px 0px -250px; width: 480px; height: 480px; border: solid 1px #000; padding: 10px; background-color: #F2FFCC;} #contentShadow {position: absolute; z-index: 1; top: 50%; left: 50%; margin: -245px 0px 0px -245px; width: 500px; height: 500px; background-color: #464630;} #titleBox {position: absolute; z-index: 0; top: 50%; left: 50%; margin: -283px 0px 0px -250px; width: 500px; height: 50px;} .failed { color: #AA0000; font-weight: bold; } .passed { color: #00AA00; font-weight: bold; } .small { font-size: 85%; text-transform: uppercase; letter-spacing: 1px; color: #20AA81; font-size: 10px; font-family: \"Lucida Grande\", Verdana, Helvetica, Arial, sans-serif; font-weight: 100; } .headline { font-family: Helvetica, Arial, sans-serif; font-size: 25px; font-style: normal; font-weight: bold; text-transform: normal; letter-spacing: -1px; line-height: 1.2em; text-decoration: none; color: #A6BF00; } a { font-family: Helvetica, Arial, sans-serif; font-size: 24px; font-style: normal; font-weight: bold; text-transform: normal; letter-spacing: -1px; line-height: 1.2em; text-decoration: none; color: #8B8B5B; } a:hover { color: #000; } input[type=\"text\"] {background-color:#FFF; border:solid 1px #DDD; font-family:Arial; font-size:11px; height:20px;} </style> </head> <body> <div id=\"contentShadow\">&nbsp;</div> <div id=\"contentBox\">"; $title = "<div class=\"small\" style=\"font-style: italic; text-align: right; float: right;\">(Step $1 of $2)</div> <div class=\"headline\" style=\"margin-bottom: 20px;\">$3</div><div style=\"width: 450px; padding: 15px;\">"; $content = ""; $footer = "</div></div><div id=\"titleBox\" class=\"headline\" style=\"font-style: italic; font-size: 37px; color: #959567; text-align: right;\">TweetrProxy Installation</div></body></html>"; /** --------------------------------- * Procedural Code (ugly i know ;) ) *----------------------------------*/ if (!isset($_GET['step'])) { $titleArr = array(1,$steps,"And so it begins.."); $phpCheck = false; $permCheck = false; $fileCheck = false; $content .= "<div><p>Hi and welcome to the Proxy Setup. Please drop me a line on the <a style=\"font-size: 12px;\" href=\"http://groups.google.com/group/tweetr-as3-library\" target=\"_blank\">Tweetr Library Discussion Group on GoogleGroups</a> if anything goes wrong or breaks during this process.</p></div>"; $content .= "<h2>Requirements Check</h2>"; $content .= "<div style=\"float: left; width: 50%; line-height: 30px; margin-bottom: 30px;\">&bull; PHP 5 or newer<br/>&bull; Read/Write access to install directory<br/>&bull; Read/Write access to index.php<br/>"; $content .= "</div><div style=\"float: left; width: 50%; text-align: center; line-height: 30px; margin-bottom: 30px;\">"; if (phpversion() < 5) { $content .= "<span class=\"failed\">FAILED</span> (".phpversion().")<br/>"; } else { $phpCheck = true; $content .= "<span class=\"passed\">PASSED</span><br/>"; } $fh = @fopen('tmpFile', 'wb'); if (!$fh) { $content .= "<span class=\"failed\">FAILED</span><br/>"; } else { fwrite($fh, 'qwerty'); fclose($fh); if (unlink('tmpFile')) { $permCheck = true; $content .= "<span class=\"passed\">PASSED</span><br/>"; } else { $content .= "<span class=\"failed\">FAILED</span><br/>"; } } $fh = @fopen('index.php', 'a+'); if (!$fh) { $content .= "<span class=\"failed\">FAILED</span><br/>"; fclose($fh); } else { $fileCheck = true; $content .= "<span class=\"passed\">PASSED</span>"; } $content .= "</div>"; if (!$phpCheck) $content .= "<p><strong>Please upgrade your PHP Installation to PHP5 or newer. <a style=\"font-size: 12px;\" href=\"http://www.php.net/downloads.php\" target=\"_blank\">Offical PHP Website</a></strong></p>"; if (!$permCheck) $content .= "<p><strong>Please ensure that the proxy folder has sufficient rights to be read/written to.</strong></p>"; if (!$fileCheck) $content .= "<p><strong>Please ensure that the index.php can be read and written to.</strong></p>"; $content .= "<div style=\"font-style: italic; color: #888;\">Please also verify that your Server is capable of URL Rewriting <i>(mod_rewrite)</i>, since it is a essential part of the Proxy and without it, it just won't work.</div>"; if ($phpCheck && $permCheck && $fileCheck) $content .= "<div style=\"position: absolute; bottom: 5px; right: 10px;\"><a href=\"?step=2\">next »</a></div>"; } else { //--------------------------------- // STEP 2 //--------------------------------- if ($_GET['step'] == 2) { $titleArr = array(2,$steps,"Folders"); $defaultCache = (isset($_POST['cacheFolder'])) ? $_POST['cacheFolder'] : Tweetr::CACHE_DIRECTORY; $defaultTemp = (isset($_POST['tempFolder'])) ? $_POST['tempFolder'] : Tweetr::UPLOAD_DIRECTORY; $content .= "<div><p>The Proxy needs two folders. A cache folder and a temp folder (used by the twitter api profile methods).</p><p>If you would like to name them yourself, please rename them now.</p></div>"; $content .= "<form id=\"pageForm\" method=\"POST\" action=\"?step=2\">\n"; $content .= "<p><strong>Cache Folder:</strong> &nbsp;&nbsp;&nbsp;".pathinfo($_SERVER['PHP_SELF'], PATHINFO_DIRNAME)."/<input style=\"width: 100px;\" name=\"cacheFolder\" type=\"text\" value=\"".$defaultCache."\"></p>"; $content .= "<p><strong>Temp Folder:</strong> &nbsp;&nbsp;&nbsp;&nbsp;".pathinfo($_SERVER['PHP_SELF'], PATHINFO_DIRNAME)."/<input style=\"width: 100px;\" name=\"tempFolder\" type=\"text\" value=\"".$defaultTemp."\"></p>"; $content .= "</form>\n"; $content .= ""; if ($_SERVER['REQUEST_METHOD'] == "POST") { $titleArr = array(2,$steps,"Folder Creation"); $content .= "<br/>Creating \"<i>".pathinfo($_SERVER['PHP_SELF'], PATHINFO_DIRNAME)."/".$_POST['cacheFolder']."</i>\" ... "; if (file_exists($_POST['cacheFolder']) && chmod($_POST['cacheFolder'], 0777)) $content .= "<strong>DONE!</strong>"; else if (mkdir($_POST['cacheFolder'])) $content .= "<strong>CREATED!</strong>"; $content .= "<br/>Creating \"<i>".pathinfo($_SERVER['PHP_SELF'], PATHINFO_DIRNAME)."/".$_POST['tempFolder']."</i>\" ... "; if (file_exists($_POST['tempFolder']) && chmod($_POST['tempFolder'], 0777)) $content .= "<strong>DONE!</strong>"; else if (mkdir($_POST['tempFolder'])) $content .= "<strong>CREATED!</strong>"; $_SESSION['cacheFolder'] = $_POST['cacheFolder']; $_SESSION['tempFolder'] = $_POST['tempFolder']; } if ($_SERVER['REQUEST_METHOD'] == "POST") $content .= "<div style=\"position: absolute; bottom: 5px; right: 10px;\"><a href=\"?step=3\">next »</a></div>"; else $content .= "<div style=\"position: absolute; bottom: 5px; right: 10px;\"><a href=\"javascript:pageForm.submit();\">next »</a></div>"; $content .= "<div style=\"position: absolute; bottom: 5px; left: 10px;\"><a href=\"javascript:history.back();\">« back</a></div>"; } //--------------------------------- // STEP 3 //--------------------------------- else if ($_GET['step'] == 3) { $titleArr = array(3,$steps,".htaccess / crossdomain.xml"); $htaccessPath = $_SERVER['HTTP_HOST'].pathinfo($_SERVER['PHP_SELF'], PATHINFO_DIRNAME)."/.htaccess"; $crossdomainPath = $_SERVER['HTTP_HOST']."/crossdomain.xml"; $content .= "<div><p>The installer will now attempt to write the following files in their respective locations:<pre> ".$htaccessPath." ".$crossdomainPath."</pre><br/> Writing ".$htaccessPath." ... "; $fh = @fopen('.htaccess', 'wb'); if (!$fh) { $content .= "<strong>FAILED! Check write permissions...</strong>"; } else { $rewriteText = '<IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . index.php [L] </IfModule>'; fwrite($fh, $rewriteText); fclose($fh); $content .= "<strong>DONE! </strong>"; } $content .= "<br/>Writing ".$crossdomainPath." ... "; if (!file_exists($_SERVER['DOCUMENT_ROOT']."/crossdomain.xml")) { $fh = @fopen($_SERVER['DOCUMENT_ROOT']."/crossdomain.xml", 'wb'); if (!$fh) { $content .= "<strong>FAILED! Check write permissions...</strong>"; } else { $crossText = '<?xml version="1.0"?> <!-- in case the proxy is not on the same (sub)domain use this crossdomain file as a template. Has to be put to the root folder of your domain. --> <cross-domain-policy> <allow-access-from domain="*" /> <allow-http-request-headers-from domain="*" headers="*"/> </cross-domain-policy>'; fwrite($fh, $crossText); fclose($fh); $content .= "<strong>DONE! </strong>"; } } else { $content .= "<strong>EXISTS.. skipping.. </strong>"; } $content .= "</p></div>"; $content .= "<div style=\"position: absolute; bottom: 5px; right: 10px;\"><a href=\"?step=4\">next »</a></div>"; $content .= "<div style=\"position: absolute; bottom: 5px; left: 10px;\"><a href=\"javascript:history.back();\">« back</a></div>"; } //--------------------------------- // STEP 4 //--------------------------------- else if ($_GET[step] == 4) { $fh = @fopen('index.php', 'wb'); if (!$fh) { $content .= "<strong>FAILED! Check write permissions...</strong>"; } else { $simpleIndex = "<?php include_once 'Tweetr.php'; \$tweetrOptions['baseURL'] = \"".pathinfo($_SERVER['PHP_SELF'], PATHINFO_DIRNAME)."\"; \$tweetr = new Tweetr(\$tweetrOptions); ?>"; fwrite($fh, $simpleIndex); fclose($fh); } $titleArr = array(4,$steps,"Stop! Test Time!"); $content .= "<div><p>We should now be able to retrieve your <a style=\"font-size: 12px;\" href=\"http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-friends_timeline\" target=\"_blank\">friends timeline XML</a> containing status elements. To test this, provide your twitter username & password:</p></div>"; $content .= "<form id=\"pageForm\" method=\"POST\" action=\"?step=4\">\n"; $content .= "<p><strong>Username:</strong> <input style=\"width: 100px;\" name=\"user\" type=\"text\" >&nbsp;&nbsp;"; $content .= "<strong>Password:</strong> <input style=\"width: 100px;\" name=\"pass\" type=\"password\" >&nbsp;<input type=\"submit\" value=\"Test it\"/></p>"; $content .= "</form>\n"; $content .= ""; if ($_SERVER['REQUEST_METHOD'] == "POST") $content .= "<iframe src=\"statuses/friends_timeline.xml?hash=".base64_encode($_POST['user'].":".$_POST['pass'])."\" width=\"100%\" height=\"230\"><p>Your browser does not support iframes.</p></iframe>"; if ($_SERVER['REQUEST_METHOD'] == "POST") $content .= "<div style=\"position: absolute; bottom: 5px; right: 10px;\"><a href=\"?step=5\">next »</a></div>"; else $content .= "<div style=\"position: absolute; bottom: 5px; right: 10px;\"><a href=\"javascript:pageForm.submit();\">next »</a></div>"; $content .= "<div style=\"position: absolute; bottom: 5px; left: 10px;\"><a href=\"javascript:history.back();\">« back</a></div>"; } //--------------------------------- // STEP 5 //--------------------------------- else if ($_GET['step'] == 5) { $titleArr = array(5,$steps,"Have some Options.."); $content .= "<div><p>Hopefully everything went smooth so far? Cool! Last but not least, let's configure some TweetrProxy Options:</p><br/></div>"; $content .= "<h2>Caching</h2>"; $content .= "<form id=\"pageForm\" method=\"POST\" action=\"?step=6\">\n"; $content .= "<script language=\"javascript\"> function toggleInput() { enabler = document.getElementById('cachingEnabled'); expiry = document.getElementById('expiry'); if (enabler.checked == true) expiry.disabled = false; else expiry.disabled = true; } </script>"; $content .= "<strong>Enable caching</strong>&nbsp;&nbsp;<input id=\"cachingEnabled\" type=\"checkbox\" onclick=\"toggleInput();\" name=\"cachingEnabled\" value=\"true\" /><br/>"; $content .= "<strong>Cache expiry: &nbsp;&nbsp;&nbsp;</strong> <input id=\"expiry\" style=\"width: 100px;\" disabled name=\"expiry\" type=\"text\" value=\"".Tweetr::CACHE_TIME."\"> (in seconds)"; $content .= "</form>\n"; $content .= "<div style=\"font-style: italic; color: #888;\">Caching will cache incoming requests for the set amount of time. If the same exact request is being made before the cache expires, the cached response will be returned, in order to prevent unnecessary calls.</div>"; $content .= "<div style=\"position: absolute; bottom: 5px; right: 10px;\"><a href=\"javascript:pageForm.submit();\">next »</a></div>"; $content .= "<div style=\"position: absolute; bottom: 5px; left: 10px;\"><a href=\"javascript:history.back();\">« back</a></div>"; } //--------------------------------- // STEP 6 //--------------------------------- else if ($_GET['step'] == 6 && $_SERVER['REQUEST_METHOD'] == "POST") { $titleArr = array(6,$steps,"Have some Options.."); $_SESSION['cachingEnabled'] = $_POST['cachingEnabled']; $_SESSION['cacheExpiry'] = $_POST['expiry']; $content .= "<h2>Ghosting</h2>"; $content .= "<form id=\"pageForm\" method=\"POST\" action=\"?step=7\">\n"; $content .= "<script language=\"javascript\"> function toggleInput() { enabler = document.getElementById('ghostingEnabled'); if (enabler.checked == true) { document.getElementById('ghostName').disabled = false; document.getElementById('ghostPass').disabled = false; document.getElementById('realUser').disabled = false; document.getElementById('realPass').disabled = false; } else { document.getElementById('ghostName').disabled = true; document.getElementById('ghostPass').disabled = true; document.getElementById('realUser').disabled = true; document.getElementById('realPass').disabled = true; } } </script>"; $content .= "<strong>Enable Ghosting</strong>&nbsp;&nbsp;&nbsp;&nbsp;<input id=\"ghostingEnabled\" type=\"checkbox\" onclick=\"toggleInput();\" name=\"ghostingEnabled\" value=\"true\" /><br/>"; $content .= "<p><strong>Ghost Username:</strong> &nbsp;&nbsp;<input id=\"ghostName\" style=\"width: 100px;\" disabled name=\"ghostName\" type=\"text\" value=\"".Tweetr::GHOST_DEFAULT."\"><br/>"; $content .= "<strong>Ghost Password:</strong> &nbsp;&nbsp;&nbsp;<input id=\"ghostPass\" style=\"width: 100px;\" disabled name=\"ghostPass\" type=\"text\" value=\"".Tweetr::GHOST_DEFAULT."\"></p>"; $content .= "<strong>Real Username:</strong> &nbsp;&nbsp;&nbsp;&nbsp;<input id=\"realUser\" style=\"width: 100px;\" disabled name=\"realUser\" type=\"text\" value=\"\"><br/>"; $content .= "<strong>Real Password:</strong> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input id=\"realPass\" style=\"width: 100px;\" disabled name=\"realPass\" type=\"text\" value=\"\">"; $content .= "</form>\n"; $content .= "<div style=\"font-style: italic; color: #888;\">This allows you to mask/hide the actual username you are going to use.<br/>From your app you pass these ghost credentials and the proxy will recognize that and actually use the userName and userPass supplied instead of the ghost credentials. </div>"; $content .= "<div style=\"position: absolute; bottom: 5px; right: 10px;\"><a href=\"javascript:pageForm.submit();\">next »</a></div>"; $content .= "<div style=\"position: absolute; bottom: 5px; left: 10px;\"><a href=\"javascript:history.back();\">« back</a></div>"; } //--------------------------------- // STEP 7 //--------------------------------- else if ($_GET['step'] == 7 && $_SERVER['REQUEST_METHOD'] == "POST") { $titleArr = array(7,$steps,"Have some Options.."); $_SESSION['ghostingEnabled'] = $_POST['ghostingEnabled']; $_SESSION['ghostName'] = $_POST['ghostName']; $_SESSION['ghostPass'] = $_POST['ghostPass']; $_SESSION['realUser'] = $_POST['realUser']; $_SESSION['realPass'] = $_POST['realPass']; $content .= "<h2>Personalization</h2>"; $content .= "<form id=\"pageForm\" method=\"POST\" action=\"?step=8\">\n"; $content .= "<p><strong>UserAgent:</strong> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input style=\"width: 200px;\" name=\"agentName\" type=\"text\" value=\"".Tweetr::USER_AGENT."\"><br/>"; $content .= "<strong>UserAgent Link:</strong> &nbsp;&nbsp;&nbsp;<input style=\"width: 200px;\" name=\"agentLink\" type=\"text\" value=\"".Tweetr::USER_AGENT_LINK."\"></p>"; $content .= "<strong>Custom Index Page:</strong><br/><textarea name=\"customHTML\" style=\"width: 100%; height: 190px; font-size: 11px;\">your html here</textarea>"; $content .= "</form>\n"; $content .= "<div style=\"font-style: italic; color: #888;\">This allows you to set a custom UserAgent for the Proxy and a Link. And if you want to go all crazy, you can even define your own custom startpage for the proxy.</div>"; $content .= "<div style=\"position: absolute; bottom: 5px; right: 10px;\"><a href=\"javascript:pageForm.submit();\">next »</a></div>"; $content .= "<div style=\"position: absolute; bottom: 5px; left: 10px;\"><a href=\"javascript:history.back();\">« back</a></div>"; } //--------------------------------- // STEP 8 (the end) //--------------------------------- else if ($_GET['step'] == 8 && $_SERVER['REQUEST_METHOD'] == "POST") { $titleArr = array(8,$steps,"Setup Complete"); $_SESSION['cachingEnabled'] = ($_SESSION['cachingEnabled'] == "true") ? "true" : "false"; $_SESSION['cacheExpiry'] = (empty($_SESSION['cacheExpiry'])) ? Tweetr::CACHE_TIME : $_SESSION['cacheExpiry']; $_SESSION['ghostingEnabled'] = ($_SESSION['ghostingEnabled'] == "true") ? "true" : "false"; $_SESSION['ghostName'] = (empty($_SESSION['ghostName'])) ? Tweetr::GHOST_DEFAULT : $_SESSION['ghostName']; $_SESSION['ghostPass'] = (empty($_SESSION['ghostPass'])) ? Tweetr::GHOST_DEFAULT : $_SESSION['ghostPass']; $_SESSION['realUser'] = (empty($_SESSION['realUser'])) ? "your_username" : $_SESSION['realUser']; $_SESSION['realPass'] = (empty($_SESSION['realPass'])) ? "<PASSWORD>" : $_SESSION['realPass']; $customHTML = ($_POST['customHTML'] == "your html here") ? null : $_POST['customHTML']; $fh = @fopen('index.php', 'wb'); if (!$fh) { $content .= "<strong>Oops, couldn't wite to index.php! Check write permissions...</strong>"; } else { $indexText = "<?php include_once 'Tweetr.php'; /** * Tweetr Proxy Class Startpoint * @author <NAME> [swfjunkie.com, Switzerland] * * see http://wiki.swfjunkie.com/tweetr:proxy * on how to use the tweetr php proxy and it's options. */ \$tweetrOptions['baseURL'] = \"".pathinfo($_SERVER['PHP_SELF'], PATHINFO_DIRNAME)."\"; \$tweetrOptions['userAgent'] = \"".$_POST['agentName']."\"; \$tweetrOptions['userAgentLink'] = \"".$_POST['agentLink']."/\";"; if (!empty($customHTML)) { $indexText .= " \$tweetrOptions['indexContent'] = \"".urlencode($customHTML)."\";"; } else { $indexText .= " //\$tweetrOptions['indexContent'] = \"my custom index page\";"; } $indexText .= " //\$tweetrOptions['debugMode'] = true;"; if ($_SESSION['ghostingEnabled'] == "true") { $indexText .= " \$tweetrOptions['ghostName'] = \"".$_SESSION['ghostName']."\"; \$tweetrOptions['ghostPass'] = \"".$_SESSION['ghostPass']."\"; \$tweetrOptions['userName'] = \"".$_SESSION['realUser']."\"; \$tweetrOptions['userPass'] = \"".$_SESSION['realPass']."\";"; } else { $indexText .= " //\$tweetrOptions['ghostName'] = \"".$_SESSION['ghostName']."\"; //\$tweetrOptions['ghostPass'] = \"".$_SESSION['ghostPass']."\"; //\$tweetrOptions['userName'] = \"".$_SESSION['realUser']."\"; //\$tweetrOptions['userPass'] = \"".$_SESSION['realPass']."\";"; } if ($_SESSION['cachingEnabled'] == "true") { $indexText .= " \$tweetrOptions['cache_enabled'] = ".$_SESSION['cachingEnabled']."; \$tweetrOptions['cache_time'] = ".$_SESSION['cacheExpiry']."; \$tweetrOptions['cache_directory'] = \"".$_SESSION['cacheFolder']."\";"; } else { $indexText .= " //\$tweetrOptions['cache_enabled'] = true; //\$tweetrOptions['cache_time'] = 120; // 2 minutes //\$tweetrOptions['cache_directory'] = \"".$_SESSION['cacheFolder']."\";"; } $indexText .= " \$tweetrOptions['upload_directory'] = \"".$_SESSION['tempFolder']."\"; \$tweetr = new Tweetr(\$tweetrOptions); ?>"; fwrite($fh, $indexText); fclose($fh); $content .= "<p><strong>Everything is setup and you are ready to use the Proxy. Awesome! ;)</strong></p> <p>For security reasons, it would be wise to either delete this install script (<i>install.php</i>) or rename it, in case you are considering changing some settings later on.</p> <p>Let me leave you with some Links: <ul> <li><a style=\"font-size: 12px;\" href=\"http://tweetr.swfjunkie.com/\" target=\"_blank\">Tweetr Library Project Homepage</a></li> <li><a style=\"font-size: 12px;\" href=\"http://groups.google.com/group/tweetr-as3-library\" target=\"_blank\">Tweetr Library Discussion Group on Google Groups</a></li> <li><a style=\"font-size: 12px;\" href=\"http://blog.swfjunkie.com\" target=\"_blank\">SWFJunkie (authors blog)</a></li> <li><a style=\"font-size: 12px;\" href=\"http://twitter.com/_sandro\" target=\"_blank\">Author on Twitter (@_sandro)</a></li> </ul></p> <p>Thanks for using the Tweetr Library and remember, if you build something cool, let me know :)</p> <p>Regards,<br/>Sandro</p>"; } $content .= "<div style=\"position: absolute; bottom: 5px; right: 10px;\"><a href=\"".pathinfo($_SERVER['PHP_SELF'], PATHINFO_DIRNAME)."/\">yay finished »</a></div>"; $content .= "<div style=\"position: absolute; bottom: 5px; left: 10px;\"><a href=\"javascript:history.back();\">« back</a></div>"; } else { header("Location: install.php"); } } echo $header; echo str_replace(array("$1", "$2", "$3"), $titleArr, $title); echo $content; echo $footer; ?><file_sep><?php function var_print_r($mixed = null) { ob_start(); print_r($mixed); $content = ob_get_contents(); ob_end_clean(); return $content; } function cdataEscape($datum = "") { return "<![CDATA[ " . $datum . " ]]>"; } function getValueFromArray($k = "",$a = null) { return (($a == null) ? "" : ((array_key_exists($k,$a)) ? $a[$k] : "")); } function getValueFromGetOrPostArray($k = "") { $val = ""; if (strlen($k) > 0) { $val = getValueFromArray($k, $_GET); if (strlen($val) == 0) { $val = getValueFromArray($k, $_POST); } } return $val; } class MSSQLDB { var $db_connection; var $serverName; var $username; var $userPassword; var $status; var $statusMsg; // Constructor function __construct($inDatabaseName, $serverName = "", $username = "", $userPassword = "") { if (strlen($serverName) == 0) { $serverName = "localhost,1433"; } $this->serverName = $serverName; if (strlen($username) > 0) { $this->username = $username; } if (strlen($userPassword) > 0) { $this->userPassword = $userPassword; } $this->db_connection = mssql_connect($this->serverName, $this->username, $this->userPassword); $retVal = mssql_select_db($inDatabaseName); } function sqlEscape($sql) { $fix_str = str_replace("'","''",stripslashes($sql)); $fix_str = str_replace("\0","[NULL]",$fix_str); return $fix_str; } function query_database($inQuery) { // Generic query function // Always include the link identifier (in this case $this->db_connection) in mssql_query $query_result = mssql_query($inQuery, $this->db_connection); if ($query_result == false) { $this->status = -200; $this->statusMsg = 'Query failed: '.$inQuery; return; } if (stripos($inQuery, "insert ") == 0) { $result = array(); // fetch the results as an array while ($row = mssql_fetch_object($query_result)) { $result[] = $row; } return $result; // return result } else { $query = 'select SCOPE_IDENTITY() AS last_insert_id'; // get the last insert id $query_result = mssql_query($query); if ($query_result == false) { $this->status = -201; $this->statusMsg = 'Query failed: '.$inQuery ; return; } $query_result = mssql_fetch_object($query_result); return $query_result->last_insert_id; } } } ?>
f9f02cccf13a4fd4561e74a2e972b78570ca06e1
[ "HTML", "JavaScript", "INI", "Text", "PHP", "Shell" ]
198
PHP
raychorn/svn_php_projects
616e01d6bfd24c7de980f91ef1b07f20c76e959e
9066ab7b04f01c3d59712d3b0f77a0875bf245fd
refs/heads/main
<file_sep>let date = new Date(); document.getElementById('footer-date').innerHTML = date.getFullYear(); $(document).ready(function() { AOS.init(); });
2af9c6b7d777c4c494cda344dd9c75ebd5021db6
[ "JavaScript" ]
1
JavaScript
stefan41/webserver_starter
5552d40bc09fd6c521964d31cf33270be7463666
852370c93e19513ca6219f8129cd7923a7a9715a
refs/heads/master
<repo_name>litalico-internship/201708-team-c<file_sep>/team-c/php/Util.php <?php class Util { // emotion_type -> phrase public static $phrase = array( 'interesting' => '楽しい', 'happy' => 'うれしい', 'sad' => '悲しい', 'tired' => 'つかれる', 'angry' => 'むかつく' ); // emotion_type -> color public static $color = array( 'interesting' => 'yellow', 'happy' => 'green', 'sad' => 'blue', 'tired' => 'purple', 'angry' => 'red' ); public static function setDisplayErr() { // エラー表示設定 ini_set("display_errors", "On"); error_reporting(E_ALL); } public static function sessionStart() { session_start(); session_set_cookie_params(0, '/team-c/team-c/'); } public static function h($str) { return htmlspecialchars($str, ENT_QUOTES, 'UTF-8'); } } ?><file_sep>/team-c/php/postEmotion.php <?php // 投稿された感情をDBに保存 $postEmotion = $_POST[]; ?><file_sep>/team-c/js/post.js function addAlpha(target, alpha_lev) { $(function () { var oldBGColor = target.css('background-color'), newBGColor = oldBGColor.replace(/[^,]+(?=\))/, alpha_lev); console.log(oldBGColor); console.log(newBGColor); target.css({ backgroundColor: newBGColor }); }); } $(function () { $("#select_emotion").change(function () { var color = { interesting: 'yellow', happy: 'green', sad: 'blue', tired: 'purple', angry: 'red' }; var emotion = $("select option:selected").val(); $("body").removeAttr("class"); $("body").removeAttr("style"); $("body").addClass(color[emotion]); $(".submit_emotion").css({ color: " " }); }); $(".input_range").change(function () { var emotion_level = { 1: '0.2', 2: '0.4', 3: '0.6', 4: '0.8', 5: '0.9' }; /* rgba_code = $("body").css('background-color'); //rgba(100,100,100,0.9) console.log('rgba'); console.log(rgba_code); code = rgba_code.match(/(\d+,)+\d*(.\d)/); //'100,100,100,0.9' console.log('code部分'); console.log(code); new_code = code[0].replace(/\d+(\.\d)*$/, '0.2'); //'100,100,100,0.8' //new_code = new_code.match(/\d+(.*)$/)[1].replace(', ', '') //'0.8' console.log('新カラーコード'); console.log(new_code); //codeの '100, 100, 100, 0.8'.replace(/new_code/, '0.5'); $("body").css('background-color').replace(/new_code/, '0.5'); if (rgba_code.match(/\,/).index == 3) { //alphaある前提 } else { //rgbのみの場合 } ; */ addAlpha($("body"), emotion_level[$(this).val()]); }); });<file_sep>/team-c/php/time_line.php <?php require_once realpath(dirname(__FILE__) ) . "/DataBase.php"; require_once realpath(dirname(__FILE__) ) . "/Util.php"; $userId = 1; $db = new DataBase(); // get current emotion type $sql = 'SELECT * FROM emotion_posts ' . 'WHERE user_id = :user_id '. 'ORDER BY created DESC LIMIT 1'; $params = array( 'user_id' => $userId ); $emotionType = $db->query($sql, $params)[0]['emotion_type']; // get same emotion TimeLine $sql = 'SELECT * FROM emotion_posts ' . "WHERE emotion_posts.emotion_type = '". $emotionType ."' ". 'ORDER BY created DESC'; $emotionTL = $db->query($sql); // get current TimeLine $sql = 'SELECT * FROM emotion_posts ' . 'ORDER BY created DESC'; $currentTL = $db->query($sql); ?> <!DOCTYPE html> <head> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>タイムライン</title> <!-- Google Fonts --> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic"> <!-- CSS Reset --> <link rel="stylesheet" href="https://cdn.rawgit.com/necolas/normalize.css/master/normalize.css"> <!-- Milligram CSS minified --> <link rel="stylesheet" href="https://cdn.rawgit.com/milligram/milligram/master/dist/milligram.min.css"> <!-- You should properly set the path from the main file. --> <link rel="stylesheet" type="text/css" href="../css/style.css"> <link rel="stylesheet" type="text/css" href="../css/time_line.css"> <link rel="stylesheet" type="text/css" href="../css/profile.css"> <link rel="stylesheet" type="text/css" href="../css/post.css"> <!-- jQuery --> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="<KEY> crossorigin="anonymous"></script> <!-- original js file --> <script type="text/javascript" src="../js/time_line.js"></script> <script type="text/javascript" src="../js/profile.js"></script> <script type="text/javascript" src="../js/post.js"></script> <!-- fontawesome --> <script src="https://use.fontawesome.com/8135123537.js"></script> </head> <body> <div class="select_time_line"> <a id="current_tl_button" class="button button-outline" href="#">みんなのTL</a> <a id="emotion_tl_button" class="button button-outline" href="#">おんなじTL</a> </div> <!-- みんなのTL --> <div id="current_tl" class="wrapper_time_line"> <?php foreach ($currentTL as $key => $val) : ?> <!--一つのブロック始まり --> <div class="a_block_time_line <?php echo Util::$color[ Util::h($val['emotion_type']) ] . '_' . Util::h($val['level']);?>" > <div class="sentence_time_line"> <a href="profile.php"> <p><?php echo Util::h($val['reason']) . '、' . Util::$phrase[ Util::h($val['emotion_type']) ]; ?></p> </a> </div> <div class="icon_time_line"> <!-- わかる --> <a><i class="fa fa-heart fa-lg" aria-hidden="true"></i></a><span class="reaction_num"><?php echo rand(1,30);?></span> <!-- すごい --> <a><i class="fa fa-thumbs-up fa-lg" aria-hidden="true"></i></a><span class="reaction_num"><?php echo rand(1,30);?></span> <!-- 応援 --> <a><i class="fa fa-flag fa-lg" aria-hidden="true"></i></a><span class="reaction_num"><?php echo rand(1,30);?></span> <!-- コメント --> <a><i class="fa fa-reply fa-lg reply" aria-hidden="true"></i></a><span class="reaction_num"><?php echo rand(1,30);?></span> </div> </div> <!--一つのブロッック終わり --> <?php endforeach ?> </div> <!-- おんなじTL --> <div id="emotion_tl" class="wrapper_time_line"> <?php foreach ($emotionTL as $key => $val) : ?> <!--一つのブロック始まり --> <div class="a_block_time_line <?php echo Util::$color[ Util::h($val['emotion_type']) ] . '_' . Util::h($val['level']);?>" > <div class="sentence_time_line"> <a href="profile.php"> <p><?php echo Util::h($val['reason']) . '、' . Util::$phrase[ Util::h($val['emotion_type']) ]; ?></p> </a> </div> <div class="icon_time_line"> <!-- わかる --> <a><i class="fa fa-heart" aria-hidden="true"></i></a> <!-- すごい --> <a><i class="fa fa-thumbs-up" aria-hidden="true"></i></a> <!-- 応援 --> <a><i class="fa fa-flag" aria-hidden="true"></i></a> <!-- コメント --> <a><i class="fa fa-reply reply" aria-hidden="true"></i></a> </div> </div> <!--一つのブロッック終わり --> <?php endforeach ?> </div> <div class="post_float_button white "> <a href="post.php">+</a> </div> <script type="text/javascript"> function showCurrentTL() { $("#emotion_tl").hide(100); $("#current_tl").show(300); } function showEmotionTL() { $("#current_tl").hide(100); $("#emotion_tl").show(300); } const _click = (window.ontouchstart === undefined)? 'click' : 'touchstart'; $("#current_tl_button").on(_click, showCurrentTL); $("#emotion_tl_button").on(_click, showEmotionTL); const emotionType = '<?php echo $emotionType;?>'; if(emotionType == '') { $("#emotion_tl").hide(); } else { $("#current_tl").hide(); } </script> </body> </html><file_sep>/team-c/php/DataBase.php <?php class DataBase { private static $_connInfo = array( 'host' => 'localhost', 'dbname' => 'team_c', 'dbuser' => 'root', 'password' => '<PASSWORD>' ); private $_pdo; public function __construct() { $this->connectDb(); } public function connectDb() { $dsn = sprintf( 'mysql:host=%s;dbname=%s;port=3306;charset=utf8mb4;', self::$_connInfo['host'], self::$_connInfo['dbname'] ); try { $this->_pdo= new PDO($dsn, self::$_connInfo['dbuser'], self::$_connInfo['password']); } catch(PDOException $e) { die($e->getMessage()); } } // クエリを実行 /* how to use $sql = 'SELECT id, name, older FROM table_name WHERE id = :user_id'; $params = array( 'user_id' => $userId ); $data = $this->query($sql, $params); */ public function query($sql, array $params = array()) { $stmt = $this->_pdo->prepare($sql); if ($params != null) { // プレースホルダの数が静的に決まる foreach ($params as $key => $val) { $stmt->bindValue(':' . $key, $val); } } $stmt->execute(); $rows = $stmt->fetchAll(); return $rows; } // INSERTを実行 /* how to use $data = array( 'id' => $userId, 'name' => $userName, 'older' => $userOlder ); $res = $this->insert('table_naem', $data); */ public function insert($table, $data) { $fields = array(); $values = array(); foreach ($data as $key => $val) { $fields[] = $key; $values[] = ':' . $key; } $sql = sprintf( "INSERT INTO %s (%s) VALUES (%s)", $this->name, implode(',', $fields), implode(',', $values) ); $stmt = $this->_pdo->prepare($sql); foreach ($data as $key => $val) { $stmt->bindValue(':' . $key, $val); } $res = $stmt->execute(); return $res; } } ?>
5fd4da928deb409ebe83faca2261b5daffe82927
[ "JavaScript", "PHP" ]
5
PHP
litalico-internship/201708-team-c
4d90edc1f9ef0c4709ac0887fbd804fe4830b347
4c1f19f40081eb38471d435d431f0b8765ec3faa
refs/heads/master
<file_sep>################################################################################ # # Class: Stream Health Parser # # This class takes a file handler, and reads every line of the file. With each line # it creates a LiveStat object and saves them in an array. # ################################################################################ # # NOTES: # # 7 different 'LiveStats' log statement categories: # # 'SD' - System Details # 'CD' - connection meta details # 'CN' - cell connection network stats # 'WF' - wifi network stats # 'CX' - connection transmission stats # 'EN' - encoder/video stats # 'GP' - GPS data # ################################################################################ class StreamHealthParser def initialize(fileHandler) @live_stats = Array.new @lost_frames = 0 @total_time = nil start_time = "" end_time = "" current_frame_size = nil current_frame_size_start_time = nil frame_size_changes = 0 max_connection_bitrate = 0 # Metrics @frame_lost_metric = 0 @frame_size_change_metric = 1 @frame_size_metric = 0 @overall_health = "Poor" current_category_hash = {"SD"=>nil,"CD"=>nil,"CN"=>nil,"WF"=>nil,"CX"=>nil,"EN"=>nil,"GP"=>nil} frame_size_hash = {"180"=>0, "240"=>0, "all-other"=>0} fileHandler.each_line do |line| live_stat = LiveStat.new(line) if live_stat.category == "SD" && live_stat.data["Action"] == "APP.STARTUP" start_time = live_stat.timestamp end if live_stat.category == "SD" && live_stat.data["Action"] == "APP.SHUTDOWN" end_time = live_stat.timestamp @total_time = calculate_total_time(start_time, end_time) end # Filter out anything within the first 30 seconds if is_within_x_seconds(start_time, live_stat.timestamp, 30) == false # Filter out excess live_stats if current_category_hash[live_stat.category] == nil || is_within_x_seconds(current_category_hash[live_stat.category].timestamp, live_stat.timestamp, 5) == false # Not within 5 seconds OR # there is no current live_stat for this category THEREFORE # save this live stat in my array AND make it the current live stat current_category_hash[live_stat.category] = live_stat @live_stats.push(live_stat) if live_stat.category == "EN" if(live_stat.data[:number_of_lost_video_frames].to_i > 0) @lost_frames += 1 end end if live_stat.category == "CX" # puts "Target: #{live_stat.data["TargetBPS"]} Smooth: #{live_stat.data["ReceivedBPS-Smoothed"]} Instant: #{live_stat.data["ReceivedBPS-Instantaneous"]}" if live_stat.data[:received_bps_smoothed].to_i > max_connection_bitrate max_connection_bitrate = live_stat.data[:received_bps_instantaneous].to_i end end end if live_stat.category == "EN" if live_stat.data["LiveVideo"] != nil live_video_data = live_stat.data["LiveVideo"] frame_size = parse_frame_size(live_video_data) if current_frame_size == nil current_frame_size = frame_size current_frame_size_start_time = live_stat.timestamp elsif current_frame_size != frame_size # Get time in current frame size and add those seconds to the hash time_in_frame = calculate_total_time current_frame_size_start_time, live_stat.timestamp seconds_in_frame = time_in_frame[1] + (time_in_frame[0] * 60) if current_frame_size == "180" frame_size_hash["180"] += seconds_in_frame.to_i elsif current_frame_size == "240" frame_size_hash["240"] += seconds_in_frame.to_i else frame_size_hash["all-other"] += seconds_in_frame.to_i end current_frame_size = frame_size current_frame_size_start_time live_stat.timestamp frame_size_changes += 1 end end end end if @total_time != nil # Shutdown message was recieved # Add last frame size time to hash time_in_frame = calculate_total_time current_frame_size_start_time, live_stat.timestamp seconds_in_frame = time_in_frame[1] + (time_in_frame[0] * 60) if current_frame_size == "180" frame_size_hash["180"] += seconds_in_frame.to_i elsif current_frame_size == "240" frame_size_hash["240"] += seconds_in_frame.to_i else frame_size_hash["all-other"] += seconds_in_frame.to_i end end end # Calculations @frame_lost_metric = 0.5 ** @lost_frames.to_f total_seconds = @total_time[1].to_i + (@total_time[0] * 60).to_i frame_size_changes_per_second = frame_size_changes / total_seconds @frame_size_change_metric = 1.0 - frame_size_changes_per_second.to_f k = calculate_k max_connection_bitrate @frame_size_metric = k.to_f * total_seconds.to_f / (16.0 * frame_size_hash["180"].to_f + 8.0 * frame_size_hash["240"].to_f + frame_size_hash["all-other"].to_f) least_value = [@frame_lost_metric, @frame_size_change_metric, @frame_size_metric].min percentage = least_value * 100 if percentage >= 90 @overall_health = "Good" elsif percentage < 90 && percentage >= 25 @overall_health = "Marginal" end fileHandler.close end # GETTERS def live_stats return @live_stats end def lost_frames return @lost_frames end def stats_text return "Lost Frames: #{@lost_frames}" end def total_time return @total_time end # GET METRICS def frame_lost_metric return @frame_lost_metric end def frame_size_change_metric return @frame_size_change_metric end def frame_size_metric return @frame_size_metric end def overall_health return @overall_health end private # HELPERS def to_s return "Live Stats: #{@live_stats}, Lost Frames: #{@lost_frames}" end def get_minimum_time(timestamp) time_pieces = timestamp.to_s.split(".") minutes = Integer(time_pieces[0]) seconds = Integer(time_pieces[1]) if seconds < 30 time_pieces[1] = (seconds += 30).to_s elsif seconds == 30 time_pieces[1] = "00" time_pieces[0] = (minutes += 1).to_s else time_pieces[1] = (seconds -= 30).to_s time_pieces[0] = (minutes += 1).to_s end return time_pieces.join(".") end # Check to see if a two timestamps are within x seconds of each other def is_within_x_seconds(start_time, end_time, x_seconds) result = false start_time_pieces = start_time.split(".") end_time_pieces = end_time.split(".") start_time_minutes = start_time_pieces[0].to_i start_time_seconds = start_time_pieces[1].to_i end_time_minutes = end_time_pieces[0].to_i end_time_seconds = end_time_pieces[1].to_i if(end_time_seconds <= start_time_seconds) end_time_seconds += 60 end_time_minutes -= 1 end total_minutes = end_time_minutes - start_time_minutes total_seconds = end_time_seconds - start_time_seconds if(total_seconds >= 60) total_seconds -= 60 total_minutes += 1 end if total_minutes > 0 || total_seconds >= x_seconds result = false elsif total_minutes == 0 && total_seconds < x_seconds result = true end result end # Calculate total time of stream def calculate_total_time(start_time, end_time) start_time_pieces = start_time.split(".") end_time_pieces = end_time.split(".") start_time_minutes = start_time_pieces[0].to_i start_time_seconds = start_time_pieces[1].to_i end_time_minutes = end_time_pieces[0].to_i end_time_seconds = end_time_pieces[1].to_i if(end_time_seconds < start_time_seconds) end_time_seconds += 60 end_time_minutes -= 1 end total_minutes = end_time_minutes - start_time_minutes total_seconds = end_time_seconds - start_time_seconds if(total_seconds >= 60) total_seconds -= 60 total_minutes += 1 end total_time = [total_minutes, total_seconds] end def parse_frame_size(video_data) x_index = video_data.index("x") + 1 t_index = video_data.index("t") frame_size = video_data[x_index, t_index - x_index] return frame_size end def calculate_k(max_connection_bitrate) k = 0 if max_connection_bitrate <= 500000 k = 16 elsif max_connection_bitrate <= 1100000 k = 8 else k = 1 end return k end end<file_sep>=begin Stream Health Parser - Get file - Create file handler - Pass it to the StreamHealthParser object =end require_relative 'StreamHealthParser' require_relative 'LiveStat' messages_on = false filename = ARGV.first if filename == nil print "File name: " filename = gets.chomp end if !File.exists? filename puts "Sorry, the file could not be opened or found. Please make sure it exists. Have a great day!" exit end file = File.open(filename, "r") stream = StreamHealthParser.new(file) puts "Stream health: #{stream.overall_health}" if messages_on puts "\n" puts "Frame loss metric: #{stream.frame_lost_metric}" puts "Frame size change metric: #{stream.frame_size_change_metric}" puts "Frame size metric: #{stream.frame_size_metric}" end puts "\n"<file_sep>################################################################################ # Class: LiveStat # # This class takes a single line from the log file in the initialization # of the object, and parses it into a few different attributes. They include: # @timestamp # @software_version # @category # @data # # All these attributes have "Getters" so they can be used by the main application ################################################################################ # NOTES: # # 7 different 'LiveStats' log statement categories: # # 'SD' - System Details # 'CD' - connection meta details # 'CN' - cell connection network stats # 'WF' - wifi network stats # 'CX' - connection transmission stats # 'EN' - encoder/video stats # 'GP' - GPS data # # All 'LiveStats' logs lines start the same: # i ii iii # |-------- |-------- |-- # 53.38.818 3.1.0.DEV LVST SD # # i - timestamp (UTC) [format: MM.SS.mil] # ii - Tx software version # iii - LiveStats category: [SD|CD|CN|WF|CX|EN|GP] ################################################################################ class LiveStat public def initialize(line) @line = line pieces = @line.split(" "); @timestamp = pieces[0] @software_version = "#{pieces[1]} #{pieces[2]}" @category = pieces[3] @data = Hash.new() # Create data string data_string = "" counter = 4 while counter < pieces.count data_string << "#{pieces[counter]} " counter += 1 end # Remove trailing space data_string = data_string.strip! case @category when "SD" process_sd(data_string) when "CD" process_cd(data_string) when "CN" process_cn(data_string) when "WF" process_wf(data_string) when "CX" process_cx(data_string) when "EN" process_en(data_string) when "GP" process_gp(data_string) end end # GETTERS def timestamp return @timestamp end def software_version return @software_version end def category return @category end def data return @data end # SETTERS def timestamp=(value) return @timestamp end def software_version=(value) return @software_version end def category=(value) return @category end # PUBLIC FUNCTIONS def to_s return "Timestamp: #{@timestamp}, Software Version: #{@software_version}, Category: #{@category}, Data: #{@data}" end private # HELPERS def parse_data_container(data_container) data_stripped = data_container.tr('[]', '') data_pieces = data_stripped.split('|') return data_pieces end def parse_key_value(key_value) pieces = key_value.split("=") if pieces.count > 0 pair = { pieces[0] => pieces[1] } else pair = nil end return pair end ################################################### # 'SD' - System Details ################################################### # Info: High-level system info/events # Frequency: On demand # # Examples: # 40.34.992 3.1.0.DEV LVST SD [CoreState=DCTxS_STARTUP_CONNECTION_DIAL] # 40.35.098 3.1.0.DEV LVST SD [Action=APP.STARTUP] # 00.41.595 3.1.0.DEV LVST SD [Action=STREAM.START|GTG=3000] # # One [Action=X] per SD line. # Valid options: # # [Action=<action>] where <action> = 'APP.STARTUP' -> Tx App startup # 'APP.SHUTDOWN' -> Tx App shutdown # 'STREAM.START|GTG=x' -> Live Stream Start (with GTG @ X milliseconds) # 'STREAM.STOP' -> Live Stream Stop # 'SNF.START' -> S&F Clip Transfer Start # 'SNF.STOP' -> S&F Clip Transfer Stop # 'FT.START' -> File Transfer Start # 'FT.STOP' -> File Transfer Stop ################################################### def process_sd(data) if !data return false end data_containers = data.split("] [") data_containers.each do |container| data_pieces = parse_data_container(container) data_pieces.each do |piece| pair = parse_key_value(piece) if pair != nil @data.merge!(pair) end end end end ################################################### # 'CD' - connection meta details ################################################### # Info: Connection/Network Interface details (i.e. modem type/model/firmware/imei) # Frequency: Once, as soon as NI connects. # # Examples: # 40.55.084 3.1.0.DEV LVST CD [0|9|ETHERNET] [NI.Type=ETH] [NI.Name=Intel(R) 82579V Gigabit Network Connection] # 40.55.229 3.1.0.DEV LVST CD [1|9|WLAN] [NI.Type=WFI] [NI.Name=ASUS EZ N 802.11b/g/n Wireless USB Adapter] # 40.57.104 3.1.0.DEV LVST CD [3|9|UMTS] [NI.Type=CEL] [NI.Name=Sierra Wireless HSPA Modem #2] [Modem.CellType=CTYPE__GSM] [Modem.Model=MC7700] [Modem.SN=012626000053064] [Modem.Manufacturer=Sierra Wireless, Incorporated] [Modem.FW=SWI9200X_03.05.20.05ap r5847 carmd-en-10527 2013/06/21 17:02:10] [Modem.AttachedToUSBExtender=false] [SIM.Carrier=Telus] [SIM.ICCID=8912230000010823953] [SIM.IMSI=302220000812419] # | | | | # | | | Start of [Key=Value] list # | | | # | | Connection Type (valid options: [CELL|UMTS|CDMA|ETHERNET|WLAN|IPHONE|MB_ETH|RNDIS_ETH]) # | | # | Connection Generation # (i.e. misc session data id) (re-generated on each new connection index mapping) # | # Connection # (same # in Tx UI and Graph logs) # # Valid Keys: # 'NI.Type' -> Network interface type. With values: [CEL|ETH|WFI|NDS|MB] # 'NI.Name' -> Network interface name. (i.e. Windows device friendly name) # 'Modem.CellType' -> Modem Cell Type. With values: [CTYPE__GSM|CTYPE__CDMA|CTYPE__UNKNOWN] # 'Modem.Model' -> Modem model. # 'Modem.SN' -> Modem Serial # (IMEI if CellType==CTYPE__GSM; ESN if CellType=CTYPE__CDMA) # 'Modem.Manufacturer' -> Modem Manufacturer # 'Modem.FW' -> Modem firmware revision # 'Modem.AttachedToUSBExtender' -> bool (true|false) -> whether or not this modem is attached to a connected USB Extender # 'SIM.Carrier' -> SIM/account carrier name # 'SIM.ICCID' -> SIM ICCID # 'SIM.IMSI' -> SIM IMSI ################################################### def process_cd(data) if !data return false end data_containers = data.split("] [") data_containers.each do |container| if container.index('=') != nil data_pieces = parse_data_container(container) data_pieces.each do |piece| pair = parse_key_value(piece) if pair != nil @data.merge!(pair) end end else data_pieces = parse_data_container(container) @data[:connection_number] = data_pieces[0] @data[:onnection_generation] = data_pieces[1] @data[:connection_type] = data_pieces[2] end end end ################################################### # 'CN' - cell connection network stats # ################################################### # Info: Cell Connection Network stats # Frequency: Every 10 seconds # Example: # # data [E-P] is in KEY=VALUE format ('KEY' strings are constant) # A B C D E F G H I J K L M N O # | | |--- |-------------------- |-------- |------- |------- |------ |------------------------ |------------ |------ |------ |-------- |--------------- |------ # 54.53.502 3.1.0.DEV LVST CN [1|9|UMTS] [STATUS=NIS__CONNECTED|CTECH=LTE|RSSI=-65|RSCP=-77|PSC=224|NREG=NREG_REGISTERED_HOME|PROVIDER=Bell|MCC=302|MNC=610|LAC=55510|CellID=138861314|TEMP=31] # # A - connection number/index # B - connection generation number (i.e. misc data session id) # C - Connection Type (valid options: [CELL|UMTS|CDMA|ETHERNET|WLAN|IPHONE|MB_ETH|RNDIS_ETH]) # D - network interface status. options: # "NIS__UNKNOWN" # "NIS__NOT_PRESENT" # "NIS__NO_SIM" # "NIS__SIM_LOCKED" # "NIS__SIM_ERROR" # "NIS__INVALID_APN" # "NIS__DISABLED" # "NIS__INITIALIZING" # "NIS__SEARCHING" # "NIS__CONNECTING" # "NIS__CONNECTED" # "NIS__DISCONNECTING" # "NIS__DISCONNECTED" # "NIS__RESETTING" # E - cell technology. options: # "NONE" # "GPRS" # "EDGE" # "UMTS" # "HSDPA" # "HSUPA" # "HSPA" # "HSPA+" # "LTE" # "CDMA_1X" # "CDMA_1XEVDO" # "CDMA_1XEVDOrA" # "CDMA_1XEVDOrB" # "CDMA_1XEVDV" # "CDMA_3XRTT" # "CDMA_UMB" # F - RSSI (dBm) # G - RSCP = Received Signal Code Power (dBm) # H - PSC = Primary Scrambling Code # I - network registration. options: # "NREG_UNKNOWN" # "NREG_NOT_REGISTERED" # "NREG_SEARCHING" # "NREG_REGISTERED_HOME" # "NREG_REGISTERED_ROAMING" # "NREG_DENIED" # J - Network Provider # K - MCC (Network) # L - MNC (Network) # M - LAC (Network) # N - CellID (Network) # O - modem temperature (C) ################################################### def process_cn(data) if !data return false end data_containers = data.split("] [") data_containers.each do |container| if container.index('=') != nil data_pieces = parse_data_container(container) data_pieces.each do |piece| pair = parse_key_value(piece) if pair != nil @data.merge!(pair) end end else data_pieces = parse_data_container(container) @data[:connection_number] = data_pieces[0] @data[:connection_generation] = data_pieces[1] @data[:connection_type] = data_pieces[2] end end end ################################################### # 'WF' - wifi network stats ################################################### # Info: WiFi network status # Frequency: Every 10 seconds # # /------------------------------------------------------ 'Development' ------------------------------------------------------------\ /-------------------------------------------------------- 'Production' ----------------------------------------------------------\ /---------------------- 'DejNAB2.4' -----------------------\ /------------------------------------------------------ 'Administration' ------------------------------------------------------------\ /------------------------------------------ 'GuestsOfDejero' ---------------------------------------------\ /-------------------- 'SqueezeBox' -------------------------\ # A B C D f g h i j k l k l k l k l f g h i j k l k l k l k l f g h i j k l f g h i j k l k l k l k l f g h i j k l k l k l f g h i j k l # | | | | |- |---------- |-- |------- | |---------------- |-- |---------------- |-- |---------------- |-- |---------------- |-- |- |--------- |-- |------- | |---------------- |-- |---------------- |-- |---------------- |-- |---------------- |-- |- |-------- |-- |------- | |---------------- |-- |- |------------- |-- |------- | |---------------- |-- |---------------- |-- |---------------- |-- |---------------- |-- |- |------------- |-- |--- | |---------------- |-- |---------------- |-- |---------------- |-- |- |------------- |-- |--- | |---------------- |-- # 19.51.334 3.1.0.DEV LVST WF [ASUS EZ N 802.11b/g/n Wireless USB Adapter|6] [Connected=true(Development)] [23|Development|-50|WPA2-PSK|BSSIDs=4=[24-A4-3C-16-6D-81(-49);24-A4-3C-16-60-E1(-65);24-A4-3C-16-69-41(-71);24-A4-3C-16-68-C1(-72);]] [24|Production|-54|WPA2-PSK|BSSIDs=4=[24-A4-3C-16-6D-82(-49);24-A4-3C-16-69-42(-71);24-A4-3C-16-60-E2(-65);24-A4-3C-16-68-C2(-73);]] [24|DejNAB2.4|-54|WPA2-PSK|BSSIDs=1=[10-FE-ED-E5-E6-33(-49);]] [25|Administration|-54|WPA2-PSK|BSSIDs=4=[24-A4-3C-16-6D-80(-49);24-A4-3C-16-69-40(-71);24-A4-3C-16-60-E0(-66);24-A4-3C-16-68-C0(-73);]] [26|GuestsOfDejero|-54|OPEN|BSSIDs=3=[24-A4-3C-16-6D-83(-49);24-A4-3C-16-69-43(-71);24-A4-3C-16-60-E3(-65);]] [26|SqueezeBox|-62|WPA2-PSK|BSSIDs=1=[A0-F3-C1-2B-C9-91(-57);]] # # A - WiFi interface name # B - the number of wifi networks scanned and reported on this line # C - connected status [Connected=true|false] # D - currently connected SSID: # if connected: "[Connected=true(D)]" # otherwise: "[Connected=false()]" # # then for each wifi network (data for up to B networks follows): # (data for each wifi network within []) # f - time (ms) since this network was detected. So, this network data was from time point (i - f). # g - SSID # h - RSSI (dBm) # i - authentication method # j - # of BSSID's detected on this wifi ap # # then for each BSSID reported for this wifi ap: BSSID(RSSI); # (semicolon-delimited list within []) # k - BSSID # l - RSSI (dBm) # [f-l] is reported for each wifi network ################################################### def process_wf(data) if !data return false end data_containers = data.split("] [") if data_containers[0] data_pieces = parse_data_container(data_containers[0]) @data[:wifi_interface_name] = data_pieces[0] @data[:count_wifi_networks_scanned] = data_pieces[1] # @data.merge! ({"WifiInterfaceName" => data_pieces[0]}) # @data.merge! ({"CountWifiNetworksScanned" => data_pieces[1]}) end if data_containers[1] data_pieces = parse_data_container(data_containers[1]) data_pieces.each do |piece| pair = parse_key_value(piece) if pair != nil @data.merge!(pair) end end end if data_containers.count > 2 # We have a list of wifi connections - let's parse them wifi_connections = Hash.new counter = 3 while counter < data_containers.count wifi_connection = Hash.new connection = data_containers[counter].tr_s(']]', ']') wifi_connection_pieces = connection.split("|") wifi_connection[:time_since_detected] = wifi_connection_pieces[0] wifi_connection[:ssid] = wifi_connection_pieces[1] wifi_connection[:rssi] = wifi_connection_pieces[2] wifi_connection[:authentication_method] = wifi_connection_pieces[3] bssids_pieces = wifi_connection_pieces[4].split("=") wifi_connection[:bssids_count] = bssids_pieces[1] bssids_string = bssids_pieces[2].tr('[]', '') wifi_connections[:bssids] = bssids_string @data.merge! (wifi_connection) counter += 1 end end end ################################################### # 'CX' - connection transmission stats ################################################### # Info: Connection transmission stats # Frequency: Every 1 second while streaming (reduced to every 10 seconds while Tx is Idle) # # Examples: # A B C D E F G H I J K L M N O # | |- | |------ |---- |----- |---- | | |----- |------ | |------ |------ |--- # 56.14.406 3.1.0.DEV LVST CX [1|10|6|2500000|33.00|100.00|22.14|0| 7|1.5841|5000000|0|2615747|2603464|1.00] # 56.43.315 3.1.0.DEV LVST CX [0|10|6|2500000|44.58|100.00|32.90|0|10|1.0615|5000000|0|2549270|2569112|1.00] # # 0 A - connection number/index # 1 B - connection generation number (i.e. misc data session id) # 2 C - Connection State (0=INITIALIZING; 1=DIALING; 2=IDLE; 3=TIME_SYNC; 4=TESTING; 5=EMERGENCY; 6=ACTIVE; 7=DEAD; 8=SHUTTING_DOWN) # 3 D - Target BPS # 4 E - 2 Sigma Latency (ms) # 5 F - Stream Health % [0, 100] # 6 G - Mean Latency (ms) # 7 H - Missing packet count # 8 I - total packet count # 9 J - latency jitter (ms) # 10 K - CAThresh BPS (Congestion Avoidance Threashold BPS) # 11 L - Remote Control BPS # 12 M - Received BPS (smoothed) # 13 N - Received BPS (instantaneous) # 14 O - Reliability % [0.0, 1.0] # NOTE: Data [A-O] delimited by '|' within [] ################################################### def process_cx(data) if !data return false end data_containers = data.split("] [") data_containers.each do |container| data_pieces = parse_data_container(container) @data[:connection_number] = data_pieces[0] @data[:generation_number] = data_pieces[1] @data[:connection_state] = data_pieces[2] @data[:target_bps] = data_pieces[3] @data[:sigma_latency] = data_pieces[4] @data[:stream_health_percentage] = data_pieces[5] @data[:mean_latency] = data_pieces[6] @data[:missing_packetCount] = data_pieces[7] @data[:total_packet_count] = data_pieces[8] @data[:latency_jitter] = data_pieces[9] @data[:cathresh_bps] = data_pieces[10] @data[:remote_control_bps] = data_pieces[11] @data[:received_bps_smoothed] = data_pieces[12] @data[:received_bps_instantaneous] = data_pieces[13] @data[:reliability] = data_pieces[14] end end ################################################### # 'EN' - encoder/video stats: ################################################### # Info: Encoder/video stats (while transmitting) # Frequency: Every 1 second while streaming # # Example: # A B C D E F G H I J K L M N O P # |-- |------ | |------ |------ |----- | | |--- |-- | | | |------- |-------------------------------------------------- |--------------------------------------------- # 56.15.732 3.1.0.DEV LVST EN [174|5000000|0|4038667|4009768|128144|0|*|7498|100|0|0|0|0.831324] [LiveVideo=1920x1080t@29.97(30000/1001)|h264|yuv420p] [LiveAudio=48000Hz|stereo(2)|opus|s16|(1000|20)] # # 0 A - StreamID # 1 B - Total Target BPS (all connections) # 2 C - Backlog BPS # 3 D - Encoder BPS (what we tell the encoder) # 4 E - Video BPS # 5 F - Audio BPS # 6 G - Encoder BPS (bitrate read back from the encoder) # 7 H - encoder mode (A=audio-only mode; K=keyframe-only mode; *=audio&video) # 8 I - total broadcast time (ms) # 9 J - network health % / buffer fill % [0,100] # 10 K - IFB GTG delay (ms) # 11 L - IFB sound level (percentage) # 12 M - num lost video frames (reported from Server: StatReport::GetNumLostVideoFrames()) # 13 N - video SSIM % [0,1] (1-second rolling average) # # O - Optional additional Video parameters: # [LiveVideo=X] # -where X is the current live video transport format # -this is added on demand when the transport format changes # # P - Optional additional Audio parameters: # [LiveAudio=X] # -where X is the current live audio transport format # -this is added on demand when the transport format changes # # NOTE: Data [A-N] delimited by '|' within [] ################################################### def process_en(data) if !data return false end data_containers = data.split("] [") if data_containers[0] data_pieces = parse_data_container(data_containers[0]) @data[:stream_id] = data_pieces[0] @data[:total_target_bps] = data_pieces[1] @data[:backlog_bps] = data_pieces[2] @data[:encoder_bps_to] = data_pieces[3] @data[:video_bps] = data_pieces[4] @data[:audio_bps] = data_pieces[5] @data[:encoder_bps_from] = data_pieces[6] @data[:encoder_mode] = data_pieces[7] @data[:total_broadcast_time] = data_pieces[8] @data[:network_health] = data_pieces[9] @data[:ifbgtg_delay] = data_pieces[10] @data[:ifb_sound_level] = data_pieces[11] @data[:number_of_lost_video_frames] = data_pieces[12] @data[:video_ssim] = data_pieces[13] end if data_containers[1] data = data_containers[1].tr('[]', '') pair = parse_key_value(data) @data.merge! pair end if data_containers[2] data = data_containers[1].tr('[]', '') pair = parse_key_value(data) @data.merge! pair end end ################################################### # 'GP' - GPS data ################################################### # Info: GPS related info # Frequency: Every 10 seconds # # Examples: # 56.35.632 3.1.0.DEV LVST GP [0|10|UMTS] [State=Idle|NumSatellites=0] # 56.35.767 3.1.0.DEV LVST GP [1|10|UMTS] [State=Fix|NumSatellites=8|Latitude=43.482953|Longitude=-80.537306|HAccuracy=57.69|Altitude=299.00|VAccuracy=24.00|Speed=0.00|Direction=155.30|FixTime=1415138182] # # Valid Keys: # 'State' -> [Idle|Searching|Fix|Disabled|Error|Unknown] # 'Latitude' -> # 'Longitude' -> # 'HAccuracy' -> m # 'Altitude' -> m # 'VAccuracy' -> m # 'Speed' -> m/s # 'Direction' -> degrees # 'NumSatellites' -> number of satellites used to provide GPS fix # 'FixTime' -> absolute, SECONDS since (Linux) EPOCH [Jan. 1, 1970] UTC ################################################### def process_gp(data) if !data return false end data_containers = data.split("] [") data_containers.each do |container| if container.index('=') != nil data_pieces = parse_data_container(container) data_pieces.each do |piece| pair = parse_key_value(piece) if pair != nil @data.merge!(pair) end end else data_pieces = parse_data_container(container) @data.merge! ({"ConnectionNumber" => data_pieces[0]}) @data.merge! ({"ConnectionGeneration" => data_pieces[1]}) @data.merge! ({"ConnectionType" => data_pieces[2]}) end end end end<file_sep>Stream Health Parser | Notes To run: just run parsestreamhealth.rb <file name> If no file name is included, it will ask for one. Currently handles one file, but that can be adjusted. Algorithm Identify - Frame loss events - Frame size change events Pre-filter - Coalesce events of the same type that are <5 seconds apart < Saving the timestamp for each type of event, and ignoring events that follow within 5 seconds, then saving a new timestamp when an event outside of 5 seconds is found > - Filter out events in the first 30 seconds < Saving timestamp from Action=APP.STARTUP event, and ignoring events for the first 30 seconds thereafter > - Filter out streams shorter than 1 minute < Not technically being done, but can easily be done in the parsestreamhealth.rb file. Just check the total_time attribue of the stream object > Calculate metric from filtered events - Count # of frame loss events < Counting number of events that have the category "EN" and whose "NumberOfLostVideoFrames" isn't 0. Not adding up the number of lost frames > - FrameLossMetric = (0.5)# of frame loss events - Calculate peak frame size change events per second (expected to be [0,1]) < Line 105 increments a counter every time the frame size changes and then line 130 calculates the changes/second by dividing the number of changes by the total number of seconds > - FrameSizeChangeMetric = 1.0 - (change events per second) - Calculate amount of time at each frame size - FrameSizeMetric = k*(total stream duration)/[16*(time at 180p)+ 8*(time at 240p) + (time at all other frame sizes)] - Where < MaxConnectionBitrate is being determined by a "CX" live stat with the greatest "Received BPS (smoothed)" attribute. Can be easily edited on lines 77 and 78 > k == 16 if MaxConnectionBitrate <= 500000 k == 8 if 500000 <= MaxConnectionBitrate < 1100000 k == 1 otherwise < Not really sure what MIN() is, appears to be a function, but I'm not sure. See lines 137 and 138 for determing percentage of stream health > - OverallHealthMetric = MIN(FrameLossMetric,FrameSizeChangeMetric, FrameSizeMetric) - Good: 90% <= OverallHealthMetric - Marginal: 25% <= OverallHealthMetric < 90% - Poor: 0% <= OverallHealthMetric < 25%
2cb92f7c6e95420a0d1705db21dd5ff86c6854b7
[ "Text", "Ruby" ]
4
Ruby
QuinnAtDejero/stream-health-parser
2ca2db131fcdf1ae8144d72fe3bd880c5deed56b
be18c664bf29bc300e4df3921c5f105d9182aa22
refs/heads/master
<file_sep>const tab1 = $('.tab-1'); const tab2 = $('.tab-2'); const tab3 = $('.tab-3'); const tab4 = $('.tab-4'); const content1 = $('.contents-container-1'); const content2 = $('.contents-container-2'); const content3 = $('.contents-container-3'); const content4 = $('.contents-container-4'); tab1.on('click', () => { tab1.addClass('active'); content1.removeClass('hidden'); tab2.removeClass('active'); content2.addClass('hidden'); tab3.removeClass('active'); content3.addClass('hidden'); tab4.removeClass('active'); content4.addClass('hidden'); }) tab2.on('click', () => { tab2.addClass('active'); content2.removeClass('hidden'); tab1.removeClass('active'); content1.addClass('hidden'); tab3.removeClass('active'); content3.addClass('hidden'); tab4.removeClass('active'); content4.addClass('hidden'); }) tab3.on('click', () => { tab3.addClass('active'); content3.removeClass('hidden'); tab1.removeClass('active'); content1.addClass('hidden'); tab2.removeClass('active'); content2.addClass('hidden'); tab4.removeClass('active'); content4.addClass('hidden'); }) tab4.on('click', () => { tab4.addClass('active'); content4.removeClass('hidden'); tab1.removeClass('active'); content1.addClass('hidden'); tab2.removeClass('active'); content2.addClass('hidden'); tab3.removeClass('active'); content3.addClass('hidden'); }) $('.header-nav').on('click', () => { $('.content-container').toggleClass('show'); })
e3f2c641a5be3bd6d253e565d8d98e4870712a7b
[ "JavaScript" ]
1
JavaScript
buji405/pattrn-party
8fb470a80da6bcafd78f07e66b1401297c3ae02b
338ebf28b305763c8e3e0c97a1b1702e56e06995
refs/heads/master
<repo_name>Segevz/Homework<file_sep>/HomeWork5/src/SVM.java import com.sun.org.apache.xml.internal.security.utils.Constants; import weka.classifiers.functions.SMO; import weka.classifiers.functions.supportVector.Kernel; import weka.core.Instance; import weka.core.Instances; public class SVM { public SMO m_smo; public SVM() { this.m_smo = new SMO(); } public void buildClassifier(Instances instances) throws Exception { m_smo.buildClassifier(instances); } public void setKernel(Kernel kernel) { m_smo.setKernel(kernel); } public void setC(double c) { m_smo.setC(c); } public double getC() { return m_smo.getC(); } public int[] calcConfusion(Instances instances) throws Exception { int truePositive = 0, falsePositive = 0, trueNegative = 0, falseNegative = 0; double classified, classValue; for (Instance instance : instances) { classified = m_smo.classifyInstance(instance); classValue = instance.classValue(); if (classified == 1.0 && classValue == 1.0) { truePositive++; } else if (classified == 1.0 && classValue == 0.0) { falsePositive++; } else if (classified == 0.0 && classValue == 1.0) { falseNegative++; } else { trueNegative++; } } return new int[]{truePositive, falsePositive, trueNegative, falseNegative}; } public double[] calculateKernelValue(Instances data) throws Exception { int[] values = calcConfusion(data); double TPR = 1.0 * values[0] / (values[0] + values[3]); double FPR = 1.0 * values[1] / (values[1] + values[2]); return new double[]{TPR, FPR}; } }<file_sep>/HomeWork3/src/HomeWork3/MainHW3.java package HomeWork3; import weka.core.Instances; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class MainHW3 { private static int[] k_values = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; private static int[] Lp_distance = {1, 2, 3, Integer.MAX_VALUE}; private static int XFolds = 10; private static String[] dataset = {"original", "scaled"}; private static Knn.DistanceCheck[] distanceChecks = {Knn.DistanceCheck.Regular, Knn.DistanceCheck.Efficient}; private static Knn.WeightingScheme[] schemes = {Knn.WeightingScheme.Weighted, Knn.WeightingScheme.Uniform}; public static BufferedReader readDataFile(String filename) { BufferedReader inputReader = null; try { inputReader = new BufferedReader(new FileReader(filename)); } catch (FileNotFoundException ex) { System.err.println("File not found: " + filename); } return inputReader; } public static Instances loadData(String fileName) throws IOException { BufferedReader datafile = readDataFile(fileName); Instances data = new Instances(datafile); data.setClassIndex(data.numAttributes() - 1); return data; } public static void main(String[] args) throws Exception { //TODO: complete the Main method Instances[] data = new Instances[2]; data[0] = loadData("auto_price.txt"); data[1] = FeatureScaler.scaleData(data[0]); int[] x_Folds = {data[0].size(), 50, 10, 5, 3}; Knn knn = new Knn(); double bestError = Double.MAX_VALUE; double currentError; int bestK = 0; int bestLP = 0; Knn.WeightingScheme majorityFunction = null; long totalTime = 0; long startTime = 0; for (int l = 0; l < dataset.length; l++) { bestError = Double.MAX_VALUE; knn.buildClassifier(data[l]); for (int i = 0; i < k_values.length; i++) { knn.setK(k_values[i]); for (int j = 0; j < Lp_distance.length; j++) { knn.setLp(Lp_distance[j]); for (int k = 0; k < schemes.length; k++) { knn.setWeightingScheme(schemes[k]); currentError = knn.crossValidationError(data[l], XFolds); if (currentError < bestError) { bestError = currentError; bestK = k_values[i]; bestLP = Lp_distance[j]; majorityFunction = schemes[k]; } } } } System.out.println("--------------------------------------"); System.out.println("Results for " + dataset[l] + " dataset:"); System.out.println("--------------------------------------"); System.out.println("Cross validation error with K = " + bestK + ", lp = " + bestLP + ", majority function"); System.out.println("= " + majorityFunction + " for auto_price data is: " + bestError); } System.out.println(); // Sets the values found in the previous stage in our knn algorithm knn.setK(bestK); knn.setLp(bestLP); knn.setWeightingScheme(majorityFunction); for (int l = 0; l < x_Folds.length; l++) { System.out.println("--------------------------------------"); System.out.println("Results for " + x_Folds[l] + " folds:"); System.out.println("--------------------------------------"); for (int m = 0; m < distanceChecks.length; m++) { knn.setDistanceMethod(distanceChecks[m]); startTime = System.nanoTime(); currentError = knn.crossValidationError(data[1], x_Folds[l]); totalTime = System.nanoTime() - startTime; if (currentError < bestError) { bestError = currentError; } printResults(x_Folds[l], totalTime, bestError, distanceChecks[m]); } } } private static void printResults(int x_Folds, long totalTime, double bestError, Knn.DistanceCheck distanceCheck) { String distanceMethod = distanceCheck == Knn.DistanceCheck.Efficient ? "efficient" : "regular"; System.out.println("Cross validation error of " + distanceMethod + " knn on auto_price dataset is " + bestError + " and"); System.out.println("the average elapsed time is " + totalTime / x_Folds); System.out.println("The total elapsed time is " + totalTime); System.out.println(); } }
c6d96dbccabba04d3a1d2e5eea5326cde1edf8cc
[ "Java" ]
2
Java
Segevz/Homework
eb155ee20e62358acf724a7e20633a7643569bfd
ba84a0022cfa315a835ada10000380c98a9d7d7f
refs/heads/master
<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/os.py<file_sep>###Monitoring awake-web-server.cern.ch### To monitor the website, go into the AwakeApp directory and run the command sudo systemctl status awakeapp To view access and error logs you can go to /var/log/nginx. ###Updating the app### If you want to update the code, be sure it works first in development mode. Once you happy with it, run these commands in the terminal in the AwakeApp directory sudo systemctl restart awakeapp sudo systemctl restart nginx If you navigate to the website, you should see that the app is now updated. ###Troubleshooting### If you get errors about libpython3.6.so.1 or something like that, you may need to execute the following command in the terminal (or whatever python library path you want to be using) export LD_LIBRARY_PATH=/home/dillon/anaconda3/lib If you get weird sytax errors when using "flask run", but "python -m flask run" runs fine, you are probably linking to a version of flask that is for an older version of python. Run python --version flask --version If the two are the same version, then what follows is not the source of your error. Make sure that you have the "pip install flask" for the version corresponding to your version of python, and then create an alias in your .bashrc file linkig to the correct version alias flask=/path/to/bin/flask ### Changing the server ### If you reconfigure the server (that is, is you change awakeapp.service), then you must run sudo systemctl daemon-reload Then you can run sudo systemctl restart awakeapp sudo systemctl restart nginx to update the app. ### Switching between https and http ### If you want to switch the website from https to http (or vice versa) please see the ~/AWAKE_server_config/README.md <file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/warnings.py<file_sep>import sys sys.path.append('/home/awakewebmaster/AwakeApp') from awake_app import app if __name__ == "__main__": # Dont actually need this to be true.. # Only true when running with the python interpretor (e.g. python xx.py) # uwsgi "runs" the app from this entry point for us app.run(host='0.0.0.0') <file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/shutil.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/copy.py<file_sep>import sys from flask import request, session def edit_raw_plots(event_id, day, month, year, path_to_desktop = ''): sys.path.append(path_to_desktop + 'AwakeApp') from awake_app import show_raw_page session['XMPP_vmin'] = request.form.get('XMPP_vmin', '') session['XMPP_vmax'] = request.form.get('XMPP_vmax', '') session['BTV_vmin'] = request.form.get('BTV_vmin', '') session['BTV_vmax'] = request.form.get('BTV_vmax', '') session['uhalo_vmin'] = request.form.get('uhalo_vmin','') session['uhalo_vmax'] = request.form.get('uhalo_vmax', '') session['dhalo_vmin'] = request.form.get('dhalo_vmin', '') session['dhalo_vmax'] = request.form.get('dhalo_vmax', '') reset = request.form.get('reset', None) if reset == 'Reset': session['counter'] = 'reset' # should do IF there is no entry then plot according to the OLD vmin and vmax return show_raw_page(event_id, day, month, year) <file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/_bootlocale.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/sre_constants.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/ntpath.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/sre_parse.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/types.py<file_sep># -*- coding: utf-8 -*- from .cmmnbuild_dep_manager import Manager __version__ = '2.1.2' <file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/abc.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/rlcompleter.py<file_sep>import os import sys import numpy as np from flask import request, session from ancillary_funcs import filter_h5, create_link def raw_viewer_post(path_to_desktop='', path_to_years = ''): os.environ['AAT'] = path_to_desktop + 'AWAKE_ANALYSIS_TOOLS/' sys.path.append(os.environ['AAT'] + 'ntupling') sys.path.append(os.environ['AAT'] + 'ntupling/' + 'map_files') #============================================================================== month = request.form['month'] year = request.form['year'] day = request.form['day'] #If month 1-9 is chosen, prepend a zero if len(month) < 2: month = '0' + month if len(day) < 2: day = '0' + day # Storing day requested as session variable may not be needed session['month'] = month session['year'] = year session['day'] = day path_to_day = path_to_years + year + '/' + month + '/' + day + '/' if os.path.isdir(path_to_day) == False: message = ''' <center> No data found for the day %s/%s/%s.<br> <a href="/event_viewer_raw/"> Make another inquiry </a> </center>''' return message %(day, month, year) # When returnGoodData is fixed, uncomment block and comment out good_list below #============================================================================== # good_list = os.listdir(path_to_day) # print(len(good_list)) # # for i in range(len(good_list)): # good_list[i] = path_to_day + good_list[i] # # data,bools,warning,timing = returnGoodData.returnGoodData('/AwakeEventData/XMPP-STREAK/StreakImage/streakImageData', # good_list) p # new_good_list = np.array([]) # for i in range(len(bools)): # if bools[i] == True: # new_good_list = np.append(new_good_list, good_list[i]) # good_list = new_good_list #============================================================================== good_list = filter_h5(path_to_day) if len(good_list) == 0: return 'returnGoodData returned a list of length zero, for the date requested.' #### timestamps = np.array([]) for f_name in good_list: f_name = ( f_name.split('/') )[-1] und_loc = f_name.find('_') timestamp = f_name[:und_loc] timestamp = int(timestamp) timestamps = np.append(timestamps, timestamp) i=0 stamps = [] for timestamp in timestamps: # First trim timestamp since for some reason, when converting # between string and int it turns the last two zeros to # 64, which makes it impossible to find a substring # within the file name. timestamp = str('%i' % timestamp) # print('timestamp is!!!!', timestamp) # So, hard code to remove these last two numbers being # 64 instead of 00 timestamp = timestamp[:-2] + '00' stamps.append( int(timestamp) ) stamps.sort() for timestamp in stamps: timestamp = str(timestamp) # Now we write the html file that gives all the links to all the events on that # day. Each of these links to a different view. # # We write this to the ./static/ directory. if i==0: string = '<html>\n' string = string + create_link('/event_viewer_raw/' + day +'/' + month + '/' + year + '/' + timestamp, 'Event: ' + timestamp) if (i >= 1) and (i < len(timestamps)-1): string = string + create_link('/event_viewer_raw/' + day +'/' + month + '/' + year + '/' + timestamp, 'Event: ' + timestamp) if i == len(timestamps) -1 : string =( string + create_link('/event_viewer_raw/' + day +'/' + month + '/' + year + '/' + timestamp, 'Event: ' + timestamp) +'</html>' ) i+=1 html_str = string path_to_static = './static/' html_fname = 'timestamp_list.html' html_file = open(path_to_static + html_fname, 'w') html_file.write(html_str) html_file.close() timelist_fname = './timestamp_lists/' + year + '_' + month + '_' + day + '_' check = open(timelist_fname + 'stamps.out', 'w') for time in stamps: check.write( str(time) + '\n' ) return app.send_static_file(html_fname) <file_sep># -*- coding: utf-8 -*- '''CommonBuild Dependency Manager Copyright (c) CERN 2015-2017 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Authors: <NAME> <<EMAIL>> ''' import cmmnbuild_dep_manager import logging import six import sys if __name__ == '__main__': '''Provides a command line interface to cmmnbuild_dep_manager Any method of the cmmnbuild_dep_manager.Manager class can be called with string arguments. For example: $ python -m cmmnbuild_dep_manager install pytimber pyjapc $ python -m cmmnbuild_dep_manager list $ python -m cmmnbuild_dep_manager resolve ''' logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') mgr = cmmnbuild_dep_manager.Manager() mgr.set_logging_level(logging.INFO) try: if len(sys.argv) >= 2: method = getattr(mgr, sys.argv[1]) args = [] kwargs = {} for a in sys.argv[2:]: if '=' in a: k, v = a.split('=') kwargs[k] = v else: if len(kwargs): raise SyntaxError('positional argument follows keyword argument') args.append(a) ret = method(*args, **kwargs) if ret is not None: if isinstance(ret, six.string_types): print(ret) elif hasattr(ret, '__iter__'): for r in ret: print(r) else: print(ret) else: raise ValueError('a method name must be provided') except Exception as e: print('{0}: {1}'.format(type(e).__name__, e)) sys.exit(1) <file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/keyword.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/bisect.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/heapq.py<file_sep>import os import sys import h5py import pandas as pd import numpy as np import scipy.signal as sig import matplotlib.pyplot as plt, mpld3 import returnPlasmaDensity import bunchRotationStatus from mpld3 import plugins from mpl_toolkits.axes_grid1 import make_axes_locatable from ancillary_funcs import find_substring, grab_between, make_textbox from flask import session, render_template from ancillary_funcs import filter_h5, create_link #============================================================================== # Now, since we have a large number of events in a day, we need to # have a large number of views. This is best done (I think) by using "pages", # in which everything enclosed in "< >" is a variable we can use. def show_ev( event_id, day, month, year, path_to_years = '', path_to_desktop = '' ): os.environ['AAT'] = path_to_desktop + 'AWAKE_ANALYSIS_TOOLS/' sys.path.append(os.environ['AAT'] + 'ntupling') sys.path.append(os.environ['AAT'] + 'ntupling/' + 'map_files') v_list = ['XMPP_vmin', 'XMPP_vmax','BTV_vmin', 'BTV_vmax', 'uhalo_vmin', 'uhalo_vmax', 'dhalo_vmin', 'dhalo_vmax'] for key in v_list: try: session[key] except KeyError: session[key] = '' XMPP_vmin = session['XMPP_vmin'] XMPP_vmax = session['XMPP_vmax'] BTV_vmin = session['BTV_vmin'] BTV_vmax = session['BTV_vmax'] uhalo_vmin = session['uhalo_vmin'] uhalo_vmax = session['uhalo_vmax'] dhalo_vmin = session['dhalo_vmin'] dhalo_vmax = session['dhalo_vmax'] # Remove old pages. We do this because (I presume) we do not want to be storing # an html file for each event locally. So, DO NOT NAME AN ACTUAL TEMPLATE YOU # WANT TO USE TO START WITH A NUMBER. If you cannot resist, however, make the # number less than 14. template_files = os.listdir('./templates') for file in template_files: try: if int(file[:2]) >= 14: os.remove('./templates/' + file) except ValueError: pass # Check to make sure month and day are formatted the same as the file system if len(month) < 2: month = '0' + month if len(day) < 2: day = '0' + day path_to_day = ( path_to_years + year + '/' + month + '/' + day + '/' ) # getting path to the file corresponding to the event requested fnames = os.listdir(path_to_day) for fname in fnames: if str(event_id) in fname: ename = fname break else: pass file_path = path_to_day + ename # reading in the event file hf0 = h5py.File(file_path) # First, we get the XMPP streak image # hv.extension('bokeh') img_w = hf0['/AwakeEventData/XMPP-STREAK/StreakImage/streakImageWidth'][0] img_h = hf0['/AwakeEventData/XMPP-STREAK/StreakImage/streakImageHeight'][0] img_data = hf0['/AwakeEventData/XMPP-STREAK/StreakImage/streakImageData'] M_0 = np.reshape( img_data ,( int(img_h),int(img_w) ) ) M_0 = M_0.astype(float) M_0 = sig.medfilt2d(M_0) # opts0 = dict(apply_ranges = True, colorbar = True, # colorbar_position = 'bottom') # XMPP_img = hv.Raster(M_0, label = 'XMPP Streak Image')(plot = opts0) # Next, we get the BTV streak image BTV_img_w = hf0['/AwakeEventData/TT41.BTV.412350.STREAK/StreakImage/streakImageWidth'][0] BTV_img_h = hf0['/AwakeEventData/TT41.BTV.412350.STREAK/StreakImage/streakImageHeight'][0] BTV_img_data = hf0['/AwakeEventData/TT41.BTV.412350.STREAK/StreakImage/streakImageData'] M_1 = np.reshape( BTV_img_data, ( int(BTV_img_h),int(BTV_img_w) ) ) M_1 = M_1.astype(float) M_1 = sig.medfilt2d(M_1) # opts1 = dict(apply_ranges = True, colorbar = True, # colorbar_position = 'bottom') # BTV_img = hv.Raster(M_1, label = 'BTV Streak Image')(plot = opts1) # Next get upstream halo cam image uhalo_img_w = hf0['/AwakeEventData/BOVWA.02TCC4.CAM10/ExtractionImage/width'][0] uhalo_img_h = hf0['/AwakeEventData/BOVWA.02TCC4.CAM10/ExtractionImage/height'][0] uhalo_img_data = hf0['/AwakeEventData/BOVWA.02TCC4.CAM10/ExtractionImage/imageRawData'] M_2 = np.reshape( uhalo_img_data, ( int(uhalo_img_h),int(uhalo_img_w) ) ) M_2 = M_2.astype(float) M_2 = sig.medfilt2d(M_2) # opts2 = dict(colorbar = True, colorbar_position = 'bottom' # , shared_axes = False, apply_ranges = True) # uhalo_img = hv.Raster(M_2, label = 'Upstream Halo Camera')(plot = opts2) # getting downstream halo cam image dhalo_img_w = hf0['/AwakeEventData/BOVWA.04TCC4.CAM12/ExtractionImage/width'][0] dhalo_img_h = hf0['/AwakeEventData/BOVWA.04TCC4.CAM12/ExtractionImage/height'][0] dhalo_img_data = hf0['/AwakeEventData/BOVWA.04TCC4.CAM12/ExtractionImage/imageRawData'] M_3 = np.reshape( dhalo_img_data, ( int(dhalo_img_h),int(dhalo_img_w) ) ) M_3 = M_3.astype(float) M_3 = sig.medfilt2d(M_3) # initialize the figure that will be displayed on the view fig, ( (ax1,ax2), (ax3, ax4) ) = plt.subplots( nrows=2, ncols=2, figsize=(11,7)) fig.tight_layout() #============================================================================== # Check to see if user hit the reset button to reset vmin and vmax. # If reset is requested, then we "trick" the session variables into thinking # that the previous request was the defaults try: if session['counter'] == 'reset': session['prev_Xmin'] = np.amin(M_0) session['prev_Xmax'] = np.amax(M_0) session['prev_Bmin'] = np.amin(M_1) session['prev_Bmax'] = np.amax(M_1) session['prev_uhalo_vmin'] = np.amin(M_2) session['prev_uhalo_vmax'] = np.amax(M_2) session['prev_dhalo_vmin'] = np.amin(M_3) session['prev_dhalo_vmax'] = np.amax(M_3) session.pop('counter') print('RESETING NOW') except KeyError: print('NOT RESETING') key_list = ['prev_Xmin','prev_Xmax', 'prev_Bmin', 'prev_Bmax', 'prev_uhalo_vmin', 'prev_uhalo_vmax', 'prev_dhalo_vmin', 'prev_dhalo_vmax' ] val_list = [np.amin(M_0), np.amax(M_0), np.amin(M_1), np.amax(M_1), np.amin(M_2), np.amax(M_2), np.amin(M_3), np.amax(M_3)] # Now, we check to make sure all of the previous values are well defined. # This is needed to keep the app from crashing when accessing direct # links to web page. We would get a key error in that case, since no values # were previously requested i = 0 for key in key_list: try: session[key] except KeyError: session[key] = val_list[i] i+=1 # print('XMPP_VMAX', XMPP_vmax) # print('session', session['prev_Xmax']) #============================================================================== Xplot_gone = False if (XMPP_vmin == '') and (XMPP_vmax == ''): cur_Xmin = session['prev_Xmin'] cur_Xmax = session['prev_Xmax'] im1 = ax1.imshow(M_0, cmap = 'inferno', vmin = cur_Xmin, vmax = cur_Xmax) Xplot_gone = True # print('HERE') if XMPP_vmin == '' and XMPP_vmax != '': cur_Xmin = session['prev_Xmin'] cur_Xmax = int(XMPP_vmax) im1 = ax1.imshow(M_0, cmap = 'inferno', vmin=cur_Xmin, vmax = cur_Xmax) session['prev_Xmax'] = cur_Xmax # print('SECOND ONE') Xplot_gone = True if XMPP_vmin != '' and XMPP_vmax == '': cur_Xmin = int(XMPP_vmin) cur_Xmax = session['prev_Xmax'] im1 = ax1.imshow(M_0, cmap = 'inferno', vmin=cur_Xmin, vmax = cur_Xmax) session['prev_Xmin'] = cur_Xmin Xplot_gone = True if XMPP_vmin != '' and XMPP_vmax != '': cur_Xmin = int(XMPP_vmin) cur_Xmax = int(XMPP_vmax) im1 = ax1.imshow(M_0, cmap = 'inferno', vmin=int(XMPP_vmin), vmax=int(XMPP_vmax)) session['prev_Xmin'] = cur_Xmin session['prev_Xmax'] = cur_Xmax Xplot_gone = True # The code should run fine without these Xplot_gone checks. They are an # artifact from debugging if Xplot_gone == False: cur_Xmin = np.amin(M_0) cur_Xmax = np.amax(M_0) im1 = ax1.imshow(M_0, cmap = 'inferno', vmin = cur_Xmin, vmax = cur_Xmax) session['prev_Xmin'] = cur_Xmin session['prev_Xmax'] = cur_Xmax # print('XPLOTGONE', Xplot_gone) # print('CURXmax', cur_Xmax) # print('newsessoin', session['prev_Xmax']) # add colorbar divider1 = make_axes_locatable(ax1) cax1 = divider1.new_vertical(size="5%", pad=0.7, pack_start=True) fig.add_axes(cax1) plt.colorbar(im1, orientation = 'horizontal', cax=cax1) # add title ax1.set_title('XMPP Streak Image') #============================================================================== Bplot_gone = False if (BTV_vmin == '') and (BTV_vmax == ''): cur_Bmin = session['prev_Bmin'] cur_Bmax = session['prev_Bmax'] im2 = ax2.imshow(M_1, cmap = 'inferno', vmin = cur_Bmin, vmax = cur_Bmax) Bplot_gone = True if BTV_vmin == '' and BTV_vmax != '': cur_Bmin = session['prev_Bmin'] cur_Bmax = int(BTV_vmax) im2 = ax2.imshow(M_1, cmap = 'inferno', vmin=cur_Bmin, vmax = cur_Bmax) session['prev_Bmax'] = cur_Bmax Bplot_gone = True if BTV_vmin != '' and BTV_vmax == '': cur_Bmin = int(BTV_vmin) cur_Bmax = session['prev_Bmax'] im2 = ax2.imshow(M_1, cmap = 'inferno', vmin=cur_Bmin, vmax = cur_Bmax) session['prev_Bmin'] = cur_Bmin Bplot_gone = True if BTV_vmin != '' and BTV_vmax != '': cur_Bmin = int(BTV_vmin) cur_Bmax = int(BTV_vmax) im2 = ax2.imshow(M_1, cmap = 'inferno', vmin=int(BTV_vmin), vmax=int(BTV_vmax)) session['prev_Bmin'] = cur_Bmin session['prev_Bmax'] = cur_Bmax Bplot_gone = True if Bplot_gone == False: cur_Bmin = np.amin(M_1) cur_Bmax = np.amax(M_1) im2 = ax2.imshow(M_1, cmap = 'inferno', vmin = cur_Bmin, vmax = cur_Bmax) session['prev_Bmin'] = cur_Bmin session['prev_Bmax'] = cur_Bmax # add colorbar divider2 = make_axes_locatable(ax2) cax2 = divider2.new_vertical(size="5%", pad=0.7, pack_start=True) fig.add_axes(cax2) plt.colorbar(im2, orientation = 'horizontal', cax=cax2) ax2.set_title('BTV Streak Image') #============================================================================== uhalo_plot_gone = False if (uhalo_vmin == '') and (uhalo_vmax == ''): cur_uhalo_vmin = session['prev_uhalo_vmin'] cur_uhalo_vmax = session['prev_uhalo_vmax'] im3 = ax3.imshow(M_2, cmap = 'inferno', vmin = cur_uhalo_vmin, vmax = cur_uhalo_vmax) uhalo_plot_gone = True if uhalo_vmin == '' and uhalo_vmax != '': cur_uhalo_vmin = session['prev_uhalo_vmin'] cur_uhalo_vmax = int(uhalo_vmax) im3 = ax3.imshow(M_2, cmap = 'inferno', vmin=cur_uhalo_vmin, vmax = cur_uhalo_vmax) session['prev_uhalo_vmax'] = cur_uhalo_vmax uhalo_plot_gone = True if uhalo_vmin != '' and uhalo_vmax == '': cur_uhalo_vmin = int(uhalo_vmin) cur_uhalo_vmax = session['prev_uhalo_vmax'] im3 = ax3.imshow(M_2, cmap = 'inferno', vmin=cur_uhalo_vmin, vmax = cur_uhalo_vmax) session['prev_uhalo_vmin'] = cur_uhalo_vmin uhalo_plot_gone = True if uhalo_vmin != '' and uhalo_vmax != '': cur_uhalo_vmin = int(uhalo_vmin) cur_uhalo_vmax = int(uhalo_vmax) im3 = ax3.imshow(M_2, cmap = 'inferno', vmin=int(uhalo_vmin), vmax=int(uhalo_vmax)) session['prev_uhalo_vmin'] = cur_uhalo_vmin session['prev_uhalo_vmax'] = cur_uhalo_vmax uhalo_plot_gone = True if uhalo_plot_gone == False: cur_uhalo_vmin = np.amin(M_2) cur_uhalo_vmax = np.amax(M_2) im3 = ax3.imshow(M_2, cmap = 'inferno', vmin = cur_uhalo_vmin, vmax = cur_uhalo_vmax) session['prev_uhalo_vmin'] = cur_uhalo_vmin session['prev_uhalo_vmax'] = cur_uhalo_vmax # add colorbar divider3 = make_axes_locatable(ax3) cax3 = divider3.new_vertical(size="5%", pad=0.7, pack_start=True) fig.add_axes(cax3) plt.colorbar(im3, orientation = 'horizontal', cax=cax3) ax3.set_title('Upstream Halo Camera') #============================ dhalo_plot_gone = False if (dhalo_vmin == '') and (dhalo_vmax == ''): cur_dhalo_vmin = session['prev_dhalo_vmin'] cur_dhalo_vmax = session['prev_dhalo_vmax'] im4 = ax4.imshow(M_3, cmap = 'inferno', vmin = cur_dhalo_vmin, vmax = cur_dhalo_vmax) dhalo_plot_gone = True if dhalo_vmin == '' and dhalo_vmax != '': cur_dhalo_vmin = session['prev_dhalo_vmin'] cur_dhalo_vmax = int(dhalo_vmax) im4 = ax4.imshow(M_3, cmap = 'inferno', vmin=cur_dhalo_vmin, vmax = cur_dhalo_vmax) session['prev_dhalo_vmax'] = cur_dhalo_vmax dhalo_plot_gone = True if dhalo_vmin != '' and dhalo_vmax == '': cur_dhalo_vmin = int(dhalo_vmin) cur_dhalo_vmax = session['prev_dhalo_vmax'] im4 = ax4.imshow(M_3, cmap = 'inferno', vmin=cur_dhalo_vmin, vmax = cur_dhalo_vmax) session['prev_dhalo_vmin'] = cur_dhalo_vmin dhalo_plot_gone = True if dhalo_vmin != '' and dhalo_vmax != '': cur_dhalo_vmin = int(dhalo_vmin) cur_dhalo_vmax = int(dhalo_vmax) im4 = ax4.imshow(M_3, cmap = 'inferno', vmin=int(dhalo_vmin), vmax=int(dhalo_vmax)) session['prev_dhalo_vmin'] = cur_dhalo_vmin session['prev_dhalo_vmax'] = cur_dhalo_vmax dhalo_plot_gone = True if dhalo_plot_gone == False: cur_dhalo_vmin = np.amin(M_3) cur_dhalo_vmax = np.amax(M_3) im4 = ax4.imshow(M_3, cmap = 'inferno', vmin = cur_dhalo_vmin, vmax = cur_dhalo_vmax) session['prev_dhalo_vmin'] = cur_dhalo_vmin session['prev_dhalo_vmax'] = cur_dhalo_vmax # add colorbar divider4 = make_axes_locatable(ax4) cax4 = divider4.new_vertical(size="5%", pad=0.7, pack_start=True) fig.add_axes(cax4) plt.colorbar(im4, orientation = 'horizontal', cax=cax4) ax4.set_title('Downstream Halo Camera') #============================================================================== # Now, we write the html file for the plots to the ./templates/ directory path_to_plot = './templates/' plot_name = str(event_id) + '.html' f = open(path_to_plot + plot_name, 'w') # For Bokeh # renderer = hv.Store.renderers['bokeh'] # img = XMPP_img + BTV_img + uhalo_img # img = hv.Layout(img) # img_html = renderer.static_html(img) # choose image tools for plots plugins.clear(fig) plugins.connect(fig, plugins.Reset(), plugins.Zoom()) img_html = mpld3.fig_to_html(fig) #============================================================================== # REPLACE WITH GRAB_BETWEEN function ix0 = find_substring('<div', img_html) ix1 = find_substring('</div>', img_html) div = img_html[ix0: ix1 + len('</div>')] # remember [1:3] includes only elements 1 and 2 ix2 = find_substring('<script>', img_html) ix3 = find_substring('</script>', img_html) script = img_html[ix2: ix3 + len('</script>')] ix4 = find_substring('<style>', img_html) ix5 = find_substring('</style>', img_html) style = img_html[ix4 : ix5 + len('</style>')] #======= # Now, we get the plasma density ( US_densities, DS_densities, Gradients, US_valve, DS_valve, US_dataBool, DS_dataBool, US_warning, DS_warning ) = returnPlasmaDensity.returnPlasmaDensity([int(str(event_id))]) if US_dataBool[0] == True: US_density = US_densities[0] else: US_density = 'NaN' if DS_dataBool[0] == True: DS_density = DS_densities[0] else: DS_density = 'NaN' density_html = ('<b> Upstream Plasma Density:</b> ' + str(US_density) + '<br>\n' + '<b> Downstream Plasma Density: </b> ' + str(DS_density) + '<br>\n' ) #======= # Now, we get the bunch rotation # Don't forget that since we clipped the time at the end by two bunch_status = bunchRotationStatus.bunchRotationStatus([int(str(event_id))]) bunch_status_html =( '<b> Bunch Rotation Status: </b>' + str(bunch_status[0]) + '<br>\n' ) # make False red and True green #============================ # get beam charge beam_charge_key = '/AwakeEventData/TT41.BCTF.412340/Acquisition/totalIntensityPreferred' beam_charge = hf0[beam_charge_key][0] beam_charge_html = '<b> Beam Charge: </b>' + str(beam_charge) + '<br>\n' #============================ # Now, we write the html file that will be written to the view header. #============================ # Now, get the list of timestamps. In the 'try' block, we check to make sure # that the timestamps for the day requested exist in a .out file #============================ timestamp_file_requested = './timestamp_lists/' + year + '_' + month + '_' + day + '_stamps.out' try: if os.path.isfile( timestamp_file_requested ): print('TIMESTAMP FILE FOUND FOR DATE REQUESTED') else: print('TIMESTAMP FILE NOT FOUND FOR DAY REQUESTED') raise KeyError # So, if we raise the error, then we make sureto get the timestamps except KeyError: print('FETCHING TIMESTAMP FOR REQUESTED DATE...' ) path_to_day = path_to_years + year + '/' + month + '/' + day + '/' good_list = os.listdir(path_to_day) good_list = filter_h5(path_to_day) #Again, when returnGoodData is fixed uncomment block, and comment good_list #============================================================================== # print(len(good_list)) # # for i in range(len(good_list)): # good_list[i] = path_to_day + good_list[i] # # data,bools,warning,timing = returnGoodData.returnGoodData('/AwakeEventData/XMPP-STREAK/StreakImage/streakImageData', # good_list) # new_good_list = np.array([]) # for i in range(len(bools)): # if bools[i] == True: # new_good_list = np.append(new_good_list, good_list[i]) # good_list = new_good_list # # print(len(good_list), '!!!!!!') #============================================================================== timestamps = np.array([]) for f_name in good_list: f_name = ( f_name.split('/') )[-1] und_loc = f_name.find('_') timestamp = f_name[:und_loc] timestamp = int(timestamp) timestamps = np.append(timestamps, timestamp) i=0 stamps = [] for timestamp in timestamps: # First trim timestamp since, for some reason, when converting # between string and int it turns the last two zeros to # 64, which makes it impossible to find a substring # within the file name. timestamp = str('%i' % timestamp) # print('timestamp is!!!!', timestamp) # # So, hard code to fix this timestamp = timestamp[:-2] + '00' stamps.append( int(timestamp) ) stamps.sort() # Now we write the html file that gives all the links to all the events on that # day. Each of these links to a different view. # # We write this to the ./static/ directory. for timestamp in stamps: timestamp = str(timestamp) if i==0: string = '<html>\n' string = string + create_link('/event_viewer/' + day +'/' + month + '/' + year + '/' + timestamp, 'Event: ' + timestamp) if (i >= 1) and (i < len(timestamps)-1): string = string + create_link('/event_viewer/' + day +'/' + month + '/' + year + '/' + timestamp, 'Event: ' + timestamp) if i == len(timestamps) -1 : string =( string + create_link('/event_viewer/' + day +'/' + month + '/' + year + '/' + timestamp, 'Event: ' + timestamp) +'</html>' ) i+=1 html_str = string path_to_static = './static/' html_fname = 'timestamp_list.html' html_file = open(path_to_static + html_fname, 'w') html_file.write(html_str) html_file.close() check = open(timestamp_file_requested, 'w') for time in stamps: check.write( str(time) + '\n' ) stamps = [] with open(timestamp_file_requested, 'r') as stamps_file: for line in stamps_file: stamps.append(line.rstrip('\n')) #=========================== # Now, we find the next and previous event_ids j = 0 for stamp in stamps: if stamp == str(event_id): try: next_id = stamps[j+1] except IndexError: next_id = 'Not Found' if (j-1 >= 0): prev_id = stamps[j-1] else: prev_id = 'Not Found' break else: True j+=1 #============================ # Now, write next and previous links, for the top of the view prev_page_link = ( '/event_viewer/' + day +'/' + month +'/' + year +'/' + prev_id +'/' ) next_page_link =( '/event_viewer/' + day +'/' + month +'/' + year +'/' + next_id + '/' ) if prev_id != 'Not Found': href_prev = create_link(prev_page_link, "Previous", html_line_break = False) else: href_prev = '' if next_id != 'Not Found': href_next = create_link(next_page_link, "Next") else: href_next = '' if ename[-1] != '/': ename += '/' # writing message at top of page with download link message = ( ' <b> Event ID</b>: ' + '<a href=' + r'"' + '/uploads/' + day +'/' + month + '/' + year + '/' + ename + r'"' + '>' + str(event_id) + '</a><br>' ) #======= datetimes = True if datetimes == True: link_name = '%s' times = pd.to_numeric(stamps, downcast = 'integer') times = pd.DataFrame( data = { 't' : pd.to_datetime(times) } ) times = times['t'].dt.tz_localize('Etc/GMT+2').dt.tz_convert('UTC') # getting time without day with .time(), and then get rid of milliseconds times = [ str(t.time())[:-7] for t in times ] # Should insert bool here to say that we have this list already else: link_name = 'Event: %s' times = stamps # writing html for the sidebar timelinks i=0 for timestamp in stamps: if i == 0: string = create_link('/event_viewer/' + day +'/' + month + '/' + year + '/' + timestamp, link_name %times[i], bootstrap = True) if (i >= 1): string = string + create_link('/event_viewer/' + day +'/' + month + '/' + year + '/' + timestamp, link_name %times[i], bootstrap = True) i+=1 time_str = string #======= # Now, we make the side bar strap_temp_path = './templates/newcss.html' # stripping off the bootstrap template contents for the file strap_head = grab_between('<head>', '</head>', strap_temp_path) nav_start = '''<div class="col-lg-2">\n <nav id="sidebar">\n <!-- sidebar-header class used for CSS -->\n <div class="sidebar-header, text-center">\n <br>\n <h3>Browse Nearby Events</h3>\n </div>\n''' searchbar = '''<center><input type="text" id="myInput" onkeyup="searchEvents()" placeholder="Search events.."></center>\n''' ul_start = '''<ul class="list-unstyled components" id="myUL">\n''' # string of timestamps gets written here (see the f.write()s) ul_close = '</ul>\n' nav_close = '</nav>\n' #======= # Now, we create the navbar at the top from the same template navbar_start = grab_between('<!--navbar_code-->', '<!--insert_page_links-->', strap_temp_path) current_page = '/event_viewer/' + day + '/' + month + '/' + year + '/' + str(event_id) cur_page_link =( '<li class="active"><a href="%s">%s/%s/%s</a></li>' %( current_page, day, month, year ) ) query_page_link = ( '<li><a href="%s">%s</a></li>' %('/event_viewer/', 'Make New Query') ) navbar_end = grab_between('<!--insert_page_links-->', '<!--navbar_code_end-->', strap_temp_path) navbar_string = ( navbar_start + '\n' + cur_page_link + '\n' + query_page_link + '\n' + navbar_end + '\n' ) #======= # prepping the vartups for writing the textbox using create_textbox() vartup1 = ('XMPP_vmin', 'XMPP_vmax') nametup1 = ('XMPP vmin', 'XMPP vmax') vartup2 = ('BTV_vmin', 'BTV_vmax') nametup2 = ('BTV vmin', 'BTV vmax') vartup3 = ('uhalo_vmin', 'uhalo_vmax') nametup3 = ('Upstream Halo vmin', 'Upstream Halo vmax') vartup4 = ('dhalo_vmin', 'dhalo_vmax') nametup4 = ('Downstream Halo vmin', 'Downstream Halo vmax') #======= # disable caching on webpage no_cache = ''' <meta http-equiv="cache-control" content="max-age=0" />\n <meta http-equiv="cache-control" content="no-cache" />\n <meta http-equiv="expires" content="0" />\n <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />\n <meta http-equiv="pragma" content="no-cache" />\n''' #======= # writing html for the "data box" at the top data = density_html + bunch_status_html + beam_charge_html #======= f.write('<html>\n') # write head f.write('<head>\n') f.write(strap_head) f.write(style +'\n') f.write(script +'\n') f.write(no_cache) f.write('</head>\n') f.write('<body>\n') f.write(navbar_string) f.write('<div class="row">\n') f.write(nav_start) f.write(searchbar) f.write('<center>\n') f.write(ul_start) f.write(time_str) f.write(ul_close) f.write('</center>\n') f.write(nav_close) f.write('</div>\n') f.write('<div class="col-lg-10">\n') f.write('<div class="container">\n') f.write('<center>') f.write(message) if href_prev != '': f.write(href_prev) if href_next != '': f.write(href_next) f.write('</center>') # write textbox with scalar data f.write('<center>\n') f.write('<fieldset style="width:30%">\n') f.write('<legend> Event Data: </legend>\n') f.write(data) f.write('</fieldset>\n') f.write('</center>') f.write('<center>\n' + div + '\n</center>\n') # make textbox f.write('<center>\n') # Changed POST to GET f.write('''<form action="." method="POST">\n''') f.write(make_textbox(vartup1, nametup1, cur_min = cur_Xmin, cur_max = cur_Xmax)) f.write(make_textbox(vartup2, nametup2, cur_min = cur_Bmin, cur_max = cur_Bmax)) f.write(make_textbox(vartup3, nametup3, cur_min = cur_uhalo_vmin, cur_max = cur_uhalo_vmax)) f.write(make_textbox(vartup4, nametup4, cur_min = cur_dhalo_vmin, cur_max = cur_dhalo_vmax)) # f.write( '''<input type="submit" name="button" class="btn btn-primary" value="Send">\n''' ) # f.write( '''<input type="submit" name="reset" class="btn btn-danger" value="Reset">\n # </form>\n''' ) f.write( '''<input type="submit" name="button" value="Send">\n''' ) f.write( '''<input type="submit" name="reset" value="Reset">\n </form>\n''' ) f.write('</center>\n') f.write('</div>\n') f.write('</div>\n') f.write('</div>\n') f.write('</body>\n') f.write('</html>\n') f.close() return render_template( plot_name )<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/random.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/__future__.py<file_sep>import os import h5py # Returns an array of the indices [ix1, .. ixn] such that ixi is the index of the # element in the longer list that is closest to the ith value in the shorter list # So "element i is closest to element ixi" def find_closest_indices(longer_list, shorter_list): if len(shorter_list) > len(longer_list): print('THE SYNTAX IS THAT THE LONGER LIST MUST GO FIRST') raise KeyError new_list = [] ix_star =0 for item2 in shorter_list: ix = 0 for item1 in longer_list: diff = abs(item1 - item2) if ix == 0: closest = diff ix_star = ix elif (diff < closest and ix != 0): closest = diff ix_star = ix ix+=1 new_list.append(ix_star) return new_list def create_link(ad, name, newline = True, html_line_break=True, bootstrap = False): if bootstrap == True: newline = False html_line_break = False if newline == True and html_line_break == True: ad = r'"' + ad + r'"' new_line = '<a href=' + ad + '>' + name + '</a><br>\n' if newline == False and html_line_break == True: ad = r'"' + ad + r'"' new_line = '<a href=' + ad + '>' + name + '</a><br>' if newline == True and html_line_break == False: ad = r'"' + ad + r'"' new_line = '<a href=' + ad + '>' + name + '</a>\n' if newline == False and html_line_break == False: ad = r'"' + ad + r'"' new_line = '<a href=' + ad + '>' + name + '</a>' if bootstrap == True: new_line = '<li>' + new_line + '</li>\n' return new_line def find_substring(sub, string): index = string.find(sub) return index def grab_between(first_key, last_key, text_file, ends = False): file = open(text_file, 'r') contents = file.read() ix0 = find_substring(first_key, contents) ix1 = find_substring(last_key, contents) if ends == False: text_between_keys = contents[ix0 + len(first_key) : ix1] else: text_between_keys = contents[ix0 : ix1 + len(last_key)] return text_between_keys def make_textbox(vartup, nametup, cur_min = None, cur_max = None): textbox = ( nametup[0] + ' (current value:' + str(cur_min) + ''') <input type="text" name= ''' + r'"' + vartup[0] + r'"' + '''>\n <br>\n''' + nametup[1] +' (current value:' + str(cur_max) +''')<input type="text" name=''' + r'"' + vartup[1] + r'"' + '''>\n <br>\n''' ) return textbox def filter_h5(path): fnames = os.listdir(path) good_list = [] for fname in fnames: try: h5py.File(path + fname) good_list.append(fname) except: pass return good_list<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/io.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/hmac.py<file_sep># -*- coding: utf-8 -*- '''CommonBuild Dependency Manager Copyright (c) CERN 2015-2017 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Authors: <NAME> <<EMAIL>> <NAME> <<EMAIL>> ''' import glob import importlib import json import logging import os import pickle import requests import shutil import site import tempfile import sys import xml.etree.ElementTree as ET import zipfile class Manager(object): def __init__(self, pkg=None, lvl=None): logging.basicConfig() self.log = logging.getLogger(__package__) if lvl is not None: self.log.setLevel(lvl) if pkg is not None: if not self.is_installed(pkg): self.install(pkg) def set_logging_level(self, lvl): '''Set the logging level''' self.log.setLevel(lvl) def help(self, method='__init__'): '''Print the docstring for a method''' print(getattr(self, method).__doc__) def jar_path(self): '''Return the directory containing the resolved jars''' return os.path.join(self._dir(), 'lib') def jars(self): '''Return a list of the resolved jars''' if os.path.isdir(self.jar_path()): return [ os.path.join(self.jar_path(), f) for f in os.listdir(self.jar_path()) if f.lower().endswith('.jar') ] else: return [] def class_list(self): '''List all classes in the resolved jars''' classes = [] for jar in self.jars(): names = zipfile.ZipFile(jar).namelist() for name in names: if name.endswith('.class'): classes.append(name[:-6].replace('/', '.')) return sorted(classes) def class_hints(self, class_name): '''Print code hints for using a Java class from Python code Usage:: mgr = cmmnbuild_dep_manager.Manager() jpype = mgr.start_jpype_jvm() print(mgr.class_hints('Fidel')) ''' names = sorted(self.class_search(class_name)) roots = set() for name in names: parts = name.split('.') cname = parts[-1] root = parts[0] if root not in roots: print('{0} = jpype.JPackage(\'{0}\')'.format(root)) roots.add(root) print('{0} = {1}'.format(cname, name)) def class_search(self, class_name): '''Search for Java classes by name''' return list(filter(lambda x: class_name in x, self.class_list())) def class_path(self, extra_jars=[]): '''Returns a delimited string suitable for java.class.path''' jars = self.jars() jars.extend(extra_jars) jars.append(os.getcwd()) return ';'.join(jars) if os.name == 'nt' else ':'.join(jars) def start_jpype_jvm(self, extra_jars=[]): '''Starts a new JPype JVM with the appropriate class path''' import jpype if not jpype.isJVMStarted(): self.log.info( 'starting a JPype JVM with {0} jars from {1}'.format( len(self.jars()), self.jar_path() ) ) javalibpath = os.environ.get('JAVA_JVM_LIB') if javalibpath is None: javalibpath = jpype.getDefaultJVMPath() jpype.startJVM( javalibpath, '-Xss2m', # Required for kernels patching CVE-2017-1000364 '-Djava.class.path={0}'.format(self.class_path(extra_jars)) ) java_version = jpype.java.lang.System.getProperty('java.version') if not java_version.startswith('1.8'): raise OSError('Java version must be >1.8: {0} is {1}'.format( javalibpath, java_version )) else: self.log.warning('JVM is already started') return jpype def _user_dir(self): '''Returns the module directory in the usersitepackages''' return os.path.join(site.getusersitepackages(), __package__) def _dist_dir(self): '''Returns the module directory in the distribution''' return os.path.dirname(__file__) def _dir(self): '''Returns the module directory''' if os.path.isdir(self._user_dir()): return self._user_dir() else: return self._dist_dir() def _load_modules(self): '''Load modules data from modules.json Returns a dictionary of the form: {'name': 'version', ...} Where 'name' is the module name and 'version' is the version of the module for which the jars were downloaded for. Version will be an empty string if the module has been registered but not downloaded. ''' modules = {} # Load pickled 'modules' files created by versions < 2.0.0 old_mod_files = ( os.path.join(self._dist_dir(), 'modules'), os.path.join(self._user_dir(), 'modules') ) for f in old_mod_files: if os.path.isfile(f): self.log.debug('loading {0}'.format(f)) with open(f, 'rb') as fp: pkl_data = pickle.load(fp) for k in pkl_data: modules[k] = '' # Load json 'modules.json' files created by version >= 2.0.0 mod_files = ( os.path.join(self._dist_dir(), 'modules.json'), os.path.join(self._user_dir(), 'modules.json') ) for f in mod_files: if os.path.isfile(f): self.log.debug('loading {0}'.format(f)) with open(f, 'r') as fp: json_data = json.load(fp) for k, v in json_data.items(): modules[k] = v return modules def _save_modules(self, modules): '''Save modules data to modules.json''' user_dir = self._user_dir() dist_dir = self._dist_dir() if os.path.isdir(user_dir): save_dir = user_dir elif os.access(dist_dir, os.W_OK | os.X_OK): save_dir = dist_dir else: self.log.info('creating directory {0}'.format(user_dir)) os.makedirs(user_dir) save_dir = user_dir mod_file = os.path.join(save_dir, 'modules.json') self.log.debug('saving {0}'.format(mod_file)) with open(mod_file, 'w') as fp: json.dump(modules, fp) # Remove 'modules' file used by versions < 2.0.0 old_modules = os.path.join(save_dir, 'modules') if os.path.isfile(old_modules): self.log.warning('removing obsolete file {0}'.format(old_modules)) os.remove(old_modules) def register(self, *args): '''Register one or more modules''' ret = [] modules = self._load_modules() for name in args: try: module = importlib.import_module(name) # Check __cmmnbuild_deps__ exists cmmnbuild_deps = None try: cmmnbuild_deps = module.__cmmnbuild_deps__ except: pass try: cmmnbuild_deps = module.cmmnbuild_deps self.log.warning('{0} uses depreciated cmmnbuild_deps and ' 'should be updated'.format(name)) except: pass if cmmnbuild_deps is None: raise AttributeError # Check __version__ exists version = module.__version__ if name not in modules.keys() or modules[name] != version: modules[name] = '' self.log.info('{0} registered'.format(name)) ret.append(name) except ImportError: self.log.error( '{0} not found'.format(name) ) except AttributeError: self.log.error( '{0}.__cmmnbuild_deps__ does not exist'.format(name) ) if ret: self._save_modules(modules) return tuple(ret) def unregister(self, *args): '''Unregister one or more modules''' ret = [] modules = self._load_modules() for name in args: if name in modules.keys(): del modules[name] self.log.info('{0} unregistered'.format(name)) ret.append(name) if ret: self._save_modules(modules) return tuple(ret) def install(self, *args): '''Register one or more modules and resolve dependencies''' ret = self.register(*args) if ret: self.resolve() return ret def uninstall(self, *args): '''Unregister one or more modules and resolve dependencies''' ret = self.unregister(*args) if ret: self.resolve() return ret def is_registered(self, name): '''Check if module is registered''' modules = self._load_modules() return name in modules.keys() def is_installed(self, name, version=None): '''Check if module is installed''' modules = self._load_modules() if name in modules.keys(): try: if version is None: version = module.__version__ module = importlib.import_module(name) if modules[name] == version: return True except: pass return False def list(self): '''Returns a list of the currently registered modules''' return sorted(self._load_modules().keys()) def resolve(self): '''Resolve dependencies for all registered modules using CBNG''' self.log.info('resolving dependencies') self.log.debug('lib directory is {0}'.format(self.jar_path())) deps = [] modules = self._load_modules() # Build the dependency list from all installed packages for name, vers in modules.items(): try: module = importlib.import_module(name) cmmnbuild_deps = None try: cmmnbuild_deps = module.__cmmnbuild_deps__ except: pass try: cmmnbuild_deps = module.cmmnbuild_deps self.log.warning('{0} uses depreciated cmmnbuild_deps and ' 'should be updated'.format(name)) except: pass if cmmnbuild_deps is None: raise AttributeError for dep in cmmnbuild_deps: if isinstance(dep, str): deps.append({'product': dep}) elif isinstance(dep, dict): deps.append({str(k): str(v) for k, v in dep.items()}) else: raise TypeError('{0}.__cmmnbuild_deps__ must be a list ' 'of str or dict'.format(name)) self.log.info('{0} has dependency {1}'.format( name, deps[-1]['product'] )) modules[name] = module.__version__ except ImportError: self.log.error('{0} not found'.format(name)) self.unregister(name) except Exception as e: self.log.error(e) self._save_modules(modules) if not deps: self.log.error('no dependencies were found') return # Generate product.xml pxml = ET.Element('products') pxml_prod = ET.SubElement(pxml, 'product', attrib={ 'name': __package__, 'version': sys.modules[__package__].__version__, 'directory': '' }) pxml_deps = ET.SubElement(pxml_prod, 'dependencies') for dep in deps: ET.SubElement(pxml_deps, 'dep', attrib=dep) # Post product.xml to CBNG web service self.log.info('resolving dependencies using CBNG web service: ' 'https://wikis.cern.ch/display/DVTLS/CBNG+Web+service') resp = requests.post('http://bewww.cern.ch/ap/cbng-web/', { 'action': 'get-deps', 'product_xml': ET.tostring(pxml) }).json() if not resp['result']: raise Exception(resp['message']) self.log.info('CBNG results: {0}'.format(resp['data']['wd_url'])) # Create user directory if dist directory is not writeable if not os.access(self._dist_dir(), os.W_OK | os.X_OK): if not os.path.exists(self._user_dir()): self.log.info('creating directory {0}'.format( self._user_dir()) ) os.makedirs(self._user_dir()) # Remove 'jars' directory used by versions < 2.0.0 old_jars_dir = os.path.join(self._dir(), 'jars') if os.path.isdir(old_jars_dir): self.log.warning('removing obsolete directory {0}'.format( old_jars_dir )) shutil.rmtree(old_jars_dir) # Remove exisiting jars old_jars = glob.glob(os.path.join(self.jar_path(), '*.jar')) self.log.info('removing {0} jars from {1}'.format( len(old_jars), self.jar_path() )) for jar in old_jars: os.remove(jar) # Download archive file self.log.info('downloading archive: {0}'.format( resp['data']['lib_all_url'] )) with tempfile.TemporaryFile() as tmp_file: lib_all = requests.get(resp['data']['lib_all_url'], stream=True) for chunk in lib_all.iter_content(chunk_size=1024): tmp_file.write(chunk) # Unzip jar archive with zipfile.ZipFile(tmp_file) as zip_file: for f in zip_file.namelist(): if os.path.dirname(f) == 'lib': self.log.info('extracting {0}'.format(f)) zip_file.extract(f, self._dir()) <file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/tempfile.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/operator.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/tarfile.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/_dummy_thread.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/sre_compile.py<file_sep> from flask import Flask, render_template, request,current_app, redirect, session, send_from_directory app = Flask(__name__) app.secret_key = 'super secret key' app.debug = True macbook = False if macbook == False: path_to_years = '/home/awakewebmaster/Desktop/AWAKE_data/' # Note that path_to_desktop is really the path to the parent directory of AWAKE_ANALYSIS_TOOLS path_to_desktop = '/home/awakewebmaster/' else: path_to_years = '/Users/dillonberger/' # Note that path_to_desktop is really the path to the parent directory of AWAKE_ANALYSIS_TOOLS path_to_desktop = '/Users/dillonberger/' import h5py import pandas as pd import numpy as np import os import matplotlib matplotlib.use('Agg') # change all to rel paths so you just have to change env vars os.environ['AAT'] = path_to_desktop + 'AWAKE_ANALYSIS_TOOLS/' import sys sys.path.append(os.environ['AAT'] + 'ntupling') sys.path.append(os.environ['AAT'] + 'ntupling/' + 'map_files') sys.path.append(path_to_desktop + 'AwakeApp/awakeAppModules') #import pytimber #import datetime import holoviews as hv import cutParser import ev_viewer_post import show_ev import edit_plots import raw_ev_viewer_post import show_raw_ev import edit_raw_plots #============================================================================== @app.route('/') def main(): return render_template('indexx.html') # return redirect('/event_viewer/') @app.route('/', methods = ['POST']) def main_post(): key = request.form['list'] db_key = request.form['list_dbs'] if (key == "XMPP") and (db_key == 'Timber'): #change_url_to_different_onw return redirect('/get_XMPP_plots_Timber/') if (key == 'plot') and (db_key == 'Timber'): return redirect('/get_plots_Timber/') if (key=='event_viewer') and (db_key == 'Timber'): return 'Feature not yet available in Timber' if (key == 'XMPP') and (db_key == 'Event_Builder'): return redirect('/get_XMPP_plots_Event_Builder/') if (key == 'plot') and (db_key == 'Event_Builder'): return redirect('/get_plots_EB/') if (key == 'event_viewer') and (db_key == 'Event_Builder'): return redirect('/event_viewer/') if (key == 'event_viewer_raw') and (db_key == 'Event_Builder'): return redirect('/event_viewer_raw/') #============================================================================== @app.route('/event_viewer/') def ev_viewer_select(): return render_template('ev_viewer_select.html') @app.route('/event_viewer/', methods = ['POST', 'GET']) def run_ev_post(): return ev_viewer_post.ev_viewer_post( app, path_to_years = path_to_years, path_to_desktop = path_to_desktop ) # ## Now, since we have a large number of events in a day, we need to ## have a large number of views. This is best done (I think) by using "pages", ## in which everything enclosed in "< >" is a variable we can use. @app.route('/event_viewer/<day>/<month>/<year>/<int:event_id>/') def show_page(event_id, day, month, year): return show_ev.show_ev( event_id, day, month, year, path_to_years = path_to_years, path_to_desktop = path_to_desktop ) @app.route('/event_viewer/<day>/<month>/<year>/<int:event_id>/', methods = ['POST']) def edit_img(event_id, day, month, year): return edit_plots.edit_plots(event_id, day, month, year, path_to_desktop = path_to_desktop) #============================================================================== @app.route('/event_viewer_raw/') def raw_viewer_select(): return render_template('ev_viewer_select.html') @app.route('/event_viewer_raw/', methods = ['POST', 'GET']) def run_raw_ev_post(): return raw_ev_viewer_post.raw_ev_viewer_post(app, path_to_desktop = path_to_desktop, path_to_years = path_to_years) # Now, since we have a large number of events in a day, we need to # have a large number of views. This is best done (I think) by using "pages", # in which the last bit of the url becomes the argument of our function. @app.route('/event_viewer_raw/<day>/<month>/<year>/<int:event_id>/') def show_raw_page(event_id, day, month, year): return show_raw_ev.show_raw_ev( event_id, day, month, year, path_to_desktop = path_to_desktop, path_to_years = path_to_years ) @app.route('/event_viewer_raw/<day>/<month>/<year>/<int:event_id>/', methods = ['POST']) def edit_raw_img(event_id, day, month, year): return edit_raw_plots.edit_raw_plots(event_id, day, month, year, path_to_desktop = path_to_desktop) @app.route('/uploads/<day>/<month>/<year>/<filename>/', methods=['GET']) def download(filename, day, month, year): directory = path_to_years + year +'/' + month +'/' + day +'/' return send_from_directory( directory = directory, filename=filename , as_attachment = True ) #============================================================================== @app.route('/get_plots_Timber/') def plot_param_dropdown_Timber(): return render_template('plot_params_dropdown_Timber.html') @app.route('/get_plots_Timber/', methods = ['POST']) def get_plot_Timber(): start_date = request.form['start_date'] end_date = request.form['end_date'] vert_key = request.form['vertical'] horiz_key = request.form['horizontal'] #get vertical keys if vert_key == 'temperature': channel_name_vert = 'XAWAVS_BEAML_TT_AVG.POSST' vert_label = 'Temperature' if vert_key == 'beam_charge': channel_name_vert = 'TT41.BCTF.412340:INT_EXTR1' vert_label = 'Beam Charge' if vert_key == '<KEY>:HOR_POS': channel_name_vert = 'TT41.BPM.412311:HOR_POS' vert_label = channel_name_vert if vert_key == '<KEY>:VER_POS': channel_name_vert = 'TT41.BPM.412311:VER_POS' vert_label = channel_name_vert if vert_key == '<KEY>:HOR_POS': channel_name_vert = 'TT41.BPM.412319:HOR_POS' vert_label = channel_name_vert if vert_key == '<KEY>:VER_POS': channel_name_vert = 'TT41.BPM.412319:VER_POS' vert_label = channel_name_vert if vert_key == '<KEY>:HOR_POS': channel_name_vert = 'TT41.BPM.412339:HOR_POS' vert_label = channel_name_vert if vert_key == '<KEY>:VER_POS': channel_name_vert = 'TT41.BPM.412339:VER_POS' vert_label = channel_name_vert if vert_key == '<KEY>:HOR_POS': channel_name_vert = 'TT41.BPM.412352:HOR_POS' vert_label = channel_name_vert if vert_key == '<KEY>:VER_POS': channel_name_vert = 'TT41.BPM.412352:VER_POS' vert_label = channel_name_vert if vert_key == '<KEY>:HOR_POS': channel_name_vert = 'TT41.BPM.412425:HOR_POS' vert_label = channel_name_vert if vert_key == '<KEY>:VER_POS': channel_name_vert = 'TT41.BPM.412425:VER_POS' vert_label = channel_name_vert #get horizontal keys if horiz_key == 'temperature': channel_name_horiz = 'XAWAVS_BEAML_TT_AVG.POSST' horiz_label = 'Temperature' if horiz_key == 'beam_charge': channel_name_horiz = 'TT41.BCTF.412340:INT_EXTR1' horiz_label = 'Beam Charge' if horiz_key == 'time': channel_name_horiz = channel_name_vert horiz_label = 'Time' if horiz_key == '<KEY>:HOR_POS': channel_name_horiz = 'TT41.BPM.412311:HOR_POS' horiz_label = channel_name_horiz if horiz_key == '<KEY>:VER_POS': channel_name_horiz = 'TT41.BPM.412311:VER_POS' horiz_label = channel_name_horiz if horiz_key == 'TT41.BPM.412319:HOR_POS': channel_name_horiz = 'TT41.BPM.412319:HOR_POS' horiz_label = channel_name_horiz if horiz_key == '<KEY>2319:VER_POS': channel_name_horiz = 'TT41.BPM.412319:VER_POS' horiz_label = channel_name_horiz if horiz_key == '<KEY>:HOR_POS': channel_name_horiz = 'TT41.BPM.412339:HOR_POS' horiz_label = channel_name_horiz if horiz_key == '<KEY>:VER_POS': channel_name_horiz = 'TT41.BPM.412339:VER_POS' horiz_label = channel_name_horiz if horiz_key == '<KEY>:HOR_POS': channel_name_horiz = 'TT41.BPM.412352:HOR_POS' horiz_label = channel_name_horiz if horiz_key == '<KEY>:VER_POS': channel_name_horiz = 'TT41.BPM.412352:VER_POS' horiz_label = channel_name_horiz if horiz_key == '<KEY>:HOR_POS': channel_name_horiz = 'TT41.BPM.412425:HOR_POS' horiz_label = channel_name_horiz if horiz_key == '<KEY>5:VER_POS': channel_name_horiz = 'TT41.BPM.412425:VER_POS' horiz_label = channel_name_horiz db = pytimber.LoggingDB() # start_date = '2017-06-02 01:00:00.000' # end_date = '2017-06-02 01:30:00.000' if horiz_key =='time': resp_vert = db.get(channel_name_vert,start_date,end_date) resp_horiz = resp_vert vert_vals = resp_vert[channel_name_vert][1] vert_times = resp_vert[channel_name_vert][0] horiz_times = vert_times horiz_vals = vert_times df = pd.DataFrame() df['t'] = horiz_vals # Have to convert to local timezones!! # Will change for daylinght savings!!! df['t'] = pd.to_datetime(df['t'], unit='s').dt.tz_localize('Etc/GMT+2').dt.tz_convert('UTC') df['v'] = vert_vals horiz_vals = df['t'] vert_vals = df['v'] else: resp_vert = db.get(channel_name_vert,start_date,end_date) resp_horiz = db.get(channel_name_horiz,start_date,end_date) vert_vals = resp_vert[channel_name_vert][1] vert_times = resp_vert[channel_name_vert][0] horiz_vals = resp_horiz[channel_name_horiz][1] horiz_times = resp_horiz[channel_name_horiz][0] #Need to eventually loop over all data between start and end if too large #and possibly restructure if it will crash server # In the case where there are not the same number of elements in domain and range # Comparing timestamps from timber if len(vert_times) > len(horiz_times): print('LISTS ARE DIFFERENT SIZES') vert_indices = find_closest_indices(vert_times, horiz_times) new_vert_vals = [] for ix in vert_indices: new_vert_vals.append(vert_vals[ix]) vert_vals = new_vert_vals if len(vert_times) < len(horiz_times): print('LISTS ARE DIFFERENT SIZES') horiz_indices = find_closest_indices(horiz_times, vert_times) new_horiz_vals = [] for ix in horiz_indices: new_horiz_vals.append(horiz_vals[ix]) horiz_vals = new_horiz_vals print(len(vert_vals)) #maybe a function even if they are equal?? if horiz_key == 'time': p = figure(plot_width=750, plot_height=700, tools=['box_zoom', 'reset', 'pan', 'tap', 'wheel_zoom'], x_axis_type="datetime") else: p = figure(plot_width=750, plot_height=700, tools=['box_zoom', 'reset', 'pan', 'tap', 'wheel_zoom']) p.circle(horiz_vals, vert_vals, size = 6) p.xaxis.axis_label = horiz_label p.yaxis.axis_label = vert_label path_to_plot = './static/' plot_name = 'myplot.html' output_file(path_to_plot + plot_name) show(p) return render_template('plot_params_dropdown_Timber.html') #============================================================================== @app.route('/test_EB/') def test_EB_home(): return render_template('test_EB_index.html') @app.route('/test_EB/', methods = ['POST']) def test_EB_post(): start_date = request.form['start_date'] end_date = request.form['end_date'] beam_status = request.form['beam_status'] message = 'Start date is %s. End date is %s. Beam status is %s' % (start_date, end_date, beam_status) return message @app.route('/get_plots_EB/') def plot_param_dropdown_EB(): return render_template('plot_params_dropdown_EB.html') @app.route('/get_plots_EB/', methods = ['POST']) def get_plot_EB(): start_date = request.form['start_date'] end_date = request.form['end_date'] vert_key = request.form['vertical'] horiz_key = request.form['horizontal'] #get vertical keys if vert_key == 'temperature': channel_name_vert = '/AwakeEventData/awake.XAWAVS_BEAML_TT_AVG/PosSt/value' vert_label = 'Temperature' if vert_key == 'beam_charge': channel_name_vert = '/AwakeEventData/TT41.BCTF.412340/Acquisition/totalIntensityPreferred' vert_label = 'Beam Charge' #get horizontal keys if horiz_key == 'temperature': channel_name_horiz = '/AwakeEventData/awake.XAWAVS_BEAML_TT_AVG/PosSt/value' horiz_label = 'Temperature' if horiz_key == 'beam_charge': channel_name_horiz = '/AwakeEventData/TT41.BCTF.412340/Acquisition/totalIntensityPreferred' horiz_label = 'Beam Charge' if horiz_key == 'time': channel_name_horiz = channel_name_vert horiz_label = 'Time' #Hard code path to template path_to_template = os.environ['AAT'] + 'scratch/' template_name = 'cuts_template.txt' #Get template contents file = open( path_to_template + template_name,"r") contents = file.read() file.close() #Write new file to out.txt output_filename = 'out.txt' file = open( path_to_template + output_filename ,"w") init_rep_contents = contents.replace('xx-xx-xxxx xx:xx:xx', start_date) rep_contents = init_rep_contents.replace('yy-yy-yyyy yy:yy:yy', end_date) file.write(rep_contents) file.close() print('done writing') # flist returns list of files that fall within the time range cp = cutParser.inputParser(path_to_template + output_filename) print('cut made') good_list = cp.flist print(good_list) timestamps = np.array([]) horiz_vals = np.array([]) vert_vals = np.array([]) ### replace with returnGoodData.py ### give it channel_name, and good_list ### returns numpy data array, bool_array, warn_array, time_array ### care about first two ### take list[bool==True] for i in range(len(good_list)): path_to_event = good_list[i] hf0 = h5py.File(good_list[i]) #extract file name f_name = ( path_to_event.split(os.sep) )[-1] #find position of first occurance of underscore in file name under_posit = f_name.find('_') #extract timestamp timestamp=f_name[:under_posit] timestamps = np.append(timestamps, float(timestamp)/(1e9)) horiz_vals = np.append(horiz_vals, hf0[channel_name_horiz]) vert_vals = np.append(vert_vals, hf0[channel_name_vert]) # In the case where there are not the same number of elements in domain and range # Comparing timestamps from timber if horiz_key =='time': horiz_vals = timestamps df = pd.DataFrame() df['t'] = horiz_vals # Have to convert to local timezones!! # Will have to change for daylight savings!! df['t'] = pd.to_datetime(df['t'], unit='s').dt.tz_localize('Etc/GMT+2').dt.tz_convert('UTC') df['v'] = vert_vals horiz_vals = df['t'] vert_vals = df['v'] if horiz_key == 'time': p = figure(plot_width=750, plot_height=700, tools=['box_zoom', 'reset', 'pan', 'tap', 'wheel_zoom'], x_axis_type="datetime") else: p = figure(plot_width=750, plot_height=700, tools=['box_zoom', 'reset', 'pan', 'tap', 'wheel_zoom']) p.circle(horiz_vals, vert_vals, size = 6) p.xaxis.axis_label = horiz_label p.yaxis.axis_label = vert_label path_to_plot = './static/' plot_name = 'myplot.html' output_file(path_to_plot + plot_name) show(p) return 'Your request is complete.' #============================================================================== @app.route('/get_XMPP_plots_Event_Builder/') def XMPP_textbox_EB(): return render_template('EB_textbox.html') @app.route('/get_XMPP_plots_Event_Builder/', methods = ['POST']) def XMPP_textbox_EB_post(): #Retrieve start date and end date from website start_date = request.form['start_date'] end_date = request.form['end_date'] ##Write error if somebody requests too much data #Hard code path to template path_to_template = os.environ['AAT'] + 'scratch/' template_name = 'cuts_template.txt' #Get template contents file = open( path_to_template + template_name,"r") contents = file.read() file.close() #Write new file to out.txt output_filename = 'out.txt' file = open( path_to_template + output_filename ,"w") init_rep_contents = contents.replace('xx-xx-xxxx xx:xx:xx', start_date) rep_contents = init_rep_contents.replace('yy-yy-yyyy yy:yy:yy', end_date) file.write(rep_contents) file.close() # cp = cutParser.inputObject(path_to_template + output_filename) # need a parsing field to call cp()^^ # flist returns list of files that fall within the time range cp = cutParser.inputParser(path_to_template + output_filename) good_list = cp.flist renderer = hv.Store.renderers['bokeh'] for i in range(len(good_list[0])): hf0 = h5py.File(good_list[i]) #Check indicies on img_w, img_h img_w = hf0['/AwakeEventData/XMPP-STREAK/StreakImage/streakImageWidth'][0] img_h = hf0['/AwakeEventData/XMPP-STREAK/StreakImage/streakImageHeight'][0] img_data = hf0['/AwakeEventData/XMPP-STREAK/StreakImage/streakImageData'] hv.extension('bokeh') M_0 = np.reshape(img_data ,( int(img_h),int(img_w))) img = hv.Raster(M_0) # renderer = hv.Store.renderers['bokeh'] if i<1: layout = img if i >= 1: layout = img + layout path_to_plot = './static/' plot_name = 'plots_EB.html' f = open(path_to_plot + plot_name, 'w') f.write(renderer.static_html(layout)) return app.send_static_file( plot_name ) # THIS IS BROKEN ???? # PERHAPS TRY OUTPUT_FILE #============================================================================== @app.route('/get_XMPP_plots_Timber/') def XMPP_textbox(): return render_template('XMPP_textbox.html') ## #### WRITE SOMETHING THAT DOESN'T LET YOU SEND A QUERY TOO LARGE SO IT WONT CRASH THE SERVER### ## @app.route('/get_XMPP_plots_Timber/', methods = ['POST']) def XMPP_textbox_post(): start_date = request.form['start_date'] end_date = request.form['end_date'] db = pytimber.LoggingDB() #### Get images for XMPP channel_name = "XMPP-STREAK/StreakImage#streakImageData" # start_date = '2017-06-02 01:00:00.000' # end_date = '2017-06-02 01:30:00.000' resp = db.get(channel_name,start_date,end_date) #Need to eventually loop over all data between '2017-06-02 01:00:00.000','2017-06-10 01:10:00.000' timestamp = resp[channel_name][0] param_vals = resp[channel_name][1] #Each param_vals[i] is an image arranged as a 1D list. img_w = (db.get("XMPP-STREAK/StreakImage#streakImageWidth", start_date, end_date))['XMPP-STREAK/StreakImage#streakImageWidth'][1][0] img_h = ( db.get("XMPP-STREAK/StreakImage#streakImageHeight", start_date, end_date) )["XMPP-STREAK/StreakImage#streakImageHeight"][1][0] for i in range(len(param_vals)): M_0 = np.reshape( np.array( param_vals[i]),( int(img_h),int(img_w) ) ) Mc = np.clip(M_0, 400, 900) # hv.extension('bokeh') img = hv.Raster(Mc, label = 'Event ID: ' + str(timestamp[i])) renderer = hv.Store.renderers['bokeh'] if i<1: layout = img if i >= 1: layout = img + layout path_to_plot = './static/' plot_name = 'plots.html' f = open(path_to_plot + plot_name, 'w') f.write(renderer.static_html(layout)) return app.send_static_file( plot_name ) #============================================================================== #Again, only has to be true when running on python interpretor if __name__ == "__main__": # port = int(os.environ.get('PORT', 5000)) # SocketIO.run(app, host='0.0.0.0') app.run(host='0.0.0.0') # print('in here!!') <file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/enum.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/genericpath.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/_collections_abc.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/tokenize.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/_weakrefset.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/token.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/reprlib.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/hashlib.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/weakref.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/copyreg.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/linecache.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/fnmatch.py<file_sep>Consult README.rst <file_sep>import sys from flask import request, session def edit_plots(event_id, day, month, year, path_to_desktop = ''): sys.path.append(path_to_desktop + 'AwakeApp') from awake_app import show_page session['XMPP_vmin'] = request.form.get('XMPP_vmin', '') session['XMPP_vmax'] = request.form.get('XMPP_vmax', '') session['BTV_vmin'] = request.form.get('BTV_vmin', '') session['BTV_vmax'] = request.form.get('BTV_vmax', '') session['uhalo_vmin'] = request.form.get('uhalo_vmin','') session['uhalo_vmax'] = request.form.get('uhalo_vmax', '') session['dhalo_vmin'] = request.form.get('dhalo_vmin', '') session['dhalo_vmax'] = request.form.get('dhalo_vmax', '') reset = request.form.get('reset', None) if reset == 'Reset': session['counter'] = 'reset' return show_page(event_id, day, month, year) <file_sep>Document on <https://github.com/hustcc/pypi-demo> <file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/posixpath.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/locale.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/base64.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/imp.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/functools.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/struct.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/re.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/stat.py<file_sep>/home/awakewebmaster/anaconda3/lib/python3.6/codecs.py
e15bb33f984b86fd01ab5f54abd79068275dca8c
[ "Markdown", "Python", "reStructuredText" ]
57
Python
dillonberger99/awake
142998155c03fd70b8b0af3a977c70f52450bee0
4a593dbeb285dcdce94210d61fc141d0ccb9040b
refs/heads/master
<repo_name>NilsBohr/JS_modules_Z-Way<file_sep>/ConditionerManager/index.js // ---------------------------------------------------------------------------- // --- Class definition, inheritance and setup // ---------------------------------------------------------------------------- function ConditionerManager (id, controller) { // Call superconstructor first (AutomationModule) ConditionerManager.super_.call(this, id, controller); } inherits(ConditionerManager, AutomationModule); _module = ConditionerManager; // ---------------------------------------------------------------------------- // --- Module instance initialized // ---------------------------------------------------------------------------- ConditionerManager.prototype.init = function (config) { ConditionerManager.super_.prototype.init.call(this, config); var self = this; this.vDev = this.controller.devices.create({ deviceId: this.getName() + '_' + this.id, defaults: { deviceType: 'switchBinary', metrics: { icon: 'switch', level: 'off', title: this.getInstanceTitle() } }, overlay: {}, handler: function(command) { if (command != 'update') { if (command === 'on') { self.vDev.set('metrics:level', command); zway.devices[self.config.node].instances[self.config.instance].commandClasses[self.config.commandclass].Set(5); } else if (command === 'off') { self.vDev.set('metrics:level', command); zway.devices[self.config.node].instances[self.config.instance].commandClasses[self.config.commandclass].Set(0); } } }, moduleId: this.id }); }; ConditionerManager.prototype.stop = function () { if (this.vDev) { this.controller.devices.remove(this.vDev.id); this.vDev = null; } ConditionerManager.super_.prototype.stop.call(this); }; // ---------------------------------------------------------------------------- // --- Module methods // ---------------------------------------------------------------------------- ConditionerManager.prototype.debug_log = function (msg) { if (this.debugState === true) { console.log('--- DBG[ConditionerManager_' + this.id + msg); } }<file_sep>/BindDeviceStatus/index.js // ---------------------------------------------------------------------------- // --- Class definition, inheritance and setup // ---------------------------------------------------------------------------- function BindDeviceStatus (id, controller) { // Call superconstructor first (AutomationModule) BindDeviceStatus.super_.call(this, id, controller); } inherits(BindDeviceStatus, AutomationModule); _module = BindDeviceStatus; // ---------------------------------------------------------------------------- // --- Module instance initialized // ---------------------------------------------------------------------------- BindDeviceStatus.prototype.init = function (config) { BindDeviceStatus.super_.prototype.init.call(this, config); var self = this; this.debugState = this.config.debug; this.checkCondition = function () { if (self.intervalTimer) { clearInterval("}:" + self.intervalTimer); } if (self.timeoutTimer) { clearTimeout(self.timeoutTimer); } self.intervalCounter = 0; self.debug_log("]: Starting interval timer.."); self.intervalTimer = setInterval(function () { self.debug_log("]: Interval is on step: " + self.intervalCounter); self.debug_log("]: Sending a command to request devices status update.."); var managedDevice = self.controller.devices.get(self.config.managedDevice), trackedDevice = self.controller.devices.get(self.config.trackedDevice); managedDevice.performCommand("update"); trackedDevice.performCommand("update"); self.debug_log("]: Setting timeout timer on 5 sec. Checking sensors state.."); self.timeoutTimer = setTimeout(function () { self.debug_log("]: Timeout is ended! Getting devices states.."); var managedDeviceValue = managedDevice.get("metrics:level"); var trackedDeviceValue = trackedDevice.get("metrics:level"); self.debug_log("]: Switch current state is: " + managedDeviceValue); self.debug_log("]: Sensor current state is: " + trackedDeviceValue); if (((trackedDeviceValue == "on") && (managedDeviceValue == "off"))) { self.debug_log("]: Condition is checked! Changing managed device state to ON.."); managedDevice.performCommand("on"); } else if (((trackedDeviceValue == "off") && (managedDeviceValue == "on"))) { self.debug_log("]: Condition is checked! Changing managed device state to OFF.."); managedDevice.performCommand("off"); } else { self.debug_log("]: Condition is checked! Nothing to do."); } }, 5 * 1000); self.intervalCounter++; if (self.intervalCounter > 29) { self.debug_log("]: Job is done! Clearing interval timer.."); clearInterval(self.intervalTimer); } }, 60 * 1000); } this.controller.devices.on(this.config.daylight, "change:metrics:level", this.checkCondition); }; BindDeviceStatus.prototype.stop = function () { if (this.intervalTimer) { clearInterval(this.intervalTimer); } if (this.timeoutTimer) { clearTimeout(this.timeoutTimer); } this.controller.devices.off(this.config.daylight, "change:metrics:level", this.checkCondition); BindDeviceStatus.super_.prototype.stop.call(this); }; // ---------------------------------------------------------------------------- // --- Module methods // ---------------------------------------------------------------------------- BindDeviceStatus.prototype.debug_log = function (msg) { if (this.debugState === true) { console.log("--- DBG[BindingDeviceStatus_" + this.id + msg); } }<file_sep>/FanManager/index.js // ---------------------------------------------------------------------------- // --- Class definition, inheritance and setup // ---------------------------------------------------------------------------- function FanManager (id, controller) { // Call superconstructor first (AutomationModule) FanManager.super_.call(this, id, controller); } inherits(FanManager, AutomationModule); _module = FanManager; // ---------------------------------------------------------------------------- // --- Module instance initialized // ---------------------------------------------------------------------------- FanManager.prototype.init = function (config) { FanManager.super_.prototype.init.call(this, config); var self = this; this.isTurnedOnViaTemperatureSensor = false; this.isTurnedOnViaLight = false; this.isEnabledManualMode = false; this.checkTemperature = function() { var vDevTSensor = self.controller.devices.get(self.config.temperatureSensor), vDevSwitch = self.controller.devices.get(self.config.switch); var vDevTSensorValue = vDevTSensor.get("metrics:level"), vDevSwitchValue = vDevSwitch.get("metrics:level"); if (!self.isEnabledManualMode) { if (!self.isTurnedOnViaLight) { if (vDevTSensorValue > self.config.degree) { if (vDevSwitchValue !== "on") { vDevSwitch.performCommand("on"); self.debug_log("Sensor's temperature is changed. It's value is more than " + self.config.degree + " (current value is: " + vDevTSensorValue + "). Fan is turned ON."); self.isTurnedOnViaTemperatureSensor = true; } else { self.debug_log("Sensor's temperature is changed. It's value is more than " + self.config.degree + " (current value is: " + vDevTSensorValue + "), but fan is already ON. Nothing to do."); } } else if (vDevTSensorValue < self.config.degree) { if (vDevSwitchValue !== "off") { vDevSwitch.performCommand("off"); self.debug_log("Sensor's temperature is changed. It's value is lower than " + self.config.degree + " (current value is: " + vDevTSensorValue + "). Fan is turned OFF."); self.isTurnedOnViaTemperatureSensor = false; } else { self.debug_log("Sensor's temperature is changed. It's value is lower than " + self.config.degree + " (current value is: " + vDevTSensorValue + "), but fan is already OFF. Nothing to do."); } } } else { self.debug_log("Temperature sensor is triggered, but fan is currently switched on by the light. Nothing to do."); } } else { self.debug_log("Temperature sensor is triggered, but manual mode is currently turned on. Nothing to do."); } }; this.checkLight = function() { var vDevTSensor = self.controller.devices.get(self.config.temperatureSensor), vDevLight = self.controller.devices.get(self.config.light), vDevSwitch = self.controller.devices.get(self.config.switch); var vDevLightValue = vDevLight.get("metrics:level"), vDevSwitchValue = vDevSwitch.get("metrics:level"); if (vDevLightValue > 0) { self.debug_log("Light changed state to on. Nothing to do."); } else { self.isEnabledManualMode = false; self.debug_log("Manual mode is disabled."); if (!self.isTurnedOnViaTemperatureSensor) { self.debug_log("Light changed state to OFF. Checking fan state.."); if (vDevSwitchValue !== "on") { vDevSwitch.performCommand("on"); self.debug_log("Fan is turned on for " + self.config.endtime + " min."); self.isTurnedOnViaLight = true; self.clear_timeout(self.timeoutTimer); self.timeoutTimer = setTimeout (function () { if ((vDevSwitch.get("metrics:level") !== "off") && (vDevTSensor.get("metrics:level") < self.config.degree)) { vDevSwitch.performCommand("off"); self.debug_log("Timer is ended. Fan is turned OFF."); } else if ((vDevSwitch.get("metrics:level") !== "off") && (vDevTSensor.get("metrics:level") > self.config.degree)) { self.debug_log("Timer is ended, but temperature sensor value is still more than " + self.config.degree + " (current value is: " + vDevTSensor.get("metrics:level") + "). Nothing to do."); } else { self.debug_log("Timer is ended, but fan is already OFF. Nothing to do."); } self.isTurnedOnViaLight = false; }, self.config.endtime * 60 * 1000); self.debug_log("Timer is started for " + self.config.endtime + " min.."); } else { self.debug_log("Fan is already ON. Nothing to do."); } } else { self.debug_log("Light is triggered, but fan is currently switched on by the temparature sensor. Nothing to do."); } } }; this.manualMode = function () { self.debug_log("Manual mode is triggered"); var vDevLight = self.controller.devices.get(self.config.light), vDevScene = self.controller.devices.get(self.config.scene), vDevSwitch = self.controller.devices.get(self.config.switch); var vDevLightValue = vDevLight.get("metrics:level"), vDevSceneValue = vDevScene.get("metrics:level"), vDevSwitchValue = vDevSwitch.get("metrics:level"); if (vDevSceneValue === self.config.sceneValue) { self.isTurnedOnViaTemperatureSensor = false; self.isTurnedOnViaLight = false; self.clear_timeout(self.timeoutTimer); if (vDevLightValue > 0) { if (!self.isEnabledManualMode) { self.isEnabledManualMode = true; self.debug_log("Manual mode is enabled."); } if (vDevSwitchValue !== "on") { vDevSwitch.performCommand("on"); self.debug_log("Fan is manually enabled."); } else { vDevSwitch.performCommand("off"); self.debug_log("Fan is manually disabled."); } } } } this.controller.devices.on(this.config.temperatureSensor, 'change:metrics:level', this.checkTemperature); this.controller.devices.on(this.config.light, 'change:metrics:level', this.checkLight); this.controller.devices.on(this.config.scene, 'change:metrics:level', this.manualMode); }; FanManager.prototype.stop = function () { FanManager.super_.prototype.stop.call(this); var self = this; this.controller.devices.off(this.config.temperatureSensor, 'change:metrics:level', this.checkTemperature); this.controller.devices.off(this.config.light, 'change:metrics:level', this.checkLight); this.controller.devices.off(this.config.scene, 'change:metrics:level', this.manualMode); }; // ---------------------------------------------------------------------------- // --- Module methods // ---------------------------------------------------------------------------- FanManager.prototype.debug_log = function (msg) { if (this.config.debug) { console.log("--- DBG[FanManager_" + this.id + "]: " + msg); } } FanManager.prototype.clear_timeout = function (timerInstance) { if (timerInstance) { this.debug_log("Found existing timeout timer. Clearing it.."); clearTimeout(timerInstance); } }<file_sep>/TowelDryer/index.js // ---------------------------------------------------------------------------- // --- Class definition, inheritance and setup // ---------------------------------------------------------------------------- function TowelDryer (id, controller) { // Call superconstructor first (AutomationModule) TowelDryer.super_.call(this, id, controller); } inherits(TowelDryer, AutomationModule); _module = TowelDryer; // ---------------------------------------------------------------------------- // --- Module instance initialized // ---------------------------------------------------------------------------- TowelDryer.prototype.init = function (config) { TowelDryer.super_.prototype.init.call(this, config); var self = this; this.runScene = function() { var vDevSwitch = self.controller.devices.get(self.config.switch); if (self.isChecked) { if (vDevSwitch.get("metrics:level") === "off") { vDevSwitch.performCommand("on"); self.debug_log("Switch value is changed state to ON"); self.timer = setTimeout(function() { if (vDevSwitch.get("metrics:level") === "on") { vDevSwitch.performCommand("off"); self.debug_log("Switch value is changed state to OFF"); } else { self.debug_log("Switch value is already in OFF state"); } self.isChecked = false; self.debug_log("self.isChecked variable changed state to FALSE"); clearTimeout(self.timer); }, self.config.offtime * 60 * 60 * 1000); } else { self.debug_log("Switch value is already in ON state"); } } }; this.checkConditions = function() { var vDevSensor = self.controller.devices.get(self.config.sensor), vDevSwitch = self.controller.devices.get(self.config.switch); var getSensorValue = vDevSensor.get("metrics:level"), getSwitchValue = vDevSwitch.get("metrics:level"); var date = new Date(); var startTime = Number(self.config.starttime.split(":")[0]) * 60 + Number(self.config.starttime.split(":")[1]), currentTime = date.getHours() * 60 + date.getMinutes(), earlyTime = startTime - 360; if (((currentTime >= earlyTime) && (currentTime < startTime)) && (!self.isChecked)) { if (getSensorValue === "on") { self.isChecked = true; self.debug_log("self.isChecked variable changed state to TRUE"); } self.debug_log("------------TowelDryer_" + self.id + " DEBUG------------"); self.debug_log("startTime: " + startTime); self.debug_log("currentTime: " + currentTime); self.debug_log("earlyTime: " + earlyTime); self.debug_log("self.isChecked: " + self.isChecked); self.debug_log("currentTime >= earlyTime: "+ (currentTime >= earlyTime)); self.debug_log("currentTime < startTime: " + (currentTime < startTime)); self.debug_log("getSensorValue === 'on': " + (getSensorValue === "on")); self.debug_log("Switch state: " + getSwitchValue); self.debug_log("------------TowelDryer_" + self.id + " DEBUG------------"); } }; // set up motion sensor handler this.controller.devices.on(this.config.sensor, 'change:metrics:level', this.checkConditions); // set up cron handler this.controller.on("TowelDryer.run." + this.id, this.runScene); // add cron schedule var wds = this.config.weekdays.map(function(x) { return parseInt(x, 10); }); if (wds.length == 7) { wds = [null]; // same as all - hack to add single cron record. NB! changes type of wd elements from integer to null } wds.forEach(function(wd) { self.controller.emit("cron.addTask", "TowelDryer.run." + self.id, { minute: parseInt(self.config.starttime.split(":")[1], 10), hour: parseInt(self.config.starttime.split(":")[0], 10), weekDay: wd, day: null, month: null }); }); }; TowelDryer.prototype.stop = function () { TowelDryer.super_.prototype.stop.call(this); this.controller.emit("cron.removeTask", "TowelDryer.run." + this.id); this.controller.off("TowelDryer.run." + this.id, this.runScene); this.controller.devices.off(this.config.sensor, 'change:metrics:level', this.checkConditions); }; // ---------------------------------------------------------------------------- // --- Module methods // ---------------------------------------------------------------------------- TowelDryer.prototype.debug_log = function (msg) { if (this.config.debug) { console.log("--- DBG[TowelDryer_" + this.id + "]: " + msg); } } <file_sep>/ThermostatShoeDryer/index.js // ---------------------------------------------------------------------------- // --- Class definition, inheritance and setup // ---------------------------------------------------------------------------- function ThermostatShoeDryer (id, controller) { // Call superconstructor first (AutomationModule) ThermostatShoeDryer.super_.call(this, id, controller); } inherits(ThermostatShoeDryer, AutomationModule); _module = ThermostatShoeDryer; // ---------------------------------------------------------------------------- // --- Module instance initialized // ---------------------------------------------------------------------------- ThermostatShoeDryer.prototype.init = function (config) { ThermostatShoeDryer.super_.prototype.init.call(this, config); var self = this; this.runScene = function() { var vDevSwitch = self.controller.devices.get(self.config.switch), vDevThermostat = self.controller.devices.get(self.config.thermostat); if (self.isChecked) { self.debug_log("It's time to turn on the shoe dryer, common condition is TRUE. Performing devices actions..."); if (vDevSwitch.get("metrics:level") === "off") { if (vDevThermostat.get("metrics:level") !== self.config.thermostatConditionDegree) { vDevThermostat.performCommand("exact", {level : self.config.thermostatConditionDegree}); self.debug_log("Shoe dryer thermostat changed its value to: " + self.config.thermostatConditionDegree); } else { self.debug_log("Shoe dryer thermostat is already at level: " + self.config.thermostatConditionDegree); } vDevSwitch.performCommand("on"); self.debug_log("Shoe dryer is set to ON"); self.timer = setTimeout(function() { if (vDevSwitch.get("metrics:level") === "on") { vDevSwitch.performCommand("off"); self.debug_log("Shoe dryer is set to OFF"); } else { self.debug_log("Shoe dryer is already OFF"); } self.isChecked = false; clearTimeout(self.timer); }, self.config.offtime * 60 * 60 * 1000); } else { self.debug_log("Shoe dryer is alredy ON"); } } else { self.debug_log("It's time to turn on the shoe dryer, but common condition is FALSE. Nothing to do"); } }; this.checkConditions = function() { var vDevWeather = self.controller.devices.get(self.config.informer), vDevSensor = self.controller.devices.get(self.config.sensor), vDevSwitch = self.controller.devices.get(self.config.switch), configStartTime = self.config.starttime.split(":"); var getWeatherValue = vDevWeather.get("metrics:zwaveOpenWeather:weather"), getSensorValue = vDevSensor.get("metrics:level"), getSwitchValue = vDevSwitch.get("metrics:level"); var date = new Date(); var startTime = Number(configStartTime[0]) * 60 + Number(configStartTime[1]), currentTime = date.getHours() * 60 + date.getMinutes(), earlyTime = startTime - 180; if (((currentTime >= earlyTime) && (currentTime < startTime))) { self.debug_log("Time condition is TRUE"); if (!self.isChecked) { if (getWeatherValue[0].main === "Rain") { self.debug_log("Rain condition is TRUE"); if (getSensorValue === "on") { self.debug_log("Motion condition is TRUE"); self.isChecked = true; self.debug_log("Common condition is set to TRUE"); } else { self.debug_log("Motion condition is FALSE"); } } else { self.debug_log("Rain condition is FALSE"); } } else { self.debug_log("Common condition is already TRUE. Waiting for start time to perform devices actions"); } } else { self.debug_log("Time condition is FALSE"); } }; // set up cron handler this.controller.on("ThermostatShoeDryer.run." + this.id, this.runScene); // set up motion and rain handler this.controller.devices.on(this.config.sensor, 'change:metrics:level', this.checkConditions); this.controller.devices.on(this.config.informer, 'metrics:zwaveOpenWeather:weather', this.checkConditions); // add cron schedule var wds = this.config.weekdays.map(function(x) { return parseInt(x, 10); }); if (wds.length == 7) { wds = [null]; // same as all - hack to add single cron record. NB! changes type of wd elements from integer to null } wds.forEach(function(wd) { self.controller.emit("cron.addTask", "ThermostatShoeDryer.run." + self.id, { minute: parseInt(self.config.starttime.split(":")[1], 10), hour: parseInt(self.config.starttime.split(":")[0], 10), weekDay: wd, day: null, month: null }); }); }; ThermostatShoeDryer.prototype.stop = function () { ThermostatShoeDryer.super_.prototype.stop.call(this); this.controller.emit("cron.removeTask", "ThermostatShoeDryer.run." + this.id); this.controller.off("ThermostatShoeDryer.run." + this.id, this.runScene); this.controller.devices.off(this.config.sensor, 'change:metrics:level', this.checkConditions); this.controller.devices.off(this.config.informer, 'metrics:zwaveOpenWeather:weather', this.checkConditions); }; // ---------------------------------------------------------------------------- // --- Module methods // ---------------------------------------------------------------------------- ThermostatShoeDryer.prototype.debug_log = function (msg) { if (this.config.debug) { console.log("--- DBG[ThermostatShoeDryer_" + this.id + "]: " + msg); } }<file_sep>/HomePresence/index.js // ---------------------------------------------------------------------------- // --- Class definition, inheritance and setup // ---------------------------------------------------------------------------- function HomePresence(id, controller){ // Call superconstructor first (AutomationModule) HomePresence.super_.call(this, id, controller); this.icon_path = '/ZAutomation/api/v1/load/modulemedia/HomePresence/'; } inherits(HomePresence, AutomationModule); _module = HomePresence; // ---------------------------------------------------------------------------- // --- Module instance initialized // ---------------------------------------------------------------------------- HomePresence.prototype.init = function (config){ HomePresence.super_.prototype.init.call(this, config); var self = this; if (!this.config.interval) { this.config.interval = 1; } if (!this.config.netcat_port) { this.config.netcat_port = 80; } if (!this.config.motion_timeout) { this.config.motion_timeout = 1; } var dev_id = 'HomePresence_' + self.id; var dev_title = 'Home presence status'; this.vDevPresence = this.controller.devices.create({ deviceId: dev_id, defaults: { deviceType: 'switchBinary', metrics: { level: 'off', icon: self.icon_path + 'icon.png', title: dev_title } }, overlay: {}, handler: function (command){ if (command != 'update') { this.set("metrics:level", command); saveObject(this.id + "_level" , command); } }, moduleId: self.id }); this.poll_addr = function () { try { self.isAddrAlive = false; self.config.network_addresses.forEach(function (item) { var addr = item.addr; var p = self.config.netcat_port; var response = system('netcat -v -z -w ' + '10' + ' ' + addr + ' ' + p + ' 2>&1'); if (response[1].indexOf('No route to host') == -1 && (response[1].indexOf('Operation now in progress') == -1)) { self.isAddrAlive = true; self.debug_log(addr + ' is present'); } else { self.debug_log(addr + ' is absent'); } }); if (self.isAddrAlive) { if (self.isTimerStarted) { clearTimeout(self.motionTimeout); self.isTimerStarted = false; } if (self.vDevPresence.get('metrics:level') === 'off') { self.vDevPresence.performCommand("on"); self.info_log('Presence switch changed state to ON'); } else { self.debug_log('Presence switch is already ON'); } } if (!self.isAddrAlive && !self.isMotionPresent) { self.checkMotion(); } } catch(err){ console.log('[HomePresence]: ' + err) var msg = 'Home Presence: No permissions to run netcat. Add command "netcat" (without quotes) to .syscommands file.'; self.controller.addNotification( 'error', msg, 'module', 'HomePresence' ); self.info_log('Polling failed, check .syscommands file'); return; } }; var crontime = {minute: [0, 59, this.config.interval], hour: null, weekDay: null, day: null, month: null}; this.crontask_name = 'HomePresence_' + this.id + '.poll'; this.controller.emit('cron.addTask', this.crontask_name, crontime); this.controller.on(this.crontask_name, this.poll_addr); this.checkMotion = function () { self.isMotionPresent = false; self.config.motion_sensors.forEach(function(dev) { var motionSensor = self.controller.devices.get(dev.motion_sensor); if (motionSensor.get('metrics:level') === 'on') { self.isMotionPresent = true; } }); if (self.isMotionPresent) { if (self.motionTimeout) { self.printMotionStatus(); clearTimeout(self.motionTimeout); self.isTimerStarted = false; } if (self.vDevPresence.get('metrics:level') === 'off') { self.printMotionStatus(); self.vDevPresence.performCommand("on"); self.info_log('Presence switch changed state to ON'); } } if (!self.isTimerStarted) { if (!self.isMotionPresent && !self.isAddrAlive) { if (self.vDevPresence.get('metrics:level') !== 'off') { self.printMotionStatus(); self.debug_log("Timer is started for " + self.config.motion_timeout + " hour(s)"); self.isTimerStarted = true; self.motionTimeout = setTimeout(function () { if (!self.isMotionPresent && !self.isAddrAlive) { self.vDevPresence.performCommand("off"); self.info_log(self.config.motion_timeout + ' hour(s) timer is ended. Presence switch changed state to OFF'); } self.isTimerStarted = false; }, self.config.motion_timeout * 60 * 60 * 1000); } else { self.debug_log('Presence switch is already OFF. No need to start timer.'); } } } } this.config.motion_sensors.forEach(function(dev) { self.controller.devices.on(dev.motion_sensor, 'change:metrics:level', self.checkMotion); }); this.poll_addr(); }; // ---------------------------------------------------------------------------- // --- Module instance stopped // ---------------------------------------------------------------------------- HomePresence.prototype.stop = function (){ HomePresence.super_.prototype.stop.call(this); var self = this; if (this.isTimerStarted) { clearTimeout(this.motionTimeout); self.isTimerStarted = false; } this.controller.devices.remove(this.vDevPresence); this.controller.emit('cron.removeTask', this.crontask_name); this.controller.off(this.crontask_name, this.poll_addr); this.config.motion_sensors.forEach(function(dev) { self.controller.devices.off(dev.motion_sensor, 'change:metrics:level', self.checkMotion); }); }; // ---------------------------------------------------------------------------- // --- Logging for debugging purposes // ---------------------------------------------------------------------------- HomePresence.prototype.printMotionStatus = function (){ var self = this; if(this.config.debug_logging){ self.config.motion_sensors.forEach(function(dev) { var motionSensor = self.controller.devices.get(dev.motion_sensor); if (motionSensor.get('metrics:level') === 'on') { console.log(motionSensor.deviceId + ' is ON'); } else { console.log(motionSensor.deviceId + ' is OFF'); } }); } }; HomePresence.prototype.debug_log = function (msg){ if(this.config.debug_logging){ console.log('[HomePresence] ' + msg); } }; HomePresence.prototype.info_log = function (msg){ console.log('[HomePresence] ' + msg); }; <file_sep>/DeadMonitor/index.js /** DeadMonitor Z-Way HA module ******************************************* Version: 1.0.0 (c) Senseloop, 2016 ----------------------------------------------------------------------------- Author: <NAME> <<EMAIL>> Description: Monitors devices to detect loss of communication with them ******************************************************************************/ // ---------------------------------------------------------------------------- // --- Class definition, inheritance and setup // ---------------------------------------------------------------------------- function DeadMonitor (id, controller) { // Call superconstructor first (AutomationModule) DeadMonitor.super_.call(this, id, controller); } inherits(DeadMonitor, AutomationModule); _module = DeadMonitor; // ---------------------------------------------------------------------------- // --- Module instance initialized // ---------------------------------------------------------------------------- DeadMonitor.prototype.init = function (config) { DeadMonitor.super_.prototype.init.call(this, config); var self = this; //Polling function self.onPoll = function () { console.log("deadMonitor polled"); for(var deviceIndex in zway.devices) { console.log(deviceIndex); if (deviceIndex == "1") { console.log("it's a controller, skip"); continue; } if (zway.devices[deviceIndex].data.isListening.value === true) { console.log("it's an always on node"); // Start polling session. Z-Way will handle everything else zway.devices[deviceIndex].SendNoOperation(); } else { if (zway.devices[deviceIndex].hasOwnProperty("Wakeup")) { console.log("it's a sleeping node"); var lastCommunication = zway.devices[deviceIndex].data.lastReceived.updateTime, wakeUpTimeInterval = zway.devices[deviceIndex].Wakeup.data.interval, currentTime = Math.floor(Date.now() / 1000); if (currentTime > (lastCommunication + wakeUpTimeInterval)) { // Nothing heard from the device for too long. Generate notification and bind to dataholder console.log("battery device seems to be dead"); self.markBatteryDead(deviceIndex); } } else { console.log("it's a FLIRS node"); //TODO add polling once a week zway.devices[deviceIndex].SendNoOperation(); } } } }; //back to life function self.batteryDeviceBackToLife = function (type, args, self) { console.log("Battery device " + args.nodeId + " is not failed anymore"); var failedArrayIndex = args.self.findNodeInFailedArray(args.nodeId); console.log("array found worked"); if (failedArrayIndex < 0) { //something went wrong. We don't know, who is calling us console.log("DeadMonitor_" + args.self.id + " Bind error. Can't stop lastReceived bind, because failed array element doesn't exist"); return; } zway.devices[args.nodeId].data.lastReceived.unbind(args.self.failedBatteryArray[failedArrayIndex].dataBind); console.log("unbinded js"); // generate notification args.self.controller.addNotification("notification", "Z-Wave device ID is back to life: " + args.nodeId, "connection", "DeadMonitor_" + args.self.id); console.log("notification added"); // remove from array args.self.failedBatteryArray.splice(failedArrayIndex); console.log("failed array removed"); }; // aux functions self.markBatteryDead = function (index) { if (self.findNodeInFailedArray(index) >= 0) { // allready failed, do nothing return; } var failRecord = {}; failRecord.nodeId = index; console.log("add notification"); //generate notification self.controller.addNotification("error", "Connection lost to Z-Wave device ID: " + failRecord.nodeId, "connection", "DeadMonitor_" + self.id); console.log("bind js"); //bind to dataholder failRecord.dataBind = zway.devices[failRecord.nodeId].data.lastReceived.bind(self.batteryDeviceBackToLife , {self: this, nodeId: failRecord.nodeId}, false); console.log("update array"); //add to failed array self.failedBatteryArray.push(failRecord); }; self.findNodeInFailedArray = function (node) { // check if index is allready failed for(var i = 0; i < self.failedBatteryArray.length; i++) { if (self.failedBatteryArray[i].nodeId == node) { return i; } } //not found return -1; }; // save hour divider self.hourDivider = this.config.interval; // failed array self.failedBatteryArray = []; // set up cron handler self.controller.on("deadMonitor.poll", self.onPoll); // add cron schedule every every hour //TODO add hours from config self.controller.emit("cron.addTask", "deadMonitor.poll", { minute: 0, hour: null, weekDay: null, day: null, month: null }); self.onPoll(); }; DeadMonitor.prototype.stop = function () { var self = this; DeadMonitor.super_.prototype.stop.call(this); self.controller.emit("cron.removeTask", "deadMonitor.poll"); self.controller.off("deadMonitor.poll", self.onPoll); // unbind from all dataholders whn stopping the module for(var i = 0; i < self.failedBatteryArray.length; i++) { zway.devices[self.failedBatteryArray[i].nodeId].data.lastReceived.unbind(self.failedBatteryArray[i].dataBind); } };<file_sep>/networkSilenceDetection/index.js // ---------------------------------------------------------------------------- // --- Class definition, inheritance and setup // ---------------------------------------------------------------------------- function networkSilenceDetection (id, controller) { // Call superconstructor first (AutomationModule) networkSilenceDetection.super_.call(this, id, controller); } inherits(networkSilenceDetection, AutomationModule); _module = networkSilenceDetection; // ---------------------------------------------------------------------------- // --- Module instance initialized // ---------------------------------------------------------------------------- networkSilenceDetection.prototype.init = function (config) { networkSilenceDetection.super_.prototype.init.call(this, config); var self = this; self.bindedDevices = []; self.restartTimeout = function () { if (self.timeoutTimer) { clearTimeout(self.timeoutTimer); } self.timeoutTimer = setTimeout(function() { // no network activity within 30 minutes, something is wrong(!) // try to recover network var data = fs.load('apikey'), apikey = data.trim() || ''; http.request({ url: 'https://api-center.senseloopcore.no/v1/hubs/' + apikey + '/z-way-freeze', method: "GET", async: true, success: function(response) { console.log("Request completed. No activity within 30 minutes"); }, error: function(response) { console.log("Can not make request remote server.No activity within 30 minutes"); } }); zway.GetHomeId(); self.timeoutTimer = false; }, 30*60*1000); } self.checkDeviceNotBindedYet = function (nodeId) { for (var i = 0; i < self.bindedDevices.length; i++) { if (self.bindedDevices[i] === nodeId) { return false; } } return true; } self.bindToAllPackets = function (nodeId) { if (self.checkDeviceNotBindedYet(nodeId)) { console.log("Binding to node", nodeId); zway.devices[nodeId].data.lastReceived.bind(self.restartTimeout); self.bindedDevices.push(nodeId); } } // catch newly created devices controller.devices.on('created', function(vDev) { var match = vDev.id.split('_'); var nodeId = parseInt(match[2]); self.bindToAllPackets(nodeId); }); // enumerate existing devices controller.devices.forEach(function(vDev) { var pattern = "(ZWayVDev_([^_]+)_([0-9]+))-([0-9]+)((-[0-9]+)*)", match = vDev.id.match(pattern); if (match) { //only for Z-Wave devices var divide = vDev.id.split('_'); var nodeId = parseInt(divide[2]); console.log(nodeId, vDev.id); self.bindToAllPackets(nodeId); } }); self.timeoutTimer = false; self.restartTimeout(); }; networkSilenceDetection.prototype.stop = function () { networkSilenceDetection.super_.prototype.stop.call(this); var self = this; }; // ---------------------------------------------------------------------------- // --- Module methods // ---------------------------------------------------------------------------- <file_sep>/CombinedRoomThermostat/index.js // ---------------------------------------------------------------------------- // --- Class definition, inheritance and setup // ---------------------------------------------------------------------------- function CombinedRoomThermostat (id, controller) { // Call superconstructor first (AutomationModule) CombinedRoomThermostat.super_.call(this, id, controller); } inherits(CombinedRoomThermostat, AutomationModule); _module = CombinedRoomThermostat; // ---------------------------------------------------------------------------- // --- Module instance initialized // ---------------------------------------------------------------------------- CombinedRoomThermostat.prototype.init = function (config) { CombinedRoomThermostat.super_.prototype.init.call(this, config); var self = this; // Creating master thermostat this.vDev = this.controller.devices.create({ deviceId: "CombinedRoomThermostat_" + this.id, defaults: { deviceType: "thermostat", probeType: "thermostat_set_point", metrics: { scaleTitle: '°C', level: 22, min: 10, max: 30, icon: "thermostat", title: self.getInstanceTitle() } }, overlay: {}, handler: function (command, args) { self.vDev.set("metrics:level", parseInt(args.level, 10)); self.checkThermostatsTemp(); self.manualACcommand = true; self.performAirConditioner(); }, moduleId: this.id }); // Handling slave thermostats temperature this.checkThermostatsTemp = function () { var temperatureSensor = self.controller.devices.get(self.config.temperatureSensor), weatherSensor = self.controller.devices.get(self.config.weatherSensor), presenceSwitch = self.controller.devices.get(self.config.presenceSwitch), mainThermostat = self.vDev; var temperatureSensorValue = temperatureSensor.get("metrics:level"), weatherSensorValue = weatherSensor.get("metrics:level"), presenceSwitchValue = presenceSwitch.get("metrics:level"), mainThermostatValue = mainThermostat.get("metrics:level"), delta = self.config.delta; if (weatherSensorValue < 5) { if (presenceSwitchValue === "on") { if ((temperatureSensorValue > (mainThermostatValue + delta)) && (global.climatState != "cooling")) { self.info_log("Sensor's temperature changed and is too hot (current temperature value is " + temperatureSensorValue + ", termostat value is " + mainThermostatValue + "). Setting thermostats temperature to 10 degree"); global.climatState = "cooling"; self.config.thermostats.forEach(function(dev) { var vDevX = self.controller.devices.get(dev.device); if (vDevX && vDevX.get("metrics:level") !== 10) { vDevX.performCommand("exact", {level : 10}); } }); } else if ((temperatureSensorValue < (mainThermostatValue - delta)) && (global.climatState != "heating")) { self.info_log("Sensor's temperature changed and is too cold (current temperature value is " + temperatureSensorValue + ", termostat value is " + mainThermostatValue + "). Setting thermostats temperature to 30 degree"); global.climatState = "heating"; self.config.thermostats.forEach(function(dev) { var vDevX = self.controller.devices.get(dev.device); if (vDevX && vDevX.get("metrics:level") !== 30) { vDevX.performCommand("exact", {level : 30}); } }); } else { self.debug_log("Sensor's temperature changed, but it is in normal range. Nothing to do."); } } else { if (global.climatState != "cooling") { self.info_log("Nobody is at home. Setting thermostats temperature to 10 degree"); global.climatState = "cooling"; self.config.thermostats.forEach(function(dev) { var vDevX = self.controller.devices.get(dev.device); if (vDevX && vDevX.get("metrics:level") !== 10) { vDevX.performCommand("exact", {level : 10}); } }); } } } }; this.controller.devices.on(this.config.temperatureSensor, 'change:metrics:level', self.checkThermostatsTemp); this.controller.devices.on(this.config.presenceSwitch, 'change:metrics:level', self.checkThermostatsTemp); // handling time conditions if exist if (this.config.useTime) { this.perfromFirstCondition = function () { if (self.vDev.get("metrics:level") !== self.config.firstDegreeCondition) { self.vDev.performCommand("exact", {level : self.config.firstDegreeCondition}); self.debug_log("First time condition is triggered. Master thermostat value changed to " + self.config.firstDegreeCondition); } }; this.perfromSecondCondition = function () { if (self.vDev.get("metrics:level") !== self.config.secondDegreeCondition) { self.vDev.performCommand("exact", {level : self.config.secondDegreeCondition}); self.debug_log("Second time condition is triggered. Master thermostat value changed to " + self.config.secondDegreeCondition); } }; this.controller.on("CombinedRoomThermostat.first.run." + this.id, this.perfromFirstCondition); this.controller.on("CombinedRoomThermostat.second.run." + this.id,this.perfromSecondCondition); this.controller.emit("cron.addTask", "CombinedRoomThermostat.first.run." + this.id, { minute: parseInt(this.config.firstTimeCondition.split(":")[1], 10), hour: parseInt(this.config.firstTimeCondition.split(":")[0], 10), weekDay: null, day: null, month: null }); this.controller.emit("cron.addTask", "CombinedRoomThermostat.second.run." + this.id, { minute: parseInt(this.config.secondTimeCondition.split(":")[1], 10), hour: parseInt(this.config.secondTimeCondition.split(":")[0], 10), weekDay: null, day: null, month: null }); } //handling air conditioner if exist if (this.config.useAirConditioner) { this.performAirConditioner = function () { var daylightSensor = self.controller.devices.get(self.config.daylightSensor), temperatureSensor = self.controller.devices.get(self.config.temperatureSensor), weatherSensor = self.controller.devices.get(self.config.weatherSensor), presenceSwitch = self.controller.devices.get(self.config.presenceSwitch), airConditionerSwitch = self.controller.devices.get(self.config.airConditionerSwitch), airConditionerThermostat = self.controller.devices.get(self.config.airConditionerThermostat), mainThermostat = self.vDev; var daylightSensorValue = daylightSensor.get("metrics:level"), temperatureSensorValue = temperatureSensor.get("metrics:level"), weatherSensorValue = weatherSensor.get("metrics:level"), presenceSwitchValue = presenceSwitch.get("metrics:level"), mainThermostatValue = mainThermostat.get("metrics:level"); if (weatherSensorValue > 5) { if (daylightSensorValue === "off") { if (temperatureSensorValue > (mainThermostatValue + self.config.delta)) { if (presenceSwitchValue === "on") { if ((!self.airConTimeoutStarted) || (self.manualACcommand)) { self.manualACcommand = false; var new_value = Math.floor(mainThermostatValue); if (new_value < 18) { new_value = 18; } else if (new_value > 27) { new_value = 27; } self.info_log("Thermostat = " + mainThermostatValue + ". Temperature = " + temperatureSensorValue + ". AC set to " + new_value + " for " + self.config.airConditionerTimeCondition + "hour(s)"); airConditionerThermostat.performCommand("exact", {level : new_value}); self.airConTimeoutStarted = true; self.airConTimeout = setTimeout(function () { self.airConTimeoutStarted = false; airConditionerSwitch.performCommand("on"); self.info_log("Timer ended. AC is turned OFF"); }, self.config.airConditionerTimeCondition * 60 * 60 * 1000); } } } else { if (self.airConTimeoutStarted) { clearTimeout(self.airConTimeout); self.airConTimeoutStarted = false; airConditionerSwitch.performCommand("on"); self.debug_log("Thermostat = " + mainThermostatValue + ". Temperature = " + temperatureSensorValue + ". AC is turned OFF"); } if (self.manualACcommand) { self.manualACcommand = false; airConditionerSwitch.performCommand("on"); self.debug_log("AC is manually turned OFF"); } } } } }; this.controller.devices.on(this.config.daylightSensor, 'change:metrics:level', this.performAirConditioner); this.controller.devices.on(this.config.presenceSwitch, 'change:metrics:level', this.performAirConditioner); this.controller.devices.on(this.config.temperatureSensor, 'change:metrics:level', this.performAirConditioner); } //handling curtain if exist if (this.config.useCurtain) { this.performCurtain = function () { var daylightSensor = self.controller.devices.get(self.config.daylightSensor), temperatureSensor = self.controller.devices.get(self.config.temperatureSensor), weatherSensor = self.controller.devices.get(self.config.weatherSensor), presenceSwitch = self.controller.devices.get(self.config.presenceSwitch), curtain = self.controller.devices.get(self.config.curtain); var daylightSensorValue = daylightSensor.get("metrics:level"), temperatureSensorValue = temperatureSensor.get("metrics:level"), weatherSensorValue = weatherSensor.get("metrics:level"), presenceSwitchValue = presenceSwitch.get("metrics:level"), curtainValue = curtain.get("metrics:level"); if (weatherSensorValue > 5) { if (daylightSensorValue === "off") { if (temperatureSensorValue > self.config.curtainDegreeCondition) { if (presenceSwitchValue === "off") { self.debug_log("Nobody is at home, but temperature is too high (current value is:"+ temperatureSensorValue + "). Performing curtain..."); if (curtainValue !== self.config.curtainLevel) { curtain.performCommand("exact", {level : self.config.curtainLevel}); self.info_log("Curtain level is set to " + self.config.curtainLevel); } else { self.debug_log("Curtain is already at level " + self.config.curtainLevel); } } } } } }; this.controller.devices.on(this.config.daylightSensor, 'change:metrics:level', this.performCurtain); this.controller.devices.on(this.config.temperatureSensor, 'change:metrics:level', this.performCurtain); } }; CombinedRoomThermostat.prototype.stop = function () { CombinedRoomThermostat.super_.prototype.stop.call(this); var self = this; this.controller.devices.off(this.config.temperatureSensor, 'change:metrics:level', this.checkThermostatsTemp); if (this.config.useTime) { this.controller.emit("cron.removeTask", "CombinedRoomThermostat.first.run." + this.id); this.controller.off("CombinedRoomThermostat.first.run." + this.id, this.perfromFirstCondition); this.controller.emit("cron.removeTask", "CombinedRoomThermostat.second.run." + this.id); this.controller.off("CombinedRoomThermostat.second.run." + this.id,this.perfromSecondCondition); } if (this.config.useAirConditioner) { if (this.airConTimeoutStarted) { clearTimeout(this.airConTimeout); self.airConTimeoutStarted = false; } this.controller.devices.off(this.config.daylightSensor, 'change:metrics:level', this.performAirConditioner); this.controller.devices.off(this.config.temperatureSensor, 'change:metrics:level', this.performAirConditioner); } if (this.config.useCurtain) { this.controller.devices.off(this.config.daylightSensor, 'change:metrics:level', this.performCurtain); this.controller.devices.off(this.config.temperatureSensor, 'change:metrics:level', this.performCurtain); } if (this.vDev) { this.controller.devices.remove(this.vDev.id); this.vDev = null; } }; // ---------------------------------------------------------------------------- // --- Module methods // ---------------------------------------------------------------------------- CombinedRoomThermostat.prototype.debug_log = function (msg) { if (this.config.debug) { console.log("[CombinedRoomThermostat_" + this.id + "]: " + msg); } }; CombinedRoomThermostat.prototype.info_log = function (msg){ console.log("[CombinedRoomThermostat_" + this.id + "]: " + msg); };<file_sep>/DevicesPolling/index.js // ---------------------------------------------------------------------------- // --- Class definition, inheritance and setup // ---------------------------------------------------------------------------- function DevicesPolling (id, controller) { // Call superconstructor first (AutomationModule) DevicesPolling.super_.call(this, id, controller); } inherits(DevicesPolling, AutomationModule); _module = DevicesPolling; // ---------------------------------------------------------------------------- // --- Module instance initialized // ---------------------------------------------------------------------------- DevicesPolling.prototype.init = function (config) { DevicesPolling.super_.prototype.init.call(this, config); var self = this; this.debugState = this.config.debug; this.garageDaylight = this.controller.devices.get(this.config.garageDaylight); this.householdDaylight = this.controller.devices.get(this.config.householdDaylight); if (this.intervalTimer) { this.debug_log("]: Interval timer is already exist! Clearing interval timer.."); clearInterval(this.intervalTimer); } this.debug_log("]: Module is started! Starting interval timer.."); this.intervalTimer = setInterval(function () { self.debug_log("]: Interval timer is ended. Updating devices status.."); self.garageDaylight.performCommand("update"); self.householdDaylight.performCommand("update"); } , this.config.interval * 60 * 1000); }; DevicesPolling.prototype.stop = function () { if (this.intervalTimer) { this.debug_log("]: Module is stopped! Clearing interval timer.."); clearInterval(this.intervalTimer); } DevicesPolling.super_.prototype.stop.call(this); }; // ---------------------------------------------------------------------------- // --- Module methods // ---------------------------------------------------------------------------- DevicesPolling.prototype.debug_log = function (msg) { if (this.debugState === true) { console.log("--- DBG[DevicesPolling_" + this.id + msg); } }<file_sep>/TestDevice/index.js // ---------------------------------------------------------------------------- // --- Class definition, inheritance and setup // ---------------------------------------------------------------------------- function TestDevice (id, controller) { // Call superconstructor first (AutomationModule) TestDevice.super_.call(this, id, controller); } inherits(TestDevice, AutomationModule); _module = TestDevice; // ---------------------------------------------------------------------------- // --- Module instance initialized // ---------------------------------------------------------------------------- TestDevice.prototype.init = function (config) { TestDevice.super_.prototype.init.call(this, config); var self = this, icon = "", level = "", deviceType = this.config.deviceType, probeType = "", min = "", max = "" switch(deviceType) { case "sensorMultilevel": icon = "temperature"; probeType = "temperature"; level = this.config.minlevel; break; case "thermostat": icon = "thermostat"; probeType = "thermostat_set_point"; level = 18; min = 10; max = 30; break; } var defaults = { metrics: { title: self.getInstanceTitle() } }; var overlay = { deviceType: deviceType, probeType: probeType, metrics: { icon: icon, probeType: probeType, level: level, min: min, max: max } }; this.vDev = self.controller.devices.create({ deviceId: "TestDevice_" + deviceType + "_" + this.id, defaults: defaults, overlay: overlay, handler: function (command, args) { var vDevType = deviceType; if (vDevType === "thermostat") { self.vDev.set("metrics:level", parseInt(args.level, 10)); } }, moduleId: this.id }); if (deviceType === "sensorMultilevel") { this.isGoingToMax = true; this.timer = setInterval(function() { self.update(self.vDev); }, this.config.updatetime * 1000); } }; TestDevice.prototype.stop = function () { if (this.timer) { clearInterval(this.timer); } if (this.vDev) { this.controller.devices.remove("TestDevice_" + this.config.deviceType + "_" + this.id); this.vDev = null; } TestDevice.super_.prototype.stop.call(this); }; // ---------------------------------------------------------------------------- // --- Module methods // ---------------------------------------------------------------------------- TestDevice.prototype.update = function (vDev) { if (this.isGoingToMax) { if(vDev.get("metrics:level") === this.config.maxlevel) { this.isGoingToMax = false; } else { vDev.set("metrics:level", vDev.get("metrics:level") + 0.5); this.debug_log("Temperature changed to " + vDev.get("metrics:level")); } } else { if(vDev.get("metrics:level") === this.config.minlevel) { this.isGoingToMax = true; } else { vDev.set("metrics:level", vDev.get("metrics:level") - 0.5); this.debug_log("Temperature changed to " + vDev.get("metrics:level")); } } }; TestDevice.prototype.debug_log = function (msg) { if (this.config.debug) { console.log("--- DBG[TestDevice_" + this.config.deviceType + "_" + this.id + "]: " + msg); } };
5f4bfb28221ac1d80e7c4ba671a70b8f67e30842
[ "JavaScript" ]
11
JavaScript
NilsBohr/JS_modules_Z-Way
e5341b50e016b8d09efa784d9b26e32cef206bd2
b80f13f3b4eee1e90929a4508724a1cdcc0f6b1d