branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>#!/bin/bash eval "`./proccgi $*`" max_show="15" http_user="apache" mktorrent="/usr/bin/mktorrent" tracker="http://thepiratebay.org/announce" torrent_directory="/home/louis/public_html/torrents" torrent_url="http://teltel.co.cc/louis/torrents" upload_directory="/home/louis/public_html/downloads" upload_url="http://teltel.co.cc/louis/downloads" tmp_directory="/var/tmp" log_directory="/home/louis/public_html/myweb/logs" echo "Content-Type: text/html" echo "" echo "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">" echo "<html>" echo "<head>" echo "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">" echo "<title>檔案櫃</title>" echo "</head>" echo "<body background=\"../images/bg.gif\">" if test ! -f "${mktorrent}"; then error="mktorrent doesn't exists!" fi if test ! -d "${torrent_directory}" -o ! -w "${torrent_directory}"; then error="torrent_directory isn't writable!" fi if test ! -d "${upload_directory}" -o ! -w "${upload_directory}"; then error="upload_directory isn't writable!" fi pass_hash=`echo "${FORM_pass}" | md5sum | cut -c1-32` torrentize=`echo -e "${FORM_torrentize}"` detorrentize=`echo -e "${FORM_detorrentize}"` mode=`echo -e "${FORM_mode}"` mailto=`echo -e "${FORM_mailto}"` if test "${pass_<PASSWORD>}" = "<PASSWORD>"; then mode="admin" fi robot=`echo "${HTTP_USER_AGENT}" | grep "Googlebot"` if test "${mode}" != "EmailPush"; then echo "<form method=\"post\" action=\"remove.cgi\" style=\"margin:0px\">" echo "<b>已上傳的檔案:</b><small>" else echo "<form method=\"post\" action=\"download.cgi?mode=EmailPush\" style=\"margin:0px\">" echo "<b>已製作的torrent:</b><small>" fi if test ! -n "${robot}"; then echo "<font color=\"gray\">[ </font>" echo "<a href=\"./download.cgi\">下載模式</a> <font color=\"gray\">|</font> <a href=\"./download.cgi?pass=upload\">管理模式</a> <font color=\"gray\">|</font> <a href=\"./download.cgi?mode=EmailPush\">EmailPush模式</a>" echo "<font color=\"gray\">|</font> <a href=\"rss.cgi\"><img src=\"http://calendar.uoregon.edu/images/rss_new.gif\" alt=\"RSS validator\"></a>" echo "<font color=\"gray\"> ]</font>" fi echo "<!-- Log Info" log_info="["`date '+%T'`"] ${REMOTE_ADDR}:${REMOTE_PORT}" log_file="${log_directory}/"`date '+%F'`".log" echo "${log_info} | user_agent | ${HTTP_USER_AGENT}" | tee -a "${log_file}" echo "-->" if test -n "${error}"; then echo "<font color=\"red\">${error}</font>"; elif test -n "${robot}"; then echo "<!-- Hello Robot -->" elif test -n "${torrentize}"; then echo "<!--" cd "${torrent_directory}" if test -f "${torrentize}.torrent"; then rm -f -v "${torrentize}.torrent" fi ${mktorrent} -v -a "${tracker}" "${upload_directory}/${torrentize}" 2>&1 echo "${log_info} | mktorrent | ${torrentize}" | tee -a "${log_file}" echo "-->" echo "<font color=\"darkgreen\">己送出製作 torrent 的請求</font>" elif test -n "${detorrentize}"; then echo "<!--" cd "${torrent_directory}" if test -f "${detorrentize}.torrent"; then rm -f -v "${detorrentize}.torrent" fi echo "${log_info} | remove_torrent | ${detorrentize}" | tee -a "${log_file}" echo "-->" echo "<font color=\"darkred\">torrent 檔己刪除</font>" elif test -n "${mailto}"; then echo "<!--" echo "mailto: ${mailto}" echo "url: http://${SERVER_ADDR}${REQUEST_URI}" curl "http://${SERVER_ADDR}${REQUEST_URI}" | mail -v -s "~ <NAME> Chris ~" "${mailto}" echo "-->" echo "<font color=\"darkgreen\">信件己送出</font>" else echo "<!-- Enviroment Variables" env echo "-->" fi echo "</small><br>" cd "${upload_directory}" /bin/ls -t1|{ total="0" usage="0" while read -r file; do if test -h "${file}" -a ! -d "${file}"; then target=`/bin/ls -o "./${file}"|sed 's/^.* -> \(.*\)$/\1/'` file_c=`echo ${file}|sed 's/%/%25/g'|sed 's/#/%23/g'|sed 's/ /%20/g'|sed 's/\\+/%2B/g'` file_ext=`echo "${file}"|awk -F . '{print $NF}'` if test "${file}" == "${file_ext}"; then file_base="${file}" else file_base=`basename "${file}" ".${file_ext}"` fi torrent_file="${torrent_directory}/${file}.torrent" temp="<input type=\"checkbox\" name=\"delete\" value=\"${file}\"" if test "${mode}" == "EmailPush"; then echo "" elif test "`/bin/ls -o "${upload_directory}/${file}"|awk '{print $3}'`" != "${http_user}"; then echo "<span style=\"color:orange\">*</span>" else if test "${mode}" == "admin" -a ! -f "${torrent_file}"; then echo "${temp}>" else echo "${temp} disabled=\"disabled\">" fi fi if test "${mode}" == "admin"; then echo "${file}<small style=\"color:gray\">" elif test "${mode}" == "EmailPush"; then echo "" else echo "<a href=\"${upload_url}/${file_c}\">${file}</a><small style=\"color:gray\">" fi info=`/bin/ls -o "${target}" 2>/dev/null |cut -d" " -f4-|sed 's/^ *//'` total=`echo "${total}+1"|bc` if test "${mode}" == "EmailPush"; then echo "" elif test -f "${target}"; then size=`echo ${info}|cut -d' ' -f1-1|tr -d " "` usage=`echo "${usage}+${size}"|bc` if test "${size}" -le "1048576"; then size=`echo "${size}/1024+1"|bc` echo "( ${size} KB )" else m_size=`echo "${size}/1048576"|bc` size=`echo "(${size}%1048576)/10485.76"|bc` size=`printf "%02d" $size` echo "( ${m_size}.${size} MB )" fi echo "<i>"`echo ${info}|cut -d' ' -f2-4`"</i>" user=`/bin/ls -o ${target}|awk '{print $3}'` if test "${user}" != "${http_user}"; then if test "${mode}" == "admin"; then echo " - <span style=\"color:green\"><i>$user</i></span>" else echo " - <span style=\"color:green\"><i>站內連結</i></span>" fi fi file_exists="yes" else echo "( <font color="darkred">不存在</font> )" file_exists="no" fi if test -f "${torrent_file}"; then if test "${mode}" == "EmailPush"; then echo "<small>${torrent_url}/${file_c}.torrent" elif test "${mode}" != "admin"; then url="${torrent_url}/${file_c}.torrent" echo " - <a href=\"${url}\"><small><i>下載 torrent</i></small></a> "; fi fi if test "${mode}" == "admin"; then if test -f "${torrent_file}"; then echo " - <small>[ <a href=\"./download.cgi?pass=upload&amp;detorrentize=${file_c}\"><i>刪除 torrent</i></a> ]</small>" elif test "${file_exists}" == "yes"; then echo " - <small>[ <a href=\"./download.cgi?pass=upload&amp;torrentize=${file_c}\"><i>Torrentize It</i></a> ]</small>" fi fi if test "${mode}" != "EmailPush" -o -f "${torrent_file}"; then echo "</small><br>" fi if test "${FORM_showall}" != "1" -a "${total}" = "${max_show}"; then break; fi fi done if test "${mode}" != "EmailPush"; then usage=`echo "${usage}/1048576"|bc` if test "${mode}" == "admin"; then echo "<input type=\"submit\" value=\"刪除\"> " else echo "<input type=\"submit\" value=\"刪除\" disabled=\"disabled\"> " fi free=`/bin/df ${tmp_directory}|tail -1|awk '{print $4}'` free=`echo "${free}/1024"|bc` echo "<small>( 顯示 ${total} 個檔案,使用 ${usage} MB,剩餘 ${free} MB) " if test "${FORM_showall}" != "1" -a "${total}" = "${max_show}"; then echo "『<a href=\"download.cgi?showall=1&amp;${QUERY_STRING}\">顯示全部檔案</a>』" fi echo "</small>" else echo "<label>MailPush:</label>" echo "<input type=\"text\" name=\"mailto\" size=\"20\">" echo "<input type=\"hidden\" name=\"mode\" value=\"EmailPush\">" echo "<input type=\"submit\" value=\"發送信件\">" fi echo "</form>" } echo "<p align=\"right\">" echo "<a href=\"http://validator.w3.org/check?uri=referer\"><img" echo " src=\"http://www.w3.org/Icons/valid-html401\"" echo " alt=\"Valid HTML 4.01 Transitional\" border=\"0\" height=\"31\" width=\"88\"></a>" echo "</p>" echo "</body></html>" <file_sep>#include <string.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <assert.h> void cgi_error(char * err_msg) { assert(err_msg); printf("Content-Type: text/plain\n\n"); printf("ERROR: %s", err_msg); exit(1); } int main(void) { char * buffer; char * content_length; char * ptr; char * tmp; char bodyname[256]; char linkname[256]; int contlen; int index; int ch; content_length = getenv("CONTENT_LENGTH"); if (content_length == NULL) cgi_error("where is CONTENT_LENGTH ?"); contlen = atoi(content_length); if (contlen <= 0) cgi_error("nothing i can do `contlen <= 0'"); buffer = (char*)malloc(contlen + 1); if (buffer == NULL) cgi_error("MALLOC"); printf("Content-Type: text/html\n\n"); printf("<html><head>\n"); printf("<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n"); printf("</head><body background=\"%s\">\n", BG); index = 0; tmp = buffer; for (;;) { for (;;) { ch = getchar(); index++; if (index == contlen) { *(tmp++) = (char)ch; *(tmp++) = '\0'; break; } else if (ch == '+') { *(tmp++) = ' '; } else if (ch == '%') { scanf("%2x", &ch); index += 2; *(tmp++) = (char)ch; if (index == contlen) { *(tmp++) = '\0'; break; } } else if (ch == '=') { *(tmp++) = '\0'; ptr = tmp; } else if (ch == '&') { *(tmp++) = '\0'; break; } else *(tmp++) = (char)ch; } printf("<b>%s</b><br>", ptr); strcpy(linkname, UPLOAD_DIR); strcat(linkname, "/"); strcat(linkname, ptr); ch = readlink(linkname, bodyname, sizeof(bodyname)); bodyname[ch] = '\0'; remove(bodyname); unlink(linkname); if (index == contlen) break; } printf("<br>.... 刪除完成! "); printf("<a href=download.cgi>"); printf("回上一頁</a>"); printf("</body></html>"); } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <assert.h> #define BUFSIZE 512 char file_name[256]; void cgi_error(char *err_msg) { assert(err_msg); printf("<p>ERROR: %s</p>", err_msg); exit(0); } char *basename(char *name) { char *ptr; assert(name); ptr = strrchr(name, '/'); if (ptr) return ptr + 1; else return name; } void decode_header(char *header) { char *tmp; char *str; int i, len; tmp = strrchr(header, '\"'); if (*tmp == *(tmp - 1)) cgi_error("NO FILE NAME!"); *tmp = '\0'; tmp = strrchr(header, '\"'); str = tmp + 1; len = strlen(str); for (i = 0; i < len; i++) { if (str[i] == '\\') // Qoo: utf-8 ? // tmp = str + i; } tmp++; if (strlen(tmp) <= 0) cgi_error("can't get the file name"); strcpy(file_name, UPLOAD_DIR); strcat(file_name, "/"); strcat(file_name, tmp); } void append_file_name(char *append) { char *ptr; assert(append); ptr = strrchr(file_name, '.'); if (!ptr) { strcat(file_name, append); } else { memmove(ptr + strlen(append), ptr, strlen(ptr) + 1); strncpy(ptr, append, strlen(append)); } } int main(void) { char *tmp; char linebuf[BUFSIZE]; char tempname[128] = TMP_DIR; char *boundary; char *contype; int match; int fd, i, ch; int filelen; extern int errno; struct stat statbuf; #ifdef DEBUG int contlen; #endif printf("Content-Type: text/html\n\n"); printf("<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" /></head><body background=\"%s\">", BG); contype = getenv("CONTENT_TYPE"); if (contype == NULL) cgi_error("Missing CONTENT_TYPE"); /* split "Content-Type" and "boundary" field from "CONTENT_TYPE" */ tmp = strchr(contype, ';'); *tmp = '\0'; tmp++; tmp = strchr(tmp, '='); tmp -= 3; strncpy(tmp, "\r\n--", 4); boundary = tmp; #ifdef DEBUG if (strcmp(contype, "multipart/form-data")) cgi_error("Content-Type is not correct!"); if (boundary == NULL) cgi_error("Something wrong with boundary"); contlen = atoi(getenv("CONTENT_LENGTH")); if (contlen <= 0) cgi_error("The length of content is incorrect"); #endif /* starting read data from STDIN */ /* first line is boundary we check if match */ fgets(linebuf, BUFSIZE, stdin); #ifdef DEBUG if (strncmp(boundary + 2, linebuf, strlen(boundary + 2))) cgi_error("boundary doesn't match"); #endif /* seconed line contain Content-Discription and filename */ fgets(linebuf, BUFSIZE, stdin); decode_header(linebuf); /* third line is the uploaded file Content-Type */ fgets(linebuf, BUFSIZE, stdin); /* forth line only has '\n' */ fgets(linebuf, BUFSIZE, stdin); if (stat(file_name, &statbuf) == 0) { append_file_name("~"); if (stat(file_name, &statbuf) == 0) { cgi_error("相同檔名重複太多。"); } } strcat(tempname, "/myweb_XXXXXX"); fd = mkstemp(tempname); if (fd <= 0) cgi_error("file open error"); filelen = 0; match = 0; i = 0; for (;;) { ch = getc(stdin); if (feof(stdin)) /* transmit not complete */ { close(fd); strcpy(linebuf, file_name); append_file_name("[上傳不完整]"); rename(linebuf, file_name); printf("<p>WARNING: %s</p>", "檔案上傳不完全,請重新上傳。"); break; } if (match) { if (ch == boundary[match]) { match++; if (boundary[match] == '\0') break; } else { write(fd, boundary, match); filelen += match; match = 0; ungetc(ch, stdin); } } else { if (ch == boundary[match]) { match++; write(fd, linebuf, i); filelen += i; i = 0; } else linebuf[i++] = (char) ch; if (i == BUFSIZE) { write(fd, linebuf, i); filelen += i; i = 0; } } } write(fd, linebuf, i); filelen += i; fchmod(fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); close(fd); /* assert(filelen > 0); */ symlink(tempname, file_name); printf("<b>%s</b>", basename(file_name)); printf(" ( %d bytes )<br><br>", filelen); printf(".... 上傳完成 <a href=download.cgi>"); printf("回上一頁</a>"); printf("</body></html>"); } <file_sep>#include <hovel.h> #include <cgi.h> #include <stdio.h> #include <string.h> typedef union int_bytes { int num; struct { char w; char xyz[3]; } ch; } int_bytes_u; int main(int argc, char * argv[]) { GDBM_FILE dbf; char * str; datum data, key; int i, j, ret; int_bytes_u idx = {0}; cgi_init(); cgi_process_form(); dbf = gdbm_open("/student/stu3/87/cs/d8728095/local/share/dict/21index.gdbm", 0, GDBM_READER, 0, 0); if (dbf == 0) cgi_fatal("can't open database."); str = cgi_param("word"); if (str == NULL || strlen(str) == 0) cgi_fatal("query string can't be null!"); cgi_init_headers(); key.dptr = str; key.dsize = strlen(str); data = gdbm_fetch(dbf, key); if (data.dptr == NULL) cgi_fatal("查無此字"); for(i = 0; i < data.dsize; i += 3) { memcpy(idx.ch.xyz, data.dptr + i, 3); if (idx.num >= 0x800000) { idx.num -= 0x800000; printf("s"); } printf("%d\n", idx.num); } gdbm_close(dbf); cgi_end(); } <file_sep>#!/bin/bash eval "`./proccgi $*`" max_show="30" torrent_directory="/home/louis/public_html/torrents" upload_directory="/home/louis/public_html/downloads" upload_url="http://xfire-a.no-ip.com/louis/downloads" echo "Content-Type: application/rss+xml" echo "" echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>" echo "<rss version=\"2.0\">" echo "<channel>" echo "<title>檔案櫃</title>" echo "<link>http://192.168.127.12/louis/myweb/upload.htm</link>" echo "<description>檔案櫃</description>" cd "${upload_directory}" /bin/ls -t1|{ total="0" usage="0" while read -r file; do if test -h "${file}" -a ! -d "${file}"; then target=`/bin/ls -o "./${file}"|sed 's/^.* -> \(.*\)$/\1/'` file_c=`echo ${file}|sed 's/%/%25/g'|sed 's/#/%23/g'|sed 's/ /%20/g'|sed 's/\\+/%2B/g'` file_ext=`echo "${file}"|awk -F . '{print $NF}'` if test "${file}" == "${file_ext}"; then file_base="${file}" else file_base=`basename "${file}" ".${file_ext}"` fi echo "<item>" echo "<title>${file}</title>" echo "<description>${file}</description>" torrent_file="${torrent_directory}/${file}.torrent" info=`/bin/ls -o "${target}" 2>/dev/null |cut -d" " -f4-|sed 's/^ *//'` total=`echo "${total}+1"|bc` size=`echo ${info}|cut -d' ' -f1-1|tr -d " "` user=`/bin/ls -o ${target}|awk '{print $3}'` content_type=`file -Lib "${upload_directory}/${file}"` echo "<guid>${upload_url}/${file_c}</guid>" echo "<link>${upload_url}/${file_c}</link>" echo "<enclosure url=\"${upload_url}/${file_c}\" length=\"${size}\" type=\"${content_type}\"/>" echo "</item>" if test "${total}" = "${max_show}"; then break; fi fi done } echo "</channel></rss>" <file_sep>UPLOAD_DIR=/home/louis/public_html/downloads BG=../images/bg.gif TMP_DIR=/var/tmp CPPFLAGS=-DTMP_DIR="\"${TMP_DIR}\"" -DUPLOAD_DIR="\"${UPLOAD_DIR}\"" -DBG="\"${BG}\"" CGIS=upload.cgi remove.cgi all: ${CGIS} proccgi proccgi: proccgi.c gcc ${CPPFLAGS} proccgi.c -o proccgi upload.cgi: upload.c gcc ${CPPFLAGS} upload.c -o upload.cgi remove.cgi: remove.c gcc ${CPPFLAGS} remove.c -o remove.cgi dict.cgi: dict.c gcc -Bstatic dict.c -o dict.cgi -lcgi -lqdbm clean: rm ${CGIS} proccgi
6b7ce126ff27dde976bc1c8baa9262f10efa3c82
[ "C", "Makefile", "Shell" ]
6
Shell
louisje/myweb
095e8f01cc6eeeac4a6d5c8a18a7094908ae6cfb
4cff1b68b44f50fa469831ddc141fd5b106c8a4c
refs/heads/master
<file_sep>#!/bin/sh env set -x if [ -n "$ICECAST_SOURCE_PASSWORD" ]; then sed -i "s/<source-password>[^<]*<\/source-password>/<source-password>$ICECAST_SOURCE_PASSWORD<\/source-password>/g" /usr/share/icecast2/icecast.xml fi if [ -n "$ICECAST_RELAY_PASSWORD" ]; then sed -i "s/<relay-password>[^<]*<\/relay-password>/<relay-password>$ICECAST_RELAY_PASSWORD<\/relay-password>/g" /usr/share/icecast2/icecast.xml fi if [ -n "$ICECAST_ADMIN_PASSWORD" ]; then sed -i "s/<admin-password>[^<]*<\/admin-password>/<admin-password>$ICECAST_ADMIN_PASSWORD<\/admin-password>/g" /usr/share/icecast2/icecast.xml fi if [ -n "$ICECAST_PASSWORD" ]; then sed -i "s/<password>[^<]*<\/password>/<password>$ICECAST_PASSWORD<\/password>/g" /usr/share/icecast2/icecast.xml fi cat /usr/share/icecast2/icecast.xml supervisord -n -c /usr/share/icecast2/supervisord.conf <file_sep>A Docker container for Icecast Based on [docker-icecast](https://github.com/moul/docker-icecast). <file_sep>FROM ubuntu:trusty MAINTAINER <NAME> <<EMAIL>> ENV DEBIAN_FRONTEND noninteractive RUN apt-get -qq -y update && \ apt-get -qq -y install icecast2 python-setuptools && \ apt-get clean RUN easy_install supervisor && \ easy_install supervisor-stdout COPY "supervisord.conf" "/usr/share/icecast2/supervisord.conf" COPY "icecast.xml" "/usr/share/icecast2/icecast.xml" COPY "silence.mp3" "/usr/share/icecast2/web/silence.mp3" CMD ["/start.sh"] EXPOSE 8000 VOLUME ["/var/log/icecast2", "/usr/share/icecast2"] ADD ./start.sh /start.sh RUN chown -R icecast2 /usr/share/icecast2
6d535af59cae70f429cbeda6b29a604580ca5912
[ "Markdown", "Dockerfile", "Shell" ]
3
Shell
trestrantham/docker-icecast
35b20980450cbba504251827aac7afb7da92ce36
e95047e07ee7d1bc9fd56dcae017c5c352659580
refs/heads/master
<repo_name>mach512/TouchDetector<file_sep>/TouchDetectFile.py #implementation of the algorithm. #loading the scaffold files (hdf5) to get the positions for moving the Purkinje neuron to the appropriate position. import pandas as pd import h5py import os import timeit from neuron import h, gui from SampPurkinje import Purkinje import multiprocessing as mp import numpy as np fid='GrcTouchLocations.dat' from neuron.rxd.morphology import parent, parent_loc import json pulist=[] h.load_file('New_SMGrC.hoc') h.load_file('SM_golgi.hoc') #st=pd.HDFStore('data.h5',mode='w') #from record3dseglocs import GetNeuronData grcgid=[] pcgid=[] f=h5py.File('scaffold_full_IO_200.0x200.0_v3.hdf5', 'r') cellpositions=np.array(f['positions']) gocpositions=cellpositions[np.where(cellpositions[:,1]==1.0)] grcpositions=cellpositions[np.where(cellpositions[:,1]==3.0)] pcpositions=cellpositions[np.where(cellpositions[:,1]==4.0)] length_range=len(grcpositions) getxsmin=[grcpositions[i,2]+(-0.21148) for i in range(length_range)] getxsmax=[grcpositions[i,2]+0.139 for i in range(length_range)] getysmin=[grcpositions[i,4]+(-2.8867) for i in range(length_range)] getysmax=[grcpositions[i,4]+2.601 for i in range(length_range)] getzsmin=[grcpositions[i,3]+0 for i in range(length_range)] getzsmax=[grcpositions[i,3]+0 for i in range(length_range)] #print 'length of the getxsmin:', len(getxsmin) #print 'length of grcpositions:', len(grcpositions) #print 'length of pcposition:', len(pcpositions) #Function to identify sections and change their positions. def setup_grcmorphology(i,pursections,x,y,z): if i > 3500: print 'i value is:', i cell=h.SMGrC2019() print 'grc here' h.define_shape() grcallsec=h.SectionList() grcallsec.wholetree(cell.soma[0]) cell.soma[0].push() n=h.n3d(sec=cell.soma[0]) xs=[h.x3d(i) for i in range(int(n))] ys=[h.y3d(i) for i in range(int(n))] zs=[h.z3d(i) for i in range(int(n))] ds=[h.diam3d(i) for i in range(int(n))] j=0 #sec.push() for a, b, c, d in zip(xs,ys,zs,ds): #print 'sec here is:', sec h.pt3dchange(j,a+x,b+y,c+z,d) j+=1 h.define_shape() h.pop_section() for sec in pursections: xsecappend=[] ysecappend=[] zsecappend=[] segstr=str(sec) #print 'segstr:', segstr segstr=segstr.split('.') if str(sec)=="axonAIS" or str(sec)=="axonmyelin" or str(sec)=="axonmyelin4" or str(sec)=="axonNOR3" or str(sec)=="axoncoll2" or str(sec)=="axonmyelin3" or str(sec)=="axoncoll" or str(sec)=="axonNOR2" or str(sec)=="axonmyelin2" or str(sec)=="axonNOR" or str(sec)=="axonAISK" or str(sec)=="axonAIS": segstr=str(sec) ext="axon" segstr=segstr[:segstr.find(ext)+len(ext)] #print 'the section name here is axonAIS' #print 'before segstr[2] split', segstr else: segstr=segstr[2].split('[') segstr=''.join([i for i in segstr[0] if not i.isdigit()]) if segstr=='bs': #print 'this section is dendrite', sec sec.push() for kj in range(int(h.n3d()-1)): xsecappend.append(h.x3d(kj)) #append_secX_list.append(h.x3d(h.n3d()-1)) ysecappend.append(h.y3d(kj)) #append_secY_list.append(h.y3d(h.n3d()-1)) zsecappend.append(h.z3d(kj)) purkallcoord=[sec.x3d(kj),sec.y3d(kj),sec.z3d(kj)] purkradius=(sec.diam/2) for gsec in grcallsec: gsegstr=str(gsec) gsegstr=gsegstr.split('.') gsegstr=gsegstr[1].split('[') gsegid=gsegstr[1].split(']') if gsegstr[0]=='axon': if gsegid > 1 and gsegid < 20: for jj in range(int(gsec.n3d()-1)): gxmin=gsec.x3d(jj) gymin=gsec.y3d(jj) gzmin=gsec.z3d(jj) grallcoord=[gsec.x3d(jj),gsec.y3d(jj),gsec.z3d(jj)] dst=distance.euclidean(grallcoord,purkallcoord) granradius=(gsec.diam/2) if dst < (purkradius+granradius): print 'probable connection' #append_secZ_list.append(h.z3d(h.n3d()-1)) h.pop_section() def callback(result): print 'rsult:', result def func_local_grcneurons(gid,sections): print 'gid value is:', gid #getpurkneuron=pulist[gid] #print 'getpurkneuron:', getpurkneuron append_secX_list=[] append_secY_list=[] append_secZ_list=[] hPurk=h5py.File('dataPurk.hdf5','a') for sec in sections: segstr=str(sec) #print 'segstr:', segstr segstr=segstr.split('.') if str(sec)=="axonAIS" or str(sec)=="axonmyelin" or str(sec)=="axonmyelin4" or str(sec)=="axonNOR3" or str(sec)=="axoncoll2" or str(sec)=="axonmyelin3" or str(sec)=="axoncoll" or str(sec)=="axonNOR2" or str(sec)=="axonmyelin2" or str(sec)=="axonNOR" or str(sec)=="axonAISK" or str(sec)=="axonAIS": segstr=str(sec) ext="axon" segstr=segstr[:segstr.find(ext)+len(ext)] #print 'the section name here is axonAIS' #print 'before segstr[2] split', segstr else: segstr=segstr[2].split('[') segstr=''.join([i for i in segstr[0] if not i.isdigit()]) if segstr=='bs': #print 'this section is dendrite', sec sec.push() for kj in range(int(h.n3d()-1)): append_secX_list.append(h.x3d(kj)) #append_secX_list.append(h.x3d(h.n3d()-1)) append_secY_list.append(h.y3d(kj)) #append_secY_list.append(h.y3d(h.n3d()-1)) append_secZ_list.append(h.z3d(kj)) #append_secZ_list.append(h.z3d(h.n3d()-1)) h.pop_section() #find max and min from each list declared above purksecdata=np.column_stack((append_secX_list,append_secY_list,append_secZ_list)) hPurkdset=hPurk.create_dataset('data_purk',data=purksecdata) print 'sec is:', sec #print 'first element:', append_secZ_list[0] min_secX_list=min(append_secX_list) max_secX_list=max(append_secX_list) min_secY_list=min(append_secY_list) max_secY_list=max(append_secY_list) min_secZ_list=min(append_secZ_list) max_secZ_list=max(append_secZ_list) #checking to see if the grcpositions x and y min, max fall within the boundaries of Purkinje neuron print 'min_secX_list,max_secX_list,min_secY_list,max_secY_list,min_secZ_list,max_secZ_list', min_secX_list,max_secX_list,min_secY_list,max_secY_list,min_secZ_list,max_secZ_list chkXcnt=0 localitercnt=0 grcxminlist=[] grcxmaxlist=[] grcyminlist=[] grcymaxlist=[] grczminlist=[] grczmaxlist=[] for (a,b,c,d,e,f) in zip(getxsmin, getxsmax,getysmin,getysmax,getzsmin,getzsmax): #print a,b,c,d localitercnt+=1 if a > min_secX_list and b < max_secX_list and c > min_secY_list and d < max_secY_list and e > min_secZ_list and f < max_secZ_list: chkXcnt+=1 #no. of granule neurons that fall into boundary for each Purkinje neuron grcgid.append(localitercnt) pcgid.append(gid) grcxminlist.append(a) grcxmaxlist.append(b) grcyminlist.append(c) grcymaxlist.append(d) grczminlist.append(e) grczmaxlist.append(f) #if c > min_secY_list and d < max_secY_list: # chkXcnt+=1 print 'length of grcgid:', len(grcgid) #for jj,iterjj in enumerate(grcgid): # print 'grcgid:', jj, iterjj print '21849 value:', grcpositions[0,2] data_grc={'grcgid':grcgid} data_pc={'pcgid':pcgid} data_xyz=np.column_stack((grcxminlist,grcxmaxlist,grcyminlist,grcymaxlist,grczminlist,grczmaxlist)) #print 'data:', data h1=h5py.File('data.hdf5','a') data=np.column_stack((grcgid,pcgid)) #print 'data:', data #df1=pd.DataFrame.from_dict(data_grc)#({'grcgid':grcgid,'pcgid':pcgid}) #df2=pd.DataFrame.from_dict(data_pc) dset=h1.create_dataset('data_grc',data=data) dset1=h1.create_dataset('grcXYZ',data=data_xyz) h1.close() del grcxminlist del grcxmaxlist del grcyminlist del grcymaxlist del grczminlist del grczmaxlist del min_secX_list del max_secX_list del min_secY_list del max_secY_list del min_secZ_list del max_secZ_list del append_secX_list del append_secY_list del append_secZ_list #grcs=[pool.apply_async(setup_grcmorphology,args=(jj, sections, grcpositions[grcgid[jj],2], grcpositions[grcgid[jj],4], grcpositions[grcgid[jj],3])) for jj in range(len(grcgid)-1)] grcs=[pool.apply(callback,args=(i)) for i in range(10)] pool.close() print 'grcs:', grcs[:20] #grcs=[setup_grcmorphology(jj,sections,grcpositions[grcgid[jj],2], grcpositions[grcgid[jj],4], grcpositions[grcgid[jj],3]) for jj in range(len(grcgid)-1)] #print 'df1:', type(df1) #st=pd.HDFStore('data.h5',mode='a') #st.append('df',df1,data_columns=['grcgid'],index=False) #st.append('df',df2,data_columns=['pcgid'],index=False) #df1.to_hdf('data.h5', key='df', table=True, data_columns=['grcgid','pcgid'],mode='a') #st.close() print 'chkXcnt:', chkXcnt #print 'min granule x is:', getxsmin def setup_pcmorphology(kk,x,y,z): print 'i value is:', kk cellpc=Purkinje() h.define_shape() sections=h.SectionList() sections.wholetree(cellpc.soma) cellpc.soma.push() n=h.n3d(sec=cellpc.soma) xs=[h.x3d(i) for i in range(int(n))] ys=[h.y3d(i) for i in range(int(n))] zs=[h.z3d(i) for i in range(int(n))] ds=[h.diam3d(i) for i in range(int(n))] j=0 #sec.push() for a, b, c, d in zip(xs,ys,zs,ds): #print 'sec here is:', sec h.pt3dchange(j,a+x,b+y,c+z,d) j+=1 h.define_shape() h.pop_section() pulist.append(cellpc) #call another function to locate the local granule neurons cellpc.soma.push() getpurksecs=h.SectionList() getpurksecs.wholetree(cellpc.soma) func_local_grcneurons(kk,getpurksecs) if __name__== '__main__': #this is extremely important for python scripts in windows filePath='C:/Users/mach5/OneDrive/Desktop/SM_granule_golgi_models/data.hdf5' file2='C:/Users/mach5/OneDrive/Desktop/SM_granule_golgi_models/dataPurk.hdf5' if os.path.exists(filePath): os.remove(filePath) else: print 'cannot delete file as it is not there' if os.path.exists(file2): os.remove(file2) else: print 'file 2 is not there' #del data.hdf5 #del dataPurk.hdf5 start=timeit.default_timer() pool=mp.Pool(8) #grcs=[pool.apply_async(setup_grcmorphology,args=(i, grcpositions[i,2], grcpositions[i,4], grcpositions[i,3])) for i in range(100)] #pcs=[pool.apply_async(setup_pcmorphology,args=(i,pcpositions[i,2],pcpositions[i,4],pcpositions[i,3])) for i in range(10)] pcs=[setup_pcmorphology(i,pcpositions[i,2],pcpositions[i,4],pcpositions[i,3]) for i in range(1)] stop=timeit.default_timer() print('Time:', stop-start) #pool.close() #pool.join() #grcs=[setup_grcmorphology(i,grcpositions[i,2],grcpositions[i,4],grcpositions[i,3]) for i in range(100)] slt=h.Shape() slt.view() <file_sep>/segment2segmenttouch.py from __future__ import division from ipyparallel import Client import pandas as pd import json from mpi4py import MPI import h5py import numpy as np rc=Client(profile='setupparallelcluster') dview=rc[:] dview.execute('from __future__ import division') dview.execute('import numpy as np') dview.execute('import pandas as pd') dview.execute('import h5py') dview.execute('import matplotlib.pyplot as plt') dview.execute('import pandas as pd') dfgrc=pd.read_csv('singlegrcsecdata.dat',sep='\t',names=["gid","xdata","ydata","zdata"]) dfgoc=pd.read_csv('singlegocsecdata.dat',sep='\t',names=["gid","xdata","ydata","zdata"]) comm=MPI.COMM_WORLD size=comm.Get_size() rank=comm.Get_rank() #with dview.sync_imports(): # import pandas as pd # dfgoc=pd.read_csv('singlegocsecdata.dat',sep='\t',names=["gid","xdata","ydata","zdata"]) f=h5py.File('scaffold_full_dcn_400.0x400.0_v3.hdf5','r') cellpositions=np.array(f['positions']) grcpositions=cellpositions[np.where(cellpositions[:,1]==3.0)] gocpositions=cellpositions[np.where(cellpositions[:,1]==1.0)] dictgrcXstore={} dictgrcYstore={} dictgrcZstore={} dictgrcgidstore={} for ii in range(5): newdfgrcX=dfgrc["xdata"]+grcpositions[ii,2] newdfgrcY=dfgrc["ydata"]+grcpositions[ii,4] newdfgrcZ=dfgrc["zdata"]+grcpositions[ii,3] dictgrcgidstore[ii]=dfgrc["gid"] dictgrcXstore[ii]=newdfgrcX dictgrcYstore[ii]=newdfgrcY dictgrcZstore[ii]=newdfgrcZ #dictallstoregrc=[dictgrcXstore[0],dictgrcYstore[0],dictgrcZstore[0]] dictgocXstore=dfgoc["xdata"]+gocpositions[0,2] dictgocYstore=dfgoc["ydata"]+gocpositions[0,4] dictgocZstore=dfgoc["zdata"]+gocpositions[0,3] newdictgocxstor={} newdictgocystor={} newdictgoczstor={} dictgocgidstore={} newdictgocxstor[0]=dictgocXstore newdictgocystor[0]=dictgocYstore newdictgoczstor[0]=dictgocZstore dictgocgidstore[0]=dfgoc["gid"] print 'length of dictgocgidstore[0] up above:', len(dictgocgidstore[0]) #print newdictgocxstor dview.push(newdictgocxstor) dview.push(newdictgocystor) dview.push(newdictgoczstor) dview.push(dictgocgidstore) print 'next step' checkdict={'43':np.array([1,2,3]),'34':np.array([4,5,6]),'343':np.array([7,8,9])} #this is for the scattering dictionaries def scatter_dict(view,name,d): ntargets=len(view) keys=d.keys() for i, target in enumerate(view.targets): subd={} for key in keys[i::ntargets]: subd[key]=d[key] view.client[target][name]=subd scatter_dict(dview,'test',dictgrcXstore) scatter_dict(dview,'test1',dictgrcYstore) scatter_dict(dview,'test2',dictgrcZstore) scatter_dict(dview,'gidtest',dictgrcgidstore) #print 'size of dictgrcXstore:', len(dictgrcXstore),len(dictgrcXstore[0]) def gather_gidgrc_dict(view,name): merged={} cellgidtotal=[] for d in view.pull(name): listgidgrc=list(d.values()) listgidgoc=list(dictgocgidstore.values()) # print 'length of the listgidgrc:', len(listgidgrc) if len(listgidgrc)>0: cellgiddata=[(x1,y1) for x,x1 in enumerate(listgidgrc[0]) for y,y1 in enumerate(listgidgoc[0])] cellgidtotal.append(cellgiddata) merged.update(d) return merged,cellgidtotal resgid,getgiddata=gather_gidgrc_dict(dview,'gidtest') def gather_dict(view,name): merged={} cellxtotal=[] cellnumxtotal=[] cnt=0 for d in view.pull(name): #cellxdata=[(x1,y1) for x,x1 in d.items() for y,y1 in newdictgocxstor.items()] #for key in d.keys(): listdgrc=list(d.values()) listdgoc=list(newdictgocxstor.values()) if len(listdgrc) > 0: cellxdata=[(x,y,x1,y1) for x,x1 in enumerate(listdgrc[0]) for y,y1 in enumerate(listdgoc[0])] cellxtotal.append(cellxdata) cnt+=1 merged.update(d) return merged,cellxtotal def gather_dict_Y(view,name): merged={} cellytotal=[] cnt=0 for d in view.pull(name): listdgrc=list(d.values()) listdgoc=list(newdictgocystor.values()) if len(listdgrc) > 0: cellydata=[(x1,y1) for x,x1 in enumerate(listdgrc[0]) for y,y1 in enumerate(listdgoc[0])] cellytotal.append(cellydata) cnt+=1 merged.update(d) return merged,cellytotal def gather_dict_Z(view,name): merged={} cellztotal=[] cnt=0 for d in view.pull(name): listdgrc=list(d.values()) listdgoc=list(newdictgoczstor.values()) if len(listdgrc) > 0: cellzdata=[(x1,y1) for x,x1 in enumerate(listdgrc[0]) for y,y1 in enumerate(listdgoc[0])] cellztotal.append(cellzdata) cnt+=1 merged.update(d) return merged,cellztotal res,getxdata=gather_dict(dview,'test') resY,getydata=gather_dict_Y(dview,'test1') resZ,getzdata=gather_dict_Z(dview,'test2') <EMAIL>(block=True) def calcintersection(a,b,c,d,cellid,grcgid,gocgid): marginofError=0.1 r=np.subtract(b,a) s=np.subtract(d,c) q=np.subtract(a,c) dotqr=np.dot(q,r) dotqs=np.dot(q,s) dotrs=np.dot(r,s) dotrr=np.dot(r,r) dotss=np.dot(s,s) denom=dotrr*dotss-dotrs*dotrs numer=dotqs*dotrs-dotqr*dotss #print 'denom:', denom if denom!=0: t=numer/denom u=(dotqs+t*dotrs)/dotss p0=a+t*r p1=c+u*s onsegment=False intersects=False mask=np.logical_and(t>=0,t<=1) mask1=np.logical_and(u>=0,u<=1) if mask==True and mask1==True: #print 'mask and mask1 are true' onSegment=True res=p0-p1 mag=np.sqrt(res.dot(res)) if (mag < marginofError): #print 'intersects is true' intersects=True with open('checkingtrueconnections.dat','a') as fsave: fsave.write('%s\t%s\t%s\t%s\t%s\t%s\n'%(p0,p1,mag,cellid,grcgid,gocgid)) if onsegment==True and intersects==True: print 'both are true' ############################## cnt=0 cnt1=-1 mocnt=0 for ij in range(len(getxdata)): print 'length of getxdata:', len(getxdata),len(getxdata[0]),getxdata[0][0][3] mocnt=0 for jk in range(len(getxdata[ij])-1): if cnt==0: storeval=getxdata[ij][jk][3] cnt+=1 if jk > 0: if getxdata[ij][jk][3]==storeval: print 'jk value here:', jk grcstart=[getxdata[ij][jk-1][2],getydata[ij][jk-1][0],getzdata[ij][jk-1][0]] grcstop=[getxdata[ij][jk][2],getydata[ij][jk][0],getzdata[ij][jk][0]] print 'grcstart',grcstart,'grcstop',grcstop itemgrcfind=getgiddata[ij][0][mocnt] getgidnum=[getgiddata[ij][jk][0]] #print 'getgidnum:', getgidnum #if grcstart==grcstop: #print grcstart,grcstop mocnt+=1 cnt1=0 if cnt1==0: if grcstart!=grcstop: #if grcstart[0] in dictgrcXstore: #next(item for item in dictgrcXstore.values() if item==grcstart[0]) #newlistgrc=list(dictgrcXstore.values()) #if grcstart[0] in newlistgrc: #getitemgrc=[item for item in newlistgrc[0] if item==grcstart[0]] # print grcstart[0],len(newlistgrc[4]) #for ij in range(len(newlistgrc)): # getitemgrc=[(i,x) for i, x in enumerate(newlistgrc[0]) if x==grcstart[0]] # print getitemgrc #if grcstart[0] in newlistgrc[0]: # print 'grcstart[0] is:', grcstart[0] # print 'length of dictgrcXstore:', newlistgrc[0].index[grcstart[0]] gocstart=[getxdata[ij][jk][3],getydata[ij][jk][1],getzdata[ij][jk][1]] gocstop=[getxdata[ij][jk+1][3],getydata[ij][jk+1][1],getzdata[ij][jk+1][1]] #print 'gocstart:', gocstart,'gocstop:', gocstop calcintersection(grcstart,grcstop,gocstart,gocstop,ij,getxdata[ij][jk][0],getxdata[ij][jk][1]) #print 'jk value:', jk #print 'grcstart:',grcstart,'grcstop:',grcstop,'gocstart:',gocstart,'gocstop:',gocstop #cnt1+=1 # if ij%2==0: # grcstart=[getxdata[ij][jk][0],getydata[ij][jk][0],getzdata[ij][jk][0]] # grcstart=[res[0][ij],resY[0][ij],resZ[0][ij]] # grcstop=[res[0][ij+1],resY[0][ij+1],resZ[0][ij+1]] # gocstart=[getxdata[ij][jk][1],getydata[ij][jk][1],getzdata[ij][jk][1]] # gocstop=[getxdata[ij][jk+1][1],getydata[ij][jk+1][1],getzdata[ij][jk+1][1]] # grcstop=[getxdata[ij][jk+1][0],getydata[ij][jk+1][0],getzdata[ij][jk+1][0]] #calcintersection(grcstart,grcstop,gocstart,gocstop) #print 'grcstart:', getxdata[0][176][0],getydata[0][176][0],getzdata[0][176][0] #print 'grcstop:', getxdata[0][353][0],getydata[0][353][0],getzdata[0][353][0] #print 'gocstart:', getxdata[0][0][1],getydata[0][0][1],getzdata[0][0][1] #print 'gocstop:', getxdata[0][1][1],getydata[0][1][1],getzdata[0][1][1] #print 'grcstop:', rcstop #dview.scatter('dictgrcXStore',dictgrcXstore) #dview.scatter('dictgrcYStore',dictgrcYstore) #dview.scatter('dictgrcZStore',dictgrcZstore) print 'distributed the dictgrcXstore' <file_sep>/getpurksegments.py import h5py import numpy as np from neuron import h, gui from SampPurkinje import Purkinje purkcell=Purkinje() f=h5py.File('scaffold_full_IO_200.0x200.0_v3.hdf5','r') cellpositions=np.array(f['positions']) pcpositions=cellpositions[np.where(cellpositions[:,1]==4.0)] h.define_shape() pcsecall=h.SectionList() pcsecall.wholetree(purkcell.soma) listgr=[] sectiondct={} maincelldct=[] dictcnt=0 for ij in range(len(pcpositions)): #exec('sectdict_%d={}'%ij) sectiondct={} for sec in pcsecall: segstr=str(sec) sec.push() listgrX=[] listgrY=[] listgrZ=[] for i in range(int(h.n3d())): listgrX.append(h.x3d(i)) listgrY.append(h.y3d(i)) listgrZ.append(h.z3d(i)) if str(sec)=="axonAIS" or str(sec)=="axonmyelin" or str(sec)=="axonmyelin4" or str(sec)=="axonNOR3" or str(sec)=="axoncoll2" or str(sec)=="axonmyelin3" or str(sec)=="axoncoll" or str(sec)=="axonNOR2" or str(sec)=="axonmyelin2" or str(sec)=="axonNOR" or str(sec)=="axonAISK" or str(sec)=="axonAIS": segstr=str(sec) buf=segstr else: segstr=segstr.split('.') segstr=segstr[2].split('[') if segstr[0]=='soma': buf=segstr[0] else: secname=segstr[0] segstr=segstr[1].split(']') secid=segstr[0] buf=secname+"_"+secid #print 'buf contains:', buf maxX=max(listgrX)+pcpositions[ij,2] minX=min(listgrX)+pcpositions[ij,2] maxY=max(listgrY)+pcpositions[ij,3] minY=min(listgrY)+pcpositions[ij,3] maxZ=max(listgrZ)+pcpositions[ij,4] minZ=min(listgrZ)+pcpositions[ij,4] #getallx=np.column_stack((minX, maxX)) #getally=np.column_stack((minY, maxY)) #getallz=np.column_stack((minZ, maxZ)) #h1=h5py.File('newpurkdata.hdf5', 'a') #h1.create_dataset('xcoord', data=getallx) #h1.create_dataset('ycoord', data=getally) #h1.create_dataset('zcoord', data=getallz) with open('savepcsegmentcoords.dat', 'a') as fsavaxon: fsavaxon.write(str(ij)) fsavaxon.write('\t') fsavaxon.write(str(buf)) fsavaxon.write('\t') fsavaxon.write(str(minX)) fsavaxon.write('\t') fsavaxon.write(str(minY)) fsavaxon.write('\t') fsavaxon.write(str(minZ)) fsavaxon.write('\n') fsavaxon.write(str(ij)) fsavaxon.write('\t') fsavaxon.write(str(buf)) fsavaxon.write('\t') fsavaxon.write(str(maxX)) fsavaxon.write('\t') fsavaxon.write(str(maxY)) fsavaxon.write('\t') fsavaxon.write(str(maxZ)) fsavaxon.write('\n') h.pop_section() #h1.close()
dc474bd4fb0eaa335b62bfbc6b7012339761fac6
[ "Python" ]
3
Python
mach512/TouchDetector
eec3c8a69239ddb3a7f8028bded2ad8d0379d47f
9ba14188c44d582e3bd5658d1080482c4bb5f329
refs/heads/master
<repo_name>prasannavijayan/LancersApp2<file_sep>/LancersApp/urls.py from django.conf.urls import patterns, include, url from django.contrib import admin import settings urlpatterns = patterns('', # Examples: # url(r'^$', 'LancersApp.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), (r'^accounts/', include('registration.backends.default.urls')), ) # App URL's for app in settings.OUR_APPS: urlpatterns += patterns('', url(r'^'+ app +'/', include(app+'.urls', app_name=app)),) # urlpatterns += patterns('', url(r'^concept/', include(app+'.urls', app_name=app))) # Template - Media if settings.DEBUG: urlpatterns += patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) <file_sep>/students/models.py from django.db import models from django.contrib.auth.models import User import datetime # Create your models here. class StudentProfile(models.Model): username = models.ForeignKey(User, null=True, blank=True) skills = models.CharField(max_length="200", blank=False, null=False) email_id = models.EmailField(max_length="200", blank=False, null=False) dob = models.DateField(default="2015-12-09", null=False, blank=False) contact_no = models.IntegerField(blank=False, null=False) college_name = models.CharField(max_length="300", null=False, blank=False) resume = models.CharField(max_length="600") year = models.CharField(max_length="200", null=False, blank=False) address = models.CharField(max_length="200", null=False, blank=False) profile_pic = models.ImageField(upload_to="./profileimg", default="IMG.JPEG") def __unicode__(self): return str(self.username) <file_sep>/students/views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .forms import StudentProfileForm from .models import StudentProfile from company.models import JobPost # Create your views here. def Home(request): user = request.user profile = StudentProfile.objects.get(username = user) return render(request, "students/index.html", {'profile': profile}) def Profile(request): if request.method == "POST": form = StudentProfileForm(request.POST, request.FILES or None) print "erro" if form.is_valid(): print "Inside Form" save_form = form.save(commit=False) save_form.save() return HttpResponseRedirect("/students/profile") else: return HttpResponseRedirect('/students/profile') else: print "welcome" user = request.user form = StudentProfileForm() profile = StudentProfile.objects.get(username=user) return render(request, "students/profile.html", {"form": form, 'profile': profile}) def ProfileUpdate(request): pass def ViewJobs(request): jp = JobPost.objects.all() return render(request, "students/viewjobs.html", {'jp': jp}) <file_sep>/students/migrations/0001_initial.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='StudentProfile', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('skills', models.CharField(max_length=b'200')), ('email_id', models.EmailField(max_length=b'200')), ('contact_no', models.IntegerField()), ('college_name', models.CharField(max_length=b'300')), ('resume', models.CharField(max_length=b'600')), ('year', models.CharField(max_length=b'200')), ('address', models.CharField(max_length=b'200')), ('username', models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True)), ], options={ }, bases=(models.Model,), ), ] <file_sep>/company/views.py from django.shortcuts import render from .models import Company from students.models import StudentProfile # Create your views here. def Home(request): company = Company.objects.get(company_name="ICICLE Technologies") return render(request, "company/index.html", {'company': company}) def Jobs(request): company = Company.objects.get(company_name = "ICICLE Technologies") skillset = company.technology.split(",") students = StudentProfile.objects.all() shortlist = {} for s in students: askill = s.skills.split(",") print askill for a in askill: if a in skillset: shortlist[s] = 100 print shortlist return render(request, "company/all_jobs.html", {'skillset': skillset, 'shortlist': shortlist }) <file_sep>/students/urls.py from django.conf.urls import patterns, include, url urlpatterns = patterns('students.views', # Examples: # url(r'^$', 'LancersApp.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^home/$', 'Home'), url(r'^profile/$', 'Profile'), url(r'^viewjobs/$', 'ViewJobs'), ) <file_sep>/company/migrations/0002_auto_20150523_0933.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('company', '0001_initial'), ] operations = [ migrations.CreateModel( name='JobPost', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('job_title', models.CharField(max_length=b'300', null=True, blank=True)), ('job_description', models.TextField(max_length=b'700', null=True, blank=True)), ('salary', models.CharField(default=b'NA', max_length=b'400', null=True, blank=True)), ('skills', models.CharField(max_length=b'300', blank=True)), ('job_location', models.CharField(max_length=b'300')), ('experience', models.IntegerField()), ('company', models.ForeignKey(to='company.Company')), ], options={ }, bases=(models.Model,), ), migrations.AddField( model_name='company', name='user', field=models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True), preserve_default=True, ), ] <file_sep>/company/urls.py from django.conf.urls import patterns, include, url urlpatterns = patterns('company.views', # Examples: # url(r'^$', 'LancersApp.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^home/$', 'Home'), url(r'^jobs/$', 'Jobs'), ) <file_sep>/company/models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Company(models.Model): user = models.ForeignKey(User, null=True, blank=True) company_name = models.CharField(max_length=200, null=False, blank=False) company_logo = models.ImageField(upload_to="./company", default="IMG.JPEG") company_description = models.TextField(max_length="500", null=False) technology = models.CharField(max_length="300", null=False, blank=False) url = models.CharField(max_length=200, null=False, blank=False) emailid = models.EmailField() def __unicode__(self): return str(self.company_name) class JobPost(models.Model): company = models.ForeignKey(Company, null=False, blank=False) job_title = models.CharField(max_length="300", null=True, blank=True) job_description = models.TextField(max_length="700", null=True, blank=True) salary = models.CharField(max_length="400", null=True, blank=True, default='NA') skills = models.CharField(max_length="300", null=False, blank=True) job_location = models.CharField(max_length="300", blank=False, null=False) experience = models.IntegerField() def __unicode__(self): return str(self.job_title) <file_sep>/students/forms.py from django import forms from .models import StudentProfile class StudentProfileForm(forms.ModelForm): class Meta: model = StudentProfile exclude = ['username']
1f7eb95f0de0a1c8be0dca48ec41c6f722652022
[ "Python" ]
10
Python
prasannavijayan/LancersApp2
7fade698be890f973d9d2cb29a38685e2d7bfba9
5418ce2d1c74823790135fa5c22e5e00e808d1d4
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Appointly.DAL { public interface IAppointmentRepository { } } <file_sep>using Appointly.Models; using Appointly.ViewModel; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace Appointly.DAL { public class VisitorRepository : IVisitorRepository { private readonly string connectionString; public VisitorRepository(IConfiguration iConfig) { connectionString = iConfig.GetSection("ConnectionStrings").GetSection("Myconnection").Value; } public void AddAppointment(Appointment appointment, int id,short Visitor_Id) { using (SqlConnection con = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand("sp_scheduleappointment", con)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Visitor_Id", Visitor_Id); cmd.Parameters.AddWithValue("@Faculty_Id", id); cmd.Parameters.AddWithValue("@From", appointment.From); cmd.Parameters.AddWithValue("@To", appointment.To); cmd.Parameters.AddWithValue("@Purpose", appointment.Purpose); con.Open(); cmd.ExecuteNonQuery(); } } } public IEnumerable<Appointment> GetFacultyAppointment(int id) { List<Appointment> appointments = null; using (SqlConnection con = new SqlConnection(connectionString)) { SqlCommand cmd1 = new SqlCommand("sp_getmeetingdetail", con); cmd1.Parameters.AddWithValue("@FacultyId", id); cmd1.CommandType = CommandType.StoredProcedure; con.Open(); using (SqlDataReader dr = cmd1.ExecuteReader()) { appointments = new List<Appointment>(); while (dr.Read()) { Appointment ap = new Appointment(); ap.From = (DateTime)dr["From"]; ap.To = (DateTime)dr["To"]; ap.FacultyId = (short)Convert.ToInt32(dr["FacultyId"]); ap.Extra = (string)dr["FirstName"]; ap.Extra += " "; ap.Extra += dr["LastName"]; appointments.Add(ap); } } } return appointments; } public IEnumerable<User> GetFaculty() { // throw new NotImplementedException(); List<User> users = null; using (SqlConnection con = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand("sp_getallfaculty", con)) { cmd.CommandType = System.Data.CommandType.StoredProcedure; con.Open(); using (SqlDataReader dr = cmd.ExecuteReader()) { users= new List<User>(); ; while (dr.Read()) { User uc = new User(); uc.Id = (short)Convert.ToInt32(dr["Id"].ToString()); uc.FirstName = dr["FirstName"].ToString(); uc.LastName = dr["LastName"].ToString(); uc.Email = dr["Email"].ToString(); uc.Phone = dr["Phone"].ToString(); users.Add(uc); } } } } return users; } public AppointmentStatusViewModel GetVisitorAppointment(int? id,short userid) { if (id == 0) id = 1; List<Appointment> appointments = new List<Appointment>(); AppointmentStatusViewModel appointmentStatusViewModel = new AppointmentStatusViewModel(); using (SqlConnection con = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand("sp_getmeetingfromstatus", con)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@visitorId", userid); cmd.Parameters.AddWithValue("@status", id); con.Open(); using (SqlDataReader dr = cmd.ExecuteReader()) { for (int i = 1; i <=5; i++) { while (dr.Read()) { switch (i) { case 1: appointmentStatusViewModel.Pending = Convert.ToInt16(dr["meeting_count"]); break; case 2: appointmentStatusViewModel.Approved = Convert.ToInt16(dr["meeting_count"]); break; case 3: appointmentStatusViewModel.Rejected= Convert.ToInt16(dr["meeting_count"]); break; case 4: appointmentStatusViewModel.Completed = Convert.ToInt16(dr["meeting_count"]); break; case 5: appointmentStatusViewModel.Total = Convert.ToInt16(dr["meeting_count"]); break; } } dr.NextResult(); } while (dr.Read()) { Appointment app = new Appointment(); app.Extra = Convert.ToString(dr["FirstName"]); app.Extra += ' '; app.Extra += (string)dr["LastName"]; app.From = (DateTime)dr["_From"]; app.To = (DateTime)dr["_To"]; app.Purpose = Convert.ToString(dr["Purpose"]); appointments.Add(app); } appointmentStatusViewModel.appointments = appointments; } } } return appointmentStatusViewModel; } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace Appointly.Models { public class Appointment { public short Id { get; set; } public short VisitorId { get; set; } public short FacultyId { get; set; } [Display(Name = "From")] public DateTime From { get; set; } [Display(Name = "To")] public DateTime To { get; set; } public DateTime Entry { get; set; } public DateTime Exit { get; set; } [Display(Name = "Purpose")] public string Purpose { get; set; } public string Response { get; set; } public Status Status { get; set; } public string Extra { get; set; } } } <file_sep>using Appointly.Models; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace Appointly.DAL { public class UserRepository : IUserRepository { private readonly string connectionString; private readonly IConfiguration Existing_staff; public UserRepository(IConfiguration iConfig) { connectionString = iConfig.GetSection("ConnectionStrings").GetSection("Myconnection").Value; Existing_staff = iConfig.GetSection("StaffRecords"); } public int Create(User uc) { int doesUserAlreadyExist = 0; using (SqlConnection con = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand("CreateUserIfNotExist", con)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@FirstName", uc.FirstName); cmd.Parameters.AddWithValue("@LastName", uc.LastName); cmd.Parameters.AddWithValue("@Email", uc.Email); cmd.Parameters.AddWithValue("@Phone", uc.Phone); cmd.Parameters.AddWithValue("@Pwd", uc.Pwd); cmd.Parameters.AddWithValue("@UserRole", uc.UserRole); cmd.Parameters.AddWithValue("@RegistrationId", uc.RegistrationId); con.Open(); using (SqlDataReader rdr = cmd.ExecuteReader()) { if (rdr.HasRows) { doesUserAlreadyExist = 1; } rdr.NextResult(); } } } return doesUserAlreadyExist; } public User Get(short userId) { User user = null; using (SqlConnection con = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand("GetUserById", con)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Id", userId); con.Open(); using (SqlDataReader dr = cmd.ExecuteReader()) { if (dr.HasRows) user = new User(); while (dr.Read()) { user.Id = (short)Convert.ToInt32(dr["Id"].ToString()); user.FirstName = dr["FirstName"].ToString(); user.LastName = dr["LastName"].ToString(); user.DateOfBirth = dr["DateOfBirth"].ToString(); user.Gender = dr["Gender"].ToString(); user.Phone = dr["Phone"].ToString(); } } } } return user; } public int Update(User user) { int isUserUpdated = 0; using (SqlConnection con = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand("UpdateUserById", con)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Id", user.Id); cmd.Parameters.AddWithValue("@FirstName", user.FirstName); cmd.Parameters.AddWithValue("@LastName", user.LastName); cmd.Parameters.AddWithValue("@Phone", user.Phone); cmd.Parameters.AddWithValue("@DateOfBirth", user.DateOfBirth); cmd.Parameters.AddWithValue("@Gender", user.Gender); con.Open(); isUserUpdated = cmd.ExecuteNonQuery(); } } return isUserUpdated; } public List<string> ExistingFaculties() { return Existing_staff.Get<List<string>>(); } public User Login(User uc) { User user = null; using (SqlConnection con = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand("ValidateUser", con)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Email", uc.Email); cmd.Parameters.AddWithValue("@Pwd", uc.Pwd); con.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { user = new User(); while (reader.Read()) { user.Id = Convert.ToInt16(reader["Id"]); user.UserRole = (Role)Convert.ToInt32(reader["UserRole"]); } } } } return user; } } } <file_sep>using Appointly.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Web; using System.Linq; using System.Data.SqlClient; using System.Threading.Tasks; using System.Data; using Appointly.DAL; namespace Appointly.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private readonly IUserRepository userRepository; public HomeController(ILogger<HomeController> logger,IUserRepository userRepository) { _logger = logger; this.userRepository = userRepository; } public IActionResult Index() { return RedirectToAction("Login", "Home"); } public IActionResult About() { return View(); } public IActionResult Register() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Register(User uc) { //return Json(uc); if (ModelState.IsValid) { short role = Convert.ToInt16(HttpContext.Request.Form["UserId"]); string reg_no = Convert.ToString(HttpContext.Request.Form["RegistrationId"]); string pwd = Convert.ToString(HttpContext.Request.Form["Pwd"]); string cpwd = Convert.ToString(HttpContext.Request.Form["confirm_Pwd"]); var list = userRepository.ExistingFaculties(); int isUserAlreadyExist = userRepository.Create(uc); if (pwd != cpwd) { ViewBag.message = "Password and Confirm password field doesn't match enter your details again."; return View(); } else { if (role == 2 || role == 3) { if (!list.Contains(reg_no) || reg_no == "") { ViewBag.message = "Enter a Valid staff ID for registering as a Faculty or Admin."; return View(); } } } if(isUserAlreadyExist == 1) { ViewBag.message = "Entered Email is already registered Please Enter Again"; return View(); } else { ViewBag.success = "User Registered Successfully"; return View(); } } else { ViewBag.message = "Something went wrong please try again."; return View(); } } [HttpGet] public IActionResult Login() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Login(User user) { User uc = new User(); uc = userRepository.Login(user); if (uc != null) { //setting value into a session key HttpContext.Session.SetString("User_Id", Convert.ToString(uc.Id)); HttpContext.Session.SetString("UserRole", Convert.ToString(uc.UserRole)); if (Convert.ToInt32(uc.UserRole) == 1) { return RedirectToAction("Index", "Visitor"); } else if (Convert.ToInt32(uc.UserRole) == 2) { return RedirectToAction("Index", "Faculty"); } else if (Convert.ToInt32(uc.UserRole) == 3) { return RedirectToAction("Index", "Admin"); } else { ViewBag.message = "You entered wrong email or password, Please try again"; return View(); } } else { ViewBag.message = "You entered wrong email or password, Please try again."; return View(); } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Appointly.Models { public enum Status { Pending = 1, Accept, Decline, Completed, Cancelled } } <file_sep>using Appointly.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace Appointly.Controllers { public class FacultyController : Controller { private readonly string connectionString; public FacultyController(IConfiguration iConfig) : base() { connectionString = iConfig.GetSection("ConnectionStrings").GetSection("Myconnection").Value; } [HttpGet] public IActionResult Index() { string userid = HttpContext.Session.GetString("User_Id"); if (string.IsNullOrWhiteSpace(userid)) { return NotFound(); } List<Appointment> appoint = null; using (SqlConnection con = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand("sp_getAllAppointment", con)) { cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Id", userid); cmd.Parameters.AddWithValue("@Status", 1); con.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { if (reader.HasRows) { appoint = new List<Appointment>(); while (reader.Read()) { var app = new Appointment(); app.Id = (short)Convert.ToInt32(reader["Id"].ToString()); app.From = (DateTime)reader["_From"]; app.To = (DateTime)reader["_To"]; app.Purpose = reader["purpose"].ToString(); app.VisitorId = (short)reader["Visitor_Id"]; appoint.Add(app); } } } } } return View(appoint); } [HttpPost] public IActionResult Index(int id, string Response, string submit) { byte val=0; if (submit == "Accept") { val = 2; }else if (submit == "Decline") { val = 3; } using (SqlConnection con = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand("sp_updateAppointmentstatus", con)) { cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@status", val); cmd.Parameters.AddWithValue("@Id", (short)id); if (!string.IsNullOrEmpty(Response)) { cmd.Parameters.AddWithValue("@Response", Response); } con.Open(); cmd.ExecuteNonQuery(); } } ViewBag.message = "Done Successfully"; return RedirectToAction("index"); } public IActionResult Profile() { string id = HttpContext.Session.GetString("User_Id"); if (string.IsNullOrWhiteSpace(id)) { return NotFound(); } short userId = Convert.ToInt16(id); User uc = new User(); using (SqlConnection con = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand("sp_getuserbyid", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Id", userId); con.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { uc.Id = (short)Convert.ToInt32(dr["Id"].ToString()); uc.FirstName = dr["FirstName"].ToString(); uc.LastName = dr["LastName"].ToString(); uc.DateOfBirth = dr["Date_of_birth"].ToString(); uc.Gender = dr["Gender"].ToString(); uc.Phone = dr["Phone"].ToString(); } con.Close(); } if (uc == null) { return NotFound(); } return View(uc); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Profile([Bind] User userEmp) { using (SqlConnection con = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand("sp_updateuser", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Id", userEmp.Id); cmd.Parameters.AddWithValue("@FirstName", userEmp.FirstName); cmd.Parameters.AddWithValue("@LastName", userEmp.LastName); cmd.Parameters.AddWithValue("@Phone", userEmp.Phone); cmd.Parameters.AddWithValue("@Date_of_birth", userEmp.DateOfBirth); cmd.Parameters.AddWithValue("@Gender", userEmp.Gender); con.Open(); int num = cmd.ExecuteNonQuery(); con.Close(); if (num != -1) { ViewBag.message = "User Profile Updated."; return View(); } else { ViewBag.message = "Something went wrong please try again."; return View(); } } } [HttpGet] public IActionResult Logout() { string User_Id = HttpContext.Session.GetString("User_Id"); if (!string.IsNullOrWhiteSpace(User_Id)) { HttpContext.Session.Clear(); HttpContext.Session.SetString("User_Id", ""); ; return RedirectToAction("Login", "Home"); } else { return RedirectToAction("Login", "Home"); } } } } <file_sep>using Appointly.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Appointly.ViewModel { public class AppointmentStatusViewModel { public int Pending { get; set; } public int Approved { get; set; } public int Rejected { get; set; } public int Completed { get; set; } public int Total { get; set; } //List<Customer> public List<Appointment> appointments; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Appointly.DAL { public class AppointmentRepository { } } <file_sep>using Appointly.Models; using Appointly.ViewModel; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Appointly.DAL { public interface IVisitorRepository { public AppointmentStatusViewModel GetVisitorAppointment(int? id, short uid); //index public IEnumerable<User> GetFaculty(); //facultyname schedule public IEnumerable<Appointment> GetFacultyAppointment(int id); //details public void AddAppointment(Appointment appointment, int id, short Vid); //schedule appointment http post } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Appointly.Models { public enum Role { Visitor = 1, Faculty, Admin } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace Appointly.Models { public class User { public short Id { get; set; } [Required(ErrorMessage = "Please Select a Role..")] [Display(Name = "Role")] public Role UserRole { get; set; } [Required(ErrorMessage = "Please Enter Firstname..")] [Display(Name = "First Name")] public string FirstName { get; set; } [Required(ErrorMessage = "Please Enter Lastname..")] [Display(Name = "Last Name")] public string LastName { get; set; } [Required(ErrorMessage = "Please Enter Email..")] [Display(Name = "Email")] public string Email { get; set; } [Required(ErrorMessage = "Please Enter Phone Number..")] [Display(Name = "Phone")] public string Phone { get; set; } [Required(ErrorMessage = "Please Enter Password..")] [DataType(DataType.Password)] [StringLength(20, MinimumLength = 6, ErrorMessage = "Minimum 6 characters are required")] [Display(Name = "Password")] public string Pwd { get; set; } [Display(Name = "Gender")] public string Gender { get; set; } [Display(Name = "Date of birth")] public string DateOfBirth { get; set; } [Display(Name = "Registration Id")] public string RegistrationId { get; set; } } }<file_sep>using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using System.Data.SqlClient; using Appointly.Models; using System.Data; using Appointly.DAL; using Appointly.ViewModel; namespace Appointly.Controllers { public class VisitorController : Controller { private readonly IVisitorRepository visitorRepository; private readonly IUserRepository userRepository; public VisitorController(IVisitorRepository visitorRepository,IUserRepository userRepository) { this.visitorRepository = visitorRepository; this.userRepository = userRepository; } public IActionResult Index(int? id) { if (id == 0) id = 0; ViewBag.Status = id; string userid = HttpContext.Session.GetString("User_Id"); if (string.IsNullOrWhiteSpace(userid)) { return NotFound(); } short userId=Convert.ToInt16(userid); AppointmentStatusViewModel appointmentStatusViewModel = new AppointmentStatusViewModel(); appointmentStatusViewModel = visitorRepository.GetVisitorAppointment(id, userId); return View(appointmentStatusViewModel); } public IActionResult FacultyInfo() { string User_Id = HttpContext.Session.GetString("User_Id"); if (!string.IsNullOrWhiteSpace(User_Id)) { List<User> users = (List<User>)visitorRepository.GetFaculty(); return View(users); } else { return NotFound(); } } public IActionResult Profile() { string id = HttpContext.Session.GetString("User_Id"); if (string.IsNullOrWhiteSpace(id)) { return NotFound(); } short userId = Convert.ToInt16(id); User user = userRepository.Get(userId); return View(user); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Profile(User user) { string id = HttpContext.Session.GetString("User_Id"); if (string.IsNullOrWhiteSpace(id)) { return NotFound(); } int num = userRepository.Update(user); if (num != -1) { ViewBag.message = "User Profile Updated."; return View(); } else { ViewBag.message = "Something went wrong please try again."; return View(); } } public IActionResult Details(int id) { string User_Id = HttpContext.Session.GetString("User_Id"); if (User_Id != "") { List<Appointment> appointments = (List<Appointment>)visitorRepository.GetFacultyAppointment(id); return View(appointments); } else { return RedirectToAction("Login", "Home"); } } public IActionResult ScheduleAppointment(int id) { string User_Id = HttpContext.Session.GetString("User_Id"); if (!string.IsNullOrWhiteSpace(User_Id)) { ViewBag.Fid = id; return View(); } else { return NotFound(); } } [HttpPost] [ValidateAntiForgeryToken] public IActionResult ScheduleAppointment(Appointment ap,int id) { short Id = Convert.ToInt16(id); string user_id = HttpContext.Session.GetString("User_Id"); if (!string.IsNullOrWhiteSpace(user_id)) { short Visitor_Id = Convert.ToInt16(user_id); if (ModelState.IsValid) { visitorRepository.AddAppointment(ap, Id, Visitor_Id); return RedirectToAction("Index", "Visitor"); } else { ViewBag.message = "Something went wrong please try again."; return View(); } } else { return NotFound(); } } [HttpGet] public IActionResult Logout() { string User_Id = HttpContext.Session.GetString("User_Id"); if (!string.IsNullOrWhiteSpace(User_Id)) { HttpContext.Session.Clear(); HttpContext.Session.SetString("User_Id", ""); ; return RedirectToAction("Login", "Home"); } else { return RedirectToAction("Login", "Home"); } } } } <file_sep>using Appointly.Models; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace Appointly.DAL { public interface IUserRepository { public int Create(User user); public User Login(User user); public User Get(short userId); public int Update(User user); public List<string> ExistingFaculties(); } }
7056c5c72668feba2c5a330c14849e6faddf25d9
[ "C#" ]
14
C#
Ayusinha/Appointly
c2ef4b29aa138240010d7a85ac9a6bba55899208
3e3868371e197463a657951621e1bd667c316997
refs/heads/master
<file_sep>function Corrector() { function calculaNota(enunciado,respuestas) { var nota = 0; respuestas.forEach(function(respuesta) { var pregunta = respuesta["pregunta"]; var valor = respuesta["respuesta"]; var correcto = buscaPregunta(enunciado,pregunta); if (valor == correcto) nota += 1; else nota -= 0.25; }); return nota; } function buscaPregunta(enunciado,pregunta) { var busca = enunciado.filter(function(e) { return e["pregunta"] == pregunta; }); if (busca.length > 0) { return busca[0]["correcta"]; } else { throw "No encontrado"; } } function corrige(enunciado,examen) { var resultado = []; examen.forEach(function(prueba) { var id = prueba["alumno"]; var respuestas = prueba["respuestas"]; var nota = calculaNota(enunciado,respuestas); var valor = { "alumno" : id, "nota": nota }; resultado.push(valor); }); return resultado; } return { corrige: corrige }; } module.exports = Corrector; <file_sep>var http= require('http'), url = require('url'), qs = require('querystring'); http.createServer(procesa).listen(3000); console.log("Servidor arrancado"); function procesa(req,resp) { switch (req.method) { case 'POST': parseBody(req,resp,saluda); break; default: resp.end("Solo acepto peticiones POST..."); break; }; } function saluda(post,req,resp) { resp.end("Nombre " + post.nombre + ", edad= " + post.edad); } function parseBody(req, resp, next) { var body = ''; req.on('data', function (data) { body += data; if (body.length > 1e6) { console.log("Body too big!"); req.connection.destroy(); } }); req.on('end', function () { var post = qs.parse(body); next(post,req,resp); }); } <file_sep>function suma3(x) { return x + 3; } var suma3 = function(x) { return x + 3; }; var aplica2 = function (f,x) { return f (f (x)); }; console.log(aplica2(suma3,4)); console.log(aplica2(function (x) { return x * x; },5)); <file_sep>const http = require('http'); const server = http.createServer(); server.on('request',procesa); server.listen(3000); console.log('Servidor arrancado'); function procesa(request, response) { let url = request.url; console.log(`URL solicitada: ${url}`); response.end("Hola"); } <file_sep>const rect = require("./22_Rect.js"); console.log("Area de rect(3,4)=" + rect(3,4).area()); <file_sep>const formidable = require('formidable'), fs = require('fs'), http = require('http') http.createServer((req, resp) => { switch (req.method) { case 'GET': pideFichero(req,resp); break; case 'POST': procesaFichero(req,resp); break; }}).listen(3000); function procesaFichero(req,resp) { let form = new formidable.IncomingForm(); form.parse(req, function(err, fields, files) { resp.writeHead(200, {'content-type': 'application/json'}); fs.readFile(files.fichero.path,'utf8', (err,datos) => { if (err) throw err; let json = JSON.parse(datos) resp.end(JSON.stringify(json)); })}); return; } function pideFichero(req,resp) { resp.writeHead(200, {'content-type': 'text/html'}); resp.end('<h1>Cargar fichero JSON</h1>' + '<form action="/" enctype="multipart/form-data" method="post">'+ '<input type="file" name="fichero"><br>'+ '<input type="submit" value="Enviar">'+ '</form>' ); } <file_sep>module.exports = class Alumnos { constructor() { this.alumnos = {}; } getAlumno(id) { if (id in this.alumnos) alumnos[id]; else return null; } insertaAlumno(id, nombre, apellidos, edad) { this.alumnos[id] = { "nombre": nombre, "apellidos": apellidos, "edad": edad } } } <file_sep>const suma3 = x => x + 3 const aplica2 = (f,x) => f (f (x)) console.log(aplica2(suma3,4)); console.log(aplica2(x => x * x,5)); <file_sep>const request = require('supertest'); const express = require('express'); const app = require('../62_apiUsers'); describe('GET /user', function() { it('respond with json', function(done) { request(app) .get('/users') .set('Accept', 'application/json') .expect('Content-Type', /application\/json/) .expect(200, done); }); it('respond with html', function(done) { request(app) .get('/users') .set('Accept', 'text/html') .expect('Content-Type', /text\/html/) .expect(200, done); }); it('respond with xml', function(done) { request(app) .get('/users') .set('Accept', 'application/xml') .expect('Content-Type', /application\/xml/) .expect(200, done); }); it('respond with plain text', function(done) { request(app) .get('/users') .set('Accept', 'text/plain') .expect('Content-Type', /text\/plain/) .expect(200, done); }); });<file_sep>EjemploNode: Ejemplos en NodeJS =========== Ejemplos en NodeJS utilizados durante un curso sobre Computación en el Servidor mediante NodeJs * [Trasparencias del curso en Slideshare](http://www.slideshare.net/jelabra/19-javascript-servidor) Autor: [<NAME>](http://www.di.uniovi.es/~labra) <file_sep>var fs = require('fs'); var input1 = "fichero1.txt"; var input2 = "fichero2.txt"; var cb1 = function(err1, datos1) { var cb2 = function(err2,datos2) { if (err2) throw err2; if (datos1.length > datos2.length) { console.log("Datos " + input1 + " > datos " + input2); } else { console.log("Datos " + input1 + " <= datos " + input2); } }; if (err1) throw err1; fs.readFile(input2,'utf8',cb2); console.log('leyendo ' + input2); }; fs.readFile(input1, 'utf8', cb1); console.log("leyendo " + input1); <file_sep>var fs = require('fs'); var input = "fichero.txt"; function procesa(err, datos) { if (err) throw "Cannot read " + input + "\n" + err; datos = datos.toUpperCase(); console.log(datos); } fs.readFile(input, 'utf8', procesa); console.log("Leyendo..." + input); <file_sep>const fs=require('fs'); const util = require('util'); // Convert fs.readFile into Promise version of same const readFile = util.promisify(fs.readFile); async function getStuff() { return await readFile('README.md'); } // Can't use `await` outside of an async function so you need to chain // with then() getStuff().then(data => { console.log(data); }); <file_sep>pideNum("Teclea un número", function(num) { console.log("El doble de tu número es " + (num * 2) ); process.exit(); }); function pideNum(msg, callback) { process.stdin.resume(); process.stdout.write(msg + ": "); process.stdin.once('data', function(data) { if (isNaN(data)) { process.stdout.write("Debe ser un número\n"); pideNum(msg, callback); } else { callback(data); } }); } <file_sep>var users = [ { name: 'Juan' } , { name: 'Luis' } , { name: 'Pedro'} ]; exports.html = function(req, res){ res.send('<ul>' + users.map(function(user){ return '<li>' + user.name + '</li>'; }).join('') + '</ul>'); }; exports.text = function(req, res){ res.send(users.map(function(user){ return ' - ' + user.name + '\n'; }).join('')); }; exports.json = function(req, res){ res.json(users); }; exports.xml = function(req, res){ res.send('<users>' + users.map(function(user){ return '<user>' + user.name + '</user>'; }).join('') + '</users>'); };<file_sep>var rect = require("./Rect.js") console.log("Area de rect(3,4) =" + rect(3,4).area());<file_sep>var assert = require('assert'); var parfact = require("../ParFact"); describe('ParFact', function() { describe('método par()', function() { it('debe devolver true con par(4)', function() { assert.equal(true,parfact.par(4)); }); it('debe devolver false con par(5)', function() { assert.equal(false,parfact.par(5)); }); }); describe('método factorial()', function() { it('debe devolver 1 con fact(1)', function() { assert.equal(1,parfact.factorial(1)); }); it('debe devolver 2 con fact(2)', function() { assert.equal(2,parfact.factorial(2)); }); it('debe devolver 6 con fact(3)', function() { assert.equal(6,parfact.factorial(3)); }); it('debe devolver 24 con fact(4)', function() { assert.equal(24,parfact.factorial(4)); }); it('debe devolver 120 con fact(5)', function() { assert.equal(120,parfact.factorial(5)); }); }); });<file_sep>function asincrona(callback) { setTimeout(callback, 200); } var color = 'azul'; asincrona(function() { console.log('El color es ' + color); }); color = 'verde'; <file_sep>var http = require('http'), fs = require('fs'), url = require('url'), qs = require('querystring'); var server = http.createServer(function (req,res){ var url_parts = url.parse(req.url,true); switch (req.method) { case 'POST': var body = ''; console.log('Request found with POST method'); req.on('data', function (data) { body += data; if (body.length > 1e6) req.connection.destroy(); }); req.on('end', function () { var POST = qs.parse(body); res.end("Sent data are name:"+POST.name+" age:"+POST.age); }); break; case 'GET': if(url_parts.pathname == '/') fs.readFile('./form.html',function(error,data){ console.log('Serving the page form.html'); res.end(data); }); else if(url_parts.pathname == '/procesa'){ res.end("Nombre:"+ url_parts.query.nombre+ ", edad:" + url_parts.query.edad); } break; default: console.log("Unsupported method" + req.method); } }); server.on('connection', function (stream) { console.log('Conexión detectada: ' + Date(Date.now())); }); server.listen(8080); console.log('Server listenning at port 8080'); <file_sep>const http = require('http'); const fs = require("fs"); http.createServer(procesa).listen(3000); function procesa(req,resp) { fs.readFile('form.html','utf8',function (err,datos) { resp.setHeader('Content-Type', 'text/html'); resp.end(datos); }); } <file_sep>var fs = require('fs'); var libxmljs = require('libxmljs') var file = process.argv[2]; fs.readFile(file, function (err, contents) { if (err) throw "Cannot open " + file + "\n" + err; var xml = libxmljs.parseXmlString(contents); var newChild = libxmljs.Element(xml, 'new-child'); xml.root().addChild(newChild); fs.writeFile(file, xml.toString(), function (err) { console.log("Updated file " + file); }); }); <file_sep>function prueba(f,x) { setTimeout(f, 500); } let color = 'azul'; function verColor(x) { console.log(`verColor(${x}): ${color}`); } verColor(1); prueba(() => verColor(2)); color = 'verde'; verColor(3); <file_sep>const http = require('http'); const server = http.createServer(); server.on('request',procesa); server.listen(3000); console.log('Servidor arrancado'); function procesa(request,response) { console.log("URL solicitada = " + request.url); response.setHeader("Content-Type", "text/html"); response.write("<p>Hola</p>"); response.end(); } <file_sep>var http=require('http'); var options = { hostname: 'www.uniovi.es', port: 80, path: '/', method: 'GET' }; var total=''; var req = http.request(options, function(response) { response.on("data", function(datos) { total+=datos; console.log("%d bytes recibidos ", datos.length); }); response.on("end", function() { console.log("Datos totales = " + total); }); }); req.end(); <file_sep>setTimeout(function() { console.log('Primer bloque'); setTimeout(function() { console.log('Siguiente bloque'); setTimeout(function() { console.log('Último bloque'); }, 100); }, 500); }, 1000); <file_sep>const http = require('http'); const qs = require('querystring') http.createServer(procesa).listen(3000); function procesa(req, resp) { parseBody(req, resp, saluda); } function saluda(post, req, resp) { console.log(post); resp.end(" nombre: " + post.nombre + ", edad: " + post.edad); } function parseBody(req, resp, next) { var body = ''; req.on('data', data => { body += data; if (body.length > 1e6) { console.log("Body too big!"); req.connection.destroy(); } }); req.on('end', () => { var post = qs.parse(body); next(post, req, resp); }); }<file_sep>var fs = require('fs'); var libxmljs = require('libxmljs') var input = process.argv[2], xpath = process.argv[3]; fs.readFile(input, function (err, contents) { if (err) throw "Cannot open " + input + "\n" + err; var xml = libxmljs.parseXmlString(contents); var result = xml.get(xpath); console.log("Resultado: " + result); }); <file_sep>var http= require('http'), url = require('url'), qs = require('querystring'), Negotiator = require('negotiator'); var alumnos = require('./alumnos.js'); http.createServer(procesa).listen(3000); console.log("Servidor arrancado"); function procesa(req,resp) { var urlparsed = url.parse(req.url,true); var id = urlparsed.query['id']; switch (req.method) { case 'GET': if (id) listarAlumno(id,req,resp); else showAlumnos(req,resp); break; case 'DELETE': if (id) borrarAlumno(id,req,resp); else notAllowed("Intento de borrar todos los alumnos",resp); break; case 'POST': if (id) notAllowed("No se puede hacer POST sobre un alumno concreto",resp); else parseBody(req,resp,crearAlumno); break; case 'PUT': if (id) { parseBody(req,resp,function (post) { modificarAlumno(post,id,req,resp); }); } else notAllowed("Intento de modificar todos los alumnos",resp); break; }; } function isEmpty(query) { return Object.keys(query) == 0 ; } function listarAlumno(id,req,resp) { getAlumno(id,function (err,alumno) { if (err) notAllowed("No se encuentra alumno " + id, resp); else { resp.write(JSON.stringify(alumno)); resp.end(); } }); } var availableMediaTypes = ['text/html', 'text/plain', 'application/json', 'application/xml']; function showAlumnos(req,resp) { var negotiator = new Negotiator(req); var mediaType = negotiator.mediaType(availableMediaTypes); console.log("Mediatype selected: " + mediaType); switch (mediaType) { case 'text/plain': alumnos.text(req,resp); break; case 'application/xml': alumnos.xml(req,resp); break; case 'application/json': alumnos.json(req,resp); break; case 'text/html': default: alumnos.html(req,resp); } } function borrarAlumno(id,req,resp) { console.log("Borrando alumno " + id); alumnos.borraAlumno(id, function(err,alumnos) { if (err) notAllowed("No se puede borrar " + id, resp); else showAlumnos(req,resp); }); } function crearAlumno(post,req,resp) { alumnos.insertaAlumno(post.nombre, post.edad, function(err,alumnos) { if (err) notAllowed("No se puede crear alumno", resp); else showAlumnos(req,resp); }); } function modificarAlumno(post,id,req,resp) { var nombre = post.nombre, edad = post.edad; alumnos.modificaAlumno(id,nombre,edad,function(err,als) { if (err) notAllowed("No se puede modificar alumno " + id,resp); else showAlumnos(req,resp); }); } function notAllowed(msg, resp) { resp.statusCode = 405; resp.write(msg); resp.end(); } function parseBody(req, resp, next) { var body = ''; req.on('data', function (data) { body += data; if (body.length > 1e6) { console.log("Body too big!"); req.connection.destroy(); } }); req.on('end', function () { var post = qs.parse(body); next(post,req,resp); }); } <file_sep>function par(x) { return (x % 2 == 0); } function factorial(x) { if (x < 0) throw "valor negativo"; if (x == 0) return 1 else return x * factorial(x - 1); } module.exports.par = par; module.exports.factorial = factorial; <file_sep>const EDAD_VOTO = 18 const persona = { nombre: "Juan", edad: 20 } function puedeVotar() { return persona.edad > EDAD_VOTO } module.exports = persona; module.exports.puedeVotar = puedeVotar; <file_sep>module.exports = class Alumno { constructor(nombre,apellidos) { this._nombre = nombre; this._apellidos = apellidos; this._edad = 0; } set edad(edad) { this._edad = edad } envejecer() { this._edad ++; } get edad() { return this._edad } } <file_sep>/* * Ejemplo de tipo abstracto para gestionar lista de alumnos * Cada alumno tiene un nombre y una edad */ // Internamente se representan como una sola lista let alumnos = []; // Se inicializan un par de valores alumnos.push({ "nombre": "pepe", "edad": 23 }); alumnos.push({ "nombre": "Luis", "edad": 34 }); // Funciones que se exportan // Utilizan patrón callback, // invocándose con una función next(error, valor) que se llama al terminar exports.getAlumno = function(id,next) { console.log(`Buscando alumno ${id} alumnos:`); console.log(alumnos); let alumno = alumnos[id]; if (alumno == undefined) next(new Error("Cannot find record with id " + id)); else next(null,alumno); }; exports.insertaAlumno = function (nombre,edad,next) { if (nombre == null) next("Campo nombre es obligatorio"); else if (edad == null) next("Campo edad es obligatorio"); else { var record = { "nombre": nombre, "edad": edad }; alumnos.push(record); next(null,alumnos); } }; exports.borraAlumno = function (id,next) { if (alumnos[id] != undefined) { alumnos.splice(alumnos.indexOf(alumnos[id]),1); next(null,alumnos); } else next(new Error("No existe alumno con id " + id)); }; exports.modificaAlumno = function(id,nombre,edad,next) { if (alumnos[id]!= undefined) { alumnos[id] = { "nombre": nombre, "edad": edad}; next(null,alumnos); } else next(new Error("No se puede modificar alumno que no existe. id = " + id)) ; }; exports.toHTML = function() { return '<ol>' + alumnos.map(function(alumno){ return '<li>' + alumno.nombre + ' ' + alumno.edad + '</li>'; }).join('') + '</ol>' ; }; exports.toText = function() { return alumnos.map(function(alumno){ return ' - ' + alumno.nombre + ' ' + alumno.edad + '\n'; }).join(''); }; exports.toJson = function() { return JSON.stringify(alumnos); }; exports.toXML = function() { return '<alumnos>' + alumnos.map(function(alumno){ return '<alumno nombre =\"' + alumno.nombre + '\">' + '<edad>' + alumno.edad + '</edad>' + '</alumno>'; }).join('') + '</alumnos>'; };<file_sep>const Alumnos = require('./27_alumnosES6'); const Alumno = require('./27_alumnoES6'); let a = new Alumnos(); a.insertaAlumno("ID1","Juan", "Torres", 23); let juan = new Alumno("Juan","Torre"); juan.edad = 34; juan.envejecer(); console.log(juan); /*alumnos.getAlumno(1, function(err,a) { if (err) throw err; console.log(a); }); */ <file_sep>const request = require('supertest'); const express = require('express'); const app = require('../62_apiUsers'); describe('GET /user', function() { it('respond with json', function(done) { request(app) .get('/users') .set('Accept', 'application/json') .expect(200) .end(function(err, res) { if (err) return done(err); console.log("End of first test...") done(); }); }); after(function() { // runs after all tests in this block console.log("End of tests..."); }); });<file_sep>const http = require('http'), fs = require('fs'), url = require('url'), qs = require('querystring'); const server = http.createServer((req, res) => { switch (req.method) { case 'POST': let body = ''; req.on('data', data => { body += data; if (body.length > 1e6) req.connection.destroy(); }); req.on('end', () => { var POST = qs.parse(body); res.end("Hola " + POST.cliente + "! Tu email es:" + POST.correo); }); break; case 'GET': if (url.parse(req.url, true).pathname == '/') { fs.readFile('form.html','utf8',(err,datos) => { res.setHeader('content-type', 'text/html'); res.end(datos); }); } break; default: console.log("Método no soportado" + req.method); }}).listen(3000); <file_sep>const fs = require('fs'); const input = process.argv[2], output = process.argv[3]; fs.readFile(input, 'utf8', function(err, data) { if (err) throw "No se puede leer " + input + "\n" + err; data = data.toUpperCase(); fs.writeFile(output,data,'utf8', function(err) { if (err) throw "No se puede escribir " + output + "\n" + err; console.log("Contenidos guardados en..." + output); }); }); console.log("Cargando..." + input); <file_sep># Example of a RESTful API in Node and Express This example is based on [this tutorial](http://scotch.io/tutorials/javascript/build-a-restful-api-using-node-and-express-4) I have simplified the example using a local MongoDB installation and changing bears for alumnos. ## Requirements - Node and npm ## Installation - Clone the repo - Install dependencies: `npm install` - Start the server: `node server.js` ## Testing the API Test your API using [Postman](https://chrome.google.com/webstore/detail/postman-rest-client-packa/fhbjgbiflinjbdggehcddcbncdddomop) <file_sep>var express = require('express'); var bodyParser = require('body-parser'); var app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); var port = process.env.PORT || 3000; var mongoose = require('mongoose'); mongoose.connect('mongodb://@localhost:27017/test'); var Alumno = require('./app/models/alumnos'); var router = express.Router(); router.use(function(req, res, next) { console.log('router funcionando...'); next(); }); router.get('/', function(req, res) { res.json({ message: 'Bienvenido al API!' }); }); router.route('/alumnos') .post(function(req, res) { var alumno = new Alumno(); alumno.nombre = req.body.nombre; alumno.apellidos = req.body.apellidos; console.log("Creando alumno " + alumno); alumno.save(function(err) { if (err) res.send(err); res.json({ message: 'Alumno creado!' }); }); }) .get(function(req, res) { Alumno.find(function(err, alumnos) { if (err) res.send(err); res.json(alumnos); }); }); router.route('/alumnos/:alumno_id') .get(function(req, res) { Alumno.findById(req.params.alumno_id, function(err, alumno) { if (err) res.send(err); res.json(alumno); }); }) .put(function(req, res) { Alumno.findById(req.params.alumno_id, function(err, alumno) { if (err) res.send(err); alumno.nombre = req.body.nombre; alumno.apelidos = req.body.apellidos; console.log("Actualizando alumno " + alumno); alumno.save(function(err) { if (err) res.send(err); res.json({ message: 'Alumno actualizado!' }); }); }); }) .delete(function(req, res) { Alumno.remove({ _id: req.params.alumno_id }, function(err, alumno) { if (err) res.send(err); res.json({ message: 'Alumno borrado' }); }); }); app.use('/api', router); app.listen(port); console.log('Servidor arrancado en puerto ' + port); <file_sep>var http = require('http'); var server = http.createServer(function (req, res) { req.setEncoding('utf8'); var body = ''; req.on('data', function (trozo) { body += trozo; }); req.on('end', function () { try { var datos = JSON.parse(body); } catch (er) { res.statusCode = 400; return res.end('error convirtiendo a Json: ' + er.message); } res.write("Json recibido: " + JSON.stringify(datos)); res.end(); }); }); server.listen(3000); <file_sep> resultado = query('SELECT * FROM posts WHERE id = 1'); hacer_algo_con(resultado); callback = function(resultado) { hacer_algo_con(resultado); } query('SELECT * FROM posts WHERE id = 1', callback); xx = pepe(); var modulo = require('module_name'); modulo.saluda() <file_sep>const fs = require('fs'); const {promisify} = require('util'); const f1 = "fichero1.txt"; const f2 = "fichero2.txt"; const f3 = "fichero3.txt"; const readFileAsync = promisify(fs.readFile); async function main() { const datos1 = await readFileAsync(f1,'utf8'); const datos2 = await readFileAsync(f2,'utf8'); const datos3 = await readFileAsync(f3,'utf8'); const total = datos1.length + datos2.length + datos3.length console.log(`Datos totales leídos: ${total}`) } main(); <file_sep>const http = require('http'), fs = require('fs'), url = require('url'), qs = require('querystring'); const server = http.createServer(function(req, res) { switch (req.method) { case 'POST': var body = ''; req.on('data', function(data) { body += data; if (body.length > 1e6) req.connection.destroy(); }); req.on('end', function() { var POST = qs.parse(body); res.end("Hola " + POST.cliente + "! Tu email es:" + POST.correo); }); break; case 'GET': if (url.parse(req.url, true).pathname == '/') { datos = "<form action=\"procesa\" method=\"POST\">" + "<label>Nombre: <input name=\"cliente\"></label><br>" + "<label>Email: <input name=\"correo\" type=\"email\"></label><br>" + "<button>Enviar</button></form>" res.end(datos); } break; default: console.log("Método no soportado" + req.method); } }); server.listen(3000); console.log('Server listenning at port 3000'); <file_sep>var mongoose = require('mongoose'); var Schema = mongoose.Schema; var AlumnoSchema = new Schema({ nombre: String, apellidos: String }); module.exports = mongoose.model('Alumno', AlumnoSchema);<file_sep>/* * Ejemplo de clase Alumno * Cada alumno tiene un nombre y una edad */ exports.Alumno = class { constructor(nombre) { this.nombre = nombre ; this.edad = 0 ; } setEdad(edad) { this.edad = edad; return this } saluda() { console.log(`Hola, me llamo ${this.nombre} y mi edad es ${this.edad}`) } } <file_sep>var http=require('http'); var server = http.createServer(); server.on('request', procesa); server.listen(3000); function procesa(request,response) { console.log("Cabeceras solicitadas:") var headers = request.headers; for (h in headers) console.log(h + ":" + headers[h]); response.setHeader("Content-Type", "text/html"); response.write("<p>Hola</p>"); response.end(); }<file_sep>const Negotiator = require('negotiator'); const http = require('http'); const tiposDisponibles = ['text/html', 'application/xml', 'application/json' ]; const alumnos = require('./alumnos'); http.createServer(showAlumnos).listen(3000); function showAlumnos(req,resp) { const negotiator = new Negotiator(req); const mediaType = negotiator.mediaType(tiposDisponibles); switch (mediaType) { case 'application/xml': resp.setHeader('content-type',mediaType); console.log("XML...") resp.end(alumnos.toXML()); break; case 'application/json': resp.setHeader('content-type',mediaType); console.log("JSON...") resp.end(alumnos.toJson()); break; case 'text/html': resp.setHeader('content-type', mediaType); resp.end(alumnos.toHTML()); break; default: resp.setHeader('content-type', 'text/html'); resp.end(alumnos.toHTML()); } } <file_sep>var edadLimite = 18; process.stdout.write('Teclea tu edad: '); process.stdin.setEncoding('utf8'); process.stdin.on('data', function (data) { var edad = parseInt(data, 10); if (isNaN(edad)) { console.log('%s no es un número correcto!', data); } else if (edad < edadLimite) { console.log('Debes tener %d para entrar, ' + 'vuelve dentro de %d años', edadLimite, edadLimite - edad); } else { zonaOculta(); } process.stdin.pause(); }); process.stdin.resume(); function zonaOculta() { console.log('Estás dentro!'); } <file_sep>var http=require('http'); /*var server = http.createServer(); server.on('request', procesa); server.listen(3000); */ http.createServer(procesa).listen(3000); function procesa(request,response) { console.log("URL solicitada = " + request.url); console.log("Headers"); console.log(request.headers); response.setHeader("Content-Type", "text/html"); response.write("<p>Hola</p>"); response.end(); } <file_sep>const http = require('http'); const server = http.createServer(); server.on('request',procesa); server.on('connection', avisa); server.listen(3000); console.log('Servidor arrancado'); function avisa(s) { console.log(`Conexión detectada: ${Date(Date.now())} en ${s.localAddress}`); } function procesa(request, response) { let url = request.url; console.log(`URL solicitada: ${url}`); response.end("Hola"); } <file_sep>function rect(a, b) { function area() { return a * b; } return { area: area }; } module.exports = rect; <file_sep>function suma3(x) { return x + 3; } function aplica2(f,x) { return f (f (x)); }; console.log(aplica2(suma3,4)); console.log(aplica2(function (x) { return x * x; },5)); <file_sep>const express = require('express'); const app = express(); const users = require('./users'); app.get('/users', function (req,res) { res.format({ 'text/html' : users.html, 'text/plain': users.text, 'application/json': users.json, 'application/xml': users.xml }); }); app.listen(3000); console.log('Express started on port 3000'); module.exports = app;
c2d35eba531f41d84b7d13fa20fb7ccd886f110f
[ "JavaScript", "Markdown" ]
52
JavaScript
cursosLabra/EjemploNode
388a3e4d3f51bf3c78c05a977dc5a855221774e6
db19038d9bcd1eeabdb1c017e4ea075d4cae1499
refs/heads/master
<repo_name>BanchouBoo/stain<file_sep>/README.md # stain ## hex2rgb ![hex2rgb](images/hex2rgb.png) ## rgb2hex ![rgb2hex](images/rgb2hex.png) ## hexblocks ![hexblocks](images/hexblocks.png) ## invert ![invert](images/invert.png) ## mix ![mix](images/mix.png) ## randcolor ![randcolor](images/randcolor.png) ## lerphex ![lerphex](images/lerphex.png) ## gradient ![gradient](images/gradient.png) ## greyscale ![greyscale](images/greyscale.png) ## shade ![shade](images/shade.png) <file_sep>/src/randcolor #!/bin/sh # Generate random hex colors rand() { i=$1 while [ "$i" -gt 0 ]; do r=$(tr -dc 1-9 < /dev/urandom | dd ibs=1 obs=1 count=5 2>/dev/null) r=$((r % 255)) printf '%s\n' "$r" i=$((i-1)) done } count=${1:-1} count=$((count * 3)) rand "$count" | rgb2hex <file_sep>/src/mix #!/bin/sh # Takes a list of hex colors and finds the average between them all [ -t 0 ] || set -- $(cat) $* r=0 g=0 b=0 count=$# for i; do hex=${i#\#} set -- $(hex2rgb "$hex") r=$((r + $1)) g=$((g + $2)) b=$((b + $3)) done r=$((r / count)) g=$((g / count)) b=$((b / count)) printf '%02x%02x%02x\n' "$r" "$g" "$b" <file_sep>/src/gradient #!/bin/sh # Create a gradient between two hex colors [ -t 0 ] || set -- $(cat) $* start=${1#\#} end=${2#\#} step=$((100 / ($3 - 1))) current_step=0 while [ "$current_step" -le 100 ]; do lerphex "$start" "$end" "$current_step" current_step=$((current_step + step)) done <file_sep>/src/hexblocks #!/bin/sh # Display a list of hex colors as color blocks with the hex value next to them [ -t 0 ] || set -- $(cat) $* # append piped hex value for i; do set -- $(hex2rgb "$i") printf '\033[48;2;%s;%s;%sm \033[m #%s\n' "$1" "$2" "$3" "$i" done <file_sep>/src/shade #!/bin/sh # Increase or decrease the brightness of hex colors shadehex() { hex=${1#\#} mult=$2 set -- $(hex2rgb "$hex") r=$(($1 * $mult)); [ $r -gt 255 ] && r=255 g=$(($2 * $mult)); [ $g -gt 255 ] && g=255 b=$(($3 * $mult)); [ $b -gt 255 ] && b=255 printf '%02x%02x%02x\n' "$r" "$g" "$b" } if [ -t 0 ]; then shadehex "$1" "$2" else for hex in $(cat); do shadehex "$hex" "$1" done fi <file_sep>/src/greyscale #!/bin/sh # Greyscale colors by averaging the RGB values (may change to a different method) [ -t 0 ] || set -- $(cat) $* for i; do hex=${i#\#} set -- $(hex2rgb "$hex") grey=$((($1 + $2 + $3) / 3)) printf '%02x%02x%02x\n' "$grey" "$grey" "$grey" done <file_sep>/src/lerphex #!/bin/sh [ -t 0 ] || set -- $(cat) $* hex_a=${1#\#} hex_b=${2#\#} p=$3 set -- $(hex2rgb "$hex_a") ar=$1 ag=$2 ab=$3 set -- $(hex2rgb "$hex_b") br=$1 bg=$2 bb=$3 r=$(( ar + (br - ar) * p / 100 )) g=$(( ag + (bg - ag) * p / 100 )) b=$(( ab + (bb - ab) * p / 100 )) printf '%02x%02x%02x\n' "$r" "$g" "$b" <file_sep>/src/invert #!/bin/sh # Invert hex color [ -t 0 ] || set -- $(cat) $* for i; do hex=${i#\#} set -- $(hex2rgb "$hex") r=$(($1*-1+255)) g=$(($2*-1+255)) b=$(($3*-1+255)) printf '%02x%02x%02x\n' "$r" "$g" "$b" done <file_sep>/src/hex2rgb #!/bin/sh # Convert a hex color to RGB [ -t 0 ] || set -- $(cat) $* for i; do hex=${i#\#} r=${hex%%????} g=${hex##??} g=${g%%??} b=${hex##????} printf '%d %d %d\n' "0x$r" "0x$g" "0x$b" done <file_sep>/src/rgb2hex #!/bin/sh # Convert an RGB color to hex [ -t 0 ] || set -- $(cat) $* while [ "$1" ]; do printf '%02x%02x%02x\n' "$1" "$2" "$3" shift 3 done
ad847f53345875329179349b2d9da5b00a5fe014
[ "Markdown", "Shell" ]
11
Markdown
BanchouBoo/stain
2bd29d5bd2d19fe5122400636788a41ddfd47e38
a551331d2c1f571bf4425cd2e42b2528bc6c6382
refs/heads/master
<file_sep>## LOAD PACKAGES ## library(dplyr) library(ggplot2) ## READ IN DATA AND ORGANIZE ## #read in data data <- read.table('./data/rcourse_lesson1_data.txt', sep = '\t', header = TRUE) #Look at data dim(data) head(data) tail(data) xtabs(~group, data) #subset out bilingual data_bl <- data %>% filter(., group == "bilingual") #Look at data dim(data_bl) head(data_bl) tail(data_bl) xtabs(~group, data_bl) xtabs(~type, data_bl) ## MAKE FIGURES ## #By group data.plot <- ggplot(data, aes(x = group, y = rt)) + geom_boxplot() pdf("figures/data.pdf") data.plot dev.off() #
ff75c826e37599a631fc81ddf4f1d251aa349861
[ "R" ]
1
R
cedunia/Rcourse
5fdcce312099465627d00b51922b41326e461fef
e121c093c383eee8ab0b3834cacc70c064d70f2f
refs/heads/master
<file_sep>#include <iostream> #include <string> #include <vector> #include <algorithm> #include <stdlib.h> #include <conio.h> using namespace std; int main() { int nb_symbole, nb_etat, nb_Trans, nb_Final; string symbole, transition, etat, mot, fiinal; vector <string> X,Q,Trans,F; char choice; cout<<" on va entrer l'automate"<<endl; do{ cout << "\nCombien de Symboles ? "; cin >> nb_symbole; }while(nb_symbole < 0); cout << "Enter Les Symboles : "; for(int i = 0; i < nb_symbole; i++){ cin >> symbole; X.push_back(symbole); } do{ cout << "Combien d' etats : "; cin >> nb_etat; }while(nb_etat < 0); cout << "Enter Les Etats : "; for(int i = 0; i < nb_etat; i++){ cin >> etat; Q.push_back(etat); } do{ cout << "\nCombien de Transitions: " ; cin >> nb_Trans; }while(nb_Trans < 0); cout << " Entrer toutes les transations sous la forme suivante <etat,symbole,etat>: "; for(int i = 0; i < nb_Trans; i++){ cin >> transition; Trans.push_back(transition); } do{ cout << "\nCombien d' Etats Finaux : " ; cin >> nb_Final; }while(nb_Final < 0); cout << "Entrer les etats finaux : "; for(int i = 0; i < nb_Final; i++){ cin >> fiinal; if (fiinal.length()==2) {fiinal=fiinal[1]; F.push_back(fiinal);} else F.push_back(fiinal); cout << F[i]; } do{ int k; if ((Trans[0][2]=='0') || (Trans[0][2]=='1' )) k=1; else k=0; etat = Trans[0][1+k]; cout << "\n\t Le mot: "; cin >> mot; for (unsigned int i = 0; i < mot.length(); i++){ for(unsigned int j = 0; j < Trans.size(); j++) { if(mot[i] == Trans[j][3+k] ) { if (etat[0] == Trans[j][1+k]) { etat = Trans[j][5+k+k]; i++; if(i == (mot.length())) { j=Trans.size(); } else j=0; } else { if(j == (Trans.size() - 1)) { etat=" "; goto message; } } } else { if(j == (Trans.size() - 1)) { etat=" "; goto message; } } } } message : if (find(F.begin(), F.end(), etat) != F.end()) cout <<"\n\tMot accepte par l'automate" << endl; else cout << "\n\tMot non accepte par l'automate" << endl; cout << "Voulez vous un autre mot ? (o/n) "; choice = getch(); }while(choice == 'o'); return 0; }
93288dcb6025fab4e43084f3e032cef7f4b432eb
[ "C++" ]
1
C++
sarrabr/automate
593baf0637436e08beab929a153eaa6e6b6f98b4
96e02360e9ed46cfdd739ad899318d9caa76e8e5
refs/heads/master
<file_sep># Pizza Website Click [here](https://therigidninja.github.io/PizzaWebsite/) to check it out, otherwise download the zip file and run it offline by opening the __index.html__ on your favourite web browser #### !!! I did not make the mockup just the code ![Mockup](Img/PizzaSite.png "Mockup") <file_sep> window.onload = function(){ var myLatLng = {lat: -37.7518787, lng:145.0094587}; var mapProp= { center:new google.maps.LatLng(myLatLng), panControl: false, zoomControl: false, mapTypeControl: false, scaleControl: false, streetViewControl: false, overviewMapControl: true, center: myLatLng, zoom:13, }; var map = new google.maps.Map(document.querySelector("map"),mapProp); var marker = new google.maps.Marker({ position: myLatLng, map: map, title: 'Hello World!' }); }
b9f9a838911fd25333b2cba5479157e81b096b58
[ "Markdown", "JavaScript" ]
2
Markdown
TheRigidNinja/PizzaWebsite
d7baf925918fd668e15a5905210fbc1ba6938faa
c879412a4db1b4008742a709e2e1ac8f5bf9b862
refs/heads/master
<repo_name>DUC-ANH-GHEL/happybirthday_album<file_sep>/assets/js/index.js $(".owl-carousel").owlCarousel({ loop: false, margin: 10, nav: false, responsive: { 0: { items: 1, }, 600: { items: 2, }, 1000: { items: 3, }, }, }); /* Set the width of the sidebar to 250px and the left margin of the page content to 250px */ function openNav() { document.getElementById("mySidebar").style.width = "250px"; // document.getElementById("main").style.marginLeft = "250px"; document.getElementById("closebtn").style.display = "block"; console.log(document.getElementById("closebtn")); } /* Set the width of the sidebar to 0 and the left margin of the page content to 0 */ function closeNav() { document.getElementById("mySidebar").style.width = "0"; document.getElementById("main").style.marginLeft = "0"; } function calcRate(r) { const f = ~~r, //Tương tự Math.floor(r) id = 'star' + f + (r % f ? 'half' : '') id && (document.getElementById(id).checked = !0) }
b75be7c8e81bab976bca305b33e8130a6a684ee0
[ "JavaScript" ]
1
JavaScript
DUC-ANH-GHEL/happybirthday_album
6be2c6c5a89ede96a613c7359ed5d7919628b48f
b242b9dfcbd87f3178d1bc6c22ca56e64a54ae46
refs/heads/master
<file_sep>//Factory method to fetch json data from Shopify API app.factory('shopifyData', ['$http', function($http){ var prodId,pDataObj; //Get all products function allProducts(){ return $http.get('http://localhost:3030/shopify/get?path=/admin/products.json'); } //Save product ID to share with another controller function setProductId(pid){ prodId = pid; console.log("prodId in Service "+prodId); } //Retrieve product ID to share with another controller function getProductId(){ return prodId; } //Get a single product detail from server function getProduct(pid){ return $http.get('http://localhost:3030/shopify/get?path=/admin/products/'+pid+'.json?fields=id,body_html,variants,images'); } //Update specific product on server function editProduct(pid, prodData){ var product = {"product":prodData}; return $http({ 'method':'PUT', 'url':'http://localhost:3030/shopify/put?path=/admin/products/'+pid+'.json', data: product }).then(successResp,errResp); } //Delete specific product on server function delProduct(pid){ return $http({ 'method':'DELETE', 'url':'http://localhost:3030/shopify/delete?path=/admin/products/'+pid+'.json', }).then(successResp,errResp); } //Save product data to share with another controller function setProductData(pData){ pDataObj = pData; console.log("object set in service "+pDataObj); } //Retrieve product data to share with another controller function getProductData(){ return pDataObj; } //Function to create a new product and call Shopify proxy function createProduct(newPrd){ var product = {"product":newPrd}; return $http({ 'method':'POST', 'url':'http://localhost:3030/shopify/post?path=/admin/products.json', data: product }).then(successResp,errResp); } //Success response from put/delete function successResp(response){ console.log("Put/delete - "+response.data); console.log("Put/delete - "+response.status); } //Error response from put/delete function errResp(response){ //return response.data; console.log("Put/delete - "+response.data); } // Factory functions return{ allProducts : allProducts, getProductById : getProduct, setProductId : setProductId, getProductId : getProductId, editProduct : editProduct, delProduct : delProduct, createProduct : createProduct, setProductData : setProductData, getProductData : getProductData } }]);<file_sep>//This js will initialize angular app and contains all the main controllers var app = angular.module('app',['ngRoute']); //routing to generate different views app.config(function($routeProvider){ $routeProvider.when("/productDetail",{ templateUrl: "views/productDetail.html", controller:"productDetailsCtrl" }) .when("/editProduct",{ templateUrl: "views/editProdView.html", controller:"editProdCtrl" }) .when("/createProduct",{ templateUrl: "views/createProdView.html", controller:"createProdCtrl" }) .otherwise({redirectTo:'/index'}); }); // This controller is for showing product details in right content app.controller('productDetailsCtrl',['$scope','shopifyData','$location','$route', function($scope, shopifyData, $location, $route){ var id = shopifyData.getProductId(); $scope.singleProduct = []; $scope.variants = []; $scope.images = []; shopifyData.getProductById(id) .success(function(response){ $scope.singleProduct = response.product; $scope.images = $scope.singleProduct.images; $scope.variants = $scope.singleProduct.variants; $scope.selected = $scope.variants[0].image_id; angular.forEach($scope.variants, function(val, key){ }) }); $scope.back = function(){ $location.path('/index'); $route.reload(); } } ]); // This is the main controller which is responsible for getting list of products app.controller('productCtrl',['$scope','shopifyData','$location','$route','$window', function($scope, shopifyData, $location, $route, $window){ var productData, prodToDel; $scope.products = []; $scope.image = []; shopifyData.allProducts() .success(function(response){ $scope.products = response.products; }); //Getting details for specific product $scope.selectProduct = function(pid){ $scope.pid = pid; shopifyData.setProductId($scope.pid); $location.path('/productDetail'); }; //Storing product details to be edited in edit view $scope.editProduct = function(pid,title,desc){ productData = {id:pid, title:title, desc:desc}; shopifyData.setProductData(productData); $location.path('/editProduct'); }; //product deletion $scope.delProduct = function(pid){ prodToDel = pid; console.log("Deleting - "+prodToDel); if (confirm("Do you really want to delete product: "+prodToDel+" ?")) { shopifyData.delProduct(prodToDel); $window.location.href = '/index'; $window.location.reload(); } }; }]); //Controller used for new product creation app.controller('createProdCtrl',['$scope','shopifyData','$location','$route', function($scope,shopifyData,$location,$route){ $scope.createPrd = function(){ $scope.imageArr = []; var newImgScr = "http:\/\/example.com\/rails_logo.gif"; var image1 = {"src":newImgScr}; $scope.imageArr.push(image1); var newProduct = {"title":$scope.pTitle,"body_html":$scope.prodDesc,"product_type":$scope.prodType,"images":$scope.imageArr}; shopifyData.createProduct(newProduct).then(reload); }; $scope.cancel = function(){ reload(); }; function reload(){ $location.path('/index'); $route.reload(); }; }]); //Controller used for editing a product app.controller('editProdCtrl',['$scope','shopifyData','$location','$route','$window', function($scope, shopifyData, $location, $route, $window){ var pdata = shopifyData.getProductData(); $scope.pid = pdata.id; $scope.pTitle = pdata.title; $scope.prodDesc = pdata.desc; //shopifyData.editProduct(prodToEdit,prodData); $scope.updSubmit = function(){ var updatedProduct = {"id":parseInt($scope.pid),"title":$scope.pTitle,"body_html":$scope.prodDesc}; console.log("updated - "+updatedProduct.id); shopifyData.editProduct(updatedProduct.id,updatedProduct).then(reload); }; $scope.cancel = function(){ reload(); }; function reload(){ $location.path('/index'); $route.reload(); } }]);
afe20e1c7d871089fdd7e2af104edda358513371
[ "JavaScript" ]
2
JavaScript
rachitsm/stitch-test
15753ec28491a90de09ff71c8226e6fbcf48bc60
da430269fd6c5c47e72029cb61166032835c3a16
refs/heads/master
<repo_name>lymnkkk/mini<file_sep>/index.js $(function(){ // 划过菜单 // $('#nav .center .link li a').hover(function(index){ // $(this).parent().css('border-bottom','4px solid #fff'); // },function(){ // $(this).parent().css('border-bottom','none'); // }) // 设置banner 内的元素 // 设置banner高度 $('#banner').css('height',$('#banner img').css('height')); // alert(($('#banner img').width()-$('#banner ul').width())/2); // 设置banner 小圆点居中 var left=($('#banner img').width()-$('#banner ul').width())/2; $('#banner ul').css('left',left); // 设置左箭头 var toLeft=($('#banner img').height()-$('#banner .left').height())/2; $('#banner .left').css('top',toLeft); // 设置右箭头 var toRight=($('#banner img').height()-$('#banner .right').height())/2; $('#banner .right').css('top',toRight); $(window).resize(function(){ $('#banner').css('height',$('#banner img').css('height')); left=($('#banner img').width()-$('#banner ul').width())/2; $('#banner ul').css('left',left); toLeft=($('#banner img').height()-$('#banner .left').height())/2; $('#banner .left').css('top',toLeft); toRight=($('#banner img').height()-$('#banner .right').height())/2; $('#banner .right').css('top',toRight); }) // 轮播器 $('#banner img').css('opacity','0'); $('#banner img').eq(0).css('opacity','1'); $('#banner ul li').eq(0).css('color','#07153d'); // 存储下一个轮播图 var banner_index=1; // 存储当前轮播图 var origin_index=0; // 自动轮动 var banner_timer=setInterval(banner_fn,3000); // 轮播左边 $('#banner .left').click(function(){ clearInterval(banner_fn); // 点的颜色 蓝色rgb(7, 21, 61) var size=$('#banner img').size(); for(var i=0;i<size;i++){ if($('#banner ul li').eq(i).css('color')=='rgb(7, 21, 61)'){ if(i==0){ banner_index=$('#banner img').size()-1; }else{ banner_index=i-1; } origin_index=i; // alert(banner_index); } } banner($('#banner ul li').get(banner_index),origin_index); // alert($('#banner img').size()); // alert($('#banner ul li').eq(0).css('color')); }) // 轮播右边 $('#banner .right').click(function(){ clearInterval(banner_fn); // 点的颜色 蓝色rgb(7, 21, 61) var size=$('#banner img').size(); for(var i=0;i<size;i++){ if($('#banner ul li').eq(i).css('color')=='rgb(7, 21, 61)'){ if(i==$('#banner img').size()-1){ banner_index=0; }else{ banner_index=i+1; } origin_index=i; // alert(banner_index); } } banner($('#banner ul li').get(banner_index),origin_index); // alert($('#banner img').size()); // alert($('#banner ul li').eq(0).css('color')); }) function banner(obj,prev){ $('#banner ul li').css('color','#fff'); $(obj).css('color','#07153d'); $('#banner img').eq(prev).animate({opacity:0},'slow').css('zIndex','1'); $('#banner img').eq($(obj).index()).animate({opacity:1},'slow').css('zIndex','2'); } function banner_fn(){ if(banner_index>=$('#banner img').size()) banner_index=0; banner($('#banner ul li').get(banner_index) ,banner_index==0 ? $('#banner img').size()-1 :banner_index-1); banner_index++; } })
3fe96fbd9c38a3046896568ffefd4404375f2b5e
[ "JavaScript" ]
1
JavaScript
lymnkkk/mini
a0ddc4d88f2eee7be42f1b1c883e25758d51d586
6bedb3b94161bb174a905d62308c27ad93568c1d
refs/heads/master
<repo_name>igorc94/formphp<file_sep>/README.md # formphp Formulario e outras coisas (3DAW) <file_sep>/aula3/user.php <html lang="pt-br"> <head> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="estilo.css"> <link href="https://fonts.googleapis.com/css?family=Sen&display=swap" rel="stylesheet"> <title>Formulario</title> <style> body{font-family: 'Sen', sans-serif; font-size: 20px; } </style> <h2 style="color:black"><div align="center">Resultado de Cadastro:</div></h2> </head> <body> <div align="center"> Olá, <?php session_start(); echo $_POST["login"]; $_SESSION['log'] = 'login'; ?>. <br> Seu cadastro atual: <br> <br> Seu nome: <?php echo $_POST["nome"]; $_SESSION['name'] = 'nome'; ?>. <br> Seu email: <?php echo $_POST["email"]; $_SESSION['correo'] = 'email'; ?>. <br> Hora atual: <?php echo strftime( '%d-%m-%Y %H:%M:%S', strtotime('now') );?> <?php echo '<br /><a href="index.php">Retornar</a>'; ?> </div> </body> </html><file_sep>/aula3/index.php <html> <head> <link rel="stylesheet" type="text/css" href="estilo.css"> <link href="https://fonts.googleapis.com/css?family=Sen&display=swap" rel="stylesheet"> <title>Formulario</title> <style> body{font-family: 'Sen', sans-serif; font-size: 20px; } </style> <h2 style="color:black"><div align="center">Cadastro Usuario</div></h2> </head> <body> <div align="center"> <form action="user.php" method="POST" target="_blank"> <?php $var_value = $_SESSION['log']; if($log == ) <br> <br> <div class="desc">Login:</div> <input type="text" id="login" name="login"><br /> <br> <div class="desc">Nome:</div> <input type="text" id="nome" name="nome"><br /> <br> <div class="desc">Email:</div> <input type="text" id="email" name="email"><br /> <br> <div class="desc">Senha:</div> <input type="password" id="senha" name="senha"><br /> <br> <br> <br> <br> <input type="submit" value="Enviar"> </form> </div> </body> </html>
0e69586bae3fedb1036cdf853c5c1c391f995bf7
[ "Markdown", "PHP" ]
3
Markdown
igorc94/formphp
0b7805d316aa4bdde47aeff23dec1a844072179a
799374c9949aad05318158cae388876473c02c06
refs/heads/main
<file_sep>import React from 'react' class Form extends React.Component { constructor(props) { super(props) this.state = { dogName: '', breed: '', age: '', } this.handleChange = this.handleChange.bind(this) } handleChange(event) { this.setState({ [event.target.name]:event.target.value }) } render() { const { dogName, breed, age } = this.state return( ) // ??????? <> <h1> {dogName}</h1> <form> <label for="dogName"> Dog Name: <input name="dogName" type="text" value={dogName} onChange={this.handleChange} /> </label> <br/> <label for="breed"> Dog Name: <input name="dogName" type="text" value={dogName} onChange={this.handleChange} /> </label> <br/> <label for="age"> Dog Name: <input name="age" type="number" value={age} onChange={this.handleChange} /> </form> </> ) } } export default Form<file_sep> // #1 code challenge function checkPal(word) { const originalWord = word.toUpperCase() const worldLength = word.length //reverse order console.log(backwardsWord, backardsWord) console.log(word, originalWord === backwardsWord) return originalWord === backwardsWord } let backwardsWord ='' for (let i = wordLength - 1; i >= 0; i--){ backwardsWor += originalWold[i] } checkPal('Wow') checkPal('Dennis')<file_sep> const myString = 'the quick brown dog jumps over the lazy fox' function mostFrequentChar (str) { // obtain list of unique characters in str let stringArray = str.split('') let uniqueChars = [... new Set(stringArray)] console.log (uniqueChars) // loop through string counting occurence of each unique character of each unique characters let freqChar = '' let freqCount = return freqChar console.log(mostFrequentChar(myString)) <file_sep>// Jan 11 2021 js:console.log(‘Hello Node.js!’); <file_sep>const fetch = require("node-fetch") const baseURL = 'https://api.sampleapis.com/wines/reds' console.log(baseURL) fetch(baseURL) .then(resp => resp.json()) .then(data => displayData(data)); function displayData(data) { // document.querySelector(“pre”).innerHTML = JSON.stringify(data, null, 2); console.log(data) displayData(data) } <file_sep>/* const lastName = 'Shea' console.log(lastName) let dogName = "Java" let dogAge = 90 console.log(dogName); console.log('my dog\'s names is ',dogName, 'his age is ', dogAge/7 ) console.log('my dog\'s name is ${myDoggy} his age is ${age}') */ //let dogBirthYear = 2009; //let currentYear = 2021 //console.log('Java will be either ', currentYear - dogBirthYear,'or', currentYear-dogBirthYear + 1, 'in year ',currentYear) let outDoorTempC = 23; let outDoorTempF = ( outDoorTempC * 9/5 ) + 32 console.log(outDoorTempC,'C', 'is ', outDoorTempF, 'F'); console.log(outDoorTempF, 'F', 'is' , (outDoorTempF -32 ) * 5/9, 'C') function toPercent (num){ let pct = num * 100 ; console.log(${num},'=', ${pct},'%') ; return pct } console.log(toPercent(.07)) // const factorial = function fac(n) { // return (n < 2) } <file_sep>import React from 'react' const DogeImage = () => { return( <img src= "https://www.google.com/imgres?imgurl=https%3A%2F%2Fwww.thelabradorsite.com%2Fwp-content%2Fuploads%2F2017%2F04%2Fblack-lab-puppy-daisies.jpg&imgrefurl=https%3A%2F%2Fwww.thelabradorsite.com%2Fblack-labrador%2F&tbnid=aq0WBTX8LuNmtM&vet=12ahUKEwjProHJsM7uAhWri4QIHcUnAy4QMygCegUIARDOAg..i&docid=mU9VluHhxT7pBM&w=750&h=1117&q=black%20labpuppy%20images&ved=2ahUKEwjProHJsM7uAhWri4QIHcUnAy4QMygCegUIARDOAg" alt= "adorable black lab puppy" /> ) } export default DogeImage<file_sep>// all conversations in currConvRate are to USD const currConvRate = [ { "name":"Euro", "xchRate":0.82 }, { "name":"Yen", "xchRate":103 }, { "name":"Rupee", "xchRate":73.18 }, { "name":"Pound", "xchRate":0.73 }, { "name":"USD", "xchRate":1 } ] console.log("Welcome! This is a cheap program to convert your currencies to other currencies") console.log("What currency would you like to convert?") //ASK USER INPUT // METHOD OF DOING SO NOT CURRENTLY PROGRAMMED let currencyName = "Yen" console.log("How much of the above currency do you have to convert?") //ASK USER INPUT // METHOD OF DOING SO NOT CURRENTLY PROGRAMMED let amountToExchange = 200 ; let inUSD = currConvRate.filter(value => (value.name === currencyName) { console.log(value.name, value.xchRate) Return (value.xchRate) } console.log(amountToExchange * currConvRate()) //function convertToUSD (currencyName, amountToExchange) console.log(currConvRate) console.log(currencyName, amountToExchange) /* if (currencyName) console.log ( ` currConvRate.currency ` ) return let intermediary = currencies.find(money => money.name === conversionCurrency) let intermediaryAmount = intermediary.stdconv * conversionAmount currencies.forEach(element => console.log(`${amountToExchang} of ${conversionCurrency} is equal to ${1/(element.stdconv/intermediaryAmount)} of ${element.name}`)) .forEach(member => { let prefix = (member.gender === 'male') ? 'sir' : 'lady' let greeting = `Hello ${prefix} ${member.name}` console.log(greeting) */ <file_sep> //#2 console.log("challenge #2") let array1 = ['Aloha','Hi', 'hawaiiIslandddd', 'a', 'Hello','E'] let array2 = ['jersey'] console.log(array1) let longest_element = array1.pop() console.log(longest_element) console.log('did we get here???????', longest_element) console.log(longest_element.length) let initialLength = array1.length + 1 console.log(array1, "longest=",longest_element) function longest_string (InputArray, longest_element) { if (InputArray.length <= 1) {longest_element = InputArray[1]} else { for (let i = 0; InputArray.length != 2 ; i++) { new_string = InputArray.pop() if (longest_element.length > new_string.length) { longest_element = new_string; console.log(longest_element) return longest_element } } } } longest_string (array1, longest_element) console.log("final_longest_string=", longest_element, array1 )<file_sep>import React, { useState } from 'react' function Counter() { const [count, setCount] = useState(0) return ( <> <h2>You clicked the button 0 times</h2> <button onClick={() => setCount(count + 1)}>+1</button> <button onClick={() => setCount(count = 0)}>Reset</button> <button onClick={() => setCount(count - 1)}>-1</button> </> ) } export default Counter<file_sep> // function printLetter9() { // let a = 1 // console.log(a) // } // printLetter9() // function printLetter() { // let a = 1 // console.log(a) // } let x = 1; x = 3 console.log(x) <file_sep> class Student { constructor(name) { this.name = name } sayHi() { return "Hello, I am " + this.name + "." } } class Project extends Student { constructor(name, proj) { super(name) this.project = proj } present() { return this.sayHi() + " My project is" + this.project + "." } } let project1 = new project1("dgs", "BikeRepair") console.log(project1.present()) // ... Hello - I am dennis and my project is DGS Bikes "<file_sep>console.log('Hello 20201 !!') console.log('Hello Boca Code !!') let myname = 'dgs' console.log(myname)
cdeb3069ae929496ef3b52f7aac9b14af822a942
[ "JavaScript" ]
13
JavaScript
DennisGShea/Todo-too-Feb26
eb8be9ba389ea76a5f7ece94a8dd6fce248b56ed
9e260cb269cf7540fcdac36e7544037c06ab32f9
refs/heads/master
<file_sep># Deck This is a library written for LOVE to provide a playlist interface for a sequence of video or sound files. I have no idea what will happen if you run this without using a version of love built without support for love.video or even a version of love lesser than 0.10.0. # Public API Functions ## deck:init() Initialize Deck or use it as shorthand to wipe its state. If used to wipe its state, it may not stop the current video from playing, for that use `deck:stop()` or `deck:destroyCurrentItem()` before calling `deck:init()`. ## deck:update(dt) Check if the current item is still playing, whether it should advance tracks or just stop. ## deck:getCurrentItem() Get whatever is "active", be it a video or a source. ## deck:insertItem(item, index*) * **item** `string/Object` either a file path or a usable love object. * **index** `int` where to insert the items, leave nil to just put it on the end. Add a file or Object to the playlist. ## deck:insertDirectory(folderpath, index*) * **folderpath** `string` a directory to scan for files and insert. * **index** `int` where to insert the items, leave nil to just put it on the end. Add an entire directory to the playlist. Does not recurse. Uses `deck:insertItem()` internally. Since getDirectoryItems has no predictable order, it will insert the items in the reverse order they were found if an index is specified; otherwise it will add them in their found order to the end of the playlist. ## deck:clear() Wipe the current playlist. Does not stop the playlist internally. ## deck:previous() Move backwards in the playlist, doesn't verify that position exists. ## deck:next() Move forwards in the playlist, doesn't verify that position exists. ## deck:random() Load a random playlist index. This prepares the video by loading it into memory, so repeatedly calling this is not advisable. ## deck:shuffle() Randomly reshuffle the playlist. If the current video index changes, it will load the video at its new position. ## deck:play() Play the entire playlist. It will load an item from the playlist into memory if there is not one loaded at present. ## deck:stop() Stop the entire playlist. Moves the playlist index back to the beginning. Unloads the active playlist item if there is any. # Internal Functions You shouldn't need these, but if you do, I won't blame you. ## deck:loadItem(index) * **index** `int` which item in the playlist to load. Load an item from the playlist at the specified index. If there is an active playlist item, it is unloaded. Returns false if the provided index is nil. If the playlist item at the specified index is a string, it will attempt to create a Source from it. If that Source is created, it will then attempt to create a Video from it. If the Video is created, it assigns the Source to the Video to safely create a video from a file that could potentially be a video or and/or source. It does all this because pcalling `love.graphics.newVideo` with or without the loadaudio flag may cause a crash if passed an mp3 or something it wasn't expecting AND because newSource will extract the audio portion of a video. ## deck:destroyCurrentItem() Unloads the current item, pausing and rewinding it first to prevent Sources to continue to play in the background. ## deck:isItemDone() Checks to see if the current playlist item has finished. This is used internally by the update function. This is mostly for easy expansion of what is considered a playlist item later on. ## deck:print(...) A debug print function that wraps `print()`. If `deck.useDebugPrints` is set to true, it will spit out a bunch of status messages to determine the source of any love hardcrashes. <file_sep>-- hail two satans local deck = { _VERSION = 'deck v1.0.0', _DESCRIPTION = 'Playlist Handling for LOVE', _URL = 'https://github.com/EntranceJew/Deck', } -- == basic stuff function deck:init() -- == state based vars -- what to do when we reach the end -- @WARNING: unused self.loopMode = 'none' --all, none -- this doesn't change unless we're told to, or the loopmode dictates it self.playState = 'stop' --stop, play, pause -- == internal data self.item = nil -- what Playlist Item we presently have loaded self.items = {} -- either file paths or pre-loaded sources (strings are probably best) self.itemIndex = -1 --which item we're peeping, -1 if we're stopped or we have no items -- == debug -- whether we want to make a mess of noise self.useDebugPrints = false end function deck:update(dt) if self.playState == 'play' then if self:isItemDone() then -- the item stopped, keep the beats running if self.itemIndex+1 <= #self.items then self:print("[debug]", "advancing item") self:next() return true else self:stop() self:print("[debug]", "end of the line") return false end end end return false end -- == useful api stuff here function deck:getCurrentItem() self:print("[debug]", "reading current item", self.item) return self.item end function deck:insertItem(item, index) self:print("[debug]", "inserting item", item, index) if index then table.insert(self.items, index, item) -- update our item index so we don't get out of whack if index <= self.itemIndex then self.itemIndex = self.itemIndex + 1 end else table.insert(self.items, item) end end function deck:insertDirectory(folderpath, index) -- no recursion, what are you, some kind of monster? local foundvids = love.filesystem.getDirectoryItems(folderpath) for k,v in ipairs(foundvids) do local abspath = folderpath .. "/" .. v if love.filesystem.isFile(abspath) then self:insertItem(abspath, index) end end end function deck:clear() self:destroyCurrentItem() self.items = {} self.itemIndex = -1 end function deck:previous() self:print("[debug]", "previous doing, loadItem-1") return self:loadItem(self.itemIndex-1) end function deck:next() self:print("[debug]", "next doing, loadItem+1") return self:loadItem(self.itemIndex+1) end function deck:random() local max = #self.items local newIndex = love.math.random(1, max) self:loadItem(newIndex) end function deck:shuffle() -- from: https://coronalabs.com/blog/2014/09/30/tutorial-how-to-shuffle-table-items/ local iterations = #self.items local j local curIndex = self.itemIndex for i = iterations, 2, -1 do j = love.math.random(1, i) self.items[i], self.items[j] = self.items[j], self.items[i] if curIndex == i then curIndex = j end end -- we're not where we used to be, so let's fix our internal state if curIndex ~= self.itemIndex then self:print("[debug]", "shuffle loadItem") deck:loadItem(curIndex) end end -- == PLAYER STATE MORE LIKE CELEBRATE function deck:play() self.playState = 'play' -- should we load the item if it wasn't already? -- I mean, I guess; we don't do it anywhere else if not self.item then self:print("[debug]", "we had no item") -- we don't have a item index, shoot to kill if self.itemIndex == -1 then self:print("[debug]", "we also had no index") self.itemIndex = 1 else self:print("[debug]", "we have an index though") end self:print("[debug]", "playload") self:loadItem(self.itemIndex) end self.item:play() end function deck:stop() self:print("[debug]", "stop the boats") self.playState = 'stop' self:destroyCurrentItem() self.itemIndex = -1 end -- == INTERNAL ONLY YOU RUDE DUDES function deck:loadItem(index) self:print("[debug]", "loadItem", index, self.items[index]) self:destroyCurrentItem() self:print("[debug]", "postDestruction") if not self.items[index] then -- you gave me unstackable cups self:print("[error]", "tried to read from nonexistant item") return false end local success, item if type(self.items[index]) == "string" then self:print("[debug]", "item was string") success, item = pcall(love.audio.newSource, self.items[index]) if success then self:print("[debug]", "item was a source") if love.video then self:print("[debug]", "is item also a video?") local suc2, vid = pcall(love.graphics._newVideo, self.items[index]) if suc2 then self:print("[debug]", "item was also a video") vid:setSource(item) item = vid else self:print("[debug]", "item was not also a video") end end else self:print("[debug]", "No idea what "..self.items[index].." is meant to be.") end self:print("[debug]", "set item") self.item = item else self.item = self.item[index] self:print("[debug]", "item was not string") end self.itemIndex = index if self.playState == 'play' then self:print("[debug]", "resuming play") self.item:play() end self:print("[debug]", "loadItem play") end function deck:destroyCurrentItem() -- destroy the old item for it is a menace and will still play in the background if self.item then self:print("[debug]", "destroying item, hail satan") self.item:pause() self.item:rewind() self.item = nil else self:print("[debug]", "did not destroy item, had no reason") end end function deck:isItemDone() if not self.item then return true elseif self.item and self.item:isPlaying() then return false else return false end end function deck:print(...) if not self.useDebugPrints then return false end print(...) end return deck
c8667db6894ab80c8e8c83ee07003d2e45adf7b7
[ "Markdown", "Lua" ]
2
Markdown
EntranceJew/Deck
8de5afec35c74b682fde0ac18e0824500b99dcc6
41f815d5d9940b2e9b0cbfd552f3a5811fe57896
refs/heads/master
<file_sep><?php $data = ''; $flash = $_SESSION[ 'flash' ]; if( isset($_SESSION['flash'] ) ) { $data = "<p>{$flash}</p>"; } else { $data = print_r( $_SESSION ); } echo $data; ?>
77b9fc528466b0460623e807312cd2ee94b53bbb
[ "PHP" ]
1
PHP
nathanfl/medtele
f8d3c821e1b298e9a6c39f14ca91d5c195daba3e
91b15ffb76e006496cf549add04d268f85910bea
refs/heads/master
<repo_name>TheNecroreaper/HomerMarkovChain<file_sep>/README.md # HomerMarkovChain Simply a quick side project for Intro to Classical Mythology. Uses a Markov Chain and Homer's works translated by <NAME> to create a pseudo work of Homer. <file_sep>/GreekPoemMarkovChain/src/HomerMarkovChain.java import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Random; import java.util.Scanner; public class HomerMarkovChain { public static Random randomGen; private static class WordMarkov{ int frequency; HashMap<String, Integer> wordFrequency; public WordMarkov(){ frequency = 0; wordFrequency = new HashMap<String, Integer>(); } public WordMarkov(String word){ this(); addWord(word); } public WordMarkov addWord(String word){ frequency++; wordFrequency.merge(word, 1, (prev, one) -> prev + one); return this; } public String getNextWord(){ int tempFreq = randomGen.nextInt(frequency); Iterator<String> wordSelector = wordFrequency.keySet().iterator(); String word = wordSelector.next(); tempFreq -= wordFrequency.get(word); while(wordSelector.hasNext() && tempFreq > 0){ word = wordSelector.next(); tempFreq -= wordFrequency.get(word); } return word; } @Override public String toString() { return "WordMarkov{" + "frequency=" + frequency + ", wordFrequency=" + wordFrequency + '}'; } } public static WordMarkov firstWords = new WordMarkov(); public static void main(String args[]){ HashMap<String, WordMarkov> homerWords = createTable(); // for(String key: homerWords.keySet()){ // System.out.println(key + " " + homerWords.get(key)); // } randomGen = new Random(System.currentTimeMillis()); writeHomer(250, homerWords); } public static void writeHomer(int words, HashMap<String, WordMarkov> homerWords){ File output = new File("HomerGen.txt"); try { output.createNewFile(); FileWriter outputWriter = new FileWriter(output); int newLine = 100; String word = firstWords.getNextWord(); outputWriter.write(word); while(words > 0){ String nextWord = homerWords.get(word).getNextWord(); // char lastChar = nextWord.toLowerCase().charAt(nextWord.length() - 1); if(!nextWord.contains(".")) { outputWriter.write(" "); } if(newLine < 0){ newLine = 100; outputWriter.write("\n"); } newLine -= nextWord.length(); outputWriter.write(nextWord); words--; } outputWriter.flush(); } catch (IOException e) { e.printStackTrace(); } } public static HashMap<String, WordMarkov> createTable(){ File odysseyFile = new File("Odyssey"); File iliadFile = new File("Iliad"); HashMap<String, WordMarkov> homerWords = new HashMap<String, WordMarkov>(); readFile(odysseyFile, homerWords); readFile(iliadFile, homerWords); return homerWords; } public static void readFile(File file, HashMap<String, WordMarkov> words){ try { Scanner inputScanner = new Scanner(file); //reads in each word boolean newSentence = true; String prevWord = ""; while(inputScanner.hasNext()){ String word = inputScanner.next(); //starts adding followers for new sentences if(newSentence){ firstWords.addWord(word); newSentence = false; } else { if (word.charAt(word.length() - 1) == '.') { newSentence = true; words.merge(word, new WordMarkov("."), (prev, addedWord) -> prev.addWord(".")); } if (word.contains(".")) { newSentence = true; word = word.replaceAll(".", ""); words.merge(word, new WordMarkov("."), (prev, addedWord) -> prev.addWord(".")); } String newWord = word.replaceAll("[^a-zA-Z0-9]", ""); //if the length has changed, the word had weird characters if (newWord.length() != word.length() && newWord.length() > 0) { newSentence = true; String punctuation = word.substring(newWord.length() - 1); words.merge(newWord, new WordMarkov(punctuation), (prev, addedWord) -> prev.addWord(punctuation)); } words.putIfAbsent(newWord, new WordMarkov()); words.put(newWord, words.get(newWord).addWord(prevWord)); word = newWord; } prevWord = word; } } catch (FileNotFoundException e) { e.printStackTrace(); } } }
ab9f97e0d2a52fda54b00384559f561663d9ef6e
[ "Markdown", "Java" ]
2
Markdown
TheNecroreaper/HomerMarkovChain
58603ecc7975400a939136a6456e900c9bfd6e8f
32a3fc11cce164fbc1d73f854ea7057d737ba21b
refs/heads/main
<repo_name>brtkuu/rick-morty-app<file_sep>/src/router/index.ts /* eslint-disable */ import Vue from "vue"; import VueRouter, { RouteConfig } from "vue-router"; import Allcharacters from "../views/Allcharacters.vue"; import Favorites from "../views/Favorites.vue"; Vue.use(VueRouter); const routes: Array<RouteConfig> = [ { path: "/", name: "characters", component: Allcharacters }, { path: "/favorites", name: "favorites", // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: Favorites } ]; const router = new VueRouter({ mode: "history", base: process.env.BASE_URL, routes }); export default router; <file_sep>/README.md # Rick & Morty Universe Application ## Technologies - Vue - TypeScript - Vuex - Axios ## Application App allow you to search your favorites characters from Rick & Morty. You can check gender, species of character or last episode in which this character appeared, also you can add store your favorites characters. ### <NAME>
0f9ffd15ce1d51b8e85ff049975c9d5780ecbfaf
[ "Markdown", "TypeScript" ]
2
TypeScript
brtkuu/rick-morty-app
4c00af8f87886d36a61c1c6dbe71baa82a4b20a4
2415c5b9e37bf435b19d6f7c88e6e26af7321f85
refs/heads/master
<file_sep>""" Efficient implementation of unstructured mesh operations Created Feb 8th, 2018 by <NAME> (<EMAIL>) """ from __future__ import print_function import numpy as np from scipy import sparse class UnstructuredAdjacency(object): """Efficient scipy implementation of unstructured mesh adjacency ops The connectivity is stored in a sparse adjencency matrix A of shape (nnode, ncell). The gather operation on vector X (nnode) yields the scattered vector Y (ncell), and the scatter operation yields the filtered vector X' (nnode). This writes: Y = 1/nvert . A . X X' = 1/bincount . A^t . Y where ^t is the transpose operation. The gatter-scatter operation resulting in filtering X can be performed efficiently by storing: F = 1/bincount . A^t . 1/nvert . A X' = F . X """ def __init__(self, connectivity): """Store connectivity as adjacency matrix, extract global parameters connectivity: a dictionary-like object with {number_of_vertex: connectivity} where: - number_of_vertex : an integer (number of vertex per element) - connectivity : a list of node indices describing elements of length number_of_vertex * number_of_cells One entry is expected per element type. Ex: {3: [triangle_cells_node_list], 4: [quad_cells_node_list]} """ self._connectivity = connectivity concat = np.hstack(connectivity.values()) self.nnode = np.unique(concat).size min_node_number = concat.min() # Ensure node numbering starts at 0 self._connectivity = {nvert: conn - min_node_number for nvert, conn in self._connectivity.items()} self._bincount = np.bincount(concat - min_node_number) self._adjacency_matrix = self._make_adjacency() @property def ncell(self): """Total number of cells""" return sum(self.ncell_per_nvert.values()) @property def ncell_per_nvert(self): """Dictionary of {nvert: ncell} For each type of element with nvert vertices, stores the nubmer of cells ncell """ return {nvert: conn.size / nvert for nvert, conn in self._connectivity.items()} def _make_adjacency(self, weights=None): """Create adjacency matrix by reading connectivity""" if weights is None: weights = {nvert: np.ones(self._connectivity[nvert].shape) for nvert in self._connectivity} adjacency = [] for nvert in sorted(self._connectivity): conn = self._connectivity[nvert] ncell = self.ncell_per_nvert[nvert] indptr = np.arange(ncell + 1) * nvert adjacency.append(sparse.csr_matrix((weights[nvert], conn, indptr), shape=(ncell, self.nnode))) return sparse.vstack(adjacency) @property def _node2cell_matrix(self): """The (ncell, nnode) matrix""" node_weights = {nvert: np.ones(self.ncell_per_nvert[nvert] * nvert) / nvert for nvert in sorted(self.ncell_per_nvert)} return self._make_adjacency(weights=node_weights) @property def _cell2node_matrix(self): """The (nnode, ncell) matrix""" mat = self._make_adjacency().T weights = sparse.diags(1. / self._bincount) return weights * mat def get_node2cell(self): """Return the node2cell function""" return lambda node_vector: self._node2cell_matrix * node_vector def get_cell2node(self): """Return the cell2node function""" return lambda cell_vector: self._cell2node_matrix * cell_vector def get_filter(self, times=1): """Return the full gather + scatter filter operation If you need to perform the operation N times, you can use the times attribute. """ gatherscatter = self._cell2node_matrix * self._node2cell_matrix def filt(node_vector): """Function to return by get_filter method""" for _ in range(times): node_vector = gatherscatter * node_vector return node_vector return filt
01496c0ce53b7883afbb100c4bfc6eb5d242e74b
[ "Python" ]
1
Python
clapeyre/unstructured-adjacency
141b57c8c50a5f36377efb181f97110883d8dd7e
61247a5d78beab9fbb761810029246bf739aa84c
refs/heads/master
<file_sep>package com.example.stream_provider; public class Triple { public static final String STATUS_IDLE = "idle"; public String ip; public String name; public String status; public Triple(String name, String ip, String status) { this.ip = ip; this.name = name; this.status = status; } @Override public String toString() { return this.name + " (" + this.ip + ") - " + this.status; } }
2cea9f23497cab24c1aca875a66b0163a814952d
[ "Java" ]
1
Java
gooney47/Stream-Provider
963b291c328f9a907ec7a3cdfc0cec5b4d874079
69ad65e8300fa0a3199dc254c26482c0b2a7b27c
refs/heads/master
<file_sep>#!/bin/bash g++ run.C -o run.exe \ `/net/hisrv0001/home/abaty/jetGrooming/CMSSW_9_0_0/src/fastjet-install/bin/fastjet-config --cxxflags --libs --plugins` -lfastjetcontribfragile $(root-config --cflags --libs) <file_sep>#include "Settings.h" #include "include/Tools.h" #include "fastjet/ClusterSequence.hh" #include "include/softDropGroomer.hh" #include "TFile.h" #include "TTree.h" #include "TH1D.h" #include "TMath.h" #include "TThread.h" //#include "TMutex.h" #include "TCondition.h" #include "TLorentzVector.h" #include <vector> #include <string> #include <iostream> #include <stdlib.h> using namespace fastjet; TMutex mtx1; void *findEvts(void *ptr){ Settings * s = (Settings*) ptr; TFile * f; if(s->isPP) f = TFile::Open(s->ppInputFile.c_str(),"read"); else f = TFile::Open(s->ppInputFile.c_str(),"read"); TTree * skim = (TTree*)f->Get("skimanalysis/HltTree"); TTree * photons; if(s->isPP) photons = (TTree*)f->Get("ggHiNtuplizerGED/EventTree"); else photons = (TTree*)f->Get("ggHiNtuplizer/EventTree"); TTree * evt = (TTree*)f->Get("hiEvtAnalyzer/HiTree"); TTree * hlt = (TTree*)f->Get("hltanalysis/HltTree"); std::cout << Form("ak%dPFJetAnalyzer/t",s->jetRadiusTimes10) << std::endl; TTree * jet = (TTree*)f->Get(Form("ak%dPFJetAnalyzer/t",s->jetRadiusTimes10)); skim->AddFriend(evt); int pVtx = 0; int beam = 0; int HBHE = 0; int trig = 0; float vz = -99; std::vector< float > * seedTime = 0; std::vector< float > * swissCrx = 0; std::vector< float > * sigmaIEtaIEta = 0; std::vector< float > * ecalR4 = 0; std::vector< float > * hcalR4 = 0; std::vector< float > * trkR4 = 0; std::vector< float > * hOverE = 0; std::vector< float > * phoEt = 0; std::vector< float > * phoPhi = 0; std::vector< float > * phoEta = 0; float jtpt[1000]; float jtphi[1000]; float jteta[1000]; int nref; skim->SetBranchAddress("pPAprimaryVertexFilter",&pVtx); skim->SetBranchAddress("HBHENoiseFilterResultRun2Loose",&HBHE); skim->SetBranchAddress("pBeamScrapingFilter",&beam); photons->SetBranchAddress("pho_seedTime",&seedTime); photons->SetBranchAddress("pho_swissCrx",&swissCrx); photons->SetBranchAddress("phoSigmaIEtaIEta",&sigmaIEtaIEta); photons->SetBranchAddress("pho_ecalClusterIsoR4",&ecalR4); photons->SetBranchAddress("pho_hcalRechitIsoR4",&hcalR4); photons->SetBranchAddress("pho_trackIsoR4PtCut20",&trkR4); photons->SetBranchAddress("phoHoverE",&hOverE); photons->SetBranchAddress("phoEt",&phoEt); photons->SetBranchAddress("phoPhi",&phoPhi); photons->SetBranchAddress("phoEta",&phoEta); evt->SetBranchAddress("vz",&vz); hlt->SetBranchAddress(s->phoTrigger.c_str(),&trig); jet->SetBranchAddress("nref",&nref); jet->SetBranchAddress("jtpt",&jtpt); jet->SetBranchAddress("jtphi",&jtphi); jet->SetBranchAddress("jteta",&jteta); for(int i = 0; i< ((s->nEvtToProcess<0)?skim->GetEntries():s->nEvtToProcess); i++){ if(i%10000 == 0) std::cout << i << "/" << skim->GetEntries() << std::endl; hlt->GetEntry(i); if(!trig) continue; skim->GetEntry(i); if(!(pVtx && beam && HBHE)) continue; if(TMath::Abs(vz)>15) continue; photons->GetEntry(i); std::vector< std::pair< float, float > > goodPhotons; for(unsigned int j = 0; j<phoEt->size(); j++){ if(phoEt->at(j) < s->phoPtCut) continue; if(TMath::Abs(phoEta->at(j)) > s->phoEtaCut) continue; if(!(TMath::Abs(seedTime->at(j))<3 && swissCrx->at(j)<0.9 && sigmaIEtaIEta->at(j)>0.002)) continue;//spike rejection if(!((ecalR4->at(j)+hcalR4->at(j)+trkR4->at(j)) < 1 && (hOverE->at(j)<0.1))) continue;//isolation if(!(sigmaIEtaIEta->at(j)<0.01)) continue;//sigmaietaieta goodPhotons.push_back(std::pair<float, float>(phoPhi->at(j), phoEt->at(j))); } if(goodPhotons.size()==0) continue; jet->GetEntry(i); bool hasBackToBackJet = false; int photonIndx = -1; std::vector< std::vector< float > > jetVars; //caution, assumes jet tree is ordered by pt for speed! for(unsigned int j = 0; j<nref; j++){ if(jtpt[j] < s->jetPtCut) break; if(TMath::Abs(jteta[j]) > s->jetEtaCut) continue; for(unsigned int p = 0; p<goodPhotons.size(); p++){ if(TMath::ACos(TMath::Cos(goodPhotons.at(p).first-jtphi[j])) > s->dPhiCut){ hasBackToBackJet = true; photonIndx = p; std::vector< float > tempJet; tempJet.push_back(jteta[j]); tempJet.push_back(jtphi[j]); tempJet.push_back(jtpt[j]); jetVars.push_back(tempJet); continue; } } } if(!hasBackToBackJet) continue; //put cuts above here //controls placing event index into a buffer accesible by the other thread mtx1.Lock(); while(s->isQueueFull){ mtx1.UnLock(); sleep(0.1); //std::cout << "Thread 2 waiting" << std::endl; mtx1.Lock(); } //std::cout << "placing evt " << i << std::endl; if(s->nextEvt[0] == -1){ s->nextEvt[0] = i; (s->photon)[0] = goodPhotons.at(photonIndx); (s->b2bJets)[0] = jetVars; } else if(s->nextEvt[1] == -1){ s->nextEvt[1] = i; (s->photon)[1] = goodPhotons.at(photonIndx); (s->b2bJets)[1] = jetVars; s->isQueueFull = true; } mtx1.UnLock(); } std::cout << "Thread 1 Done!" << std::endl; mtx1.Lock(); s->isEvtThreadDone = true; mtx1.UnLock(); } void runGrooming(){ TH1::SetDefaultSumw2(); Settings s = Settings(); std::cout << "Initializing evt search thread" << std::endl; //thread setup and control TThread * thread1 = new TThread("thread1",findEvts, (void*)(&s)); thread1->Run(); bool isDone = false; TFile * out = TFile::Open("output.root","recreate"); TH1D * xjg_LT[s.nSoftDrops]; TH1D * xjg_GT[s.nSoftDrops]; for(int i = 0; i<s.nSoftDrops; i++){ xjg_LT[i] = new TH1D(Form("xjg_lt_%d",i),Form("xjg_lt_%d",i),20,0,2); xjg_GT[i] = new TH1D(Form("xjg_gt_%d",i),Form("xjg_gt_%d",i),20,0,2); } //loading pfcands TFile * f; if(s.isPP) f = TFile::Open(s->ppInputFile.c_str(),"read"); else f = TFile::Open(s->ppInputFile.c_str(),"read"); TTree * pf = (TTree*)f->Get("pfcandAnalyzer/pfTree"); std::vector< int > * id = 0; std::vector< float > * pt = 0; std::vector< float > * eta = 0; std::vector< float > * phi = 0; std::vector < float > * e = 0; pf->SetBranchAddress("pfId",&id); pf->SetBranchAddress("pfPt",&pt); pf->SetBranchAddress("pfEta",&eta); pf->SetBranchAddress("pfPhi",&phi); pf->SetBranchAddress("pfEnergy",&e); int nPho = 0; float photonPhi = -1; float photonPt = -1; std::vector< std::vector< float > > jetVars;//contains a list of jets w/ eta/phi/pt while(true){ sleep(0.01); //std::cout << "Thread 1 waiting" << std::endl; mtx1.Lock(); if(s.nextEvt[0] != -1){ int thisEvt = s.nextEvt[0]; photonPhi = (s.photon)[0].first; photonPt = (s.photon)[0].second; jetVars = (s.b2bJets)[0]; s.nextEvt[0] = s.nextEvt[1]; (s.photon)[0] = (s.photon)[1]; (s.b2bJets)[0] = (s.b2bJets)[1]; s.nextEvt[1] = -1; s.isQueueFull = false; if(s.isEvtThreadDone && s.nextEvt[0]==-1) isDone = true; mtx1.UnLock(); //analysis code here std::cout << "\nPhoton Pt: " << photonPt << " Photon Phi: " << photonPhi << std::endl; //pfcandSetup for fastJet pf->GetEntry(thisEvt); nPho++; std::vector<PseudoJet> particles; for(unsigned int i = 0; i<id->size(); i++){ TLorentzVector vec = TLorentzVector(); vec.SetPtEtaPhiE(pt->at(i),eta->at(i), phi->at(i), e->at(i)); particles.push_back( PseudoJet(vec.Px(),vec.Py(),vec.Pz(), vec.E()) ); } //clustering algorithm JetDefinition jet_def(antikt_algorithm, s.jetRadiusTimes10/10.0); ClusterSequence cs(particles, jet_def); std::vector<PseudoJet> jets = sorted_by_pt(cs.inclusive_jets()); //matching and SoftDrop std::vector<PseudoJet> matchedJets; softDropGroomer sd[s.nSoftDrops]; for(int k = 0; k<s.nSoftDrops; k++) sd[k] = softDropGroomer(s.softDropZ[k], s.softDropBeta[k], s.jetRadiusTimes10/10.0); for(unsigned int j = 0; j < jetVars.size(); j++){ bool isMatched = false; std::cout << "Forest Jet " << j << " Pt: " << jetVars.at(j).at(2) << " Eta: " << jetVars.at(j).at(0) << " Phi: " << jetVars.at(j).at(1) << std::endl; for (unsigned int i = 0; i < jets.size(); i++) { if(TMath::Abs(jets[i].eta()-jetVars.at(j).at(0))>0.05) continue; if(TMath::Abs(jets[i].phi_std()-jetVars.at(j).at(1))>0.05) continue; isMatched = true; std::cout << "FJ jet: " << i << ": "<< jets[i].pt() << " " << jets[i].eta() << " " << jets[i].phi_std() << std::endl; for(int k = 0; k<s.nSoftDrops; k++){ std::vector<PseudoJet> groomedJets = sd[k].doGrooming(jets); if(sd[k].getDR12().at(i) <= s.subjetDRCut) xjg_LT[k]->Fill(jetVars.at(j).at(2)/photonPt); else xjg_GT[k]->Fill(jetVars.at(j).at(2)/photonPt); } continue; } /*if(!isMatched){ std::cout << "No Match!!!" << std::endl; std::cout << "Forest jet: " << j << ": "<< jetVars.at(j).at(2) << " " << jetVars.at(j).at(0) << " " << jetVars.at(j).at(1) << std::endl; for (unsigned int i = 0; i < jets.size(); i++) { std::cout << "FJ jet: " << i << ": "<< jets[i].pt() << " " << jets[i].eta() << " " << jets[i].phi() << std::endl; } }*/ } //std::cout << "done with " << thisEvt << std::endl; //end analysis code if(isDone) break; }else{ if(s.isEvtThreadDone && s.nextEvt[0]==-1) isDone = true; mtx1.UnLock(); if(isDone) break; } } thread1->Join(); for(int i = 0; i<s.nSoftDrops; i++){ xjg_LT[i]->Scale(1/(float)nPho); xjg_GT[i]->Scale(1/(float)nPho); xjg_GT[i]->SetLineColor(kRed); } out->Write(); } int main(){ runGrooming(); return 1; } <file_sep>#ifndef softDropGroomer_h #define softDropGroomer_h #include <iostream> #include <vector> #include <string> #include <algorithm> #include <fstream> #include "fastjet/PseudoJet.hh" #include "fastjet/ClusterSequenceArea.hh" #include "fastjet/contrib/SoftDrop.hh" #include "jetCollection.hh" //--------------------------------------------------------------- // Description // This class runs SoftDrop grooming on a set of jets // Author: <NAME>, <NAME> //--------------------------------------------------------------- class softDropGroomer { private : double zcut_; double beta_; double r0_; std::vector<fastjet::PseudoJet> fjInputs_; //ungroomed jets std::vector<fastjet::PseudoJet> fjOutputs_; //groomed jets std::vector<double> zg_; //zg of groomed jets std::vector<int> drBranches_; //dropped branches std::vector<double> dr12_; //distance between the two subjets std::vector<std::vector<fastjet::PseudoJet>> constituents_; std::vector<std::vector<fastjet::PseudoJet>> constituents1_; std::vector<std::vector<fastjet::PseudoJet>> constituents2_; public : softDropGroomer(double zcut = 0.1, double beta = 0., double r0 = 0.4); void setZcut(double c); void setBeta(double b); void setR0(double r); void setInputJets(std::vector<fastjet::PseudoJet> v); std::vector<fastjet::PseudoJet> getGroomedJets() const; std::vector<double> getZgs() const; std::vector<int> getNDroppedSubjets() const; std::vector<double> getDR12() const; std::vector<fastjet::PseudoJet> doGrooming(jetCollection &c); std::vector<fastjet::PseudoJet> doGrooming(std::vector<fastjet::PseudoJet> v); std::vector<fastjet::PseudoJet> doGrooming(); std::vector<std::vector<fastjet::PseudoJet>> getConstituents() {return constituents_;} std::vector<std::vector<fastjet::PseudoJet>> getConstituents1() {return constituents1_;} std::vector<std::vector<fastjet::PseudoJet>> getConstituents2() {return constituents2_;} }; softDropGroomer::softDropGroomer(double zcut, double beta, double r0) : zcut_(zcut), beta_(beta), r0_(r0) { } void softDropGroomer::setZcut(double c) { zcut_ = c; } void softDropGroomer::setBeta(double b) { beta_ = b; } void softDropGroomer::setR0(double r) { r0_ = r; } void softDropGroomer::setInputJets(const std::vector<fastjet::PseudoJet> v) { fjInputs_ = v; } std::vector<fastjet::PseudoJet> softDropGroomer::getGroomedJets() const { return fjOutputs_; } std::vector<double> softDropGroomer::getZgs() const { return zg_; } std::vector<int> softDropGroomer::getNDroppedSubjets() const { return drBranches_; } std::vector<double> softDropGroomer::getDR12() const { return dr12_; } std::vector<fastjet::PseudoJet> softDropGroomer::doGrooming(jetCollection &c) { return doGrooming(c.getJet()); } std::vector<fastjet::PseudoJet> softDropGroomer::doGrooming(std::vector<fastjet::PseudoJet> v) { setInputJets(v); return doGrooming(); } std::vector<fastjet::PseudoJet> softDropGroomer::doGrooming() { fjOutputs_.reserve(fjInputs_.size()); zg_.reserve(fjInputs_.size()); drBranches_.reserve(fjInputs_.size()); dr12_.reserve(fjInputs_.size()); constituents_.reserve(fjInputs_.size()); constituents1_.reserve(fjInputs_.size()); constituents2_.reserve(fjInputs_.size()); for(fastjet::PseudoJet& jet : fjInputs_) { std::vector<fastjet::PseudoJet> particles, ghosts; fastjet::SelectorIsPureGhost().sift(jet.constituents(), ghosts, particles); fastjet::JetDefinition jet_def(fastjet::cambridge_algorithm, 999.); fastjet::ClusterSequence cs(particles, jet_def); std::vector<fastjet::PseudoJet> tempJets = fastjet::sorted_by_pt(cs.inclusive_jets()); if(tempJets.size()<1) { fjOutputs_.push_back(fastjet::PseudoJet(0.,0.,0.,0.)); zg_.push_back(-1.); drBranches_.push_back(-1.); constituents1_.push_back(std::vector<fastjet::PseudoJet>()); constituents2_.push_back(std::vector<fastjet::PseudoJet>()); continue; } fastjet::contrib::SoftDrop * sd = new fastjet::contrib::SoftDrop(beta_, zcut_, r0_ ); sd->set_verbose_structure(true); fastjet::PseudoJet transformedJet = tempJets[0]; if ( transformedJet == 0 ) { fjOutputs_.push_back(fastjet::PseudoJet(0.,0.,0.,0.)); zg_.push_back(-1.); drBranches_.push_back(-1.); constituents1_.push_back(std::vector<fastjet::PseudoJet>()); constituents2_.push_back(std::vector<fastjet::PseudoJet>()); if(sd) { delete sd; sd = 0;} continue; } transformedJet = (*sd)(transformedJet); fastjet::PseudoJet j1, j2; if(transformedJet.has_parents(j1, j2) == true) { constituents1_.push_back(j1.constituents()); constituents2_.push_back(j2.constituents()); } else { constituents1_.push_back(std::vector<fastjet::PseudoJet>()); constituents2_.push_back(std::vector<fastjet::PseudoJet>()); } constituents_.push_back(transformedJet.constituents()); double zg = transformedJet.structure_of<fastjet::contrib::SoftDrop>().symmetry(); int ndrop = transformedJet.structure_of<fastjet::contrib::SoftDrop>().dropped_count(); //std::vector<double> dropped_symmetry = transformedJet.structure_of<fastjet::contrib::SoftDrop>().dropped_symmetry(); //get distance between the two subjets std::vector<fastjet::PseudoJet> subjets; if ( transformedJet.has_pieces() ) { subjets = transformedJet.pieces(); fastjet::PseudoJet subjet1 = subjets[0]; fastjet::PseudoJet subjet2 = subjets[1]; dr12_.push_back(subjet1.delta_R(subjet2)); } else { dr12_.push_back(-1.); } fjOutputs_.push_back( transformedJet ); //put CA reclusterd jet after softDrop into vector zg_.push_back(zg); drBranches_.push_back(ndrop); if(sd) { delete sd; sd = 0;} } return fjOutputs_; } #endif <file_sep>#ifndef TOOLS #define TOOLS #endif <file_sep>#include "fastjet/ClusterSequence.hh" #include "include/softDropGroomer.hh" #include "TFile.h" #include "TTree.h" #include "TH1D.h" #include "TMath.h" #include <iostream> #include <vector> using namespace fastjet; void runFJ(){ // TFile * f = TFile::Open("/data/cmcginn/HighPt10Skims/outSkimFile_99p2Percent.root","read");//dijet tree TFile * f = TFile::Open("/mnt/hadoop/cms/store/user/luck/2015-Data-promptRECO-photonSkims/pp-photonHLTFilter-v0-HiForest/0.root","read"); TTree * pf = (TTree*)f->Get("pfcandAnalyzer/pfTree"); std::vector< int > * id = 0; std::vector< float > * pt = 0; std::vector< float > * eta = 0; std::vector< float > * phi = 0; std::vector < float > * e = 0; pf->SetBranchAddress("pfId",&id); pf->SetBranchAddress("pfPt",&pt); pf->SetBranchAddress("pfEta",&eta); pf->SetBranchAddress("pfPhi",&phi); pf->SetBranchAddress("pfEnergy",&e); pf->GetEntry(1); std::cout << id->at(0) << " " << pt->at(0) << " " << eta->at(0) << " " << phi->at(0) << " " << e->at(0) << std::endl; std::vector<PseudoJet> particles; for(unsigned int i = 0; i<id->size(); i++){ if(TMath::Abs(eta->at(i))>2.6) continue; particles.push_back( PseudoJet(pt->at(i)*TMath::Cos(phi->at(i)),pt->at(i)*TMath::Sin(phi->at(i)),pt->at(i)/(TMath::Tan(2*TMath::ATan(TMath::Exp(-eta->at(i))))),e->at(i))); } JetDefinition jet_def(antikt_algorithm, 0.4); ClusterSequence cs(particles, jet_def); std::vector<PseudoJet> jets = sorted_by_pt(cs.inclusive_jets(20.0)); std::cout << "Clustering with " << jet_def.description() << std::endl; std::cout << " pt y phi" << std::endl; for (unsigned i = 0; i < jets.size(); i++) { std::cout << "jet " << i << ": "<< jets[i].pt() << " " << jets[i].rap() << " " << jets[i].phi() << std::endl; std::vector<PseudoJet> constituents = jets[i].constituents(); for (unsigned j = 0; j < constituents.size(); j++) { std::cout << " constituent " << j << "'s pt: " << constituents[j].pt() << std::endl; } } softDropGroomer sd = softDropGroomer(0.1,0,0.4); std::vector<PseudoJet> groomedJets = sd.doGrooming(jets); std::cout << jets.at(1).pt() << " " << sd.getDR12().at(1) << std::endl; /* if( groomedJets.at(1).has_pieces() ) { std::vector<PseudoJet> subjets = groomedJets.at(1).pieces(); fastjet::PseudoJet subjet1 = subjets[0]; fastjet::PseudoJet subjet2 = subjets[1]; std::cout << subjet1.pt() << " " << subjet1.eta() << " " << subjet1.phi() << std::endl; std::cout << subjet2.pt() << " " << subjet2.eta() << " " << subjet2.phi() << std::endl; }*/ /* std::vector<PseudoJet> jetConstituents = jets[0].constituents(); JetDefinition CAjet_def(fastjet::cambridge_algorithm, 999); fastjet::ClusterSequence CAcs(jetConstituents, CAjet_def); std::vector<fastjet::PseudoJet> tempJets = fastjet::sorted_by_pt(CAcs.inclusive_jets()); if(tempJets.size()<1) return; fastjet::contrib::SoftDrop * sd = new fastjet::contrib::SoftDrop(0.1, 0, 0.4 ); fastjet::PseudoJet transformedJet = tempJets[0]; if ( transformedJet == 0 ) return; transformedJet = (*sd)(transformedJet); std::vector<fastjet::PseudoJet> subjets; std::cout << "here" << std::endl;*/ /*if ( transformedJet.has_pieces() ) { subjets = transformedJet.pieces(); fastjet::PseudoJet subjet1 = subjets[0]; fastjet::PseudoJet subjet2 = subjets[1]; std::cout << subjet1.pt() << " " << subjet1.eta() << " " << subjet1.phi() << std::endl; std::cout << subjet2.pt() << " " << subjet2.eta() << " " << subjet2.phi() << std::endl; }*/ } int main(){ runFJ(); return 1; } <file_sep>#ifndef SETTINGS #define SETTINGS #include <string> #include <iostream> #include "TH1F.h" #include "TMutex.h" class Settings{ public: std::string ppInputFile = "/mnt/hadoop/cms/store/user/luck/2015-Data-promptRECO-photonSkims/pp-photonHLTFilter-v0-HiForest/0.root"; //std::string PbPbInputFile = "/mnt/hadoop/cms/store/user/richard/2015-Data-promptRECO-photonSkims/HIPhoton40AndZ/PbPb-photonHLTFilter-v3/160202_145715/000*/*.root"; bool isPP = true; int nEvtToProcess = -1;//set to -1 to get full data sample int jetRadiusTimes10 = 3; static const int nSoftDrops = 5; float subjetDRCut = 0.1; float softDropZ[nSoftDrops] = {0.1,0.2,0.5,0.1,0.2}; float softDropBeta[nSoftDrops] = {0,0,1.5,1,1}; std::string phoTrigger = "HLT_HISinglePhoton40_Eta1p5_v1"; float phoPtCut = 60; float phoEtaCut = 1.44; float jetPtCut = 30; float jetEtaCut = 1.6; float dPhiCut = 2.74889357; //7pi/8 //for controlling threads std::pair< float, float > photon[2];//stores phi,pt for passing between threads std::vector< std::vector< float > > b2bJets[2];//stores eta,phi,pt of back to back jets for passing between threads int nextEvt[2] = {-1,-1}; bool isQueueFull = false; bool isEvtThreadDone = false; Settings(); private: }; Settings::Settings(){ std::cout << "Initializing Settings!" << std::endl; } #endif
aa4254bfeb9af63aa422692d4abdd04ccc77cccf
[ "C", "C++", "Shell" ]
6
Shell
abaty/GroomedXjgamma
26682821a39110ceb5db0fe525533f350bdc8f87
4210ade7f74a93079e37b93288c73b04905540b8
refs/heads/master
<file_sep>ENV["RAILS_ENV"] ||= 'test' require 'spec_helper' require 'capybara/rspec' require 'capybara/rails' Capybara.register_driver :selenium_with_long_timeout do |app| client = Selenium::WebDriver::Remote::Http::Default.new client.timeout = 120 Capybara::Selenium::Driver.new(app, :browser => :firefox, :http_client => client) end Capybara.javascript_driver = :selenium_with_long_timeout RSpec.configure do |config| config.include Capybara::DSL, type: :features config.use_transactional_fixtures = false config.before(:each, type: :feature) do WebMock.allow_net_connect! create_region_and_city end config.after(:each, type: :feature) do config.use_transactional_fixtures = true WebMock.disable_net_connect! end end <file_sep>require 'spec_helper' describe ProfilesController do login_user let(:user) { User.last } let(:profile_id) { user.profile.id } describe 'routing' do it "profile/profile_id rout to profiles#show" do expect(get: "profile/#{profile_id}").to route_to({"controller"=>"profiles", "action"=>"show", "id"=> "#{profile_id}" }) end it "profiles rout to profiles#index" do expect(get: "profiles").to route_to({"controller"=>"profiles", "action"=>"index" }) end end describe '#show' do render_views it 'successfully renders the index template on GET /' do get :show, id: profile_id expect(response).to be_successful expect(response).to render_template(:show) end it "have the content 'Profile'" do get :show, id: profile_id expect(response.body).to have_content('Profile') end it "have the first_name" do get :show, id: profile_id expect(response.body).to have_content("#{user.profile.first_name}") end it "have the second_name" do get :show, id: profile_id expect(response.body).to have_content("#{user.profile.second_name}") end it "have the about" do get :show, id: profile_id expect(response.body).to have_content("#{user.profile.about}") end end describe '#index' do render_views it "have the content 'Profile'" do get :index expect(response.body).to have_content('Profiles') end it "have the first_name" do get :index expect(response.body).to have_content("#{user.profile.first_name}") end it "have the second_name" do get :index expect(response.body).to have_content("#{user.profile.second_name}") end it "have the about" do get :index expect(response.body).to have_content("#{user.profile.about}") end end end <file_sep>FactoryGirl.define do factory :profile do first_name 'Виктор' second_name 'Романов' about "Нечего сказать о нём" end end <file_sep>require 'features_spec_helper' describe Users::RegistrationsController do describe 'registration process', :js => true do it 'register user' do visit new_user_registration_path fill_in 'first_name', :with => 'Виктор' fill_in 'second_name', :with => 'Романов' fill_in 'about', :with => 'Teeeeeeeeeeeeeeeeeext' fill_in 'email', :with => '<EMAIL>' fill_in 'password', :with => '<PASSWORD>' fill_in 'password_confirmation', :with => '<PASSWORD>' click_button 'commit' expect(Profile.last.first_name).to eq 'Виктор' end end end <file_sep>require 'spec_helper' describe User do subject { create :user } it { should respond_to(:email) } it { should respond_to(:password) } end <file_sep>require 'spec_helper' describe Profile do subject { create :profile } it { should respond_to(:second_name) } it { should respond_to(:about) } it { should respond_to(:first_name) } end <file_sep>require 'spec_helper' describe WelcomeController do describe 'routing' do it "routes / to welcome#index" do expect(get: '/').to route_to("welcome#index") end end describe "Welcome requests" do it 'successfully renders the index template on GET /' do get :index expect(response).to be_successful expect(response).to render_template(:index) end end context 'when user in not sign in' do render_views it "have the content 'Sign Up'" do get :index expect(response.body).to have_content('Sign up') end it "have the content 'Sign Up'" do get :index expect(response.body).to have_content('Login') end end context 'when user is sign in' do render_views login_user it "should have a current_user" do subject.current_user.should_not be_nil end it "have the content" do get :index expect(response.body).to have_content('Home') expect(response.body).to have_content('Show My Profile') expect(response.body).to have_content('Show all Profile') expect(response.body).to have_content('Edit profile') expect(response.body).to have_content('Logout') end end end
1eb0e069f035c6c53510091e44d17768c7c91e31
[ "Ruby" ]
7
Ruby
Denis4317/practice
384f177968a58bb55cacfc1d6cdae53b2a52a0e2
067af204aa5de22ee782a557362127bd9b853bce
refs/heads/master
<file_sep><!-- footer --> <footer> <div class="container clearfix"> <!-- <ul class="list-social pull-right"> <li><a class="icon-1" href="#"></a></li> <li><a class="icon-2" href="#"></a></li> <li><a class="icon-3" href="#"></a></li> <li><a class="icon-4" href="#"></a></li> </ul> --> <div class="privacy pull-left">&copy; <?php echo date("Y"); ?> | <a href="http://www.jameslittle.org"><NAME></a> | <a href="http://www.servage.net/?coupon=jameslittle">Hosted By Servage One</a> | <a href="http://twitter.github.com/bootstrap/" target="_blank">Bootstrap</a> </div> </footer> <script type="text/javascript" src="js/bootstrap.js"></script> </body> </html><file_sep><!DOCTYPE html> <html lang="en"> <head> <title><NAME> | <?php echo $title; ?></title> <meta charset="utf-8"> <link rel="icon" href="http://jameslittle.org/favicon.png" type="image/x-icon"> <link rel="shortcut icon" href="http://jameslittle.org/favicon.png" type="image/x-icon" /> <meta name="description" content="Hello, my name is <NAME>. This is my project website or portfolio website; Whichever."> <meta name="keywords" content="james, little, portfolio, programming, resume, stuff"> <meta name="author" content="<NAME>"> <link rel="stylesheet" href="css/bootstrap.css" type="text/css" media="screen"> <link rel="stylesheet" href="css/responsive.css" type="text/css" media="screen"> <link rel="stylesheet" href="css/style.css" type="text/css" media="screen"> <link rel="stylesheet" href="css/touchTouch.css" type="text/css" media="screen"> <link rel="stylesheet" href="css/kwicks-slider.css" type="text/css" media="screen"> <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300' rel='stylesheet' type='text/css'> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/superfish.js"></script> <script type="text/javascript" src="js/jquery.flexslider-min.js"></script> <script type="text/javascript" src="js/jquery.kwicks-1.5.1.js"></script> <script type="text/javascript" src="js/jquery.easing.1.3.js"></script> <script type="text/javascript" src="js/jquery.cookie.js"></script> <script type="text/javascript" src="js/touchTouch.jquery.js"></script> <script src="js/forms.js"></script> <script type="text/javascript">if($(window).width()>1024){document.write("<"+"script src='js/jquery.preloader.js'></"+"script>");} </script> <script> jQuery(window).load(function() { $x = $(window).width(); if($x > 1024) { jQuery("#content .row").preloader(); } jQuery('.magnifier').touchTouch(); jQuery('.spinner').animate({'opacity':0},1000,'easeOutCubic',function (){jQuery(this).css('display','none')}); }); </script> <!--[if lt IE 8]> <div style='text-align:center'><a href="http://www.microsoft.com/windows/internet-explorer/default.aspx?ocid=ie6_countdown_bannercode"><img src="http://www.theie6countdown.com/img/upgrade.jpg"border="0"alt=""/></a></div> <![endif]--> <!--[if (gt IE 9)|!(IE)]><!--> <!--<![endif]--> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <link rel="stylesheet" href="css/docs.css" type="text/css" media="screen"> <link rel="stylesheet" href="css/ie.css" type="text/css" media="screen"> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Open+Sans:400' rel='stylesheet' type='text/css'> <![endif]--> <!--Google analytics code--> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-29231762-1']); _gaq.push(['_setDomainName', 'jameslittle.org']); _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> </head> <body> <div class="spinner"></div> <!-- header start --> <header> <div class="container clearfix"> <div class="row"> <div class="span12"> <div class="navbar navbar_"> <div class="container"> <h1 class="brand brand_"><a href="?page=home"><img alt="" src="img/logo.png"> </a></h1> <a class="btn btn-navbar btn-navbar_" data-toggle="collapse" data-target=".nav-collapse_">Menu <span class="icon-bar"></span> </a> <?php include("menu.php"); ?> </div> </div> </div> </div> </div> </header> <file_sep>Portfolio-Website ================= This website is based off of the codester template and has been implmented as my portfolio website. <file_sep> <!-- MENU --> <div class="nav-collapse nav-collapse_ collapse"> <ul class="nav sf-menu"> <?php $pages = array("Home", "Projects", "About Me", "Resume", "Contact"); foreach($pages as $file){ $filename = strtolower(str_replace(" ", "_", $file)); $li = '<li>'; if($page == $filename) $li = '<li class="active">'; echo $li.'<a href="?page='.$filename.'">'.$file.'</a></li>'; } ?> <!-- <li><a href="?page=home">Home</a></li> <li><a href="?page=projects">Projects</a></li> <li><a href="?page=about_me">About Me</a></li> <li><a href="?page=resume">Resume</a></li> <li><a href="?page=contact">Contact</a></li> --> </ul> </div> <?php //I didn't want this to show up in the HTML source, but below is how to have a sub-menu using this template /* <li class="sub-menu"><a href="process.html">Process</a> <ul> <li><a href="#">Process 01</a></li> <li><a href="#">Process 02</a></li> <li><a href="#">Process 03</a></li> </ul> </li> */ ?><file_sep><?php $title = "Home"; include("head.php"); ?><!-- <div style="text-align:center; background: #000; background-image: url('img/code_image.jpg'); width: 100%; height: 300px;"> <h1 style="font-family:'Open Sans'; color:#FFFFFF;"><NAME> <br /> Subtext</h1> </div> --> <div style="text-align:center; background: #000;"> <img src="img/front.png" alt="" /> </div> <div class="bg-content"> <div class="container"> <div class="row"> <div class="span12" style="margin-top: 20px;"> <!-- slider --> <span id="responsiveFlag"></span> <div class="block-slogan"> <h2>Hello There!<br /></h2> <div> <p>My name is <NAME>, I am currently 23 years old and a student at Texas Tech Universtiy. I am studying Computer Science and hope to one day achieve a doctorate degree in the field of Computer Science. This website contains some recent project I have done for fun or for learning. Not only do I have a passion for programming, but all aspects of computing. I discoverd this love of computers when I was 15 years old and decided to take down the challenge of building my own computer. After weeks of researching and saving, I was able to build my computer. I haven't stop learning and exploring all areas of computing to better my understanding of these machines, to better understand myself.</p> </div> </div> </div> </div> </div> </div> <!-- content --> <?php include("foot.php"); ?><file_sep><?php $title = "Contact"; include("head.php"); ?> <div class="bg-content"> <!-- content --> <div id="content"><div class="ic"></div> <div class="container"> <div class="row"> <article class="span8"> <h3>Contact Me</h3> <div class="inner-1"> <p>Coming Soon!</p><!-- <form id="contact-form"> <div class="success"> Your message has been sent succesfuly!<strong> We will be in touch soon.</strong> </div> <fieldset> <div> <label class="name"> <input type="text" value="Your name"> <br> <span class="error">*This is not a valid name.</span> <span class="empty">*This field is required.</span> </label> </div> <div> <label class="phone"> <input type="tel" value="Telephone"> <br> <span class="error">*This is not a valid phone number.</span> <span class="empty">*This field is required.</span> </label> </div> <div> <label class="email"> <input type="email" value="Email"> <br> <span class="error">*This is not a valid email address.</span> <span class="empty">*This field is required.</span> </label> </div> <div> <label class="message"> <textarea>Message</textarea> <br> <span class="error">*The message is too short.</span> <span class="empty">*This field is required.</span> </label> </div> <div class="buttons-wrapper"> <a class="btn btn-1" data-type="reset">Clear</a> <a class="btn btn-1" data-type="submit">Send</a></div> </fieldset> </form> --> </div> </article> <article class="span4"> <h3>Contact info</h3> <div class="map"> <iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=lubbocktexas&amp;aq=&amp;sll=31.968599,-99.901813&amp;sspn=23.168934,43.022461&amp;t=h&amp;ie=UTF8&amp;hq=&amp;hnear=Lubbock,+Texas&amp;ll=32.7688,-101.821289&amp;spn=6.464575,9.338379&amp;z=6&amp;iwloc=A&amp;output=embed"></iframe> <address class="address-1"> <span>&zwnj;</span><u><NAME></u><br /> <span>Mobile:</span>(806)577-8990<br /> <span>E-mail:</span><a href="#" class="mail-1"><EMAIL></a> <div class="overflow"> </div> </address> </article> </div> </div> </div> </div> <?php include("foot.php"); ?><file_sep><?php $title = "Page Not Found"; include("head.php"); ?> <div class="bg-content"> <div id="content"> <div class="container"> <div class="row "> <div class="span12"> <div class="block-404"> <img class="img-404" src="img/404.jpg" alt=""> <div class="box-404"> <h2>Oopss!</h2> <h3>404 page not found</h3> <p>The page you are looking for does not exists, please select a page from the menu above. </p> </div> </div> </div> </div> </div> </div> </div> <?php include("foot.php"); ?><file_sep><?php if(isset($_GET['page'])) $page = $_GET['page']; if(!isset($page) || $page == "head" || $page == "foot" || $page == "menu" || empty($page)) $page = "home"; $file = "includes/".$page.".php"; if(file_exists($file)) include $file; else include "includes/404.php"; ?> <file_sep><?php $title = "Projects"; include("head.php"); ?> <style> img.project{ border: 2px #29c solid; } </style> <div class="bg-content"> <!-- content --> <div id="content"><div class="ic"></div> <div class="container"> <div class="row"> <article class="span12"> <h4>Projects</h4> </article> <div class="clear"></div> <ul class="thumbnails thumbnails-1 list-services"> <li class="span4"> <div class="thumbnail thumbnail-1"> <img class="project" src="img/this_website.png" alt="" /> <section> <a href="https://github.com/Lamez/Portfolio-Website" class="link-1">This Website</a> <p align="left"><strong>Language</strong>: HTML, JS, CSS, PHP</p> <p align="left"><strong>Status</strong>: Incompleted, Active</p> <p align="left">Whoa, that's meta. I took the "off the shelf" approach to creating this website. I am not much of a designer, but more of a devloper. That being said, this website is bassed of the template "Codester".</p> </section> </div> </li> <li class="span4"> <div class="thumbnail thumbnail-1"> <img class="project" src="img/trianglegame.png" alt="" /> <section> <a href="https://github.com/Lamez/Triangle-Game" class="link-1">Cracker Barrel Triangle Game</a> <p align="left"><strong>Language</strong>: C++</p> <p align="left"><strong>Status</strong>: Incomplete, Active</p> <p align="left">This project was to teach me how to solve puzzles using the general backtracking algorithm. The idea of the game is, you select your starting peg, then you jump a peg to an empty location and remove the middle peg, kind of like checkers. You win when you only have one peg left.</p> </section> </div> </li> <li class="span4"> <div class="thumbnail thumbnail-1"> <img class="project" src="img/feed_me.png" alt="" /> <section> <a href="https://github.com/Lamez/FeedMe" class="link-1">FeedMe</a> <p align="left"><strong>Language</strong>: HTML, JS, CSS, PHP</p> <p align="left"><strong>Status</strong>: Incompleted, Active</p> <p align="left">This project takes any given website and turns into a phone application. The idea is to have this back-end system website to parse the given website and turn it into a RSS feed which would periodically be updated. The phone application will read the RSS feed and produce usuable content to the user. This porject will teach me about mobile development.</p> </section> </div> </li> <li class="span4"> <div class="thumbnail thumbnail-1"> <img class="project" src="img/proxy.png" alt="" /> <section> <a href="/downloads/building_a_transparent_proxy_server.pdf" class="link-1">Transparent Proxy Server</a> <p align="left"><strong>Language</strong>: English</p> <p align="left"><strong>Status</strong>: Completed, inactive</p> <p align="left">I really wanted to create a transparent proxy server, mainly as a learning experience and to say I have done so. The whole learning process took me about a year, I worked on it off and on. To display my efforts and to help my fellow nerds I created a white paper on how create one on your own.</p> </section> </div> </li> <li class="span4"> <div class="thumbnail thumbnail-1"> <img class="project" src="img/statspackage.png" alt="" /> <section> <a href="https://github.com/Lamez/StatsPackage" class="link-1">StatsPackage</a> <p align="left"><strong>Language</strong>: Java</p> <p align="left"><strong>Status</strong>: Completed, inactive</p> <p align="left">A simple program that takes in a list of numbers from a plain text files and does several static operations like mean, mode and etc.</p> </section> </div> </li> </ul> </div> </div> </div> </div> <?php include("foot.php"); ?><file_sep><?php $title = "Resume"; include("head.php"); ?> <div class="bg-content"> <div id="content"> <div class="container"> <div class="row"> <article class="span8"> <h3>Resume</h3> <h4 style="font-size: 25px; text-decoration:underline; padding-bottom:0px;">Experience</h4> 2009-Present &nbsp;&nbsp; United Supermarkets &nbsp;&nbsp; Lubbock, Texas <ul> <li>Point 1</li> <li>Point 2</li> </ul> <h4 style="font-size: 25px; text-decoration:underline; padding-bottom:0px;">Education</h4> 2009-Present &nbsp;&nbsp; United Supermarkets &nbsp;&nbsp; Lubbock, Texas <ul> <li>Point 1</li> <li>Point 2</li> </ul> </article> <article class="span4" style="margin-top: 62px;"> <h4 style="font-size: 25px; text-decoration:underline; padding-bottom:0px;">Contact</h4> <u><NAME></u><br /> 16401 FM 1730<br /> Lubbock, Texas, 79424<br /> (806)577-8990<br /> <a href="mailto:<EMAIL>"><EMAIL></a> <h4 style="font-size: 25px; text-decoration:underline; padding-bottom:0px;">Download</h4> <a href="downloads/James_Little_Resume.pdf"><img src="img/document-pdf.png" alt="PDF" />PDF Format</a> <a href="downloads/James_Little_Resume.doc"><img src="img/document-word.png" alt="DOC" />Doc Format</a> </article> </div> </div> </div> </div> <?php include("foot.php"); ?>
b793fe28daddbce452c5b042242d60310f94c144
[ "Markdown", "PHP" ]
10
PHP
jamesraylittle/Portfolio-Website
284288f3bd168057bff3a095902d1163d46abed9
c8ad393c06d4e0f16ae89df686b433cd34130489
refs/heads/master
<repo_name>jburnitz/memory-tools<file_sep>/dumpmem.c #include <stdio.h> #include <stdlib.h> #include <sys/ptrace.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #define CNORMAL "\x1B[0m" #define CRED "\x1B[31m" void usage(char **argv); int main(int argc, char **argv) { int boolPrettyPrint = 1; unsigned int WIDTH = 0x20u; if (argc < 4) { usage(argv); return -1; } //check if the user wants raw output for use in like xxd int arg_idx = 1; if (strcmp(argv[arg_idx], "-r") == 0 || strcmp(argv[arg_idx], "--raw-output") == 0) { boolPrettyPrint = 0; arg_idx++; } //interpret address as hex unsigned long offsetBegin = strtoul(argv[arg_idx++], NULL, 16); unsigned long offsetEnd = strtoul(argv[arg_idx++], NULL, 16); //pid is always the last argument unsigned int pid = atoi(argv[arg_idx]); char mem_file_name[80]; int mem_fd; //most efficient to read page by page unsigned char buf[_SC_PAGE_SIZE]; sprintf(mem_file_name, "/proc/%d/mem", pid); //read the memory image now mem_fd = open(mem_file_name, O_RDONLY); //pauses the process sends SIG_STOP ptrace(PTRACE_ATTACH, pid, NULL, NULL); waitpid(pid, NULL, 0); int i = 0; unsigned int offsetItr; //first lets start with a 0x....0 offset offsetBegin = (offsetBegin - (offsetBegin & 0xFF)); //gives contexual information to the output if (boolPrettyPrint) { //header printf("%15s", CRED); for (i = 0; i < WIDTH; i++) printf("%.2X ", i); printf("%s", CNORMAL); for (offsetItr = offsetBegin; offsetItr < offsetEnd; offsetItr += WIDTH) { lseek(mem_fd, offsetItr, SEEK_SET); read(mem_fd, buf, WIDTH); printf("\n%#x: ", offsetItr); for (i = 0; i < WIDTH; i++) printf("%.2X ", buf[i]); for (i = 0; i < WIDTH; i++) if(isprint((char) buf[i])) printf("%c", buf[i]); else printf("."); } //footer printf("\n%15s", CRED); for (i = 0; i < WIDTH; i++) printf("%.2X ", i); printf("%s\n", CNORMAL); } else { //if not pretty its ugly for (offsetItr = offsetBegin; offsetItr < offsetEnd; offsetItr += WIDTH) { lseek(mem_fd, offsetItr, SEEK_SET); read(mem_fd, buf, WIDTH); fwrite(buf, 1, WIDTH, stdout); } } //just to be proper close(mem_fd); return 0; } void usage(char **argv) { printf("Usage: %s [-r|--raw-output] <Start Address in hex> <End Address in hex> <PID>\n", argv[0]); } <file_sep>/patchmem.c #define _GNU_SOURCE #include <string.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <sys/ptrace.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> void usage(char** argv); unsigned char* hex2bytes( const unsigned char *hexstring, unsigned int len); int main(int argc, char** argv){ int i=0; if(argc !=4){ usage(argv); return -1; } int pid = atoi(argv[1]); unsigned long startAddress=strtoul(argv[2], NULL, 16); unsigned char* inputBytes=NULL; if( (inputBytes = hex2bytes( (const unsigned char*)argv[3], strlen(argv[3]) ) ) == NULL ){ usage(argv); return -2; } int numInputBytes = ( strlen( argv[3] ) / 2 ); printf("input bytes =\n"); for(i=0; i<numInputBytes; i++) printf("%02X\n", inputBytes[i]); int mem_fd; unsigned char buf[_SC_PAGE_SIZE]; //20 should be biggest ever char mem_file_name[20]; sprintf(mem_file_name, "/proc/%d/mem", pid); //open the memory of the image and pause it's execution mem_fd = open(mem_file_name, O_RDONLY); ptrace(PTRACE_ATTACH, pid, NULL, NULL); waitpid(pid, NULL, 0); //unsigned long offsetEditStart = 0x8048474u+0x14u; //long type should be the word size int numWordsToWrite = ceil( (double)numInputBytes/(double)sizeof(long) ); printf("num words to write %d\n", numWordsToWrite); int numTotalBytesToWrite = numWordsToWrite * sizeof(long); unsigned char writeByteBuf[ numTotalBytesToWrite ]; //ptrace writes 1 word per call, so on x64 means 8 bytes //Read the extra bytes int deltaBytes = numTotalBytesToWrite-numInputBytes; lseek(mem_fd, startAddress+deltaBytes, SEEK_SET); //I don't think read can write in reverse unsigned char* endBytesStart=(writeByteBuf+numInputBytes); read(mem_fd, endBytesStart, deltaBytes ); memcpy(writeByteBuf, inputBytes, numInputBytes); printf("total bytes to write %d @ %X - %X\n", numTotalBytesToWrite, startAddress, startAddress+numTotalBytesToWrite); for(i=0; i<numTotalBytesToWrite; i++) printf("%02X ", writeByteBuf[i]); printf("\n"); //long* writeBufPtr = (*((long*)writeByteBuf)); long* writeBufPtr = (long*)writeByteBuf; long ptraceRet; for(i=0; i<numWordsToWrite; i++){ printf("poking value %X @ %X\n", writeBufPtr[i], startAddress); ptraceRet = ptrace (PTRACE_POKEDATA, pid, startAddress, writeBufPtr[i]); startAddress += sizeof(long); if( ptraceRet < 0 ){ printf("fatal: ptrace return code %d\n", ptraceRet); return -3; } } printf("bytes written at %X\n", startAddress); for(i=0; i<numTotalBytesToWrite; i++) printf("%02X ", writeByteBuf[i]); printf("\n"); //just to be proper close(mem_fd); ptrace(PTRACE_DETACH, pid, NULL, NULL); return 0; } void usage(char** argv){ printf("Usage:\n %s <pid> <Start Address in hex> <Bytes, \"E8C29090\">\n", argv[0]); printf("Ex:\n %s 1234 0xdeadbeef \"90E8C29090\"\n", argv[0]); printf(" Writes the 5 bytes into 0xdeadbeef to 0xdeadbef4\n"); } unsigned char* hex2bytes(const unsigned char *hexstring, unsigned int len) { //needs to be even if(len % 2) return -1; //2 ascii hex chars per byte unsigned char* bytes = NULL; int byteSize = len/2; bytes = (unsigned char*)malloc(byteSize); if(bytes == NULL) printf("malloc error\n"); int i=0; for (;i<byteSize;++i) { int value; sscanf(hexstring+2*i,"%02x",&value); // printf("%02X", value); bytes[i] = value; // printf("%02X ", *bytes[i]); } return bytes; /* int j; */ } <file_sep>/README.md # memory-tools Some simple tools to view and edit a running process using ptrace, without the overhead of gdb GDB is the obvious better tool for any real work, but it's a neat insight into how the syscalls work An example usage would be on a.out with PID 12969, first find the memory location of the image with joe@debian:~$ cat /proc/12969/maps 08048000-08049000 r-xp 00000000 08:04 6045666 /home/joe/tmp/a.out ... joe@debian:~$ The first line of /proc/PID/maps is memory address of the executable section, indicated by the x in the permissions field. 08048000 08049000 are the start and end memory addresses of the a.out executable, which dumpmem and patchmem can use. <file_sep>/makefile CC=gcc all: dumpmem patchmem dumpmem: dumpmem.c $(CC) -o dumpmem dumpmem.c patchmem: patchmem.c $(CC) -o patchmem patchmem.c -lm clean: rm -f patchmem dumpmem
f79738f0cd18e42dae69ab11eb949e6fdf7ab7c4
[ "Markdown", "C", "Makefile" ]
4
C
jburnitz/memory-tools
19ede7f365f1f40f41c37535be357391eed967cf
696306575ed19e868642bd769add0d228a87cfc8
refs/heads/master
<repo_name>INN/theme-cpi<file_sep>/page-support.php <?php /** * * Template Name: Support Us * * Learn more: http://codex.wordpress.org/Template_Hierarchy */ $context = Timber::get_context(); // get page $context['page'] = Timber::get_post(); // Render view Timber::render( 'pages/support.twig', $context ); <file_sep>/src/Blocks/StationID/station-id.js // Import CSS. import './editor.scss'; class StationId { constructor(el) { this.registerMyBlock(); } registerMyBlock() { const { __ } = wp.i18n; const { registerBlockType } = wp.blocks; // Import registerBlockType() from wp.blocks registerBlockType('cpi/station-id', { title: __('Station Identification'), // Block title. icon: { src: 'nametag', background: '#ecf6f6', }, category: 'widgets', keywords: [__('station id'), __('id')], attributes: { content: { source: 'html', selector: 'p', }, }, /** * @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/ */ edit({ className }) { return ( <div className={className}> <h3>Who We Are</h3> <p>{whoWeAre}</p> </div> ); }, save({ attributes, className }) { return null; }, }); } } export default StationId; <file_sep>/README.md # Center for Public Integrity -- WordPress Theme ## Local Admin login credentials for all environments can be found in 1Password -- `CPI - Dotenv (Local)`. - **url**: https://cpi.ups.dock - **wordpress admin**: https://cpi.ups.dock/wp-admin ## Development - **url**: https://dev-public-integrity.pantheonsite.io/ - **wordpress admin**: https://dev-public-integrity.pantheonsite.io/wp-admin/ - **username/password**: cpi / <PASSWORD> ## Staging - **url**: https://test-public-integrity.pantheonsite.io/ - **wordpress admin**: https://test-public-integrity.pantheonsite.io/wp-admin/ - **username/password**: cpi / <PASSWORD> ## Prerequisites 1. Install [Docker for Mac](https://www.docker.com/docker-mac) 1. Install [ups-dock](https://github.com/upstatement/ups-dock) 1. Ensure [NVM](https://github.com/creationix/nvm) and [NPM](https://yarnpkg.com/en/) are installed globally. 1. Ensure you are running > PHP 7.0 locally (this is needed for PHP linting and testing purposes) ## Installation 1. Run `nvm install` to ensure you're using the correct version of Node. If you are switching to projects with other versions of Node, we recommend using something like [Oh My Zsh](https://github.com/robbyrussell/oh-my-zsh) which will automatically run `nvm use` 1. Create a file called `.env` in this directory and populate it with configuration from the `CPI - Dotenv (Local)` file in 1Password 1. Run the install command: ``` ./bin/install.sh ``` 1. Install composer and npm packages ``` composer install npm install ``` Once completed, you should be able to access your WordPress installation via `ups.dock`. If you need to SSH into your container, from your project root run `docker-compose exec wordpress /bin/bash` ## Development Workflow 1. Run `nvm use` to ensure you're using the correct version of Node 1. Pull down changes and, if necessary, run `composer install` and `npm install` 1. Run `./bin/start.sh` to start the WordPress backend / static build server 1. Open the `Local` URL that appears below `[Browsersync] Access URLs:` in your browser (https://localhost:3000/) Quitting this process (`Ctrl-C`) will shut down the container. ## Database Synchronization ## wp-cli `docker-compose exec wordpress wp [command]` <file_sep>/src/Blocks/EmailSignUp/EmailSignUp.php <?php /** * Blocks Initializer * * Enqueue CSS/JS of all the blocks. */ namespace CPI\Blocks\EmailSignUp; use Timber\Timber; class EmailSignUp { /** * Constructor */ public function __construct() { add_action('acf/init', array($this,'createEmailSignUpBlock')); } /** * Uses ACF function to register custom blocks * * @return void */ public function createEmailSignUpBlock() { // check function exists if (function_exists('acf_register_block')) { // register RelatedArticles block acf_register_block( array( 'name' => 'emailSignUp', 'title' => __('Email Sign-up'), 'description' => __('A custom block for inserting a call to action with an email sign-up.'), 'render_callback' => array($this, 'renderEmailSignUpBlock'), 'category' => 'widgets', 'icon' => array('background' => '#ecf6f6', 'src' => 'email'), 'keywords' => array('email', 'sign', 'up'), 'mode' => 'edit' ) ); } } /** * Get the Related Articles text and related articles, * and then render corrosponding template * * @param array $block The block settings and attributes. * @param string $content The block content (empty content). * @param bool $is_preview True during AJAX preview. * * @return void */ public function renderEmailSignUpBlock($block, $content, $is_preview) { $templates = ['templates/components/article-email-signup.twig', 'templates/components/mailchimp-form.twig']; $context['email_signup_headline'] = get_field('email_signup_headline'); $context['email_signup_text'] = get_field('email_signup_text'); // ob_start(); if ($is_preview) { echo "Preview mode is not supported for related articles. Please change to Edit mode by clicking the pencil icon in the toolbar above."; } else { Timber::render($templates, $context); } } } <file_sep>/src/core.php <?php /** * Core setup, site hooks and filters. * * @package CPI\Core */ namespace CPI\Core; /** * Set up theme defaults and register supported WordPress features. * * @return void */ function setup() { $n = function ($function) { return __NAMESPACE__ . "\\$function"; }; add_action('after_setup_theme', $n('theme_setup')); add_action('wp_enqueue_scripts', $n('scripts')); add_action('wp_enqueue_scripts', $n('styles')); } /** * Sets up theme defaults and registers support for various WordPress features. * * @return void */ function themeSetup() { add_theme_support('post-thumbnails'); add_theme_support('automatic-feed-links'); add_theme_support('title-tag'); // This theme uses wp_nav_menu() in three locations. register_nav_menus( array( 'primary' => 'Primary Menu' ) ); } /** * Enqueue scripts for front-end. * * @return void */ function scripts() { wp_enqueue_script( 'app', CPI_THEME_URL . '/dist/app.js', [], null, true ); } /** * Enqueue styles for front-end. * * @return void */ function styles() { wp_enqueue_style( 'styles', CPI_THEME_URL . '/dist/css/app.css', [], trie ); } <file_sep>/page-jh-test.php <ul class="updated-posts"> <?php // Show recently modified posts $recently_updated_posts = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => 1000, 'orderby' => 'modified', 'no_found_rows' => true // speed up query when we don't need pagination ) ); ?><table><?php if ( $recently_updated_posts->have_posts() ) : while( $recently_updated_posts->have_posts() ) : $recently_updated_posts->the_post(); ?> <tr><td><a href="<?php the_permalink(); ?>" title="<?php esc_attr( get_the_title() ); ?>"><?php the_title(); ?></a></td> <td><?php echo get_the_date() ?></td> <td><?php echo get_the_modified_date(); ?></td> <td><?php echo get_the_modified_time(); ?></td> </tr> <?php endwhile; ?> <?php wp_reset_postdata(); ?> <?php endif; ?> </ul> <file_sep>/src/Blocks/StationID/StationID.php <?php /** * Blocks Initializer * * Enqueue CSS/JS of all the blocks. */ namespace CPI\Blocks\StationID; use Timber\Timber; class StationID { /** * Constructor */ public function __construct() { register_block_type( 'cpi/station-id', array( 'render_callback' => array($this,'renderStationId'), ) ); } /** * Get the Station ID text and render corrosponding template * * @param array $attributes Gutenberg attributes * @param string $content Gutenberg content * * @return string Rendered content */ public function renderStationId($attributes, $content) { $stationIdText = get_field('who_we_are', 'option'); $stationIdLink = get_field('about_us_page_link', 'option'); $stationIdPage = null; if (is_array($stationIdLink) && sizeof($stationIdLink) > 0) { $stationIdPage = Timber::get_post($stationIdLink[0]->ID); } ob_start(); Timber::render('templates/components/station-id.twig', ['stationIdText'=>$stationIdText,'stationIdPage'=>$stationIdPage]); return ob_get_clean(); } } <file_sep>/src/Blocks/Gallery/Gallery.php <?php /** * Blocks Initializer * * Enqueue CSS/JS of all the blocks. */ namespace CPI\Blocks\Gallery; use Timber\Timber; class Gallery { /** * Constructor */ public function __construct() { add_action('acf/init', array($this, 'createGalleryBlock')); } /** * Uses ACF function to register a custom blocks * * @return void */ public function createGalleryBlock() { // check function exists if (function_exists('acf_register_block')) { // register a testimonial block acf_register_block( array( 'name' => 'cpiGallery', 'title' => __('CPI Gallery'), 'description' => __('A custom gallery block.'), 'render_callback' => array($this, 'renderGalleryBlock'), 'category' => 'widgets', 'icon' => array('background' => '#ecf6f6', 'src' => 'images-alt2'), 'keywords' => array( 'gallery', 'images' ), 'mode' => 'edit' ) ); } } /** * Renders the custom gallery block in preview and front endDate * * @param array $block The block settings and attributes. * @param string $content The block content (emtpy string). * @param bool $is_preview True during AJAX preview. * * @return void */ public function renderGalleryBlock($block, $content, $is_preview) { $context['gallery_caption']= get_field('gallery_caption'); $context['images'] = array_map( function ($image) { return new \TimberImage($image['image']); }, get_field('images') ); if ($is_preview) { echo "Preview mode is not supported for galleries. Please change to Edit mode by clicking the pencil icon in the toolbar above."; } else { Timber::render('templates/components/gutenberg-gallery.twig', $context); } } } <file_sep>/single.php <?php /** * Front page * * @return void */ use CPI\Models\CPIPost; $context = Timber::get_context(); // Get post $post = new CPIPost(); $context['article'] = $post; if (!$post->validMicro()) { $context['article'] = $post; } else { wp_redirect($post->link); die(); } // Get CPIPost topic $context['term'] = $post->articleTopic(); // Get author(s) for CPIPost $context['article_authors'] = $post->articleAuthors(); // Set relatedPosts $relatedPosts = []; $relatedPostQuery = $post->recircPosts(); foreach ($relatedPostQuery as $relatedPost) { $relatedPosts[] = $relatedPost; } $context['relatedPosts'] = $relatedPosts; wp_reset_postdata(); // Render view. Timber::render('pages/article.twig', $context); <file_sep>/src/Blocks/Blocks.js import StationID from './StationID/station-id'; new StationID(); <file_sep>/src/Managers/PostsManager.php <?php /** * Bootstraps settings and configurations for post types and taxonomies. */ namespace CPI\Managers; class PostsManager { /** * Runs initialization tasks. * * @return void */ public function run() { } /** * Register post types in WordPress * * @return void */ // public function registerPostTypes() // { // Author post type // $authorLabels = ['name' => __('Authors'), // 'singular_name' => __('Author'), // 'add_new_item' => __('Add New Author')]; // register_post_type( // 'author', // ['labels' => $authorLabels, // 'public' => true, // 'has_archive' => true, // 'menu_position' => 5, // 'rewrite' => ['slug' => 'authors'], // 'supports' => ['editor', 'excerpt', 'title', 'thumbnail'], // 'taxonomies' => []] // ); // Press Release post type. // $pressReleaseLabels = ['name' => __('Press Release'), // 'singular_name' => __('Press Release'), // 'add_new_item' => __('Add New Press Release')]; // register_post_type( // 'pressrelease', // ['labels' => $pressReleaseLabels, // 'public' => true, // 'has_archive' => true, // 'menu_position' => 20, // 'rewrite' => ['slug' => 'press-releases'], // 'supports' => ['editor', 'excerpt', 'title', 'thumbnail'], // 'taxonomies' => []] // ); // } } <file_sep>/static/js/components/member-form.js import $ from 'jquery'; class MemberForm { constructor() { this.$dollarInput = $('.member-form input#dollar_amount'); this.$radioInputs = $('.member-form__radio'); this.$noteContainer = $('.member-form__radio-help'); this.init(); } init() { // Update on load and when radios or number input changes let that = this; that.updateHelpText(); this.$dollarInput.on('change keyup paste', function() { that.updateHelpText(); }); this.$radioInputs.change(function() { that.updateHelpText(); }); } updateHelpText() { let level = this.computeLevel(); let updated_text = level ? `<p>This donation will make you ${level} member.</p>` : '<p><strong>Donate $35 or more</strong> and receive special members-only updates, behind-the-scenes Q&A with journalists, and more.</p>'; this.$noteContainer.html(updated_text); } computeLevel() { let dollarAmount = parseInt($('.member-form input#dollar_amount').val()); let frequency = $('.member-form__radio:checked').val(); let multiplier = frequency == 'monthly' ? 12 : 1; let annualAmount = dollarAmount * multiplier; let level = annualAmount >= 1e3 ? 'an <strong>Investigator</strong>' : annualAmount >= 500 ? 'a <strong>Truth Teller</strong>' : annualAmount >= 35 ? 'a <strong>Watchdog</strong>' : null; return level; } } export default MemberForm; <file_sep>/src/Repositories/RepositoryFactory.php <?php /** * Basic factory for generating repository objects. */ namespace CPI\Repositories; class RepositoryFactory { const POST_TYPE = 'post_type'; const TERM = 'term'; /** * Returns correct repository * * @param mixed $which - Constant used to determine Repository * * @return \Repository */ public static function get($which) { switch ($which) { case self::POST_TYPE: return new PostTypeRepository(); case self::TERM: return new TermRepository(); } } } <file_sep>/src/Models/CPIPartner.php <?php /** * Functionality for Partner Terms */ namespace CPI\Models; use Timber\Timber; use Timber\Post; use Timber\Term; use Timber\Image; use CPI\Repositories\RepositoryFactory; use CPI\Models\CPIPost; class CPIPartner extends Term { /** * Constructs instance of CPIPartner * * @param mixed $pid - defaults to null * * @return \CPIPartner */ public function __construct($pid = null) { parent::__construct($pid); } /** * Returns Partner Icon as TimberImage * * @return \Image */ public function getIcon() { $termRepo = RepositoryFactory::get(RepositoryFactory::TERM); return $termRepo->getImage($this); } } <file_sep>/page-search.php <?php /** * Template Name: Search */ use CPI\Repositories\PostTypeRepository; use CPI\Models\CPIPost; $context = Timber::get_context(); $context['post'] = Timber::get_post(); // Get Home Features Posts $homeID = get_page_by_title( 'Home' )->ID; $homeFeatures = get_field('home_features', $homeID); // limit to 4 $homeFeatures = array_slice($homeFeatures, 4); if (is_array($homeFeatures) && !empty($homeFeatures)) { $context['homeFeatures'] = array_map( function ($post) { return new CPIPost($post); }, $homeFeatures ); } Timber::render(['pages/search.twig'], $context); <file_sep>/src/Services/Redirects.php <?php namespace CPI\Services; use WP_Query; use WP_Post; use WP_Term; use Timber\PostQuery; use CPI\Models\CPIPost; use CPI\Services\WordPressService; class Redirects { const LEGACY_TOPIC_URIS = array( '/politics', '/national-security', '/business', '/immigration', '/environment', '/accountability', '/health', '/inside-publici' ); const LEGACY_NESTED_TOPIC_URIS = array( "/accountability-education", "/after-the-meltdown", "/alex-finley-analysis", "/betting-on-justice", "/big-oil-bad-air", "/blue-dogs", "/breathless-and-burdened", "/broadband", "/broken-government", "/buying-of-the-president", "/buying-of-the-president-2000", "/buying-of-the-president-2004", "/buying-the-senate-2014", "/carbon-wars", "/climate-change-lobby", "/coal-ash", "/cracking-the-codes", "/criminalizing-kids", "/danger-in-the-air", "/dangers-in-the-dust", "/debt-deception", "/democracy-ink", "/divine-intervention", "/dollars-and-dentists", "/education", "/environmental-justice-denied", "/exposed-decades-of-denial-on-poisons-environment", "/finance", "/fueling-fears", "/gun-wars", "/immigration-decoded", "/inside-publici", "/iraq-the-war-card", "/justice-obscured", "/juvenile-justice", "/local-voters-distant-donors-state-politics", "/looting-the-seas", "/looting-the-seas-ii", "/looting-the-seas-iii", "/manipulating-medicare", "/medicaid-under-the-influence-state-politics", "/medicare-advantage-money-grab", "/military-children-left-behind", "/military-children-left-behind-education", "/model-workplaces", "/murtha-method", "/mystery-in-the-fields", "/one-nation-under-debt", "/party-lines", "/pentagon-travel", "/perils-of-the-new-pesticides", "/poisoned-places", "/politics-of-poison", "/primary-source", "/profiles-in-patronage", "/profiting-from-prisoners", "/raw-deal", "/renegade-refineries", "/scared-red", "/science-for-sale", "/sexual-assault-on-campus", "/sexual-assault-on-campus-education", "/shadow-government", "/silent-partners", "/skin-and-bone", "/source-check", "/state-integrity-2012", "/state-integrity-2015", "/state-integrity-investigation", "/states-of-disclosure", "/stimulating-hypocrisy", "/takings-initiatives-accountability-project", "/the-gift-economy", "/the-great-mortgage-cover-up", "/the-misinformation-industry", "/the-panama-papers", "/the-transportation-lobby", "/the-truth-left-behind", "/the-water-barons", "/tobacco", "/toxic-clout", "/unequal-risk", "/up-in-arms", "/weed-rush", "/weekly-watchdog", "/well-connected", "/wendell-potter-commentary", "/who-bankrolls-congress", "/whos-behind-the-financial-meltdown", "/whos-calling-the-shots-in-state-politics", "/workers-rights" ); const MICROSITE_TOPICS = array( // "/abandoned-in-america", // "/blowout", "/disclosure", "/the-trench", // "/united-states-of-petroleum", // "/nuclear-negligence", "/oil-education" ); const MICROSITES = array( "https://apps.publicintegrity.org/abandoned-in-america/yazoo-education-history/" => "/race-relations-in-yazoo-city-mississippi-a-brief-history", "https://apps.publicintegrity.org/abandoned-in-america/forgotten-and-failing/" => "/forgotten-and-failing-black-students-languish-as-a-mississippi-town-reckons-with-its-painful-past", "https://apps.publicintegrity.org/abandoned-in-america/no-place-to-call-home/" => "/st-louis-poorest-residents-ask-why-cant-our-houses-be-homes", "https://apps.publicintegrity.org/abandoned-in-america/train-off-track/" => "/high-speed-rail-could-transform-fresno-will-trump-get-on-the-train", "https://apps.publicintegrity.org/abandoned-in-america/ballot-box-barriers/" => "/what-stands-in-the-way-of-native-american-voters", "https://apps.publicintegrity.org/abandoned-in-america/disastrous-recovery/" => "/hope-to-hopelessness-will-government-step-up-after-second-storm", "https://apps.publicintegrity.org/abandoned-in-america/walled-off/" => "/how-trumps-wall-could-kill-a-texas-border-town", "https://apps.publicintegrity.org/abandoned-in-america/border-closing-history/" => "/the-closing-of-an-international-border-a-brief-history", "https://apps.publicintegrity.org/blowout/us-energy-dominance/" => "/how-washington-unleashed-fossil-fuel-exports-and-sold-out-on-climate", "https://apps.publicintegrity.org/blowout/" => "/as-oil-and-gas-exports-surge-west-texas-becomes-the-worlds-extraction-colony", "https://apps.publicintegrity.org/tax-breaks-the-favored-few/" => "/congress-snuck-dozens-of-tax-breaks-into-the-budget-deal-heres-where-they-went", "https://apps.publicintegrity.org/the-trench/" => "/death-by-suffocation-under-a-pile-of-dirt-jim-spencers-on-the-job-death-shows-the-weakness-of-americas-worker-safety-laws", "https://apps.publicintegrity.org/united-states-of-petroleum/" => "/the-united-states-of-petroleum-governments-secret-alliance-with-big-oil", "https://apps.publicintegrity.org/disclosure/statehouses/" => "/find-your-state-legislators-financial-interests", "https://apps.publicintegrity.org/nuclear-negligence/shipping-violations/" => "/nuclear-weapons-contractors-repeatedly-violate-shipping-rules-for-dangerous-materials", "https://apps.publicintegrity.org/nuclear-negligence/repeated-warnings/" => "/repeated-radiation-warnings-go-unheeded-at-sensitive-idaho-nuclear-plant", "https://apps.publicintegrity.org/nuclear-negligence/inhaled-uranium/" => "/more-than-30-nuclear-experts-inhale-uranium-after-radiation-alarms-at-a-weapons-site-are-switched-off", "https://apps.publicintegrity.org/nuclear-negligence/light-penalties/" => "/light-penalties-and-lax-oversight-encourage-weak-safety-culture-at-nuclear-weapons-labs", "https://apps.publicintegrity.org/nuclear-negligence/delayed-warheads/" => "/safety-problems-at-a-los-alamos-laboratory-delay-u-s-nuclear-warhead-testing-and-production", "https://apps.publicintegrity.org/nuclear-negligence/near-disaster/" => "/a-near-disaster-at-a-federal-nuclear-weapons-laboratory-takes-a-hidden-toll-on-americas-arsenal", "https://apps.publicintegrity.org/oil-education/" => "/oils-pipeline-to-americas-schools", "/abandoned-in-america/yazoo-education-history", "/abandoned-in-america/forgotten-and-failing", "/abandoned-in-america/no-place-to-call-home", "/abandoned-in-america/train-off-track", "/abandoned-in-america/ballot-box-barriers", "/abandoned-in-america/disastrous-recovery", "/abandoned-in-america/walled-off", "/abandoned-in-america/border-closing-history", "/blowout/us-energy-dominance", "/disclosure/statehouses", "/tax-breaks-the-favored-few", "/united-states-of-petroleum/venue-of-last-resort", "/united-states-of-petroleum/fueling-dissent", "/united-states-of-petroleum/century-of-influence", "/disclosure/statehouses", "/nuclear-negligence/shipping-violations", "/nuclear-negligence/repeated-warnings", "/nuclear-negligence/inhaled-uranium", "/nuclear-negligence/light-penalties", "/nuclear-negligence/delayed-warheads", "/nuclear-negligence/near-disaster", ); /** * Add filter for redirect * * @return void */ public function __construct() { add_filter('template_redirect', array($this, 'redirect_override')); } /** * Setup redirects * * @return void */ public function redirect_override() { global $wp_query; $requestURI = $_SERVER['REQUEST_URI']; // Split requestURI into 2 parts and remove trailing `/` // i.e. `/politics/broken-government` becomes `array( '/politics', '/broken-government' );` $pattern = '/(\/[a-z \-]+)/m'; $uriArray = preg_split($pattern, $requestURI, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); // Set uriCheck variable if (count($uriArray) >= 2 && $uriArray[1] !== "/") { $uriCheck = implode('', $uriArray); } elseif (count($uriArray) < 2 || $uriArray[1] === "/") { $uriCheck = $uriArray[0]; } // Force redirects for legacy microsite archives // Handle microsites (as of Oct. 31st content import) // -- Handle microsite topics $microTopic = array_search($uriArray[0], self::MICROSITE_TOPICS, true); if (!$microTopic && count($uriArray) >= 2) { $microTopic = array_search($uriArray[1], self::MICROSITE_TOPICS, true); } if (is_int($microTopic)) { $this->triggerRedirect(self::MICROSITE_TOPICS[$microTopic], true); } // -- Set microKey variable $microKey = array_search($uriArray[0], self::MICROSITES, true); if (!$microKey && count($uriArray) >= 2) { $microKey = array_search($uriArray[1], self::MICROSITES, true); } // -- Handle legacy mircrosite paths if (is_int($microKey)) { $this->triggerRedirect($uriCheck, true); // -- Handle imported microsite slugs, pass in full URL as $microKey } elseif (is_string($microKey)) { $this->triggerRedirect($uriCheck, true, $microKey); } if ($wp_query->is_404) { // Temp fix for '/topics' if ($uriArray[0] === '/topics' && count($uriArray) === 1) { $this->triggerRedirect('/'); } // ADDITIONAL CHECKS FOR WEIRD LEGACY SUB-TOPIC PATH STRUCTURES // Accountability if (array_search('/hate-in-america', $uriArray, true) !== false) { $this->triggerRedirect('/topics/accountability/hate-in-america'); } else if (array_search('/secrecy-sale', $uriArray, true) !== false) { $this->triggerRedirect('/topics/accountability/secrecy-for-sale'); } else if (array_search('/panama-papers', $uriArray, true) !== false) { $this->triggerRedirect('/topics/accountability/the-panama-papers'); } else if (array_search('/truth-left-behind', $uriArray, true) !== false) { $this->triggerRedirect('/topics/accountability/the-truth-left-behind'); // Business } else if (array_search('/after-meltdown', $uriArray, true) !== false) { $this->triggerRedirect('/topics/business/after-the-meltdown'); } else if (array_search('/betting-justice', $uriArray, true) !== false) { $this->triggerRedirect('/topics/business/betting-on-justice'); } else if (array_search('/profiting-prisoners', $uriArray, true) !== false) { $this->triggerRedirect('/topics/business/profiting-from-prisoners'); } else if (array_search('/great-mortgage-cover', $uriArray, true) !== false) { $this->triggerRedirect('/topics/business/the-great-mortgage-cover-up'); } else if (array_search('/whos-behind-financial-meltdown', $uriArray, true) !== false) { $this->triggerRedirect('/topics/business/whos-behind-the-financial-meltdown'); // Education } else if (array_search('/sexual-assault-campus', $uriArray, true) !== false) { $this->triggerRedirect('/topics/business/sexual-assault-on-campus'); // Environment } else if (array_search('/danger-air', $uriArray, true) !== false) { $this->triggerRedirect('/topics/environment/danger-in-the-air'); } else if (array_search('/politics-oil', $uriArray, true) !== false) { $this->triggerRedirect('/topics/environment/energy/politics-of-oil'); } else if (array_search('/exposed-decades-of-denial-on-poisons-environment', $uriArray, true) !== false) { $this->triggerRedirect('/topics/environment/exposed-decades-of-denial-on-poisons-environment'); } else if (array_search('/looting-seas', $uriArray, true) !== false) { $this->triggerRedirect('/topics/environment/natural-resources/looting-the-seas'); } else if (array_search('/looting-seas-i', $uriArray, true) !== false) { $this->triggerRedirect('/topics/environment/natural-resources/looting-the-seas-i'); } else if (array_search('/looting-seas-ii', $uriArray, true) !== false) { $this->triggerRedirect('/topics/environment/natural-resources/looting-the-seas-ii'); } else if (array_search('/looting-seas-iii', $uriArray, true) !== false) { $this->triggerRedirect('/topics/environment/natural-resources/looting-the-seas-iii'); } else if (array_search('/water-barons', $uriArray, true) !== false) { $this->triggerRedirect('/topics/environment/natural-resources/the-water-barons'); } else if (array_search('/politics-poison', $uriArray, true) !== false) { $this->triggerRedirect('/topics/environment/politics-of-poison'); } else if (array_search('/disaster-gulf', $uriArray, true) !== false) { $this->triggerRedirect('/topics/environment/pollution/disaster-in-the-gulf'); } else if (array_search('/science-sale', $uriArray, true) !== false) { $this->triggerRedirect('/topics/environment/science-for-sale'); // Federal Politics } else if (array_search('/buying-president', $uriArray, true) !== false) { $this->triggerRedirect('/topics/federal-politics/buying-of-the-president'); } else if (array_search('/buying-president-2000', $uriArray, true) !== false) { $this->triggerRedirect('/topics/federal-politics/buying-of-the-president-2000'); } else if (array_search('/buying-president-2004', $uriArray, true) !== false) { $this->triggerRedirect('/topics/federal-politics/buying-of-the-president-2004'); } else if (array_search('/buying-senate-2014', $uriArray, true) !== false) { $this->triggerRedirect('/topics/federal-politics/buying-the-senate-2014'); } else if (array_search('/iraq-war-card', $uriArray, true) !== false) { $this->triggerRedirect('/topics/federal-politics/iraq-the-war-card'); } else if (array_search('/profiles-patronage', $uriArray, true) !== false) { $this->triggerRedirect('/topics/federal-politics/profiles-in-patronage'); } else if (array_search('/chairmen', $uriArray, true) !== false) { $this->triggerRedirect('/topics/federal-politics/the-chairmen'); } else if (array_search('/misinformation-industry', $uriArray, true) !== false) { $this->triggerRedirect('/topics/federal-politics/the-misinformation-industry'); } else if (array_search('/transportation-lobby', $uriArray, true) !== false) { $this->triggerRedirect('/topics/federal-politics/the-transportation-lobby'); // Health } else if (array_search('/cracking-codes', $uriArray, true) !== false) { $this->triggerRedirect('/topics/health/cracking-the-codes'); } else if (array_search('/dangers-dust', $uriArray, true) !== false) { $this->triggerRedirect('/topics/health/dangers-in-the-dust'); } else if (array_search('/island-widows', $uriArray, true) !== false) { $this->triggerRedirect('/topics/health/island-of-the-widows'); } else if (array_search('/mystery-fields', $uriArray, true) !== false) { $this->triggerRedirect('/topics/health/mystery-in-the-fields'); } else if (array_search('/smoke-screen-part-ii', $uriArray, true) !== false) { $this->triggerRedirect('/topics/health/tobacco/smoke-screen-2'); // National Security } else if (array_search('/homeland-security-boom-and-bust', $uriArray, true) !== false) { $this->triggerRedirect('/topics/national-security/homeland-security/homeland-security-boom-bust'); } else if (array_search('/war-error', $uriArray, true) !== false) { $this->triggerRedirect('/topics/national-security/intelligence/war-on-error'); } else if (array_search('/gift-economy', $uriArray, true) !== false) { $this->triggerRedirect('/topics/national-security/the-gift-economy'); } else if (array_search('/outsourcing-pentagon', $uriArray, true) !== false) { $this->triggerRedirect('/topics/national-security/military/outsourcing-the-pentagon'); } else if (array_search('/arms', $uriArray, true) !== false) { $this->triggerRedirect('/topics/national-security/up-in-arms'); } else if (array_search('/windfalls-war', $uriArray, true) !== false) { $this->triggerRedirect('/topics/national-security/windfalls-of-war'); // State Politics } else if (array_search('/medicaid-under-influence', $uriArray, true) !== false) { $this->triggerRedirect('/topics/state-politics/medicaid-under-the-influence'); } else if (array_search('/who-s-calling-shots-state-politics', $uriArray, true) !== false) { $this->triggerRedirect('/topics/state-politics/whos-calling-the-shots-in-state-politics'); } // Set URI to be used in conditionals if (count($uriArray) >= 2 && $uriArray[1] !== "/") { // $uriCheck = implode('', $uriArray); $mainTopic = array_search($uriArray[0], self::LEGACY_TOPIC_URIS, true); $nestedTopic = array_search($uriArray[1], self::LEGACY_NESTED_TOPIC_URIS, true); $metaVal = array($uriArray[0], $uriArray[1]); } elseif (count($uriArray) < 2 || $uriArray[1] === "/") { // $uriCheck = $uriArray[0]; $mainTopic = array_search($uriArray[0], self::LEGACY_TOPIC_URIS, true); // Change slug to singular words for query $metaVal = preg_replace(array('/(\/)/', '/(\-)/'), array('', ' '), $uriArray[0]); } // Accounts for `/2018/10/18/55544` from legacy site, which prepends post-title slug $numberPath = preg_match('/(\/\d{4}\/\d{2}\/\d{2}\/\d+[^\/])/', $uriArray[0], $matches); // ONLY handle this logic for paths with 2 or less parts (i.e. '/go-here' or '/go-here/and-there') if (count($uriArray) <= 2) { // Handle special cases: State Politics, Federal Politics, Education, Workers Rights if ($uriCheck === '/politics/state-politics') { $this->triggerRedirect('/topics/state-politics'); } elseif ($uriCheck === '/politics/federal-politics' || $uriCheck === '/politics') { $this->triggerRedirect('/topics/federal-politics'); } elseif ($uriCheck === '/accountability/education') { $this->triggerRedirect('/topics/education'); } elseif ($uriCheck === '/environment/workers-rights') { $this->triggerRedirect('/topics/workers-rights'); // Handle other topic URIs // -- Search legacy main topics } elseif ($mainTopic !== false) { if (count($uriArray) < 2 || $uriCheck !== "/") { $this->triggerRedirect('/topics' . $requestURI); // -- Search legacy nested topics } elseif (count($uriArray) >= 2 && $nestedTopic !== false) { $this->triggerRedirect('/topics' . $uriArray[1]); } } } // echo "<pre style='font-family: monospace; font-size: 12px'>"; // var_dump($mainTopic, $nestedTopic, $numberPath, $matches); // echo "</pre>"; // die(); // Individual Post redirect only with valid legacy paths if ($mainTopic || ($mainTopic && $nestedTopic) || !empty($numberPath)) { // Match post title slug if request URI contains legacy date/ID path if ($numberPath === 1) { $args = array( 'post_status' => array('published'), 'order' => 'DESC', 'meta_key' => 'legacy_url', 'meta_value' => $matches[0], 'meta_compare' => 'RLIKE' ); // Set query_args based on metaVal } else if (is_array($metaVal)) { $args = array( 'post_status' => array('published'), 'order' => 'DESC', 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'legacy_url', 'value' => $metaVal, 'compare' => 'LIKE' ), array( 'key' => 'microsite_url', 'value' => $metaVal, 'compare' => 'LIKE' ) ) ); } else { $args = array( 'post_status' => array('published'), 'order' => 'DESC', 'orderby' => 'relevance', 's' => $metaVal, 'meta_key' => 'microsite_url', 'meta_compare' => 'EXISTS' ); } // CPIPost query using above args $queryObj = new PostQuery($args, CPIPost::class); if (key_exists(0, $queryObj)) { $post = $queryObj[0]; if ($post instanceof CPIPost) { $redirectURI = $post->path; $legacyURL = $post->get_field('legacy_url'); $microURL = $post->get_field('microsite_url'); // Prioritize redirect with microsite URL if (!empty($microURL)) { $this->triggerRedirect($requestURI, true, $microURL); } elseif (!empty($legacyURL)) { // Check if root in legacyURL matches microsite pattern $microRoot = strpos($legacyURL, '//apps.publicintegrity.org'); // Redirect based on root if ($microRoot !== false) { $this->triggerRedirect($redirectURI, true, $legacyURL); // Redirect to new single view if request URI matches legacy URI } else { $legacyURI = preg_replace('/(https:\/\/\S+\.\S+\.org)/i', '', $legacyURL); $legacyURIArray = explode("/", $legacyURI); $pathArr = explode("/", $_SERVER['REQUEST_URI']); // Try to match based on legacy post ID if ((sizeof($legacyURIArray) == 6) && (sizeof($pathArr) == 6) ) { $requestedID = $pathArr[4]; $legacyId = $legacyURIArray[4]; if ($requestedID === $legacyId) { $this->triggerRedirect($redirectURI); } } $this->urlMatchPath($legacyURI) ? $this->triggerRedirect($redirectURI) : ''; } } } } } // end Individual Post with valid path // before we fail, try redirect by just post id if (count($matches) > 0) { $urlArray = explode("/", $matches[0]); $legacyId = $urlArray[4]; $legacyIdInt = intval($legacyId); if (is_int($legacyIdInt) && ($legacyIdInt > 0) ) { $args = array( 'post_status' => array('published'), 'order' => 'DESC', 'meta_key' => 'legacy_url', 'meta_value' => $legacyId, 'meta_compare' => 'RLIKE' ); $queryObj = new PostQuery($args, CPIPost::class); if (key_exists(0, $queryObj)) { $post = $queryObj[0]; $redirectURI = $post->path; $this->triggerRedirect($redirectURI); } } } WordPressService::abort_request(404); } } /** * Check for match based on PHP_URL_QUERY * * @param string $string String to match against * * @return boolean */ private function urlMatch($string) { parse_str(parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY), $output); $contentId = $output['id']; return $contentId == $string; } /** * Check for match based on $_SERVER['REQUEST_URI'] * * @param string $string String to match against REQUEST_URI * * @return boolean */ private function urlMatchPath($string) { $path = $_SERVER['REQUEST_URI']; return $path === $string; } /** * Triggers redirect * * @param string $uri URI to append to CPI_DOMAIN * @param bool $microsite Indicate if redirect is for microsites * @param string $microURL Control for microsite slugs in WP from import * * @return void */ private function triggerRedirect($uri, bool $microsite = false, string $microURL = '') { // TODO: Only redirect if the ID is an exact match if (!empty($microURL) && $microsite) { header('HTTP/1.0 200'); header("Location: $microURL"); die(); } else if ($microsite) { header('HTTP/1.0 200'); header('Location: https://apps.publicintegrity.org' . $uri); die(); } else { global $wp_query; status_header(200); $wp_query->is_404 = false; header('HTTP/1.0 301 Moved Permanently'); header('Location: ' . CPI_DOMAIN . $uri); die(); } } } <file_sep>/cypress/integration/homepage_spec.js describe('The Home Page', function() { it('successfully loads', function() { cy.visit('/', { auth: { username: 'cpi', password: '<PASSWORD>', }, }); }); it('opens hamburger menu', function() { cy.get('.js-nav-open').click(); cy.get('.nav--active').should('be.visible'); }); }); <file_sep>/taxonomy-author.php <?php /** * The template for displaying Author pages. * * Used to display archive-type pages if nothing more specific matches a query. * For example, puts together date-based pages if no date.php file exists. * * Learn more: http://codex.wordpress.org/Template_Hierarchy */ use Timber\Post; use CPI\Models\CPIPost; use CPI\Models\CPIAuthor; $context = Timber::get_context(); $query_args = null; $per_page = 8; if ( is_tax('author') ) { $term = new CPIAuthor(); $query_args = array( 'posts_per_page' => $per_page, 'post_status' => 'publish', 'authors' => $term->slug, 'paged' => $paged ); // TODO: refactor in line with CPITopic changes if ($term->featured_articles) { // Set array of IDs of Featured Posts for query arguments $featured_posts_ids = []; // Check for array in case featuredPosts is single object if (is_array($term->featured_articles)) { foreach ($term->featured_articles as $post) { $featured_posts_ids[] = $post->ID; } } else { $featured_posts_ids[] = $term->featured_articles->ID; } if (!empty($featured_posts_ids)) { // Arguments for Featured Posts query $featured_query_args = array( 'posts_per_page' => $per_page, 'post_status' => 'publish', 'cat' => $term->id, 'paged' => $paged, 'post__in' => $featured_posts_ids ); // Arguments for Posts query that excludes Featured Posts $query_args['post__not_in'] = $featured_posts_ids; } } $context['author'] = $term; } // Make Post queries based on whether Author term has Featured Posts if (!empty($featured_query_args)) { // TODO: move featuredPosts method to TermRepo $context['featured_posts'] = new Timber\PostQuery($featured_query_args, CPIPost::class); } $context['posts'] = $term->getArticles($query_args, CPIPost::class); // Render view Timber::render( 'pages/author.twig', $context ); <file_sep>/documentation/cpi-documentation.md # Introduction This document serves as a reference for administrating the WordPress CMS backend of the Center for Public Integrity website. ## Useful URLs | Link | Description | | -------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | | [Publicintegrity.org](https://publicintegrity.org) ([Login](https://publicintegrity.org/wp-admin/) ) | Live server: the live, public website. | | [Pantheon Test Site](https://test-public-integrity.pantheonsite.io) ([Login](https://test-public-integrity.pantheonsite.io/wp-admin/)) | Test server: updates when deployment is run via Pantheon | | [Pantheon Dev Site](https://dev-public-integrity.pantheonsite.io) ([Login](https://dev-public-integrity.pantheonsite.io/wp-admin/)) | Dev server: updates automatically when code is merged into the `develop` branch | **See also:** [How to create an article](https://docs.google.com/document/d/1XOi-pPW4-XNWzr3CHNXAoovEDe9Me16MCi0XXoaDR8Q/edit), a guide (in Google Docs) focused on article creation for those new to the CMS. # Media Guidelines ## Block Alignments Many Gutenberg blocks — including images, videos, embeds, and tables — offer a set of alignment buttons. We've implemented layout styles for these selectively as follows: ![Alignment buttons](images/alignments-no-shadow.png) | Alignment Button | Meaning | | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `(No Alignment)` | The default alignment, with none of the buttons selected: images and video break out of the text column into the right margin, with their captions hanging below. Twitter, Facebook, Instagram, and DocCloud embeds are exempted and default to their "natural" width of 500px. | | `Align Center` | Constrains the block to the text column on wide screens. Useful if you don't have a high-resolution image or simply to prevent the image from taking up too much space. | | `Align Left & Right` | On wider screens the block is inset (floated) in the text either left or right, taking up 50% of the column. The caption goes below. | | `Full Width` | Displays the block edge-to-edge of the browser. Should be reserved for very special cases, and only once or twice in an article. Note that full-width blocks will run over the sidebar content on wide screens. ⚠️ **Note:** for Full Width images, it's best to crop your upload to a wide aspect ration (at least 16:9) to keep the image from getting too tall on wide screens. | ## Preparing Images Because the CMS handles image sizing, cropping, and optimization (and outputs images scaled for the user's browser), you should feel free to upload large images. For more details, see the table below. | Field | Prep before upload | Notes | | ------------------------------------ | -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Article Featured Image | Size to ~2500 px wide | This image gets used in many contexts, often cropped to a square or circle. If the **Topper Style** field is set to "Full-Width", the topper uses a 2:1 (very wide) crop. | | Article content images | Size to ~2500 px wide | If your only file size is less than 700 px wide, use **Align Left/Right** or **Align Center**. <br /> Images used with a **Full Width** treatment should be cropped to 16:9. wider | | Home: Data Point Illustration | Upload as 900 px square | Cropped to a square/circle on output | | Home: Impact Images | (None) | Cropped to 350 px wide by 500 px tall on output | | Home: Spotlight Image | Convert to grayscale | Cropped variously on output depending on browser | | Home: About Us Image | Convert to grayscale | Cropped variously on output depending on browser | | Home: Partner Logos | Size to 600 px by 300 px PNG or SVG, with the logo centered on white | Outputs as uploaded | | Authors: Photos | Size to 500 px square | Cropped to a square/circle on output | | Partners: Icons | Size to 80 px square PNG | Create the logo as white-on-black circle | | Site Settings: Support Us Image | Convert to grayscale | Cropped variously on output depending on browser | | Site Settings: Big Newsletter Signup | Convert to grayscale | Cropped variously on output depending on browser | | About Page: Intro Image | (None) | Cropped to 800px wide by 600 px tall on output | | Support Page: Support Summary Image | Convert to grayscale | Cropped to 800px wide by 600 px tall on output | | Topics: Main Topic Illustrations | Size to 900 px square | Cropped to a square on output | # Home Page To edit and curate the content on the home page, click **Pages** in the Wordpress sidebar and then click into the **Home Page** entry. Each primary component gets its own tab here. ⚠️ **Note:** The Newsletter Signup and Support Us modules aren't specific to the home page — their fields are under the [Site Settings](#site-settings) tab in Wordpress. ## Topper ![Home Topper](images/home-topper.png) The topper is primarily for CPI "data points" — facts and figures that showcase CPI's relevance and effectiveness in investigative reporting. Use the fields to add your headline text and attach an illustration graphic, sized to ~1200px square. You can also optionally specify a Wordpress page (like About Us or Support): this wraps the headline and graphic in a link and adds a small text link below the dek as well. Occasionally you may want to use this space to showcase an important article. Change the radio button to Featured Article and find the article in the picker. The templates will pull in the article's title, subtitle, and image, along with a "Read" link. ## Features Carousel ![Features Carousel](images/home-features.png) These article teases appear in a horizontal carousel just below the topper with their images cropped to a circle. Choose four to eight articles and drag and drop them to reorder. ## Impact Pieces ![Our Impact](images/home-impact.png) This section lets you showcase _results_ from CPI's work, whether recent or not. Size the illustration graphics vertically, to 350px x 500px. This is a repeater field, so you can add and order 1 to 3 items (the templates will alternate the text/image layout automatically). ## Editors’ Roundup ![Home Roundup](images/home-roundup.png) This module appears further down the home page: Select 4 or 6 articles (for balanced columns) to appear in a centered grid. This module is especially useful for resurfacing older articles that have become relevant again. Remove all roundup articles to disable the entire module. ## Spotlight ![Home Spotlight](images/home-spotlight.png) The optional spotlight area lets you use a white-on-dark-blue block to showcase a link to an article or a custom URL. Convert your image to grayscale before uploading — the image will be tinted/faded in the background automatically. Leave the Spotlight Headline blank to disable the entire module. ## Partners ![Home Partners](images/home-partners.png) Add your partners text and logos here. Partner logos should be centered on a 600p by 300px artboard. Remove all the logos to disable the entire module. ## About Us ![Home about us](images/home-about-us.png) This "Who We Are" module is useful if the topper is set to feature an article instead of a data point. As with the Spotlight image, convert your image to grayscale before uploading — the image will be tinted/faded in the background automatically. Leave the About Us Headline blank to disable the entire module. ## Welcome Message ![Home Welcome](images/home-welcome.png) This field is intended only for a short period after launch. Text here will show up at the top of the home page in large type on a beige background. Leave the field blank to remove the message from the site. # Articles ## Legacy Articles Articles imported from the previous version of the site have a few differences than articles you'll be creating from scratch: First, in order to catch duplicate records and other issues, legacy articles have been given several Wordpress tags automatically: | Tag | Meaning | | ----------------- | ---------------------------------------------------------------------------------- | | `Legacy` | Applied to every imported article | | `Title ok` | Title is less than 75 characters and article title matches archive view title | | `Oversized title` | Title is greater than 75 characters and both scraped titles _may or may not_ match | | `Content ok` | Scraped article body is greater than or equal to 1200 characters | | `Needs checking` | Title less than 75 characters and both scraped titles _don't_ match | | `Not an Article` | Scraped article body is less than 1200 characters | ⚠️ **Note:** While tags in general are not displayed publicly, the article view checks for the `Legacy` tag when building article chapters — if tagged as legacy, chapters are built from `Heading 4`s instead of the usual `Heading 2`s. This means that if you "rebuild" a legacy article with `Heading 2`s and want to retain chaptering, you must remove the `Legacy` tag. ![Convert to Blocks](images/convert-to-blocks.png) Second, legacy articles use Wordpress’s “Classic Editor,” which is a single WYSIWYG field without Gutenberg's concept of blocks. Wordpress offers a **Convert to Blocks** action in the block menu — this feature works but may produce inconsistent or unexpected results. For instance, pull quotes may be rendered as block quotes and captions will need to be moved back into their associated image block. ## Creating Articles Gutenberg is Wordpress's new content editing interface: it treats each component of an article — every paragraph, heading, image and caption, etc. — as a discrete block that can be (a) edited with a predefined set of fields and formatting buttons and (b) dragged and dropped up and down in the article's content. Be sure to check out the keyboard shortcuts (get an overview by typing `^` `⌥` `H`). As you create and edit blocks, the right-hand inspector pane updates to show additional controls. You can click **Document** to see article-level controls and then back to **Block** to see block-level controls. ## Article Content ### Titles ![Article title and slug](images/article-title-slug.png) Choose **Posts › Add New** from the Wordpress sidebar to create a new article. Type or paste your title where you see `Add title`. _Aim for article titles below 75 characters_. ⚠️ **Note:** When you click the **Save Draft** or **Publish** buttons, Wordpress automatically generates a "slug" and permalink URL from your article title. You can review or change this by mousing over the title and clicking the **Edit** button that appears. ### Basic Text ![Editing a paragraph in Gutenberg](images/paragraph.png) Below the article title is the primary Gutenberg content interface. The _paragraph_ is the default block in Gutenberg, and it contains buttons to bold, italicize, add hyperlinks, etc. Some tips for base text styles: - Links, bold, and italics will be preserved when pasting in from Word or other rich text environments like Google Docs. - We've set up pre-built heading styles, so they should be applied consistently. Apply `Heading 2` through `Heading 4` to reflect the document outline; in many cases a few `Heading 2`s will be all that is required. - To ensure site-wide consistency, avoid ad-hoc formatting that affects text-alignment, color, or text size. ⚠️ **Note:** The sidebar will automatically include “chapter” jump-links and a progress meter built from your `Heading 2` sub-headings. The exception is legacy articles (imported from the previous site and tagged in Wordpress as `Legacy`) — the jump-links for these are built from `Heading 4`s. ### Images Insert an image using Gutenberg's image block: you can then upload your image file, add or edit the caption, and then optionally set alignment using the alignment buttons. Vertical (portrait) images are best set to `Align Left` or `Align Right`. ### Gallery Block ![Gallery](images/galleries.png) Galleries are useful when you have more than three images and want to create a slideshow overlay with optional captions. Choose **CPI Gallery** via the block picker, write a caption to describe the gallery as a whole in the caption field, then upload or choose your images. As you're selecting your images via the Media Gallery, you can edit the `caption` field for each image: this is the caption that appears in the slideshow overlay only. Once published, galleries are automatically displayed as a cluster of the _first three images_ in the gallery (all cropped to a square), followed by the gallery caption and a "Launch Gallery" link. The rest of the images are only displayed in the slideshow overlay. You can have multiple galleries in an article, but it's best for them to be separated by text for visual clarity. ### Related Articles Block ![Related Articles](images/related-articles.png) While articles in a series are automatically linked in the left-hand sidebar, you can also add insert a sidebar with links and previews of articles of your choosing, wherever you want in your article. Choose **Related Articles** from the block picker, optionally add Header Text (e.g. “Related Articles”, “More on Campaign Finance”, etc.), and then use the Chosen Articles repeater to add one or more articles. Multiple Related Articles blocks are allowed. ⚠️ Since this component "floats" to the right and lets text wrap around it on wide screens, make sure you place it in a location that has two or three paragraphs below it. Use the article preview to make sure the sidebar doesn't bump up against content further down the page. ### Tables ![Tables](images/tables.png) Gutenberg's table block lets you create and edit HTML tables. You can also paste table markup into the `HTML` block and use **Convert to Blocks** to get a Gutenberg table block. All alignments are available here as well as some other options under the Block inspector: a **Stripes** setting will apply a light color to every other table row (useful for very long tables), while **Fixed width table cells** will enforce equal-width table columns regardless of the amount of content in each cell. ⚠️ Tables with _five columns or more_ will automatically scroll horizontally on mobile. If you wish to invoke this behavior for tables with fewer columns, add `wide` to the Additional CSS Class field in the Advanced section of the Block inspector. Just make sure to keep a space between wide and any other classes that appear here. ### Email Sign-up Block ![Email Sign-up](images/email-signup.png) Articles are also an opportunity to build your email list. You can place the **Email Sign-up** block anywhere in your article. Customize it by adding a headline and body text (samples are available in the help text). Alignment buttons have no effect. ### Pull Quotes ![Pull quote](images/pullquote.png) Create a block and choose the pull quote option: it provides a field for the quote itself as well as for a citation. Alignment buttons have no effect. ⚠️ If your pull quote is literally a quotation, remember to use curly quotation marks a the beginning and end. `“` can be typed on a Mac with `Opt` `[`, while `”` is `Opt` `Shift` `[`. Read more at [smartquotesforsmartpeople.com](http://smartquotesforsmartpeople.com). Alignment buttons have no effect. ### Block Quotes Block quotes (not to be confused with Pull Quotes) are useful for displaying text cited from another source — choose the **Quote** Gutenberg block, add your text and an optional citation; the text gets a muted gray treatment with a left-side border. ### Embeds The Gutenberg editor is generally good about detecting URLs for common services. You can paste the direct URL (not an iframe) for Tweets, Instagram post, Vimeo/Youtube videos, DocCloud, and Soundcloud audio directly into the editor and the UI will embed the media automatically. By default, videos get the same wide treatment that images do, though you can constrain them to the text column with the "Align Center" button. For services like Highcharts that provide `<iframe>` code, choose the `HTML` block and paste. You can click the Preview tab above the block to be sure the embed is working without leaving the editor. The Align Left/Right alignment buttons work for common "rich" embed services like Twitter, Facebook, Instagram, and Document Cloud. "Align Center" will cap the width at 500px and center the embed in the text column. ### Station Identification ![Station ID](images/station-id.png) Insert a new block under **Widgets › Station ID**. The block always pulls content from the text set under **[Site Settings](#site-settings) › Who We Are**. ### Corrections We've added a custom (aka "reusable") Gutenberg block useful for creating a linkable anchor in the middle of an article. The block is really just a shortcut for setting up the following format of HTML: ``` <p id="correction-1"><strong>Correction: </strong> Correction text goes here.</p> ``` 1. Choose the **Correction** block from the Gutenberg pop-up menu. 2. ⚠️ **Click the kebab menu and choose Convert to Regular Block**. This step disconnects this instance from the block template, so you don't end up editing the global version. 3. If adding more than one correction to the page, increment the number in the id (e.g. `<p id="correction-2">...`). 4. Write your correction or update in the paragraph tags. 5. At the beginning or end of the article, add a paragraph mentioning the update/correction and link to the correction paragraph. A same-page anchor link just needs `#correction-1` or similar in the link destination field. ## Other controls ### Article Topper Style ![Article Toppers](images/article-toppers.png) You can choose one of several styles for article toppers: **Image, Light Background**, **Image, Dark Background**, **Image, Full Width**, and **No Image, Light Background** . The first three require a Featured Image attachment with both sides greater than 600px — without one, this field is ignored and the No Image layout will be applied. Sizing and cropping is automatic, so _we recommend uploading images around 3000px wide._ The **Image, Full Width** style should be reserved for high-investment articles with a striking featured image, and your image file should be at least 2000px wide. This treatment overlays the type on a semi-transparent blue-black gradient and auto-crops the image to a square on mobile and a (very wide) `2:1` ratio on desktop. You can also optionally turn off the **Topper tucked under logo?** switch in the rare case you don't want the site header overlaid on CPI logo. ### Partnership Description Use this field to summarize partnerships with other publications, (`This story was co-published with the Daily Beast.`). You can include light formatting like links, and the description will appear above the article body. ### Article Partners ![Tease with partner icon](images/tease-with-partner-icon.png) In addition to the above description, you can also add a partner icon to appear in certain article teases. Frequent partners (like AP and NPR) and their icons are stored in **Posts › Partners** and can be updated over time. Once these are created, you can select them under Article Partners (in the Partnership field group). As a rule, collaborations with partners should be assigned the CPI icon as well as the partner icon. ### Subtitle This field outputs as a mid-sized dek below the article topper; this text also gets used when an article is shared to Facebook and in. Shoot for ~120 characters or fewer. ### Published & Updated Dates Every article shows a **Published** date controlled by Wordpress's native Published field (under Status & Visibility in the post's sidebar). This is automatically set to the current date and time when the article is first published, which you can manually override. If you set it to a date/time in the future, the article will go live at that time. Below the post content is the **Updated** custom field, which provides a second date-and-time picker. This field is completely under your control — you can choose to set it or leave it blank when editing a previously-published post. If set, it outputs the date and time next to an "Updated" label, to the right of the Published date. If the Updated _day_ matches the Published day, only the time outputs. ### More Stories Links Used for legacy articles only. ### Microsites Articles have a button which can be checked to indicate that it's a **Microsite**. For legacy microsites imported before October 30th, 2018, they should already have correct redirect URLs, which can be found in the **Legacy URL** ACF field. If there is an issue with the URL from that field or a microsite is being added _after_ the aforementioned import, the redirect URL for the microsite should be put into the **Microsite URL** ACF field. Please note that if both URL fields have valid URLs, the **Microsite URL** field will take priority. ### Post Authors When publishing an article, use the autocomplete-as-you-type **Author(s)** field near the bottom of the page under the Post Authors heading. If you add more than one author, you can re-order them by dragging and dropping — this order will be respected on output. # Authors Visit **Posts › Authors** to view and edit the full list of article authors. (For flexibility, authors are managed independently of Wordpress user accounts). Click into an author to edit his or her name, job title, organization, biography, photo, Twitter URL, and PGP key. "Organization" should be left empty for CPI staff. Pasting in a PGP key will create a link that lets users copy the string of text to their clipboard. Finally, you can optionally feature a few articles to which the author has been assigned. These appear under a Feature heading in a large tease format above the standard (automated) reverse-chronological, paginated archive for that author. You can also link an author to an entry from the partner organization taxonomy (NPR, the AP, etc). Doing so adds the partner organization's icon as a badge on the author's photo (article view only). # Topics Topic pages and their associated archive of articles are automatically generated from the list under **Posts › Categories**. This taxonomy provides a two-level hierarchy, with primary topics getting an illustration at the top, an email sign-up partway down, and a full sub-topic director at the bottom. The Wordpress category tools let change Topic names, change a Sub-Topic to a topic, etc. and the change will be reflected everywhere on the site. Deleting a topic here removes it from any articles to which it has been assigned. To add a topic or sub-topic to the navigation overlay, use the [Nav Topics menu](/#navigation-menus-navigation-overlay-navigation-topics). Note: Be sure to select the **Category Type** manually: every parent topic should be set to `Main Topic`, and every child topic should be set to `Sub-Topic`, or, in the case of Immigration Decoded sub-topic, `Blog`. This setting will ensure you see the correct fields for the template that gets used. ## Featured Articles and Series By default, the public pages created by these topic and sub-topic settings create a reverse-chron archive for articles assigned to them. But you can customized these pages in additional ways: 1. Main topics allow you to "pin" a few articles above the reverse-chronological list of articles. Use these for high-investment pieces. 2. Sub-Topics can optionally contain a Series: select the articles in the series via the Featured Posts picker. **Series constructed here automatically output "Part 1 of 3", etc. in their toppers** You can also optionally override the labels (headings) that appear on the landing page. For example, you could change the default "Featured" text to "Our three-part series" and "Latest" to "Further Coverage". ⚠️ **Note 1:** While the site accommodates “sub-sub-topics” (topics nested at the third level), a Series sub-topic must always be at the “bottom” of its hierarchy to display its article teases correctly. ⚠️ **Note 2:** Series language ("Part x of y") is only applied when a series has _more than one_ article in it. # Comments Comments on articles can be managed in Wordpress: click the **Comments** tab to view, delete, and moderate incoming comments. Further administrative controls live under **Comments › Settings**. Note that the Styling section interacts with base styles we have applied, so it's best not to change anything under this tab. # Navigation Menus You can control the pages and topics that appear in the navigation overlay. In Wordpress, visit **Appearance › Menus**. By default you'll be viewing one of the three "menus" that control the navigation contents: _Masthead Links_, _Nav Pages_ or _Nav Topics_. Use the pop-menu to toggle between them. While the UI here will let you put any kind of link (page, topic, post, custom URL, etc.) into either menu, it's best to stick to these guidelines: ## Masthead Link Choose **one and only one** page to add to the masthead next to the Menu button (wide screens only). This will probably be the Support Us page, and should be repeated in Navigation Pages so it is available to mobile users. Note that you can use the item dropdown to give the link a custom label (e.g. _Support Our Work_ instead of just _Support Us_). ## Navigation Overlay ### Navigation Pages - Add links to pages like About, Privacy Policy, and Support Us. These appear in a horizontal row at the top of the navigation overlay. - Don't use the nesting feature — nested items won't show up. ### Navigation Topics - You can choose _which_ topics to feature here and in what order, and it's fine if that's just a subset of the full topic list. - Use the nesting feature to preserve the hierarchy of topic and subtopics: once you have your featured topics added to the Menu Structure pane, drag the subtopics a little to the right, under their parent. These will then output as sub-items in the navigation overlay on the website. # Pages ## Basic Pages To create a free-standing page like "Privacy Policy", choose **Pages › Add New** in Wordpress. Give the page a title and fill out the content via the Gutenberg editor — styles will be applied that match article styles. You can then optionally add this page to the Pages section of the [navigation menu](#navigation-menus-navigation-overlay-navigation-pages). ![Sub-page](images/sub-page.png) Basic pages can also be nested one level: when creating the page, look under the Document inspector and choose a parent from the **Parent Page** pop-up menu. Nested pages automatically add a sidebar containing navigation links to the (the sidebar outputs the section's same list of links on both the landing- and sub-pages). To change the sidebar heading from the default "In this section" text, use the Sidebar Heading field located in the parent page. ## Special Pages The About Us (landing) page and Support Us pages use custom fields and templates to manage their content. Once published, don't alter the **Template** or **Parent Page** settings in the Document inspector. The About Us page can accommodate child pages via the parent-child relationship described above. The Support page cannot. The support page gives you control over the membership form that sends the user to members.publicintegrity.org, as well as all the text on the page as well. The fields are grouped under the tabs **Page Topper**, **Membership Form**, and **Page Content**. The Membership Form fields lets you set the default dollar value in the input and sort/disable any of the installment options. # Site Footer Edit the global footer content in [**Site Settings**](#site-settings): you can select pages to appear in the list of linked pages, set the Support page, and edit the mission statement. # Site Settings Certain fields control content in modules that may appear in several parts of the site (e.g. the Newsletter sign-up module). In Wordpress, click **Site Settings** in the sidebar to view and edit this content. # RSS Feeds With the current URL structure, RSS Feeds can be accessed but tacking `/feed` to the end of the URL (i.e.`https://publicintegrity.org/topics/environment/feed`). Additional explanation and examples can be found in the following [WordPress documentation](#https://codex.wordpress.org/WordPress_Feeds). # Redirects To create and manage redirects, go to `Tools -> Safe Redirect Manager` in the WordPress admin. Here you can create redirects i.e. from `/old-url` to `/new-url`. # Google Optimize Tests [Google Optimize](https://optimize.google.com) allows for testing different versions of pages to see which one performs better based on a user specified event i.e. a button being clicked or a page being visited. 1. Create two pieces of content in WordPress. 2. Be sure to check `Enable this page to be tested using Google Optimize` at the bottom of the page. 3. In Google Optimize create a new experience of type "Redirect test", and follow the instructions. <file_sep>/src/Repositories/TermRepository.php <?php /** * Repository entity for retrieving post type terms. */ namespace CPI\Repositories; use CPI\Repositories\PostTypeRepository; use WP_Error; use WP_Post; use WP_Query; use WP_Term; use Timber\Image; use Timber\Term; use CPI\Models\CPIPost; use CPI\Models\CPIAuthor; use CPI\Models\CPIPartner; use CPI\Models\CPITopic; class TermRepository extends Repository { /** * Get the category's thumbnail image. Returns null if thumbnail not found. $term * can either be int (term ID), object (Term || WP_Term) or string (term slug). * * @param mixed $obj Object passed in * * @return Repository */ public function getImage($obj) { // Clear old result sets. $this->reset(); $image = null; if ($obj instanceof CPIPost) { $imgArg = $obj->thumbnail; } else if ($obj instanceof CPIAuthor) { $imgArg = $obj->picture; } else if ($obj instanceof CPIPartner) { $imgArg = $obj->partner_icon; } else if ($obj instanceof CPITopic) { $imgArg = $obj->image_attachment; } else if ($obj instanceof Term) { $imgArg = $obj->thumbnail; } else if ($term instanceof WP_Term) { $imgArg = $term->thumbnail; } else if ($obj instanceof WP_Post) { $imgArg = $obj->featured_image; } if ($imgArg) { $image = new Image($imgArg); } return $image; } } <file_sep>/src/Models/CPITopic.php <?php /** * Functionality for Topic Terms */ namespace CPI\Models; use Timber\Timber; use Timber\Post; use Timber\PostQuery; use Timber\Term; use Timber\Image; use CPI\Repositories\RepositoryFactory; use CPI\Models\CPIPost; class CPITopic extends Term { /** * Constructs instance of CPITopic * * @param mixed $pid - defaults to null * * @return \CPITopic */ public function __construct($pid = null) { parent::__construct($pid); // Set empty array for $menuChildren $this->menuChildren = array(); // Set array of term IDs of other related categories if (!isset($this->otherTermIDs)) { $this->otherTermIDs = []; } } /** * Returns an array of other term IDs from this topic's hierarchy * * @return array */ public function otherTermIDs() { $mainTopics = get_terms('category', array('parent' => 0)); $parent = $this->topParent(); $children = $parent->children(); $allIDs = []; if (!empty($children) && is_array($children)) { foreach ($children as $child) { if ($this->term_id !== $child->term_id) { array_push($allIDs, $child->term_id); } } } if (!empty($mainTopics)) { foreach ($mainTopics as $topic) { if ($parent->term_id !== $topic->term_id) { array_push($allIDs, $topic->term_id); } } } return $allIDs; } /** * Find and return top-most topic in this topic's hierarchy * * @return \CPITopic */ public function topParent() { $term = $this; // limit check against nested levels to 5 for ($i = 0; $i < 5; $i++) { if (!$term->parent) { return $term; } else { $term = new CPITopic($term->parent); } } } /** * Returns array of IDs for Featured Posts * * @return array $featuredPostsIDs */ public function featuredPostsIDs() { $featuredPosts = $this->featured_posts(); $featuredIDs = array(); if (!empty($featuredPosts) && is_array($featuredPosts)) { $featuredIDs = array_map( function ($post) { return $post->ID; }, $featuredPosts ); } return $featuredIDs; } /** * Returns Featured Posts as collection of CPIPosts * * @param array $q_args Array of query arguments * * @return array $featuredPost(s) */ public function featuredPosts($q_args = []) { if (empty($q_args)) { $featuredPosts = $this->featuredPostsIDs(); if (is_array($featuredPosts) && !empty($featuredPosts)) { global $paged; if (!isset($paged) || !$paged) { $paged = 1; } // Set query args for series if ($this->series) { $q_args = array( 'posts_per_page' => 8, 'post_status' => 'publish', 'cat' => $this->id, 'paged' => $paged, 'post__in' => $featuredPosts, 'order' => 'ASC', 'orderby' => 'post_date' ); } else { $q_args = array( 'posts_per_page' => 8, 'post_status' => 'publish', 'cat' => $this->id, 'paged' => $paged, 'post__in' => $featuredPosts, 'orderby' => 'post__in' ); } return new PostQuery($q_args, CPIPost::class); } } else { return new PostQuery($q_args, CPIPost::class); } } /** * Returns Featured Authors as collection of CPIAuthors * * @return array $featuredAuthor(s) */ public function featuredAuthors() { $featuredAuthors = $this->featured_authors(); if (!empty($featuredAuthors)) { if (is_array($featuredAuthors)) { return array_map( function ($featuredAuthor) { return new CPIAuthor($featuredAuthor); }, $featuredAuthors ); } else { return new CPIAuthor($featuredAuthors); } } } // TODO: getIllustration? Add field for illustration image? /** * Returns Image Attachment as TimberImage * * @return \Image */ public function getImage() { $termRepo = RepositoryFactory::get(RepositoryFactory::TERM); return $termRepo->getImage($this); } } <file_sep>/functions.php <?php /** * WP Theme constants and setup functions * * @package ThemeScaffold */ require_once 'vendor/autoload.php'; /** * Use Dotenv to set required environment variables and load .env file in root */ $dotenv = new Dotenv\Dotenv(__DIR__); $dotenv->load(); /** * Set up our global environment constant and load its config first * Default: production */ define('WP_ENV', getenv('WP_ENV') ?: 'production'); $timber = new Timber\Timber(); Timber::$dirname = array('templates'); // Cache twig in staging and production. if (WP_ENV != 'development') { Timber::$cache = true; } use CPI\Managers\GutenbergManager; use CPI\Managers\PostsManager; use CPI\Managers\ThemeManager; use CPI\Managers\TaxonomiesManager; use CPI\Managers\WordPressManager; use CPI\Services\Redirects; define('CPI_THEME_URL', get_stylesheet_directory_uri()); define('CPI_THEME_PATH', dirname(__FILE__) . '/'); define('CPI_DOMAIN', get_site_url()); define('CPI_SITE_NAME', get_bloginfo('name')); define('CPI_THEME_VERSION', wp_get_theme()->get('Version')); define('ALGOLIA_INDEX_NAME_PREFIX', determineAlgoliaPrefix()); /** * Use a different Algolia index depending on if we're production, test, * dev, or local -- based on URL. * @return string prefix */ function determineAlgoliaPrefix() { if (strpos($_SERVER['HTTP_HOST'], 'publicintegrity.org') !== false) { return "live_wp_"; } elseif (strpos($_SERVER['HTTP_HOST'], 'live-public-integrity.pantheonsite.io') !== false) { return "live_wp_"; } elseif ($_SERVER['HTTP_HOST'] == 'test-public-integrity.pantheonsite.io') { return "test_wp_"; } elseif ($_SERVER['HTTP_HOST'] == 'dev-public-integrity.pantheonsite.io') { return "test_wp_"; } else { return "test_wp_"; } } // Set up ACF options page if (function_exists('acf_add_options_page')) { acf_add_options_page(array( 'page_title' => 'Site Settings', 'menu_title' => 'Site Settings', 'menu_slug' => 'site-settings' )); } // Allow SVG uploads function cc_mime_types($mimes) { $mimes['svg'] = 'image/svg+xml'; return $mimes; } add_filter('upload_mimes', 'cc_mime_types'); add_action( 'after_setup_theme', function () { $managers = [ new GutenbergManager(), new PostsManager(), new TaxonomiesManager(), new WordPressManager() ]; $themeManager = new ThemeManager($managers); $themeManager->run(); new Redirects(); } ); add_action('pre_get_posts', 'archive_modify_query_limit_posts'); function archive_modify_query_limit_posts($query) { // Check if on frontend and main query is modified if (! is_admin() && $query->is_main_query() && $query->is_archive()) { $query->set('posts_per_page', 8); } } function deactivate_plugin_conditional() { if (is_plugin_active('search-by-algolia-instant-relevant-results/algolia.php') && (WP_ENV != 'development')) { deactivate_plugins('search-by-algolia-instant-relevant-results/algolia.php'); } } add_action('admin_init', 'deactivate_plugin_conditional'); <file_sep>/src/Blocks/Blocks.php <?php /** * Blocks Initializer * * Enqueue CSS/JS of all the blocks. */ namespace CPI\Blocks; class Blocks { /** * Enqueue assets needed for block */ public function __construct() { add_action('enqueue_block_editor_assets', array($this,'enqueueBlockEditorAssets')); new StationID\StationID(); new EmailSignUp\EmailSignUp(); new RelatedArticles\RelatedArticles(); new Gallery\Gallery(); } /** * Enqueue Gutenberg block assets for backend editor. * * @return null */ public function enqueueBlockEditorAssets() { // Scripts. wp_enqueue_script( 'block-js', // Handle. CPI_THEME_URL . '/dist/blocks.build.js', // Block.block.build.js: We register the block here. Built with Webpack. array( 'wp-blocks', 'wp-i18n', 'wp-element' ), // Dependencies, defined above. true // Enqueue the script in the footer. ); // For StationID block $whoWeAre = get_field('who_we_are', 'option'); wp_localize_script('block-js', 'whoWeAre', $whoWeAre); // Styles. wp_enqueue_style( 'block-editor-css', // Handle. CPI_THEME_URL . '/dist/block-editor.build.css', // Block editor CSS. array( 'wp-edit-blocks' ) // Dependency to include the CSS after it. ); } } <file_sep>/static/js/components/scrollable-tables.js import $ from 'jquery'; class ScrollableTables { constructor() { this.$articleTables = $('.article-main table'); this.columnCountThreshold = 5; this.approxPixelsPerColumn = 130; this.wrapWideTables(); } wrapWideTables() { let that = this; this.$articleTables.each(function() { let $this = $(this); let columnCount = $this.find('tbody > tr:first > td').length; // check this table's column count is above the threshold setting, // or the admins have added the wide class if ($this.hasClass('wide') || columnCount >= that.columnCountThreshold) { // create a wrapping div and copy the table's classes to it $this.wrap(function() { let tableClasses = $this.attr('class'); return `<div class="scrollable-table-wrap ${tableClasses}"></div>`; }); // remove the table's original classes $this.attr('class', ''); let tableMinWidth = that.approxPixelsPerColumn * columnCount; // set a min width based on # of columns and approxPixelsPerColumn $(this).attr('style', `min-width: ${tableMinWidth}px`); } }); } } export default ScrollableTables; <file_sep>/page-modified-posts.php <ul class="updated-posts"> <?php // Show recently modified posts $recently_updated_posts = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => -1, 'orderby' => 'modified', 'no_found_rows' => true // speed up query when we don't need pagination ) ); $deadline = DateTime::createFromFormat('Y-m-d H:i:s', '2018-11-03 13:00:00'); if ( $recently_updated_posts->have_posts() ) : while( $recently_updated_posts->have_posts() ) : $recently_updated_posts->the_post(); /** ?> */ $modified_date = get_the_modified_date('Y-m-d H:i:s'); $mod_date_time = DateTime::createFromFormat('Y-m-d H:i:s', $modified_date); if ($mod_date_time < $deadline) : $postID = get_the_ID(); wp_delete_post($postID, true); // force delete the post else : ?><li><a href="<?php the_permalink(); ?>" title="<?php esc_attr( get_the_title() ); ?>"><?php the_title(); ?></a><?php echo get_the_modified_date('Y-m-d H:i:s'); ?></li> <?php endif ?> <?php endwhile; ?> <?php wp_reset_postdata(); ?> <?php endif; ?> </ul> <file_sep>/static/js/app.js import $ from 'jquery'; import wpUtil from './wp-util.js'; import ArticleScrolling from './components/article-scrolling'; import Comments from './components/comments'; import CopyToClipboard from './components/copy-to-clipboard'; import ArticleGallery from './components/article-gallery'; import GridOverlay from './components/grid-overlay'; import Menu from './components/menu'; import MemberForm from './components/member-form'; import Nav from './components/nav'; import HangingPunctuation from './components/hanging-punctuation'; import HomeFeatures from './components/home-features'; import ScrollableTables from './components/scrollable-tables'; $(document).ready(() => { new HangingPunctuation(); // must load before ArticleScrolling if ($('.js-article-gallery').length) { new ArticleGallery(); } if ($('.article-content').length) { new ArticleScrolling(); } if (['localhost', 'cpi.ups.dock'].includes(location.hostname)) { new GridOverlay(); } if ($('.js-copy-to-clipboard').length) { new CopyToClipboard(); } if ($('.article-comments').length) { new Comments(); } new Nav(); if ($('.member-form__radio').length) { new MemberForm(); } if ($('.home-features__list').length) { new HomeFeatures(); } if ($('.article-main table').length) { new ScrollableTables(); } // Search if ($('#js-search-box').length > 0) { require.ensure( ['./components/search'], require => { const Search = require('./components/search').default; this.search = new Search(); }, 'search' ); } }); <file_sep>/static/js/components/grid-overlay.js import $ from 'jquery'; class GridOverlay { constructor(el) { this.$body = $('body'); if (!this.$body) { throw new Error('Invalid element reference.'); } this.init(); } init() { $(document).keydown(evt => { if (evt.altKey && evt.shiftKey && 76 === evt.keyCode) { evt.preventDefault(); this.$body.toggleClass('grid-is-shown'); } }); } } export default GridOverlay; <file_sep>/page-home.php <?php /** * Template Name: Home Page */ use Timber\Image; use CPI\Repositories\PostTypeRepository; use CPI\Models\CPIPost; $context = Timber::get_context(); $page = Timber::get_post(); $context['page'] = $page; $homeTopperType = $page->home_topper_type; // $homeTopperType = $page->get_field('home_topper_type'); $context['home_topper_type'] = $homeTopperType; // TODO: if time allows, refactor if ($homeTopperType === 'datapoint' && $page->linked_page()) { // Set HomeTopper - Linked Page $linkedPage = new CPIPost($page->linked_page()[0]); $illustration = !empty($page->data_point_illustration) ? new Image($page->data_point_illustration) : null; $context['home_topper_linked_page'] = $linkedPage; $context['home_topper_image'] = $illustration; $context['home_topper_headline'] = $page->get_field('data_point_headline'); $context['home_topper_dek'] = $page->get_field('data_point_dek'); $context['home_topper_link'] = $linkedPage->link(); $context['home_topper_link_text'] = 'page' == $linkedPage->post_type ? $linkedPage->title() : "Read more"; } else if ($homeTopperType === 'article' && $page->topper_article()) { // Set Home Topper - Topper Article $topperArticle = new CPIPost($page->topper_article()[0]); $context['home_topper_article'] = $topperArticle; $context['home_topper_image'] = $topperArticle->getThumbnail(); $context['home_topper_topic'] = $topperArticle->articleTopic(); $context['home_topper_headline'] = $topperArticle->title(); $context['home_topper_dek'] = $topperArticle->subtitle(); $context['home_topper_link'] = $topperArticle->link(); $context['home_topper_link_text'] = 'Read'; } // Set Home Features Posts $homeFeatures = get_field('home_features'); if (is_array($homeFeatures) && !empty($homeFeatures)) { $context['homeFeatures'] = array_map( function ($post) { return new CPIPost($post); }, $homeFeatures ); } // Set Home Impact if (!empty($page->get_field('home_impact'))) { $context['home_impact'] = $page->get_field('home_impact'); } // Set Home Partners Logos $partnerLogos = $page->get_field('home_partners_logos'); if (!empty($partnerLogos)) { $context['home_partners_logos'] = array_map( function($logo) { return new Image($logo['partner_logo']); }, $partnerLogos ); } // Render view. Timber::render('pages/home.twig', $context); <file_sep>/static/js/components/hanging-punctuation.js class HangingPunctuation { constructor() { this.$container = $('.js-hang-punc'); this.punctuationMarks = { '\u201c': 'medium', // “ - ldquo - left smart double quote '\u2018': 'small', // ‘ - lsquo - left smart single quote '\u0022': 'medium', // " - ldquo - left dumb double quote '\u0027': 'small', // ' - lsquo - left dumb single quote '\u00AB': 'large', // « - laquo - left double angle quote '\u2039': 'medium', // ‹ - lsaquo - left single angle quote '\u201E': 'medium', // „ - bdquo - left smart double low quote '\u201A': 'small', // ‚ - sbquo - left smart single low quote }; if (this.$container.length > 0) { this.hangPunc(); } } hangPunc() { const containerChildren = this.$container.children(); // Loop over all direct descendants of the $container // If it's a blockquote, loop over its direct descendants for (let i = 0; i < containerChildren.length; i += 1) { const el = containerChildren[i]; // For blockquotes, which are marked up as <figure class="wp-block-pullquote"><blockquote><p>"Text"</p><cite>Citation</cite></blockquote></figure>, // target the paragraph only: if (el.tagName === 'FIGURE') { let $blockquote_paragraph = $(el).find('blockquote > p'); if ($blockquote_paragraph.length) { this.hangIfEligible($blockquote_paragraph[0]); } } else { this.hangIfEligible(el); } } } hangIfEligible(el) { const text = el.innerText || el.textContent; let htmlClass = 'hang-punc-'; // for (const mark in this.punctuationMarks) { const marks = Object.keys(this.punctuationMarks); marks.forEach(mark => { if (text.indexOf(mark) === 0) { if ( el.tagName === 'H1' || el.tagName === 'H2' || el.tagName === 'H3' || el.tagName === 'H4' || el.tagName === 'H5' ) { htmlClass += 'header-'; } el.classList.add(htmlClass + this.punctuationMarks[mark]); } }); } createTips() { $(this.toolTipTargets).each((i, el) => { const $el = $(el); const tipURL = new URL($el.attr('href')); const $toolTip = $('<span/>'); $toolTip.text(tipURL.hostname); $toolTip.addClass('tool-tip'); $el.append($toolTip); }); } } export default HangingPunctuation; <file_sep>/page.php <?php /** * Default Page Template */ use CPI\Models\CPIPost; $context = Timber::get_context(); $context['post'] = Timber::get_post(); // Even if we're on a subpage, we want the directory to list every page that descends // https://css-tricks.com/snippets/wordpress/find-id-of-top-most-parent-page/ if ($post->post_parent) { $ancestors=get_post_ancestors($post->ID); $root=count($ancestors)-1; $topMostPageID = $ancestors[$root]; } else { $topMostPageID = $post->ID; } $pageDirectoryObjects = get_pages([ 'child_of' => $topMostPageID, 'sort_column' => 'menu_order' ]); // Create array of CPI Post objects, // store in context as pageDirectory if ($pageDirectoryObjects) { // include the topmost page itself at the top $context['pageDirectory'][] = new CPIPost($topMostPageID); foreach ($pageDirectoryObjects as $pageObject ) { $context['pageDirectory'][] = new CPIPost($pageObject); } } // sidebar heading $pageSidebarHead = get_field('page_sidebar_heading', $topMostPageID) ?: 'In this section'; $context['pageSidebarHead'] = $pageSidebarHead; Timber::render(['pages/basic-page.twig'], $context); <file_sep>/static/js/admin.js import $ from 'jquery'; $(document).ready(() => { // Make ACF wysiwyg shorter if (typeof acf !== 'undefined') { acf.add_action('wysiwyg_tinymce_init', function(ed, id, mceInit, $field) { // set height of wysiwyg on frontend var minHeight = 200; var mceHeight = $(ed.iframeElement) .contents() .find('html') .height() || minHeight; if (mceHeight < minHeight) { mceHeight = minHeight; } $(ed.iframeElement).css('height', mceHeight); }); } }); <file_sep>/static/js/components/copy-to-clipboard.js import $ from 'jquery'; import Clipboard from 'clipboard'; class CopyToClipboard { constructor(el) { this.$copyBtn = $('.js-copy-to-clipboard'); if (!this.$copyBtn) { throw new Error('Invalid element reference.'); } this.$copyBtnFeedback = $('.js-copy-to-clipboard-feedback'); this.init(); } init() { let that = this; let clipboard = new Clipboard('.js-copy-to-clipboard'); clipboard.on('success', function(e) { let successText = that.$copyBtn.data('success-text'); let defaultText = that.$copyBtn.data('default-text'); that.$copyBtnFeedback.text(successText); that.$copyBtn.addClass('copy-to-clipboard--success'); setTimeout(function() { that.$copyBtn.blur(); that.$copyBtnFeedback.text(defaultText); that.$copyBtn.removeClass('copy-to-clipboard--success'); }, 2500); e.clearSelection(); }); clipboard.on('error', function(e) { that.$copyBtnFeedback.text('Not Supported'); setTimeout(function() { that.$copyBtn.attr('disabled', 'disabled'); that.$copyBtnFeedback.text(''); that.$copyBtn.blur(); }, 2500); }); } } export default CopyToClipboard; <file_sep>/src/Models/CPIPost.php <?php /** * Functionality for Article Posts */ namespace CPI\Models; use Carbon\Carbon; use Timber\Timber; use Timber\Post; use Timber\PostQuery; use Timber\Term; use Timber\Image; use CPI\Repositories\RepositoryFactory; use CPI\Models\CPIAuthor; use CPI\Models\CPIPartner; use CPI\Models\CPITopic; class CPIPost extends Post { /** * Constructs instance of CPIPost * * @param mixed $pid - defaults to null * * @return \CPIPost */ public function __construct($pid = null) { parent::__construct($pid); // Set redirect URL for link depending on microsite if (!empty($this->microsite_url)) { // if ($this->microsite && !empty($this->microsite_url)) { $this->link = $this->microsite_url; } else if (!empty($this->legacy_url)) { $legacyURL = $this->legacy_url; $microDomain = (bool)strpos($legacyURL, 'apps.publicintegrity.org'); if ($this->microsite || $microDomain) { $this->link = $this->legacy_url; } } } /** * Returns collection of CPIAuthor objects for Authors * * @return array $authors */ public function articleAuthors() { $authors = $this->get_field('authors'); if (!empty($authors)) { if (is_array($authors)) { return array_map( function ($author) { return new CPIAuthor($author); }, $authors ); } else { return new CPIAuthor($authors); } } } /** * Formats publish date * * @return string $date */ public function formatUpdated() { // Return if updated_date field is empty if (empty($this->get_field('updated_date'))) { return; } $pubDate = date_create_from_format('Y-m-d H:i:s', $this->date('Y-m-d H:i:s')); $upDate = date_create_from_format('Y-m-d H:i:s', $this->get_field('updated_date')); if (date_format($upDate, 'F j, Y g\:i a') === date_format($pubDate, 'F j, Y g\:i a')) { return; } else { // Checks if month, day, and year are same for updated and published dates if (date_format($upDate, 'F j, Y') === date_format($pubDate, 'F j, Y')) { return 'Today at ' . date_format($upDate, 'g\:i a') . ' EST'; } else { return date_format($upDate, 'F j, Y \a\t g\:i a') . ' ET'; } } } /** * Returns collection of CPIPartner objects for Partners * * @return array $partners */ public function articlePartners() { $partners = $this->get_field('article_partners'); if ($partners) { if (is_array($partners)) { return array_map( function ($partner) { return new CPIPartner($partner); }, $partners ); } else { return new CPIPartner($partners); } } } /** * Returns string from Partnership Description field * * @return string $partnership_description */ public function partnershipDescription() { $partnership_description = $this->get_field('partnership_description'); if (!empty($partnership_description) || !$partnership_description) { return $partnership_description; } } /** * Formats author(s) names for displaying in views * * @return string $formatted_display */ public function formattedAuthors() { $authors = $this->articleAuthors(); if (!empty($authors)) { $formatted_display = ''; foreach ($authors as $i => $author) { $author_name = $author->formattedName(); $total = count($authors); if ($total > 2 && $i != ($total - 1)) { $formatted_display .= "<strong>$author_name</strong>, "; } elseif ($total === 2 && $i != ($total - 1)) { $formatted_display .= "<strong>$author_name</strong> "; } elseif ($total >= 2 && $i === ($total - 1)) { $formatted_display .= "and <strong>$author_name</strong>"; } else { $formatted_display .= "<strong>$author_name</strong>"; } } return $formatted_display; } } /** * Returns Topic as CPITopic * * @return \CPITopic */ public function articleTopic() { // TODO: refactor? $topics = $this->categories(); if (is_array($topics) && !empty($topics)) { foreach ($topics as $term) { if (($term->parent) && !($term->children)) { return new CPITopic($term); } } return new CPITopic($topics[0]); } } /** * Return Article topper style * * @return string $style */ public function topperStyleArticle() { // TODO: change to setTopperStyles, which change topperStyleArticle and topperStyleTease? $thumbnail = $this->getThumbnail; if ($thumbnail && ($thumbnail->width >= 600 && $thumbnail->height >= 600)) { if ($this->get_field('topper_style')) { return $this->get_field('topper_style')['value']; } else { return 'light'; } } else { return 'no-image'; } } /** * Return Tease topper style * * @return string $style */ public function topperStyleTease() { $thumbnail = $this->getThumbnail; if ($thumbnail && ($thumbnail->width >= 600 && $thumbnail->height >= 600)) { if ($this->get_field('topper_style') === 'no-image') { return 'no-image'; } else { return 'image'; } } else { return 'no-image'; } } /** * Returns Thumbnail as TimberImage * * @return \Image */ public function getThumbnail() { $termRepo = RepositoryFactory::get(RepositoryFactory::TERM); return $termRepo->getImage($this); } /** * Get Article's place in a Series * * @return int */ public function seriesPlace() { $featuredPosts = $this->articleTopic()->featuredPosts(); if (!empty($featuredPosts) && count($featuredPosts) > 1) { foreach ($featuredPosts as $index => $post) { if ($post->ID === $this->ID) { return $index + 1; } } } } /** * Get number of Articles in Article's Series * * @return int */ public function seriesTotal() { $featuredPosts = $this->articleTopic()->featuredPosts(); if (!empty($featuredPosts) && count($featuredPosts) > 1) { return count($featuredPosts); } } /** * Redirects to microsites on single views * * @return void */ public function validMicro() { $microCheck = !empty($this->get_field('microsite_url')); $legacyURL = $this->get_field('legacy_url'); $legacyCheck = (bool)strpos($legacyURL, 'apps.publicintegrity.org'); return $microCheck ?: $legacyCheck; } /** * Get recirc CPIPosts for single view * * @return array $recircPosts Array is empty if no posts are found for recirculation */ public function recircPosts() { global $post; $recirc = []; $recircIDs = []; $topic = $this->articleTopic(); if ($topic) { $tax = $topic->taxonomy(); $excludedIDs = $topic->otherTermIDs(); } else { $tax = 'category'; } $temp = $post; $getPrev = false; // TODO: cache results? // Set recirdIDs based on number of previous posts, i.e. if only // 1 previous post found, then get next post, and if no previous posts // found, get 2 next posts for ($i = 0; $i < 2; ++$i) { // Get adjacent post based on whether previous post has been added if ($getPrev) { $post = get_adjacent_post(true, $excludedIDs, true, $tax); } else { $post = get_adjacent_post(true, $excludedIDs, false, $tax); } if (!empty($post)) { if ($post->post_title !== $temp->post_title) { // If previous post has been added, prepend post to $recirc if ($getPrev) { $recircIDs[] = $post->ID; } else { array_unshift($recircIDs, $post->ID); } setup_postdata($post); } } else { // If next post not found, reset $post and get previous $post = $temp; setup_postdata($post); $post = get_adjacent_post(true, $excludedIDs, true, $tax); if (!empty($post)) { if ($post->post_title !== $temp->post_title) { $recircIDs[] = $post->ID; setup_postdata($post); $getPrev = true; } } } } $post = $this; setup_postdata($post); if (!empty($recircIDs)) { $args = array( 'post_status' => 'published', 'post__in' => $recircIDs ); $recirc = new PostQuery($args, CPIPost::class); } return $recirc; } } <file_sep>/src/Managers/WordPressManager.php <?php /** * Mostly involved with cleaning up default WordPress cruft. */ namespace CPI\Managers; class WordPressManager { /** * Runs initialization tasks. * * @return void */ public function run() { add_action('wp_loaded', [$this, 'cleanup'], 1); add_action('wp_dashboard_setup', array($this, 'removeDashboardWidgets')); } /** * Cleans up and removes unnecessary Wordpress bloat. * * @return void */ public function cleanup() { remove_action('template_redirect', 'redirect_canonical'); remove_action('template_redirect', 'rest_output_link_header', 11, 0); remove_action('template_redirect', 'wp_shortlink_header', 11); remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10); remove_action('wp_head', 'feed_links', 2); remove_action('wp_head', 'feed_links_extra', 3); remove_action('wp_head', 'noindex', 1); remove_action('wp_head', 'parent_post_rel_link'); remove_action('wp_head', 'print_emoji_detection_script', 7); remove_action('wp_head', 'rel_canonical'); remove_action('wp_head', 'rest_output_link_wp_head'); remove_action('wp_head', 'rsd_link'); remove_action('wp_head', 'start_post_rel_link'); remove_action('wp_head', 'wlwmanifest_link'); remove_action('wp_head', 'wp_oembed_add_discovery_links'); remove_action('wp_head', 'wp_oembed_add_host_js'); remove_action('wp_head', 'wp_generator'); remove_action('wp_head', 'wp_resource_hints', 2); remove_action('wp_head', 'wp_shortlink_wp_head'); remove_action('wp_print_styles', 'print_emoji_styles'); add_filter('json_enabled', '__return_false'); add_filter('json_jsonp_enabled', '__return_false'); add_filter('xmlrpc_enabled', '__return_false'); add_filter('plugin_action_links', array($this, 'disablePluginDeactivation'), 10, 4); // Remove pingbacks from cron jobs. if (defined('DOING_CRON') && DOING_CRON) { remove_action('do_pings', 'do_all_pings'); wp_clear_scheduled_hook('do_pings'); } } /** * Forces REST endpoints to be accessed only by logged in users. See * https://developer.wordpress.org/rest-api/using-the-rest-api/frequently-asked-questions/#require-authentication-for-all-requests * * @return void */ public function requireRestAuth() { add_filter( 'rest_authentication_errors', function ($result) { if (!empty($result)) { return $result; } if (!is_user_logged_in()) { return new WP_Error('rest_not_logged_in', 'You are not currently logged in.', ['status' => 401]); } return $result; } ); } /** * Hide extranneous dashboard widgets * * @return void */ public function removeDashboardWidgets() { global $wp_meta_boxes; unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']); unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']); unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']); unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']); unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_drafts']); unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']); unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']); unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']); unset($wp_meta_boxes['dashboard']['normal']['core']['yoast_db_widget']); } /** * Don't allow Timber to be disabled * * @param mixed $actions Actions * @param mixed $plugin_file Plugin file * @param mixed $plugin_data Plugin data * @param mixed $context Context * * @return void */ public function disablePluginDeactivation($actions, $plugin_file, $plugin_data, $context) { // Remove edit link for all plugins if (array_key_exists('edit', $actions)) { unset($actions['edit']); } // Remove deactivate link for important plugins if (array_key_exists('deactivate', $actions) && in_array( $plugin_file, array( 'timber-library/timber.php', ) ) ) { unset($actions['deactivate']); } return $actions; } } <file_sep>/page-compact-archives.php <?php /** * * Template Name: Compact Archives * * Learn more: http://codex.wordpress.org/Template_Hierarchy */ $context = Timber::get_context(); // get page $context['page'] = Timber::get_post(); $posts = new Timber\PostQuery(array( 'posts_per_page' => 8, 'post_status' => 'publish', 'paged' => $paged )); $context['posts'] = $posts; // Render view Timber::render( 'pages/archive.twig', $context ); <file_sep>/archive.php <?php /** * The template for displaying Archive pages. * * Used to display archive-type pages if nothing more specific matches a query. * For example, puts together date-based pages if no date.php file exists. * * Learn more: http://codex.wordpress.org/Template_Hierarchy */ use CPI\Models\CPIPost; use CPI\Models\CPITopic; global $paged; if (!isset($paged) || !$paged) { $paged = 1; } $context = Timber::get_context(); $templates = ['pages/archive.twig', 'pages/index.twig']; $query_args = null; $per_page = 8; $context['title'] = 'Archive'; $context['description'] = false; if (is_day()) { $context['title'] = 'Archive: ' . get_the_date('D M Y'); } else if (is_month()) { $context['title'] = 'Archive: ' . get_the_date('M Y'); } else if (is_year()) { $context['title'] = 'Archive: ' . get_the_date('Y'); } else if (is_tag()) { $context['title'] = single_tag_title('', false); $query_args = array( 'posts_per_page' => $per_page, 'post_status' => 'publish', 'tag' => get_query_var('tag'), 'paged' => $paged, ); } else if (is_category()) { $term = new CPITopic(); $query_args = array( 'posts_per_page' => $per_page, 'post_status' => 'publish', 'cat' => $term->id, 'paged' => $paged, ); if ($term->parent) { $context['parent_term'] = new CPITopic($term->parent); } // Set array of IDs of Featured Posts for query arguments $featured_posts_ids = $term->featuredPostsIDs; if (!empty($featured_posts_ids)) { // Argument for Posts query that excludes Featured Posts $query_args['post__not_in'] = $featured_posts_ids; } $context['term'] = $term; array_unshift($templates, 'pages/archive-' . get_query_var('cat') . '.twig'); } else if (is_post_type_archive()) { $context['title'] = post_type_archive_title('', false); array_unshift($templates, 'pages/archive-' . get_post_type() . '.twig'); } // Make Post queries based on whether Term has Featured Posts if (!empty($featured_posts_ids)) { $context['featured_posts'] = $term->featuredPosts(); } $context['posts'] = $query_args ? new Timber\PostQuery($query_args, CPIPost::class) : new Timber\PostQuery(null, CPIPost::class); // Render view Timber::render( $templates, $context ); <file_sep>/page-about.php <?php /** * * Template Name: About Us (landing only) * * Learn more: http://codex.wordpress.org/Template_Hierarchy */ use CPI\Models\CPIPost; $context = Timber::get_context(); // get page $context['post'] = Timber::get_post(); // TODO: refactor lines ~ 18-49 to avoid repeating what's in page.php // Even if we're on a subpage, we want the directory to list every page that in the section // https://css-tricks.com/snippets/wordpress/find-id-of-top-most-parent-page/ if ($post->post_parent) { $ancestors=get_post_ancestors($post->ID); $root=count($ancestors)-1; $topMostPageID = $ancestors[$root]; } else { $topMostPageID = $post->ID; } $pageDirectoryObjects = get_pages([ 'child_of' => $topMostPageID, 'sort_column' => 'menu_order' ]); // Create array of CPI Post objects, // store in context as pageDirectory if ($pageDirectoryObjects) { // include the topmost page itself at the top $context['pageDirectory'][] = new CPIPost($topMostPageID); foreach ($pageDirectoryObjects as $pageObject ) { $context['pageDirectory'][] = new CPIPost($pageObject); } } // sidebar heading $pageSidebarHead = get_field('page_sidebar_heading', $topMostPageID) ?: 'In this section'; $context['pageSidebarHead'] = $pageSidebarHead; // Render view Timber::render( 'pages/basic-page.twig', $context ); <file_sep>/src/Models/CPIAuthor.php <?php /** * Functionality for Author Terms */ namespace CPI\Models; use Timber\Timber; use Timber\Post; use Timber\Term; use Timber\Image; use CPI\Repositories\RepositoryFactory; use CPI\Models\CPIPost; use CPI\Models\CPIPartner; class CPIAuthor extends Term { /** * Constructs instance of CPIAuthor * * @param mixed $pid - defaults to null * * @return \CPIAuthor */ public function __construct($pid = null) { parent::__construct($pid); } /** * Formats Author's name * * @return string */ public function formattedName() { $first_name = $this->first_name; $last_name = $this->last_name; $name = $this->name; if ($first_name && $last_name) { return "$first_name $last_name"; } else if ($name) { return $name; } } /** * Get Author's Articles * * @param array $q_args - query arguments * @param string $postClass - default to CPIPost * * @return array $posts - CPIPost collection */ public function getArticles(array $q_args, $postClass = 'CPIPost') { $postTypeRepo = RepositoryFactory::get(RepositoryFactory::POST_TYPE); return $postTypeRepo->latestPosts($q_args, CPIPost::class)->get(); } /** * Set Partner Organization as CPIPartner * * @return \CPIPartner */ public function partnerOrg() { // TODO: refactor after creating TermRepository // $taxRepo = RepositoryFactory::get(RepositoryFactory::TERM); return new CPIPartner($this->partner_organization); } /** * Returns Picture as TimberImage * * @return \Image */ public function getPicture() { $termRepo = RepositoryFactory::get(RepositoryFactory::TERM); return $termRepo->getImage($this); } } <file_sep>/src/Managers/ThemeManager.php <?php /** * Bootstraps WordPress theme related functions, most importantly enqueuing javascript and styles. */ namespace CPI\Managers; use Timber; use Timber\Menu as TimberMenu; use CPI\Models; use CPI\Models\CPITopic; class ThemeManager { private $managers = []; /** * Constructor * * @param array $managers Array of managers */ public function __construct(array $managers) { $this->managers = $managers; add_filter('timber/context', array($this, 'addIsHomeToContext')); add_filter('timber/context', array($this, 'addACFOptionsToContext')); add_filter('timber/context', array($this, 'addHostNametoContext')); add_filter('timber/context', array($this, 'addIsGoogleTestToContext')); add_filter('timber/context', array($this, 'addThemeVersion')); add_filter('timber/context', array($this, 'addMenusToContext')); add_action('admin_enqueue_scripts', array($this,'enqueueAdminScripts')); add_action('wp_dashboard_setup', array($this, 'addDocumentationWidget')); add_action('admin_menu', array($this, 'addDocumentationMenuItem')); add_action('admin_init', array($this,'register_menus')); add_action('admin_init', array($this,'redirectToDocs'), 1); add_action('admin_init', array( $this, 'sync_fields_with_json' )); add_action('init', array($this, 'registerOptions'), 1, 3); add_filter('acf/fields/relationship/query', array($this,'acf_post_relationship_query'), 10, 3); add_filter('acf/fields/post_object/query', array($this,'acf_post_object_query'), 10, 3); add_filter('gutenberg_can_edit_post_type', array($this,'disableGutenbergOnSpecificPosts'), 10, 2); add_filter('algolia_template_locations', array($this, 'algolia_template_locations'), 10, 2); } /** * Runs initialization tasks. * * @return void */ public function run() { if (count($this->managers) > 0) { foreach ($this->managers as $manager) { $manager->run(); } } add_action('wp_enqueue_scripts', [$this, 'enqueue'], 999); add_theme_support('post-thumbnails'); add_theme_support('menus'); add_theme_support('align-wide'); } /** * Enqueue javascript using WordPress * * @return void */ public function enqueue() { // don't use WordPress jquery in production. (admin bar and wordpress debug bar needs it in development) if (WP_ENV != 'development') { wp_deregister_script('jquery'); } // Remove default Gutenberg CSS wp_deregister_style('wp-block-library'); // enqueue vendor script output from webpack wp_enqueue_script('manifest', CPI_THEME_URL . '/dist/manifest.js', array(), CPI_THEME_VERSION, true); wp_enqueue_script('vendor', CPI_THEME_URL . '/dist/vendor.js', array(), CPI_THEME_VERSION, true); // enqueue custom js file, with cache busting wp_enqueue_script('script.js', CPI_THEME_URL . '/dist/app.js', array(), CPI_THEME_VERSION, true); // this is needed for the Algolia search template, but we include our own copy wp_deregister_script('wp-util'); } /** * Enqueue JS and CSS for WP admin panel * * @return void */ public function enqueueAdminScripts() { wp_enqueue_style('admin-styles', CPI_THEME_URL . '/dist/admin.css'); wp_enqueue_script('manifest', CPI_THEME_URL . '/dist/manifest.js'); wp_enqueue_script('vendor', CPI_THEME_URL . '/dist/vendor.js'); wp_enqueue_script('admin.js', CPI_THEME_URL . '/dist/admin.js'); } /** * Adds ability to access array of ACF options fields in a twig field * * @param array $context Timber context * * @return array */ public function addACFOptionsToContext($context) { $context["options"] = get_fields('option'); return $context; } /** * Adds ability to check if we are on the homepage in a twig file * * @param array $context Timber context * * @return array */ public function addIsHomeToContext($context) { $context['is_home'] = is_home(); return $context; } /** * Get host name and add to context * * @param array $context Timber context * * @return array */ public function addHostNametoContext($context) { $context['hostname'] = $this->get_host_name(); return $context; } /** * Checks if the Google Optimize Test checkbox is enabled. If so, * the page hiding code from Google will be enabled in the head. * * @param array $context Timber context * * @return array */ public function addIsGoogleTestToContext($context) { $context['isGoogleOptimizeTest'] = (get_field('google_optimize_test', get_the_ID())); return $context; } /** * Get host name * * @return string host name */ private function get_host_name() { $hostName = $_SERVER['HTTP_HOST']; if (empty($hostName)) { $hostName = $_SERVER['SERVER_NAME']; } if (empty($hostName)) { $hostName = $_SERVER['VIRTUAL_HOST']; } return $hostName; } /** * Register nav menus * @return void */ public function register_menus() { register_nav_menus( array( 'nav_topics_menu' => 'Navigation Topics Menu', 'nav_pages_menu' => 'Navigation Pages Menu', 'masthead_links_menu' => 'Masthead Link', ) ); } /** * Registers and adds menus to context * * @param array $context Timber context * * @return array */ public function addMenusToContext($context) { $navTopicsMenu = new Timber\Menu('nav_topics_menu'); $navItems = $navTopicsMenu->items; if (is_array($navItems) && !empty($navItems)) { $navCPITopics = array_map( function ($item) { if ($item->object === "category") { $term = Timber::get_term((int)$item->object_id, '', CPITopic::class); $term->menuChildren = $item->children; return $term; } else { return $item; } }, $navItems ); } if (!empty($navCPITopics)) { $context['nav_topics_menu_items'] = $navCPITopics; } else { // temp $context['nav_topics_menu'] = $navTopicsMenu->items; } $context['nav_pages_menu'] = new Timber\Menu('nav_pages_menu'); $context['masthead_links_menu'] = new Timber\Menu('masthead_links_menu'); return $context; } /** * Adds timestamp of last modified time of CSS file to context in order * to allow for automatic cache busting. * * @param array $context Timber context * * @return array */ public function cssLastModified($context) { $context['css_last_modified'] = filemtime(get_stylesheet_directory() . '/dist/app.css'); return $context; } /** * Add theme's version to Timber context * * @param array $context Timber context * * @return void */ public function addThemeVersion($context) { $context['theme_version'] = wp_get_theme()->get('Version'); return $context; } /** * Adds a widget to the dashboard with a link to editor docs * * @return void */ public function addDocumentationWidget() { wp_add_dashboard_widget( 'custom_dashboard_widget', 'Editor Documentation', function () { echo "<p><a href='/wp-content/themes/cpi/documentation/index.html' target='_blank' rel='noopener noreferrer'>View</a> the editor documentation</p>"; } ); } /** * Adds a menu item to WP admin that links to editor docs * * @return void */ public function addDocumentationMenuItem() { add_menu_page('Editor Docs', 'Editor Docs', 'manage_options', 'link-to-docs', array($this,'redirectToDocs'), 'dashicons-admin-links', 100); } /** * To have an external link to the docs we need this weird function * * @return void */ public function redirectToDocs() { $menu_redirect = isset($_GET['page']) ? $_GET['page'] : false; if ($menu_redirect == 'link-to-docs') { header('Location: https://' . $_SERVER['HTTP_HOST'] . '/wp-content/themes/cpi/documentation'); exit(); } } /** * Add ACF options page to WordPress * * @return void */ public function registerOptions() { if (function_exists('acf_add_options_page')) { acf_add_options_page( array( 'page_title' => 'Site Settings', 'menu_title' => 'Site Settings', 'menu_slug' => 'site-settings' ) ); } } /** * Modify ACF relationship field to show most recent posts instead of alpha * * @param array $args Args * @param string $field Field * @param int $post_id Post ID * * @return void */ public function acf_post_relationship_query($args, $field, $post_id) { // order returned query collection by date, starting with most recent $url = wp_get_referer(); $parts = parse_url($url); parse_str($parts['query'], $query); if (key_exists('taxonomy', $query) && key_exists('tag_ID', $query)) { $args['tax_query'] = array( 'relation' => 'OR', array( 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => intval($query['tag_ID']) ), array( 'taxonomy' => 'author', 'field' => 'term_id', 'terms' => intval($query['tag_ID']) ) ); } $args['order'] = 'DESC'; $args['orderby'] = 'relevance'; return $args; } /** * Modify ACF post_object select fields Post query * * @param array $args Args * @param array $field Field Array * @param int $post_id Post ID * * @return void */ public function acf_post_object_query($args, $field, $post_id) { $url = wp_get_referer(); $parts = parse_url($url); parse_str($parts['query'], $query); if (key_exists('taxonomy', $query) && key_exists('tag_ID', $query)) { $args['tax_query'] = array( 'relation' => 'OR', array( 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => intval($query['tag_ID']) ), array( 'taxonomy' => 'author', 'field' => 'term_id', 'terms' => intval($query['tag_ID']) ) ); } $args['order'] = 'DESC'; $args['orderby'] = 'relevance'; return $args; } /** * Templates and Page IDs without editor * * @param int $id Post ID * * @return bool If post's id is in excluded array */ public function postsToExcludeGutenberg($id = false) { $excluded_templates = array( 'page-about.php', 'page-home.php', 'page-support.php' ); $excluded_ids = array( // get_option( 'page_on_front' ) ); if (empty($id)) { return false; } $id = intval($id); $template = get_page_template_slug($id); return in_array($id, $excluded_ids) || in_array($template, $excluded_templates); } /** * Disable Gutenberg by template * * @param bool $can_edit Whether Gutenberg is used * @param string $post_type Custom post type * * @return bool Whether to enable Gutenberg */ public function disableGutenbergOnSpecificPosts($can_edit, $post_type) { if (! (is_admin() && !empty($_GET['post']))) { return $can_edit; } if ($this->postsToExcludeGutenberg($_GET['post'])) { $can_edit = false; } return $can_edit; } /** * Automatically sync any JSON field configuration. * * @return null */ public function sync_fields_with_json() { if (defined('DOING_AJAX') || defined('DOING_CRON')) { return; } if (! function_exists('acf_get_field_groups')) { return; } $groups = acf_get_field_groups(); if (empty($groups)) { return; } $sync = array(); foreach ($groups as $group) { $local = acf_maybe_get($group, 'local', false); $modified = acf_maybe_get($group, 'modified', 0); $private = acf_maybe_get($group, 'private', false); if ($local !== 'json' || $private) { // ignore DB / PHP / private field groups continue; } if (! $group['ID']) { $sync[ $group['key'] ] = $group; } elseif ($modified && $modified > get_post_modified_time('U', true, $group['ID'], true)) { $sync[ $group['key'] ] = $group; } } if (empty($sync)) { return; } foreach ($sync as $key => $v) { if (acf_have_local_fields($key)) { $sync[ $key ]['fields'] = acf_get_local_fields($key); } acf_import_field_group($sync[ $key ]); } } /** * Tell Algolia to use our own template instead of their default * * @param array $locations Locations * @param string $file File * * @return array */ public function algolia_template_locations(array $locations, $file) { if ($file === 'instantsearch.php') { $locations[] = 'page-search.php'; } return $locations; } }
4e137fe2044eeb084d77081c8bf2b5641e4e9f18
[ "JavaScript", "Markdown", "PHP" ]
39
PHP
INN/theme-cpi
7b8396fcf5328abf2a9261abe9910b832472ba1c
2a42c92826ab2e833456f8f919134f3532f24244
refs/heads/master
<repo_name>ConcepcionTransparente/ConcepcionTransparenteScrapper<file_sep>/README.md ConcepcionTransparenteScrapper ============================== Es un scrapper basado en [https://github.com/matthewmueller/x-ray](x-ray) desarrollado para procesar los datos abiertos provistos por la [http://www.cdeluruguay.gob.ar/datagov/proveedoresContratados.php]( Municipalidad de Concepción del Uruguay), concretamente lo relacionado a la información de proveedores contratados. La aplicación está diseñada como una long-running app que calendariza su propia ejecución de scrapping. <file_sep>/models.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var Float = require('mongoose-float').loadType(mongoose, 2); // Define models mongoose.model('Year', new Schema({ year: Number, numberOfContracts: Number, totalAmount: { type: Float }, budget: { type: Float } })); mongoose.model('Provider', new Schema({ cuil: Number, grant_title: String })); mongoose.model('Category', new Schema({ cod : String, category: String // Repartición })); mongoose.model('PurchaseOrder', new Schema({ year: String, month: String, date: Date, numberOfContracts: Number, // Cantidad de contrataciones import: { type: Float }, // Importe fk_Provider: {type: Schema.ObjectId, ref: "Provider"}, fk_Category: {type: Schema.ObjectId, ref: "Category"} })); <file_sep>/email-notify.js var mongoose = require('mongoose'); const nodemailer = require('nodemailer'); function sendEmailNotification(data) { var currentDate = new Date(); var nextExecutionDate = new Date(currentDate.getTime() + data.nextExecutionDelay); var emailHtmlContent = `<strong>Concepción Transparente - Scrapper</strong><br />` + `<br />` + `Scrapping completado a las: <b>${currentDate}</b><br />` + `Actualmente se cuenta en la base de datos con:<br />` + `<i>Cantidad de proveedores: ${data.cantidadProveedores}</i><br />` + `<i>Cantidad de órdenes de compra: ${data.cantidadOrdenesCompra}</i><br />` + `<br />` + `<br />` + `Siguiente scrapping programado para: <b>${nextExecutionDate}</b><br />`; var transporter = nodemailer.createTransport({ host: process.env.EMAIL_HOST, port: process.env.EMAIL_PORT, secure: true, auth: { user: process.env.EMAIL_USERNAME, pass: <PASSWORD> } }); var mailOptions = { from: process.env.EMAIL_SEND_FROM, to: process.env.EMAIL_SEND_TO, subject: 'Concepción Transparente - Scrapper', html: emailHtmlContent }; transporter.sendMail(mailOptions, function(error, info) { if (error) { return console.log(error); } console.log('Email notification sent: %s', info.messageId); }); } module.exports = function(nextExecutionDelay) { mongoose .connect(process.env.MONGODB_URI + '?socketTimeoutMS=90000') .then(function () { return mongoose .model('PurchaseOrder') .count() .exec() .then(function(cantidadOrdenesCompra) { return mongoose .model('Provider') .count() .exec() .then(function(cantidadProveedores) { mongoose.connection.close(); sendEmailNotification({ cantidadProveedores, cantidadOrdenesCompra, nextExecutionDelay }); }) }); }) .then(function() { console.log('Email notification completed'); }); } <file_sep>/app.js // Concepcion Transparente Scraper var time = require('node-tictoc'); var http = require('http'); require('./models'); require('dotenv').config(); var scrape = require('./scrape'); var emailNotify = require('./email-notify'); /** * Schedule a scraping involves performing the actual scraping and also setting the * next execution. * * @return {[type]} [description] */ function scheduleScraping() { scrape() .then(function() { // La siguiente ejecución se agenda para en cuatro horas $hours = 12; $minutes = 0; $seconds = 0; var nextExecutionDelay = ($hours * 60 * 60 * 1000) + ($minutes * 60 * 1000) + ($seconds * 1000); if (process.env.EMAIL_HOST) { emailNotify(nextExecutionDelay); } setTimeout(function() { scheduleScraping(); }, nextExecutionDelay) }); } scheduleScraping(); // Connect to port to allow Heroku consider this as a running app var server = http.createServer(); /** * Event listener for HTTP server "error" event. */ function onError(error) { if (error.syscall !== 'listen') { throw error; } var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use'); process.exit(1); break; default: throw error; } } /** * Event listener for HTTP server "listening" event. */ function onListening() { var addr = server.address(); var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; console.log('Listening on ' + bind); } /** * Normalize a port into a number, string, or false. */ function normalizePort(val) { var port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } var port = normalizePort(process.env.PORT || '3000'); server.listen(port); server.on('error', onError); server.on('listening', onListening); <file_sep>/scrape.js var error = []; var Xray = require('x-ray'); var mongoose = require('mongoose'); function printMemoryUsage() { console.log('---------------------'); console.log('Memory usage:') const used = process.memoryUsage(); for (var key in used) { console.log(`${key} ${Math.round(used[key] / 1024 / 1024 * 100) / 100} MB`); } console.log('---------------------'); } // Throttle the requests to n requests per ms milliseconds. var requestPerSecond = parseInt(process.env.REQUEST_PER_SECOND) || 5; console.log('Initializing x-ray with ' + requestPerSecond + ' request per second'); var x = Xray().throttle(requestPerSecond, 1000); var findOneAndUpdateOptions = { upsert: true, new: true, setDefaultsOnInsert: true }; function monthStringToNumber(m) { if (m == 'Enero') { return 0; } else if (m == 'Febrero') { return 1; } else if (m == 'Marzo') { return 2; } else if (m == 'Abril') { return 3; } else if (m == 'Mayo') { return 4; } else if (m == 'Junio') { return 5; } else if (m == 'Julio') { return 6; } else if (m == 'Agosto') { return 7; } else if (m == 'Septiembre') { return 8; } else if (m == 'Octubre') { return 9; } else if (m == 'Noviembre') { return 10; } else if (m == 'Diciembre') { return 11; } else { return 13; } } function parseImporteStringAsFloat(m) { var y = m.replace(/\./g, '').replace(/\,/g, '.'); y = parseFloat(y); return y; } // Convert month and year in date function stringToDate(month, year) { // new Date(year, month, day, hours, minutes, seconds, milliseconds) var d = new Date(year, month, 1, 0, 0, 0, 0); d.toISOString().slice(0, 10); return d; } function procesarAnio(lineaAnio) { return x(lineaAnio.href, 'body tr.textoTabla', [{ cuil: 'td', // CUIL proveedor: Código único de identificación laboral grant_title: 'td:nth-of-type(2)', // Nombre de fantasia del proveedor total_contrats: 'td:nth-of-type(4)', // Cantidad de contrataciones en ese año href: 'td:nth-of-type(8) a@href' // a@href a Ver por rubros }]) .then(function(lineasProveedor) { if (lineasProveedor == null) { error.push(lineasProveedor); return; } if (process.env.MAX_PROVEEDORES_POR_ANIO) { lineasProveedor = lineasProveedor.slice(0, parseInt(process.env.MAX_PROVEEDORES_POR_ANIO)); } return Promise.all( // The second argument to the map function refers the whatever it is going // to be referenced by 'this' on the invoked function. // See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map lineasProveedor.map(procesarProveedorDeAnio, { year: lineaAnio.year, total_amount: lineaAnio.total_amount }) ); }) .catch(function(error) { console.log('Got error while executing procesarAnio'); console.log(error); }); } function procesarProveedorDeAnio(lineaProveedor) { var parentObject = this; return x(lineaProveedor.href, 'body tr.textoTabla', [{ cod: 'td', // Código del rubro category: 'td:nth-of-type(2)', // Nombre del rubro href: 'td:nth-of-type(7) a@href' // a@href a Meses }]) .then(function(lineasRubros) { if (lineasRubros == null) { error.push(lineasRubros); return; } if (process.env.MAX_RUBROS_POR_PROVEEDOR) { lineasRubros = lineasRubros.slice(0, parseInt(process.env.MAX_RUBROS_POR_PROVEEDOR)); } return Promise.all( lineasRubros.map(procesarRubroDeProveedor, { provider: lineaProveedor, year: parentObject.year, total_amount: parentObject.total_amount }) ); }) .catch(function(error) { console.log('Got error while executing procesarProveedorDeAnio'); console.log(error); }); }; function procesarRubroDeProveedor(lineaRubro) { var parentObject = this; return x(lineaRubro.href, 'body tr.textoTabla', [{ month: 'td', // Mes numberOfContracts: 'td:nth-of-type(2)', // Cantidad de contratos import: 'td:nth-of-type(4)' // Importe para ese mes }]) .then(function(lineasMeses) { if (lineasMeses == null) { error.push(lineasMeses); return; } if (process.env.MAX_MESES_POR_RUBRO) { lineasMeses = lineasMeses.slice(0, parseInt(process.env.MAX_MESES_POR_RUBRO)); } return Promise.all( lineasMeses.map(persistir, { category: lineaRubro, provider: parentObject.provider, year: parentObject.year, total_amount: parentObject.total_amount }) ); }) .catch(function(error) { console.log('Got error while procesarRubroDeProveedor'); console.log(error); }); }; function updateCategoria(proveedor, categoria, childObject) { var monthNumber = monthStringToNumber(childObject.month); var newDate = stringToDate(monthNumber, childObject.year); // Importe de un proveedor en un cierto mes var partialImport = parseFloat( parseImporteStringAsFloat(childObject.import) ); // Insertar orden de compra return mongoose .model('PurchaseOrder') .findOneAndUpdate( { year: childObject.year, month: monthNumber, date: newDate, numberOfContracts: childObject.numberOfContracts, import: partialImport, fk_Provider: proveedor._id, fk_Category: categoria._id }, { year: childObject.year, month: monthNumber, date: newDate, numberOfContracts: childObject.numberOfContracts, import: partialImport, fk_Provider: proveedor._id, fk_Category: categoria._id }, { upsert: true, new: false, setDefaultsOnInsert: true } ) .exec() .then(function(purchaseOrder) { if (purchaseOrder) { console.log('Orden de compra actualizada'); } else { console.log('Orden de compra creada'); } }) .catch(function(error) { console.log('Got error while updating PurchaseOrder'); console.log(error); }); } function updateProvider(proveedor, childObject) { // Insertar categoría return mongoose .model('Category') .findOneAndUpdate( { category: childObject.category }, { cod: childObject.cod, category: childObject.category }, findOneAndUpdateOptions ) .exec() .then(function(categoria) { console.log('Categoría persistida: ' + childObject.category); printMemoryUsage(); return updateCategoria(proveedor, categoria, childObject); }) .catch(function(error) { console.log('Got error while calling updateCategoria'); console.log(error); }); } function persistir(lineaMes) { var parentObject = this; var year = parseInt(parentObject.year); // Año var childObject = { year: year, // Year cuil: parentObject.provider.cuil, // Proveedor grant_title: parentObject.provider.grant_title, // Proveedor total_amount: parentObject.total_amount, // Importe de ese proveedor en UN AÑO total_contrats: parentObject.provider.total_contrats, // Cantidas de contrataciones en UN AÑO cod: parentObject.category.cod, // Codigo del rubro category: parentObject.category.category, // Nombre del rubro (reparticion) month: lineaMes.month, // Mes numberOfContracts: lineaMes.numberOfContracts, // Cantidad de contratos para ese mes import: lineaMes.import // Importe en ese mes }; // Importe total para el años correspondiente a esta fila var totalImport = parseFloat( parseImporteStringAsFloat(childObject.total_amount) ); // See: http://mongoosejs.com/docs/4.x/docs/api.html var updateProviderPromise = mongoose .model('Provider') .findOneAndUpdate( { cuil: childObject.cuil }, { cuil: childObject.cuil, grant_title: childObject.grant_title }, findOneAndUpdateOptions ) .exec() .then(function(proveedor) { console.log('Proveedor persistido: ' + childObject.grant_title); printMemoryUsage(); return updateProvider(proveedor, childObject); }) .catch(function(error) { console.log('Got error while calling updateProvider'); console.log(error); }); var updateYearPromise = mongoose .model('Year') .findOneAndUpdate( { year: childObject.year }, { year: childObject.year, total_contrats: childObject.total_contrats, totalAmount: totalImport }, findOneAndUpdateOptions ) .exec() .then(function() { console.log('Anio persistdo: ' + childObject.year); printMemoryUsage(); }) .catch(function(error) { console.log('Got error while updating Year'); console.log(error); }); return Promise.all([updateProviderPromise, updateYearPromise]); }; module.exports = function() { console.log('Inicializando scrapping.'); return mongoose .connect(process.env.MONGODB_URI + '?socketTimeoutMS=90000') .then(function () { console.log('Successfully connected to server'); var url = 'http://www.cdeluruguay.gob.ar/datagov/proveedoresContratados.php'; // Reporte: Proveedores Contratados return x(url, 'body tr.textoTabla', [{ year: 'td', // Año total_amount: 'td:nth-of-type(4)', // Total de importe de ese año href: 'td:nth-of-type(8) a@href' // a@href a Ver por proveedores }]) .then(function(lineasAnios) { if (process.env.MAX_ANIOS) { lineasAnios = lineasAnios.slice(0, parseInt(process.env.MAX_ANIOS)); } return Promise.all(lineasAnios.map(procesarAnio)); }) .then(function () { console.log('Done. Closing connection.'); printMemoryUsage(); // En este punto es seguro cerrar la conexión de Mongoose porque se supone // que ya todo lo que se tenía que hacer se hizo mongoose.connection.close(); }) .catch(function(error) { console.log('Got error while parsing report'); console.log(error); }); }) .catch(function (error) { console.log('Unable to connect to the server. Please start the server.') console.log(error); return; }); };
c04548757ca2660b0f2267d68cb49db4ee7b30bf
[ "Markdown", "JavaScript" ]
5
Markdown
ConcepcionTransparente/ConcepcionTransparenteScrapper
33bea6a1ffbb23fc28777cb4946202df05e71cce
2a928cac0a9fc4b1f309bc76f03f7a3dfaa66ec9
refs/heads/master
<file_sep>/**** Filename: Find tests Version: 1.0 Notes: Todos: ****/ const assert = require('chai').assert; var Dbhelper = require('../index.js'); var testDb = new Dbhelper('mongodb://localhost:27017', 'sas-dbhelper'); describe('Db Helper', function () { /**** BLOCK 1: Query tests ****/ it('"Create" creates an object in the database.', function() { return new Promise ( (resolve, reject) => { testDb.create({email: '<EMAIL>', password: '<PASSWORD>', collection: 'testDB'}, (obj, wasCreated) => { assert.equal(wasCreated, true, 'wasCreated should equal true.'); assert.typeOf(obj, 'object', 'Response data should be an object.'); resolve(); }); }) }); it('"DeleteOne" deletes an object.', function (done) { testDb.deleteOne({email: '<EMAIL>', password: '<PASSWORD>', collection: 'testDB'}, (obj) => { assert.notEqual(obj, false, "Response object should be true."); done(); }); }); it('"FindOne" finds one object in the database.', function(done) { testDb.create({email: '<EMAIL>', password: '<PASSWORD>', collection: 'testDB'}, (obj, wasCreated) => { assert.equal(wasCreated, true, 'wasCreated should equal true.'); testDb.findOne({email: '<EMAIL>', password: '<PASSWORD>', collection: 'testDB'}, (obj, wasCreated) => { assert.typeOf(obj, 'object', 'Response data should be an object.'); assert.include(obj, {email: '<EMAIL>', password: '<PASSWORD>'}, 'Response object should include keys "email" and "password"'); done(); }); }); }); it('"Find" find all objects in the database that match.', function(done) { testDb.find({email: '<EMAIL>', collection: 'testDB'}, (array, wasCreated) => { assert.typeOf(array, 'array', 'Response data should be an array of objects.'); assert.include(array[0], {email: '<EMAIL>', password: '<PASSWORD>'}, 'Response array should include an object with keys "email" and "password"'); done(); }); }); it('"findOrCreate" finds an object found in the db.', function (done) { testDb.findOrCreate({email: '<EMAIL>', password: "<PASSWORD>", collection: 'testDB'}, (obj, wasCreated) => { assert.equal(wasCreated, false) assert.typeOf(obj, 'object', 'Response data should be an object.'); assert.include(obj, {email: '<EMAIL>', password: '<PASSWORD>'}, 'Response object should include keys "email" and "password"'); done(); }); }); it('"findOrCreate" creates an object.', function (done) { testDb.findOrCreate({email: '<EMAIL>', password: '<PASSWORD>', collection: 'testDB'}, (obj, wasCreated) => { assert.equal(wasCreated, true) assert.typeOf(obj, 'object', 'Response data should be an object.'); done(); }); }); it('"Update" updates an object.', function (done) { testDb.updateOne({email: '<EMAIL>', password: '<PASSWORD>', collection: 'testDB'}, {email: '<EMAIL>', password: '<PASSWORD>'}, (obj, wasUpdated) => { assert.equal(wasUpdated, true); assert.typeOf(obj, 'object', 'Response data should be an object.'); done(); }); }); /**** BLOCK 2: .validate tests ****/ it('"Validate" validates an object against a schema.', function () { testDb.schema({ email: {type: 'string'}, password: {type: 'string'} }); return new Promise( (resolve, reject) => { resolve(testDb.validate({email: '<EMAIL>', password: '<PASSWORD>'})); }) .then( obj => { assert.typeOf(obj, 'object'); }) }); it('"Validate" returns an error when required field isn\'t supplied.', function (done) { testDb.schema({ email: {type: 'string'}, password: {type: 'string', required: true} }) testDb.validate({email: '<EMAIL>'}) .catch(err => { assert.typeOf(err, 'error'); done(); }) }); it('"Validate" sets password to default value if required is set to true.', function () { testDb.schema({ email: {type: 'string'}, password: {type: 'string', required: true, default: "<PASSWORD>"} }) return new Promise( (resolve, reject) => { resolve(testDb.validate({email: '<EMAIL>'})); }) .then( obj => { assert.typeOf(obj, 'object'); assert.equal(obj.password, '<PASSWORD>'); }) }); it('"Validate" returns type error when value type does not match the one set in schema.', function (done) { testDb.validate({email: '<EMAIL>', password: <PASSWORD>}) .catch(err => { assert.typeOf(err, 'error'); done(); }) }); /**** BLOCK 3: Clean collection tests ****/ it('Cleans test collection.', function () { return new Promise( (resolve, reject) => { testDb.deleteOne({email: '<EMAIL>', password: '<PASSWORD>', collection: 'testDB'}, (obj) => { assert.notEqual(obj, true, "Response object should be true."); resolve(obj); }); }) .then( () => { testDb.deleteOne({email: '<EMAIL>', password: '<PASSWORD>', collection: 'testDB'}, (obj) => { assert.notEqual(obj, false, "Response object should be true."); }); }) }); }); <file_sep># DB Helper Db helper is a lightweight wrapper for common db actions that wraps around MongoDB and uses Redis for caching. Db helper is a project package by the [Suits & Sandals](https://suits-sandals.com/) team. ### Warning Db helper is currently in beta and not suitable for production. ### Prerequisites To begin, Dbhelper uses Redis & Mongo as a dependency. Make sure you have downloaded, installed, and running Redis in your environment. ``` brew install redis ``` Once installed run the following command: ``` redis-server ``` Db helper will also require you to install and run mongodb. For instructions on setting that up visit the MongoDb docs here: (https://docs.mongodb.com/manual/installation/) ### Installing Now that Db helper's dependencies have been installed download and install the db helper npm package to your local project. ``` npm install dbhelper --save ``` This will install Db helper to your local project's modules. ## Usage To use Db helper import it at the top of your file: ``` var Dbhelper = require('sas-dbhelper'); ``` Then create a dbhelper object and pass in your Mongo connection url & database name like so: ``` var User = new Dbhelper('YOUR MONGO URL', 'YOUR DBNAME'); ``` Db helper comes bundled with database query wrappers for Mongo and Redis. When Redis querying is turned on, db helper will use Redis as a cache: Querying Redis first for the data, and if it not present querying mongo for the data. If data is found in mongo, db helper will cache it to Redis for future requests. Since Db helper is wrapped around the Mongo native driver for Node, many of the commands will be similar to Mongo native API with one exception: Db helper expects all commands to be passed with a callback to return the data to your app. ~~Because Db helper is a schema-less wrapper, you must be thoughtful of how you store data in Mongo and Redis to ensure consistent data.~~ Optional schema API available as of version 0.2.0 ### Available Commands The following commands are available to you: find, findOne, findOrCreate (no caching), create, updateOne, deleteOne, deleteMany (no caching) To use caching for find, findOne, create, updateOne, & deleteOne commands you must pass in the options object with a key 'cache' set to 'true'. You will also need to name the key you'd like to [get]('https://redis.io/commands/get') or [set]('https://redis.io/commands/set') in case that the value does not yet exist in your Redis instance. You may also pass in other options in accordance to [Mongo Native's docs]('http://mongodb.github.io/node-mongodb-native/3.0/api/'). #### find To run a find query using db helper WITHOUT caching use: ``` User.find(query = {email: "<EMAIL>", collection: "users"}, callback, options); //Returns data as an object ``` To run a find query WITH caching use: ``` User.find(query = {email: "<EMAIL>", collection: "users"}, callback, options = {cache: true, key: "<EMAIL>"}); //Returns data as an object ``` #### findOne To run a find query using db helper WITHOUT caching use: ``` User.findOne(query = {email: "<EMAIL>", collection: "users"}, callback, options); //Returns data as an object ``` To run a find query WITH caching use: ``` User.findOne(query = {email: "<EMAIL>", collection: "users"}, callback, options = {cache: true, key: "<EMAIL>"}); //Returns data as an object ``` #### findOrCreate This command will return two things: A boolean indicating whether or not your object was saved to the db & the object that was found/saved. To run a find or create query using Db helper use: ``` User.findOrCreate({email: '<EMAIL>', collection: 'user'}, callback, options) ``` The variable ```data```, in this example, is what we want to save to the database should the object not be found. #### create This command will return two things: A boolean indicating whether or not your object was saved to the db & the object that was saved. To run a create query using Db helper use: ``` User.create({email: '<EMAIL>', collection: 'user'}, callback, options) ``` NOTE: ```create``` now internally uses ```insertOne``` see [Mongo Native Docs]('http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#insertOne') for more on optional usage instructions. #### updateOne To run an update query using db helper WITHOUT caching use: ``` User.updateOne(query = {email: "<EMAIL>", collection: "users"}, data = {email: "<EMAIL>"}, callback, options); //Returns modified data as an object ``` To run a find query WITH caching use: ``` User.updateOne(query = {email: "<EMAIL>", collection: "users"}, data = {email: "<EMAIL>"}, callback, options = {cache: true, key: "<EMAIL>"}); //Returns modified data as an object ``` NOTE: ```updateOne``` now internally uses ```findOneAndUpdate``` see [Mongo Native Docs]('http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#findOneAndUpdate') for more on optional usage instructions. #### deleteOne To delete an object from your db WITHOUT caching use: ``` User.deleteOne(query = {email: "<EMAIL>", collection: "users"}, callback, options); ``` To delete an object from your db WITH caching use: ``` User.deleteOne(query = {email: "<EMAIL>", collection: "users"}, callback, options = {cache: true, key: "<EMAIL>"}); ``` ### Schemas As of version 0.2.0 of Db helper, you are now free to define a schema object and have it enforced against any query that creates or updates. To define a schema first create an object like so: ``` let mySchemaObj = { email: 'string', password: {required: 'true', type: 'string'}, phone: {type: 'number', default: '5515555555'} } ``` Then pass your schema object to your declared Db helper object like so: ``` User.schema(mySchemaObj); ``` Now to enforce schema, pass an options object in whatever create or update query you're making like so: ``` User.updateOne(query = {email: "<EMAIL>", collection: "users"}, data = {email: "<EMAIL>"}, callback, options = {schema: true}); ``` ### Relationships As of version 0.3.0 of Db helper you may now define a One-to-One relationship with Db helper using the ```via``` key when defining your schema, like so: ``` var mySchemaObj = { email: 'string', password: {required: 'true', type: 'string'}, phone: {type: 'number', default: '5515555555'}, createdBy: {default: '', via: 'user'} } ``` The example above added the ```via``` flag to the key of createdBy. Now when an ObjectId as a string is passed to it, it will query your collection (as defined by the ```via``` key) and append the key with the result. ### Validate Version 0.4.0 of Db helper exposes the internal function ```.validate(object)```. This function validates the object passed to it against your schema. It returns the validated object making modifications to any key that has a schema value object with a ```via``` key. It will also create a key if it is ```required``` and has a ```default``` value set in the schema but isn't present in the object being validated. <file_sep>var mongodb = require('mongodb'); var ObjectId = require('mongodb').ObjectId; var redis = require('redis'), client = redis.createClient(); const MongoClient = require('mongodb').MongoClient; module.exports = class Dbhelper { constructor(url, dbName) { this.url = url; this.dbName = dbName; this.schemaObj; } schema (schemaObj) { if (typeof schemaObj == 'object') { this.schemaObj = schemaObj; } else { throw new Error("Schema must be of type object."); } } async validate (obj) { let schema = this.schemaObj; let schemaKeys = Object.keys(schema); let objKeys = Object.keys(obj); objKeys.forEach(key => { //Validates data types if (schema[key] == undefined) { throw new Error(`Schema validation error. '${key}' not found in the Schema`); } else { if (typeof schema[key] == 'object'){ if (typeof obj[key] !== schema[key].type) throw new Error(`Data type mismatch. Data for '${key}' is not a ${schema[key].type}`); } else { if (typeof obj[key] !== schema[key]) throw new Error(`Data type mismatch. Data for '${key}' is not a ${schema[key]}`); } } }); for(let index = 0; index < schemaKeys.length; index++){// Validates optional rules let key = schemaKeys[index]; if (schema[key].required && objKeys.indexOf(key) === -1) { if (schema[key].default || schema[key].default == '') { obj[key] = schema[key].default; } else { throw new Error(`Schema validation error. Missing required key of '${key}'`); } } if (schema[key].via) { let ObjectId = require('mongodb').ObjectId; let id = new ObjectId(obj[key]); let keyId = '_id'; let filter = {collection: schema[key].via}; filter[keyId] = id; await new Promise( (resolve, reject) => { this.findOne(filter, response => { resolve(response); }) }) .then( response => obj[key] = response) } } return obj; } find (query = {}, cb, options = {}) { let mongoQuery = (query, options, cb) => { let url = this.url; MongoClient.connect(url, (err, client) => { if (err) throw err; let dbName = this.dbName; let db = client.db(dbName); let collection = db.collection(query.collection); ['collection'].forEach(key => delete query[key]); ['cache', 'key', 'schema'].forEach(key => delete options[key]); collection.find(query, options).toArray(function (err, data) { if (err) throw err; cb(data); client.close(); }); }); }; let redisQuery = (query, options, cb) => { client.get(options.key, function (err, reply) { switch (true) { case err: throw err; break; case !reply: let key = options.key; mongoQuery(query, options, function (data) { let dataString = JSON.stringify(data); client.set(key, dataString, 'EX', 84600); cb(data); }); break; default: cb(JSON.parse(reply)); } }); }; if (options.cache == false || options.cache == undefined) { mongoQuery(query, options, function (payload) { cb(payload); }); } else if (options.cache) { if (!options.key) throw new Error("Cache key not present."); redisQuery(query, options, function (payload) { cb(payload); }); } } findOne (query, cb, options = {}) { let mongoQuery = (query, options, cb) => { let url = this.url; MongoClient.connect(url, (err, client) => { if (err) throw err; let dbName = this.dbName; let db = client.db(dbName); let collection = db.collection(query.collection); ['collection'].forEach(key => delete query[key]); options ? ['cache', 'key', 'schema'].forEach(key => delete options[key]) : options = {}; collection.findOne(query, options, function (err, obj) { if (err) throw err; cb(obj); client.close(); }); }); }; let redisQuery = (query, options, cb) => { client.get(options.key, function (err, reply) { switch (true) { case err: throw err; break; case !reply: let key = options.key; mongoQuery(query, options, function (data) { let dataString = JSON.stringify(data); client.set(key, dataString, 'EX', 84600); cb(data); }); break; default: cb(JSON.parse(reply)); } }); }; if (options.cache == false || options.cache == undefined) { mongoQuery(query, options, function (payload) { cb(payload); }); } else if (options.cache) { if (!options.key) throw new Error("Cache key not present."); redisQuery(query, options, function (payload) { cb(payload); }); } } findOrCreate (data, cb, options = {}) { if (options.cache == undefined) { let url = this.url; MongoClient.connect(url, async (err, client) => { if (err) throw err; let dbName = this.dbName; let db = client.db(dbName); let collection = db.collection(data.collection); ['collection'].forEach(key => delete data[key]); ['cache', 'key'].forEach(key => delete options[key]); if (options.schema) { delete options.schema; await new Promise( (resolve, reject) => { resolve(this.validate(data)); }) .then( payload => data = payload) } collection.findOne(data, options, function (err, obj) { if (err) throw err; if (obj == null) { collection.insertOne(data, options, function (err, obj) { if (err) throw err; cb(obj, true); client.close(); }); } else { cb(obj, false); client.close(); } }); }); } else if (options.key) { client.get(options.key, function (err, data) { if (err) throw err; cb(data); }); } } create (data, cb, options = {}) { let mongoQuery = (query, options, cb) => { let url = this.url; MongoClient.connect(url, async (err, client) => { if (err) throw err; let dbName = this.dbName; let db = client.db(dbName); let collection = db.collection(query.collection); ['collection'].forEach(key => delete query[key]); ['cache', 'key'].forEach(key => delete options[key]); if (options.schema) { delete options.schema; await new Promise( (resolve, reject) => { resolve(this.validate(data)); }) .then( payload => data = payload) } collection.insertOne(data, options, function (err, obj) { if (err) throw err; cb(obj, true); client.close(); }); }); }; let redisQuery = (data, options, cb) => { client.get(options.key, function (err, reply) { switch (true) { case err: throw err; break; case !reply: let key = options.key; mongoQuery(data, options, function (data, wasCreated) { if (wasCreated){ let dataString = JSON.stringify(data); client.set(key, dataString, 'EX', 84600); cb(data, true); } }); break; default: cb(JSON.parse(reply), true); } }); }; if (Object.keys(options).length == 0 || options.cache == false) { mongoQuery(data, options, function (payload) { cb(payload, true); }); } else if (options.cache) { if (!options.key) throw new Error("Cache key not present."); redisQuery(data, options, function (payload, wasCreated) { if (wasCreated) cb(payload, true); }); } } updateOne (query, data, cb, options = {}) { let mongoQuery = (query, data, options, cb) => { let url = this.url; MongoClient.connect(url, async (err, client) => { if (err) throw err; let dbName = this.dbName; let db = client.db(dbName); let collection = db.collection(query.collection); ['collection'].forEach(key => delete query[key]); ['cache', 'key'].forEach(key => delete options[key]); if (options.schema) { delete options.schema; await new Promise( (resolve, reject) => { resolve(this.validate(data)); }) .then( payload => data = payload) } let filter = {}; filter["$set"] = data; collection.findOneAndUpdate(query, filter, options, function (err, obj) { if (err) throw err; obj.value == null ? cb(obj, false) : cb(obj, true); client.close(); }); }); }; let redisQuery = (query, data, options, cb) => { client.get(options.key, function (err, reply) { switch (true) { case err: throw err; break; case !reply: let key = options.key; mongoQuery(query, data, options, function (data) { let dataString = JSON.stringify(data); client.set(key, dataString, 'EX', 84600); cb(data, true); }); break; default: cb(JSON.parse(reply), true); } }); }; if (options.cache == false || options.cache == undefined) { mongoQuery(query, data, options, function (payload, wasCreated) { wasCreated ? cb(payload, true): cb(payload, false); }); } else if (options.cache) { if (!options.key) throw new Error("Cache key not present."); redisQuery(query, data, options, function (payload, wasCreated) { wasCreated ? cb(payload, true): cb(payload, false); }); } } deleteOne (query, cb, options = {}) { let mongoQuery = (query, options, cb) => { let url = this.url; MongoClient.connect(url, (err, client) => { if (err) throw err; let dbName = this.dbName; let db = client.db(dbName) let collection = db.collection(query.collection); ['collection'].forEach(key => delete query[key]); ['cache', 'key', 'schema'].forEach(key => delete options[key]); collection.deleteOne(query, function (err, obj) { if (err) throw err; obj == null ? cb(false) : cb(obj); client.close(); }); }); }; let redisQuery = (query, data, options, cb) => { let deletedObj = mongoQuery(query, data, options, cb); deletedObj ? (client.del(options.key), cb(true)) : cb(false); } if (options.cache == false || options.cache == undefined ) { mongoQuery(query, options, function (payload) { cb(payload); }); } else if (options.cache) { if (!options.key) throw new Error("Cache key not present."); redisQuery(query, options, function (payload) { cb(payload); }); } } deleteAll (query, cb, options = {}) { let url = this.url; MongoClient.connect(url, (err, client) => { if (err) throw err; let dbName = this.dbName; let db = client.db(dbName); let collection = db.collection(query.collection); ['collection'].forEach(key => delete query[key]); ['cache', 'key', 'schema'].forEach(key => delete options[key]); collection.deleteMany({}, options, function (err, obj) { if (err) throw err; cb(obj); client.close(); }); }); } }
b1073ea971db74ae1f15a43551c1deaac870a4e9
[ "JavaScript", "Markdown" ]
3
JavaScript
suits-sandals/dbhelper
a3772e83b00ebf350419eae5e2979173ed344b72
5f9e2e805fd5bbf7bb8479e86246f94b028c32f9
refs/heads/master
<repo_name>aswathysaji/django-todo-app<file_sep>/notes/migrations/0004_auto_20200909_2117.py # Generated by Django 3.1.1 on 2020-09-09 15:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('notes', '0003_auto_20200909_2111'), ] operations = [ migrations.AlterField( model_name='task', name='completed', field=models.BooleanField(default=False), ), migrations.AlterField( model_name='task', name='created', field=models.DateField(auto_now_add=True), ), ] <file_sep>/notes/migrations/0005_task_deadline.py # Generated by Django 3.1.1 on 2020-09-10 06:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('notes', '0004_auto_20200909_2117'), ] operations = [ migrations.AddField( model_name='task', name='deadline', field=models.DateTimeField(default=False), ), ] <file_sep>/notes/migrations/0006_remove_task_deadline.py # Generated by Django 3.1.1 on 2020-09-10 06:29 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('notes', '0005_task_deadline'), ] operations = [ migrations.RemoveField( model_name='task', name='deadline', ), ]
f46e9fe957f72cf8524c2a9f15eaee884968b547
[ "Python" ]
3
Python
aswathysaji/django-todo-app
08273aee4d1132c7ad45948d41aa27b46dc053e4
f1e1d521d04e247edc3919baa096d27e5f082b08
refs/heads/master
<repo_name>navikt/esi-dev-proxy<file_sep>/index.js const proxy = require('express-http-proxy'); const app = require('express')(); const ESI = require('nodesi'); const esi = new ESI(); app.use('/', proxy(process.env.ORIGIN, { userResDecorator: function(proxyRes, proxyResData, userReq, userRes) { return Promise.resolve() .then(function() { //console.log(proxyRes.headers['content-type']); if (proxyRes.headers['content-type'] && proxyRes.headers['content-type'].indexOf('text/html') > -1) { return esi.process(proxyResData.toString()); } return proxyResData; }); } })); app.listen(process.env.PORT, () => { console.log(`Proxying on port: ${process.env.PORT}`); });<file_sep>/README.md # Development purposes only. On production it is recommended to use Varnish or Ngnix ## Running ``` npm install npm run start-default ```
ac644ba5ebec38faa21ff8606d0ba1818a3237e1
[ "JavaScript", "Markdown" ]
2
JavaScript
navikt/esi-dev-proxy
8b2c9fd0f31a6904edf28c6615c511082cf7f6d3
a5a2332cd9dadb5a1af251830bca2a6ffa61eb38
refs/heads/master
<file_sep>//----------------------------------------------------------------------- // <copyright file="TestKit.cs" company="Akka.NET Project"> // Copyright (C) 2009-2016 Typesafe Inc. <http://www.typesafe.com> // Copyright (C) 2013-2017 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using Akka.Actor; using Akka.Configuration; namespace Akka.TestKit.MSTestV2 { public class TestKit : TestKitBase { private static readonly MSTestAssertions _assertions = new MSTestAssertions(); /// <summary> /// Create a new instance of the <see cref="TestKit"/> for the test class. /// If no <paramref name="system"/> is passed in, a new system /// with <see cref="DefaultConfig"/> will be created. /// </summary> /// <param name="system">Optional: The actor system.</param> public TestKit(ActorSystem system = null) : base(_assertions, system) { //Intentionally left blank } /// <summary> /// Create a new instance of the <see cref="TestKit"/> for the test class. /// A new system with the specified configuration will be created. /// </summary> /// <param name="config">The configuration to use for the system.</param> /// <param name="actorSystemName">Optional: the name of the system. Default: "test"</param> public TestKit(Config config, string actorSystemName = null) : base(_assertions, config, actorSystemName) { //Intentionally left blank } /// <summary> /// Create a new instance of the <see cref="TestKit"/> for the test class. /// A new system with the specified configuration will be created. /// </summary> /// <param name="config">The configuration to use for the system.</param> public TestKit(string config) : base(_assertions, ConfigurationFactory.ParseString(config)) { //Intentionally left blank } public new static Config DefaultConfig { get { return TestKitBase.DefaultConfig; } } public new static Config FullDebugConfig { get { return TestKitBase.FullDebugConfig; } } protected static MSTestAssertions Assertions { get { return _assertions; } } } } <file_sep>#### 1.3.1 September 24 2017 #### First release - Support for Akka.NET 1.3.1<file_sep>//----------------------------------------------------------------------- // <copyright file="TestKitTests.cs" company="Akka.NET Project"> // Copyright (C) 2009-2016 Typesafe Inc. <http://www.typesafe.com> // Copyright (C) 2013-2017 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using Akka.Actor; using Akka.TestKit.TestActors; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Akka.TestKit.MSTestV2.Tests { [TestClass] public class TestKitTestFixtureTests : TestKit { [TestMethod] public void Can_create_more_than_one_test_in_a_fixture_with_the_same_actor_name_test1() { Sys.ActorOf<BlackHoleActor>("actor-name"); } [TestMethod] public void Can_create_more_than_one_test_in_a_fixture_with_the_same_actor_name_test2() { Sys.ActorOf<BlackHoleActor>("actor-name"); } } } <file_sep># Akka.TestKit.MSTestV2 This is the MSTestV2 TestKit integration plugin for Akka.NET. Please check out our documentation for examples on how to create and run tests using this plugin.
653b41e77713323ea8eeed39d99f2fb23080ff74
[ "Markdown", "C#" ]
4
C#
dwalleck/Akka.TestKit.MSTestV2
fb9da7e907a9937e4a682ddcd56120486c7f067c
2f994732d153f0e6334954a1814a08f08a6fe2b7
refs/heads/master
<file_sep>// <form action=""> // <input type="radio" name="state" value="0.0825">CA<br> // // <input type="radio" name="gender" value="female"> Female<br> // // <input type="radio" name="gender" value="other"> Other // </form> $( document ).ready(function() { function calcul() { var tax = $('input[name=state]:checked').val(); var qtt = $('#qtt').val() var result = $('#price').val() var result_notax = result * qtt if (result_notax > 50000) { result_notax = result_notax * 0.85 } result = result_notax * (1 - tax) $('#result').val(result) } $("input[name=state]:radio").change(function () { calcul() }) $('#price').on('input',function(e){ calcul() }); $('#qtt').on('input',function(e){ calcul() }); });
9fc173068dbcc43288b0260ecfea86c917e6ab95
[ "JavaScript" ]
1
JavaScript
tmdzk/zenika-quincaillerie
34e363df32a0c1f6b38296a9c0338860e0732353
bad0a388b541e2263f5394cc5ba9ec35558d181d
refs/heads/master
<repo_name>ekhtiar1971/HBOFrameWork<file_sep>/HBO/src/test/java/testHomePage/TestSearch.java package testHomePage; import base.CommonAPI; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.Test; //import pages.SearchPage; import pages.SearchPageForSQLDB; import reporting.TestLogger; import java.io.IOException; import java.sql.SQLException; public class TestSearch extends CommonAPI { @Test public void searchItemsDB () throws Exception, IOException, SQLException, ClassNotFoundException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); SearchPageForSQLDB searchPageForSQLDB = PageFactory.initElements(driver, SearchPageForSQLDB.class); searchPageForSQLDB.searchItemsAndSubmitButton(); } } <file_sep>/HBO/src/test/java/testHomePage/TestMouseOverHandle.java package testHomePage; import homePage.MouseOverHandle; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class TestMouseOverHandle extends MouseOverHandle { MouseOverHandle mo; @BeforeMethod public void getInformation(){mo=PageFactory.initElements(driver,MouseOverHandle.class);} @Test public void testMouseOver()throws InterruptedException{ mo.mouseOverForSports(); } } <file_sep>/HBO/src/main/java/homePage/MouseOverHandle.java package homePage; import base.CommonAPI; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.FindBy; public class MouseOverHandle extends CommonAPI { @FindBy(linkText = "Sports") WebElement findSports; public void mouseOverForSports()throws InterruptedException{ findSports.click(); Actions action=new Actions(driver); action.moveToElement(driver.findElement(By.linkText("NFL"))).build().perform(); Thread.sleep(2000); driver.findElement(By.linkText("Buffalo")).click(); } } <file_sep>/HBO/src/main/java/pages/XcelElement.java package pages; import base.CommonAPI; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import reporting.TestLogger; import java.util.List; //import reporting.TestLogger; public class XcelElement extends CommonAPI { @FindBy(xpath = "/html/body/main/div[1]/div/div/header/div[1]/div/div[2]/div/div/div") public static WebElement getXcelElement; public void getXcelElement() { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object() { }.getClass().getEnclosingMethod().getName())); getXcelElement.click(); } @FindBy(xpath = "/html/body/main/div[1]/div/div/header/div[1]/div/div[2]/div[2]/div[1]/input") public static WebElement searchBox; public void putSearchItem(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object() { }.getClass().getEnclosingMethod().getName())); searchBox.sendKeys("searchItems"); } } <file_sep>/HBO/src/main/java/homePage/SearchBox.java package homePage; import base.CommonAPI; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import reporting.TestLogger; public class SearchBox extends CommonAPI { @FindBy(xpath = "/html/body/main/div[1]/div/div/header/div[1]/div/div[2]/div/div/div") WebElement findSearchbar; public void getSearchBox()throws InterruptedException{ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); findSearchbar.click(); Thread.sleep(3000); typeOnElementNEnter("//input[@type='text']","MOVIES"); clearField("//input[@type='text']"); navigateBack(); typeOnElementNEnter("//input[@type='text']","SPORS"); clearField("//input[@type='text']"); navigateBack(); } } <file_sep>/HBO/src/test/java/datatest/GoogleSheetTest.java package datatest; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import reader.SearchUsingGS; import reporting.TestLogger; import java.io.IOException; public class GoogleSheetTest extends SearchUsingGS { SearchUsingGS searchUsingGS; @BeforeMethod public void initialization() { searchUsingGS = PageFactory.initElements(driver, SearchUsingGS.class); } @Test public void testLogInByInvalidIdPassUsingGoolgleSheet() throws IOException, InterruptedException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object() { }.getClass().getEnclosingMethod().getName())); sendSpreadSheetIdAndRange("1f_Q0KK88_vOOYPiybA1Qw3_B_PCdNPXjtiTKnQGqYL8", "Sheet1!A2:A2"); } }
504828c441755c9f031efc60d4afa72336500865
[ "Java" ]
6
Java
ekhtiar1971/HBOFrameWork
29f61d4950c2604c6a3009e68fc1118b15b8dec1
49ca1f72fb4f85d9c40e76cad1415df5009bd229
refs/heads/master
<file_sep>#include<bits/stdc++.h> #define llt long long int #define ullt unsigned long long int #define MOD 1000000007 using namespace std; #define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); int c=-1,n; int a[14][14]; void done(int r,int d,int posx,int posy) { if(posx==n-1&&posy==n-1) { if(a[posx][posy]%2==0) c=1;return; } if(a[posx][posy]%2==0) { if(a[posx+1][posy]%2==0) { if(r>0) done(r-1,d,posx+1,posy); } if(a[posx][posy+1]%2==0) { if(d>0) done(r,d-1,posx,posy+1); } } else return; } void solve() { //llt n; cin>>n; for(llt i=0;i<n;++i) for(int j=0;j<n;++j) { cin>>a[i][j]; } int r=n-1,d=n-1,posx=0,posy=0; if(a[0][0]%2==0) { if(a[posx+1][posy]%2==0) { if(r>0) done(r-1,d,posx+1,posy); } if(a[posx][posy+1]%2==0) { if(d>0) done(r,d-1,posx,posy+1); } } if(c==1) cout<<"YES"<<endl; else cout<<"NO"<<endl; } int main() { fast #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif int t=1; //cin>>t; while(t--) solve(); return 0; }
e9aa8722b6c5357b7575c27fc14b6b651bf7a9cc
[ "C++" ]
1
C++
5564ram/brute-force-example
f43810b10aba59f12a711dd7af705c293bfbc6cd
f91e2568527c51d31cbf785b35223e542a341578
refs/heads/master
<repo_name>liteng0436/angular-draggable-droppable<file_sep>/demo/demo.component.ts import { Component } from '@angular/core'; import { DropEvent } from '../src'; @Component({ selector: 'mwl-demo-app', template: ` <div mwlDraggable dropData="foo" dragActiveClass="drag-active"> Drag me! </div> <div mwlDraggable dropData="bar" dragActiveClass="drag-active" [dragSnapGrid]="{x: 100, y: 100}"> I snap to a 100 x 100 grid </div> <div mwlDroppable (drop)="onDrop($event)" dragOverClass="drop-over-active"> <span [hidden]="droppedData">Drop here</span> <span [hidden]="!droppedData">Item dropped here with data: "{{ droppedData }}"!</span> </div> `, styles: [ ` [mwlDraggable] { background-color: red; width: 200px; height: 200px; position: relative; z-index: 2; float: left; margin-right: 10px; cursor: move; } [mwlDroppable] { background-color: green; width: 400px; height: 400px; z-index: 1; position: relative; top: 50px; left: 100px; } [mwlDraggable], [mwlDroppable] { color: white; text-align: center; display: flex; align-items: center; justify-content: center; } .drop-over-active { border: dashed 1px black; background-color: lightgreen; } .drag-active { z-index: 3; } ` ] }) export class DemoComponent { droppedData: string = ''; onDrop({ dropData }: DropEvent<string>): void { this.droppedData = dropData; setTimeout(() => { this.droppedData = ''; }, 2000); } }
1b1d9634266cfc4637d9855f35c11953637f6e7a
[ "TypeScript" ]
1
TypeScript
liteng0436/angular-draggable-droppable
594c45af14355a33d8e3c1b2b797337054a326c8
a917107c02f906cf3a2f3d173855f25a21f6ac7f
refs/heads/master
<repo_name>nisher07/online-food-delivery-system<file_sep>/login.php <!DOCTYPE html> <html> <head> <title>Login</title> <link rel="stylesheet" type="text/css" href="css/login.css"> </head> <body> <div class="loginbox"> <img src="images/site_images/avatar.png" class="avatar"> <h1>Login Here</h1> <?php if( isset( $_GET['error'] ) ) { if( $_GET['error'] == 'user_mismatch' ) { echo '<p style="color: red;">User not found</p>'; } } ?> <form action="do_login.php" method="POST"> <p>Email</p> <input type="text" name="email" placeholder="Enter Email"> <p>Password</p> <input type="<PASSWORD>" name="password" placeholder="Enter <PASSWORD>"> <input type="submit" name="" value="Login"> <a href="#">Forgot your password?</a> <br> <a href="registration.php">Don't have an account?</a> </form> </div> </body> </html><file_sep>/home.php <?php session_start(); ?> <!DOCTYPE html> <html lang="en"> <head> <title>Online food delivery</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link href="css/home.css" rel="stylesheet" type="text/css"> </head> <body> <header> <!-- Navbar --> <div class="nav"> <ul> <li> <?php if( isset( $_SESSION['id'] ) ) { echo '<p style="font-family: arial;font-size: 20px; color:mediumseagreen;">Hi <b>' . $_SESSION['name'] . '</b>'; } ?> </li> <li><a href="home.php">Home</a></li> <li><a href="aboutus.php" target="_blank">About</a></li> <li><a href="all_restaurant.php" target="_blank">Restaurants</a></li> <li><a href="contactus.php" target="_blank">Contact</a></li> <?php if( isset( $_SESSION['id'] ) ) { echo '<li><a href="logout.php">Logout</li>'; } else { echo '<li><a href="login.php">Login</a></li>'; echo '<li><a href="registration.php">Sign Up</a></li>'; } ?> </ul> </div> <!-- banner --> <div class="title"> <h1><strong>FOODFUN</strong></h1> <h2><strong>Don't Dig Your Grave With Your Own Knife and Fork</strong></h2> </div> <!-- title section --> <div class="box"> <form action="search_result.php" method="get"> <input type="text" name="query" placeholder="search by food"> <input type="submit" name="" value="Search"> </form> </div> </header> <!-- payment method --> <div class="div1"> <div class="container bg-1"> <div class="payment"> <h2><strong>Payment Method</strong></h2> <div> <center> <table> <tr> <td><img src="images/site_images/icon1.png" alt="icon1" width="80" height="40"></td> <td><img src="images/site_images/icon2.png" alt="icon2" width="80" height="40"></td> <td><img src="images/site_images/icon3.png" alt="icon3" width="80" height="20"></td> <td><img src="images/site_images/icon4.png" alt="icon4" width="80" height="20"></td> </tr> </table> </center> </div> </div> </div> </div> <!-- How it works --> <!-- latest food --> <div class="div2"> <h1 style="text-align: center;">Latest Food Items</h1> <div class="responsive"> <div class="gallery"> <a href="images/site_images/image5.jpg" target="_blank"><img src="images/site_images/image5.jpg" width="300" height="200"></a> <div class="des">description</div> </div> </div> <div class="responsive"> <div class="gallery"> <a href="images/site_images/image5.jpg" target="_blank"><img src="images/site_images/image5.jpg" width="300" height="200"></a> <div class="des">description</div> </div> </div> <div class="responsive"> <div class="gallery"> <a href="images/site_images/image5.jpg" target="_blank"><img src="images/site_images/image5.jpg" width="300" height="200"></a> <div class="des">description</div> </div> </div> <div class="responsive"> <div class="gallery"> <a href="images/site_images/image5.jpg" target="_blank"><img src="images/site_images/image5.jpg" width="300" height="200"></a> <div class="des">description</div> </div> </div> </div> <!-- Download App --> <div class="div3"> <div class="bg-2"> <div class="app"> <h2><strong>Download App</strong></h2> </div> <div> <center> <table> <tr> <td><img src="images/site_images/image8.png" alt="image8" width="100" height="50"></td> <td><img src="images/site_images/image9.png" alt="image9" width="100" height="50"></td> </tr> </table> </center> </div> </div> </div> <!-- order by food & area --> <div class="container-fluid bg-4"> <div class="row"> <div class="column"> <h2 class="text"><strong>Order By Food</strong></h2> <div class="column1"> SoupsAsian<br> FusionOther<br> sEuropean<br> Thai<br> Arabian<br> SliderSea<br> FoodChips<br> </div> <div class="column1"> SoupsAsian<br> FusionOther<br> sEuropean<br> Thai<br> Arabian<br> SliderSea<br> FoodChips<br> </div> </div> <div class="column"> <h2 class="text"><strong>Order By Area</strong></h2> <div class="column1"> SoupsAsian<br> FusionOther<br> sEuropean<br> Thai<br> Arabian<br> SliderSea<br> FoodChips<br> </div> <div class="column1"> SoupsAsian<br> FusionOther<br> sEuropean<br> Thai<br> Arabian<br> SliderSea<br> FoodChips<br> </div> </div> </div> </div> <!-- footer --> <div class="footer-main-div"> <div class="footer-social-icons"> <ul> <li><a href="#" target="_blank"><i class="fa fa-facebook"></i></a></li> <li><a href="#" target="_blank"><i class="fa fa-twitter"></i></a></li> <li><a href="#" target="_blank"><i class="fa fa-instagram"></i></a></li> </ul><br> </div> <div class="footer-menu-one"> <ul> <li><a href="#">About Us</a></li> <li><a href="#">Join Us</a></li> <li><a href="#">Contact Us</a></li> <li><a href="#">Terms of Use</a></li> <li><a href="#">Customer support</a></li> </ul><br> </div> <div class="footer-bottom"> <p>Designed by: <a href="#">Online food</a></p> </div> </div> </body> </html> <file_sep>/add_to_cart.php <?php include ('dbconnect.php'); $item_id = $_GET['item_id']; $res = mysqli_query( $conn, "SELECT title, restaurant_id, price FROM items WHERE id='$item_id'"); $arr = mysqli_fetch_array( $res ); session_start(); $food_cart = $_SESSION['food_cart']; $exist = false; for( $i = 0; $i < count( $food_cart ); $i++ ) { if( $food_cart[ $i ]['item_id'] == $item_id ) { $food_cart[ $i ]['quantity'] = ( $food_cart[ $i ]['quantity'] + 1 ); $exist = true; break; } } if( !$exist ) { $food_cart[] = array( 'item_id' => $item_id, 'title' => $arr['title'], 'price' => $arr['price'], 'quantity'=> 1 ); } $_SESSION['food_cart'] = $food_cart; header("location:restaurant_detail.php?id=" . $arr['restaurant_id']); die(); ?><file_sep>/item_list.php <!DOCTYPE html> <html> <head> <title>Item List</title> <link rel="stylesheet" type="text/css" href="css/login.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <style> table { position: absolute; transform: translate(-50%,-50%); top: 50%; left: 50%; padding: 70px 30px; } h1 { position: absolute; padding: 70px 30px; } </style> </head> <body> <div class="table table-dark table-striped"> <?php include ('dbconnect.php'); $res = mysqli_query( $conn, "SELECT id, restaurant_id, title, type, price FROM items"); echo '<table>'; echo'<h1>Item Info</h1>'; echo '<tr><th>Image</th><th>Restaurant</th><th>Title</th><th>Type</th><th>Price</th></tr>'; while( $row = mysqli_fetch_array( $res ) ) { $restaurant = mysqli_query( $conn, "SELECT title FROM restaurants WHERE id='" . $row['restaurant_id'] . "'"); $restaurant_arr = mysqli_fetch_array( $restaurant ); echo '<tr>'; echo '<td><img src="images/item_images/' . $row['id'] . '.jpg" style="max-width: 50px; max-height: 50px;"></td>'; echo '<td>' . $restaurant_arr['title'] . '</td>'; echo '<td>' . $row['title'] . '</td>'; echo '<td>' . $row['type'] . '</td>'; echo '<td>' . $row['price'] . '</td>'; echo '<td>'; echo '<a href="edit_item.php?id=' . $row['id'] . '"><button type="button" class="btn btn-danger">Edit</button></a>'; echo ' <a href="delete_item.php?id=' . $row['id'] . '"><button type="button" class="btn btn-danger">Delete</button></a>'; echo '</td>'; echo '</tr>'; } echo '</table>'; ?> </div> </body> </html><file_sep>/delete_restaurant.php <?php include ('dbconnect.php'); $id = $_GET['id']; mysqli_query( $conn, "DELETE FROM restaurants WHERE id='$id'"); if( file_exists( 'images/restaurant_images/' . $id . '.jpg' ) ) { unlink( 'images/restaurant_images/' . $id . '.jpg' ); } header('location:restaurant_list.php?message=successfully_deleted'); die(); ?><file_sep>/registration.php <!DOCTYPE html> <html> <head> <title>Registration</title> <link rel="stylesheet" type="text/css" href="css/Reg.css"> </head> <body> <div class="loginbox"> <img src="avatar.png" class="avatar"> <h1>Sign Up Here</h1> <?php if( isset( $_GET['error'] ) ) { if( $_GET['error'] == 'password_mismatch' ) echo '<p style="color: red">Password mismatch</p>'; } ?> <form method="POST" action="register.php"> <p>Full name</p> <input type="text" name="name" placeholder="Enter Fullname" required=""> <p>E-mail</p> <input type="text" name="email" placeholder="Enter E-mail" required=""> <p>Password</p> <input type="<PASSWORD>" name="password" placeholder="Enter Password" required=""> <p>Confirm Password</p> <input type="<PASSWORD>" name="cpassword" placeholder="Confirm Password" required=""> <p>Mobile No</p> <input type="text" name="mobile" placeholder="Enter Mobile No" required=""> <input type="submit" name="" value="Sign Up"> </form> </div> </body> </html><file_sep>/insert_restaurant.php <?php include ('dbconnect.php'); $title = $_POST['title']; $address = $_POST['address']; $phone = $_POST['phone']; $email = $_POST['email']; $sql = "INSERT INTO restaurants ( `title`, `address`, `phone`, `email` ) VALUES ( '$title', '$address', '$phone', '$email')"; if (mysqli_query( $conn, $sql ) ) { $res = mysqli_query( $conn, "SELECT id FROM restaurants ORDER BY id DESC LIMIT 1") or die( mysqli_error( $conn ) ); $arr = mysqli_fetch_array( $res ); $id = $arr['id']; $target_dir = "images/restaurant_images/"; $target_file = $target_dir . $id . '.jpg'; $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image $check = getimagesize($_FILES["image"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $target_file . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if( $uploadOk ) { move_uploaded_file($_FILES["image"]["tmp_name"], $target_file); } header('location:restaurant_list.php'); die(); } else{ echo mysqli_error( $conn ); header('location:add_restaurant.php?error=database_error'); } ?><file_sep>/add_items.php <!DOCTYPE html> <html> <head> <title>Add Items</title> <link rel="stylesheet" type="text/css" href="css/Reg.css"> </head> <body> <div class="loginbox"> <img src="images/site_images/avatar.png" class="avatar"> <h1>Add Items</h1> <?php if( isset( $_GET['error'] ) ) { if( $_GET['error'] == 'password_mismatch' ) echo '<p style="color: red">Password mismatch</p>'; } ?> <form method="POST" action="insert_item.php" enctype="multipart/form-data"> <p>Restaurant</p> <select name="restaurantid"> <?php include ('dbconnect.php'); $restaurants = mysqli_query( $conn, "SELECT id, title FROM restaurants"); while( $row = mysqli_fetch_array( $restaurants ) ) { echo '<option value="' . $row['id'] . '">' . $row['title'] . '</option>'; } ?> </select> <p>Title</p> <input type="text" name="title" placeholder="Write Title" required=""> <p>Type</p> <select name="type"> <option value="0">Drinks</option> <option value="1">Main course</option> <option value="2">Desert</option> <option value="3">Fast food</option> <option value="4">Set menu</option> </select> <p>Price</p> <input type="text" name="price" placeholder="Price" required=""> <p>Image</p> <input type="file" name="image"> <input type="submit" name="" value="Submit"> </form> </div> </body> </html><file_sep>/aboutus.html <!DOCTYPE html> <html lang="en"> <head> <title> FOOD DELIVERY SYSTEM </title> <link href="css/aboutus.css" rel="stylesheet" type="text/css"> </head> <body> <div class="nav"> <ul> <li> <?php if( isset( $_SESSION['id'] ) ) { echo '<p style="font-family: arial;font-size: 20px; color:mediumseagreen;">Hi <b>' . $_SESSION['name'] . '</b>'; } ?> </li> <li><a href="home.php">Home</a></li> <li><a href="aboutus.php" target="_blank">About</a></li> <li><a href="all_restaurant.php" target="_blank">Restaurants</a></li> <li><a href="contactus.php" target="_blank">Contact</a></li> <?php if( isset( $_SESSION['id'] ) ) { echo '<li><a href="logout.php">Logout</li>'; } else { echo '<li><a href="login.php">Login</a></li>'; echo '<li><a href="registration.php">Sign Up</a></li>'; } ?> </ul> </div> <div class="row2"> <ul class="about"> <li><p>Who we are?</p></li> <li><a>Food delivery system is a 100% Bangladeshi Online Food Ordering and Delivery Service launched in 2013 to deliver your cravings at your doorsteps. We are passionate about food and are always prompt to deliver whenever the radar blips hungry. Come rain, heat and storm our delivery team will be at your doorstep with a bright smile and holding the food you have been craving, intact through our insulated boxes!</a></li> <li><r>Our purpose</r></li> <li><c>We just do not want you to be hungry. A hungry (wo)man is an angry (wo)man. HungryNaki gives you another reason to be stress-free in life. We do not want you to sweat in the kitchen to waste your valuable pastime after a long day of work. So here we are, helping you find the right restaurant, cafe or any other eatery in your neighborhood to order their food online via our website. The country is already taking a high blood pressure toll. We are here to soothe your hearts simply by lightening up your rumbling stomachs. Right now we are capturing the hearts of people living in a limited amount of areas in Dhaka, Chittagong and Sylhet (we cover pretty much all the major areas, though). Do not be disheartened if we can not provide service in the area you are living in just yet, we are working on capturing your hearts too.</c></li> </ul> </div> <div class="row3"> <ul class="footer"> <li><b>All Rights Reserved Food Delivery System</b></li> </ul> </div> </header> </body> </html><file_sep>/contactus.php <!DOCTYPE html> <html lang="en"> <head> <title>Contact Us</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link href="css/contactus.css" rel="stylesheet" type="text/css"> <link href="css/home.css" rel="stylesheet" type="text/css"> </head> <body> <header> <!-- Navbar --> <div class="nav"> <ul> <li> <?php if( isset( $_SESSION['id'] ) ) { echo '<p style="font-family: arial;font-size: 20px; color:mediumseagreen;">Hi <b>' . $_SESSION['name'] . '</b>'; } ?> </li> <li><a href="home.php">Home</a></li> <li><a href="aboutus.php" target="_blank">About</a></li> <li><a href="all_restaurant.php" target="_blank">Restaurants</a></li> <li><a href="contactus.php" target="_blank">Contact</a></li> <?php if( isset( $_SESSION['id'] ) ) { echo '<li><a href="logout.php">Logout</li>'; } else { echo '<li><a href="login.php">Login</a></li>'; echo '<li><a href="registration.php">Sign Up</a></li>'; } ?> </ul> </div> <div class="row1"> <ul class="text"> <li><a>Contact Us</a></li> <li><b>Hello, is it me you’re looking for?</b></li> </ul> </div> <div class="row2"> <ul class="info"> <li><a>We’re committed to providing the best online ordering service available. To that end, we’d very much appreciate any sort of feedback. Don’t hesitate to contact us:</a></li><br><br><br> <li><c>Via email:</c></li> <li><b href="mailto:<EMAIL>"><EMAIL></b></li><br><br><br> <li><d>Or call us at</d></li> <li><e href="tel:+8809000000000">09000000000</e></li><br> <li><f href="tel:+8809000000001">09000000001</f></li><br><br><br> <li><g>Want your restaurant to be a part of the Ki Khaben community? We'd love to work with you!</g></li><br><br><br> <li><h>Contact us at: </h></li> <li><i href="mailto:<EMAIL>"><EMAIL></i></li><br><br><br> </ul> </div> <!-- footer --> <div class="footer-main-div"> <div class="footer-social-icons"> <ul> <li><a href="#" target="_blank"><i class="fa fa-facebook"></i></a></li> <li><a href="#" target="_blank"><i class="fa fa-twitter"></i></a></li> <li><a href="#" target="_blank"><i class="fa fa-instagram"></i></a></li> </ul><br> </div> <div class="footer-menu-one"> <ul> <li><a href="#">About Us</a></li> <li><a href="#">Join Us</a></li> <li><a href="#">Contact Us</a></li> <li><a href="#">Terms of Use</a></li> <li><a href="#">Customer support</a></li> </ul><br> </div> <div class="footer-bottom"> <p>Designed by: <a href="#">Online food</a></p> </div> </header> </body> </html> <file_sep>/add_restaurant.php <!DOCTYPE html> <html> <head> <title>Add restaurant</title> <link rel="stylesheet" type="text/css" href="css/Reg.css"> </head> <body> <div class="loginbox"> <img src="images/site_images/avatar.png" class="avatar"> <h1>Add Restsursnts</h1> <?php if( isset( $_GET['error'] ) ) { if( $_GET['error'] == 'password_mismatch' ) echo '<p style="color: red">Password mismatch</p>'; } ?> <form method="POST" action="insert_restaurant.php" enctype="multipart/form-data"> <p>Title</p> <input type="text" name="title" placeholder="Write Title" required=""> <p>Address</p> <input type="text" name="address" placeholder="Write Address" required=""> <p>Phone</p> <input type="text" name="phone" placeholder="Enter Phone No" required=""> <p>E-mail</p> <input type="text" name="email" placeholder="Enter E-mail" required=""> <p>Image</p> <input type="file" name="image"> <input type="submit" name="" value="Submit"> </form> </div> </body> </html><file_sep>/restaurant_detail.php <?php include ('dbconnect.php'); $id = $_GET['id']; $res = mysqli_query( $conn, "SELECT title, address, phone, email FROM restaurants WHERE id='$id'"); $arr = mysqli_fetch_array( $res ); ?> <!DOCTYPE html> <html lang="en"> <head> <title><?php echo $arr['title']; ?></title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link href="css/sp_rest.css" rel="stylesheet" type="text/css"> </head> <body> <header style="background-image:linear-gradient(rgba(0,0,0,0.2),rgba(0,0,0,0.2)), url(images/restaurant_images/<?php echo $id; ?>.jpg);"> <!-- Navbar --> <div class="nav"> <ul> <li><a href="home.php">Home</a></li> <li><a href="aboutus.php" target="_blank">About</a></li> <li><a href="allrast.php" target="_blank">Restaurants</a></li> <li><a href="contactus.php" target="_blank">Contact</a></li> <li><a href="login.php">Login</a></li> </ul> </div> <!-- banner --> <div class="title"> <h1><strong><?php echo $arr['title']; ?></strong></h1> <h2><strong><?php echo $arr['address']; ?></strong></h2> <h3 style="color: white;"><strong>Contact:</strong><?php echo $arr['phone'] . ' (' . $arr['email'] . ')'; ?></h3> </div> </header> <!-- Menu bar --> <div class="nav1"> <ul> <li><a class="active" href="#">Menu</a></li> <li><a href="review.html" target="_blank">Review</a></li> <li><a href="aboutus.html" target="_blank">About Us</a></li> </ul> </div> <!-- delivery history --> <div class="nav2"> <ul> <li><a href="#">Min. Food Price:<br>50.00 TK</a></li> <li><a href="#">Min. Delivery Time:<br>40 MIN</a></li> <li><a href="#">Min. Delivery Fee:<br>40.00 TK</a></li> </ul> </div> <!-- Food list --> <div class="grid"> <div> <table class="table1"> <tr class="header"> <th>Food Name</th> <th>Type</th> <th>Price</th> <th>Add</th> </tr> <!-- list of food --> <?php $foods = mysqli_query( $conn, "SELECT id, title, type, price FROM items WHERE restaurant_id='$id'" ); while( $frow = mysqli_fetch_array( $foods ) ) { echo '<tr>'; echo '<td>' . $frow['title'] . '</td>'; echo '<td>'; if( $frow['type'] == 0 ) echo 'Drink'; elseif( $frow['type'] == 1 ) echo 'Main course'; elseif( $frow['type'] == 2 ) echo 'Desert'; elseif( $frow['type'] == 3 ) echo 'Fast food'; elseif( $frow['type'] == 4 ) echo 'Set menu'; echo '</td>'; echo '<td>' . $frow['price'] . '</td>'; echo '<td><a href="add_to_cart.php?item_id=' . $frow['id'] . '" class="btn1" style="cursor: pointer;">Add</a></td>'; echo '</tr>'; } ?> </table> </div> <!-- order cart --> <div> <h2>Order Cart</h2> <table class="table2"> <tr></tr> <tr></tr> </table> <table class="table3"> <?php session_start(); $sub_total = 0; $vat = .15; $delivery_charge = 120; if( isset( $_SESSION['food_cart'] ) ) { $food_cart = $_SESSION['food_cart']; for( $i = 0; $i < count( $food_cart ); $i++ ) { echo '<tr>'; echo '<td>' . $food_cart[ $i ]['title'] . ' (' . $food_cart[ $i ]['quantity'] . 'pcs)</td>'; echo '<td>' . ( $food_cart[ $i ]['price'] * $food_cart[ $i ]['quantity'] ) . '</td>'; echo '</tr>'; $sub_total += ( $food_cart[ $i ]['price'] * $food_cart[ $i ]['quantity'] ); } } $vat_amount = ( $sub_total * $vat ); ?> <tr> <td>Vat(%)</td> <td><?php echo $vat_amount; ?> TK</td> </tr> <tr> <td>Delivery Charge</td> <td><?php echo $delivery_charge; ?> TK</td> </tr> <tr> <td>Total</td> <td><?php echo ( $sub_total + $vat_amount + $delivery_charge ); ?></td> </tr> </table> </div> </div> <!-- footer --> <div class="footer-main-div"> <div class="footer-social-icons"> <ul> <li><a href="#" target="_blank"><i class="fa fa-facebook"></i></a></li> <li><a href="#" target="_blank"><i class="fa fa-twitter"></i></a></li> <li><a href="#" target="_blank"><i class="fa fa-instagram"></i></a></li> </ul><br> </div> <div class="footer-menu-one"> <ul> <li><a href="#">About Us</a></li> <li><a href="#">Join Us</a></li> <li><a href="#">Contact Us</a></li> <li><a href="#">Terms of Use</a></li> <li><a href="#">Customer support</a></li> </ul><br> </div> <div class="footer-bottom"> <p>Design by: <a href="#">Online food</a></p> </div> </body> </html> <file_sep>/restaurant_list.php <!DOCTYPE html> <html> <head> <title>Restaurant List</title> <link rel="stylesheet" type="text/css" href="css/login.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <style> table { position: absolute; transform: translate(-50%,-50%); top: 50%; left: 50%; padding: 70px 30px; } h1 { position: absolute; padding: 70px 30px; } </style> </head> <body> <div class="table table-dark table-striped"> <?php include ('dbconnect.php'); $res = mysqli_query( $conn, "SELECT id, title, address, phone, email FROM restaurants"); echo '<table>'; echo'<h1>Restaurant Info</h1>'; echo '<tr><th>Image</th><th>Title</th><th>Address</th><th>Phone</th><th>Email</th><th>Option</th></tr>'; while( $row = mysqli_fetch_array( $res ) ) { echo '<tr>'; echo '<td><img src="images/restaurant_images/' . $row['id'] . '.jpg" style="max-width: 50px; max-height: 50px;"></td>'; echo '<td>' . $row['title'] . '</td>'; echo '<td>' . $row['address'] . '</td>'; echo '<td>' . $row['phone'] . '</td>'; echo '<td>' . $row['email'] . '</td>'; echo '<td>'; echo '<a href="edit_restaurant.php?id=' . $row['id'] . '"><button type="button" class="btn btn-danger">Edit</button></a>'; echo ' <a href="delete_restaurant.php?id=' . $row['id'] . '"><button type="button" class="btn btn-danger">Delete</button></a>'; echo '</td>'; echo '</tr>'; } echo '</table>'; ?> </div> </body> </html><file_sep>/aboutus.php <!DOCTYPE html> <html lang="en"> <head> <title>About Us</title> <link href="css/aboutus.css" rel="stylesheet" type="text/css"> <link href="css/home.css" rel="stylesheet" type="text/css"> </head> <body> <!--Navbar--> <div class="nav"> <ul> <li> <?php if( isset( $_SESSION['id'] ) ) { echo '<p style="font-family: arial;font-size: 20px; color:mediumseagreen;">Hi <b>' . $_SESSION['name'] . '</b>'; } ?> </li> <li><a href="home.php">Home</a></li> <li><a href="aboutus.php">About</a></li> <li><a href="all_restaurant.php">Restaurants</a></li> <li><a href="contactus.php">Contact</a></li> <?php if( isset( $_SESSION['id'] ) ) { echo '<li><a href="logout.php">Logout</li>'; } else { echo '<li><a href="login.php">Login</a></li>'; echo '<li><a href="registration.php">Sign Up</a></li>'; } ?> </ul> </div> <div class="row2"> <ul class="about"> <li><p>Who we are?</p></li> <li><a>Food delivery system is a 100% Bangladeshi Online Food Ordering and Delivery Service launched in 2013 to deliver your cravings at your doorsteps. We are passionate about food and are always prompt to deliver whenever the radar blips hungry. Come rain, heat and storm our delivery team will be at your doorstep with a bright smile and holding the food you have been craving, intact through our insulated boxes!</a></li> <li><r>Our purpose</r></li> <li><c>We just do not want you to be hungry. A hungry (wo)man is an angry (wo)man. HungryNaki gives you another reason to be stress-free in life. We do not want you to sweat in the kitchen to waste your valuable pastime after a long day of work. So here we are, helping you find the right restaurant, cafe or any other eatery in your neighborhood to order their food online via our website. The country is already taking a high blood pressure toll. We are here to soothe your hearts simply by lightening up your rumbling stomachs. Right now we are capturing the hearts of people living in a limited amount of areas in Dhaka, Chittagong and Sylhet (we cover pretty much all the major areas, though). Do not be disheartened if we can not provide service in the area you are living in just yet, we are working on capturing your hearts too.</c></li> </ul> </div> <!--Footer--> <div class="footer-main-div"> <div class="footer-social-icons"> <ul> <li><a href="#" target="_blank"><i class="fa fa-facebook"></i></a></li> <li><a href="#" target="_blank"><i class="fa fa-twitter"></i></a></li> <li><a href="#" target="_blank"><i class="fa fa-instagram"></i></a></li> </ul><br> </div> <div class="footer-menu-one"> <ul> <li><a href="#">About Us</a></li> <li><a href="#">Join Us</a></li> <li><a href="#">Contact Us</a></li> <li><a href="#">Terms of Use</a></li> <li><a href="#">Customer support</a></li> </ul><br> </div> <div class="footer-bottom"> <p>Designed by: <a href="#">Online food</a></p> </div> </div> </body> </html><file_sep>/all_restaurant.php <!DOCTYPE html> <html lang="en"> <head> <title>All Restaurant</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link href="css/allrast.css" rel="stylesheet" type="text/css"> </head> <body> <header> <!-- Navbar --> <div class="nav"> <ul> <li><a href="home.php">Home</a></li> <li><a href="aboutus.php">About</a></li> <li><a href="all_restaurant.php">Restaurants</a></li> <li><a href="contactus.php">Contact</a></li> <li><a href="login.php">Login</a></li> </ul> </div> <!-- banner --> <div class="title"> <h1><strong>FOODFUN</strong></h1> <h2><strong>Find A Restaurant You Will Love</strong></h2> </div> <!-- title section --> <div class="box"> <form> <input type="text" name="" placeholder="search by food,place & restaurants"> <input type="submit" name="" value="Search"> </form> </div> </header> <!-- rastaurant list --> <div class="xop-section"> <ul class="xop-grid"> <?php include ('dbconnect.php'); $res = mysqli_query( $conn, "SELECT id, title, address, phone, email FROM restaurants"); while( $row = mysqli_fetch_array( $res ) ) { echo '<li>'; echo '<div class="xop-box xop-img-1" style="background: linear-gradient( rgba(0, 0, 0, 0.50), rgba(0, 0, 0, 0.10)), url(images/restaurant_images/' . $row['id'] . '.jpg);">'; echo '<a href="restaurant_detail.php?id=' . $row['id'] . '" target="_blank">'; echo '<div class="xop-info">'; echo '<h3>' . $row['title'] . '</h3>'; echo '<p><b>Address:</b> ' . $row['address'] . '<br><b>Phone:</b> ' . $row['phone'] . '<br><b>Email:</b> ' . $row['email']. '</p>'; echo '</div>'; echo '</a>'; echo '</div>'; echo '</li>'; } ?> </ul> </div> <!-- footer --> <div class="footer-main-div"> <div class="footer-social-icons"> <ul> <li><a href="#" target="_blank"><i class="fa fa-facebook"></i></a></li> <li><a href="#" target="_blank"><i class="fa fa-twitter"></i></a></li> <li><a href="#" target="_blank"><i class="fa fa-instagram"></i></a></li> </ul><br> </div> <div class="footer-menu-one"> <ul> <li><a href="#">About Us</a></li> <li><a href="#">Join Us</a></li> <li><a href="#">Contact Us</a></li> <li><a href="#">Terms of Use</a></li> <li><a href="#">Customer support</a></li> </ul><br> </div> <div class="footer-bottom"> <p>Design by: <a href="#">Online food</a></p> </div> </body> </html> <file_sep>/edit_item.php <!DOCTYPE html> <html> <head> <title>Edit Item</title> <link rel="stylesheet" type="text/css" href="css/Reg.css"> </head> <body> <div class="loginbox"> <img src="images/site_images/avatar.png" class="avatar"> <h1>Edit Item Here</h1> <?php if( isset( $_GET['error'] ) ) { if( $_GET['error'] == 'password_mismatch' ) echo '<p style="color: red">Password mismatch</p>'; } ?> <?php include ('dbconnect.php'); $id = $_GET['id']; $res = mysqli_query( $conn, "SELECT restaurant_id, title, type, price FROM items WHERE id='$id'") or die( mysqli_error( $conn ) ); $arr = mysqli_fetch_array( $res ); ?> <form method="POST" action="update_item.php" enctype="multipart/form-data"> <input type="hidden" name="id" value="<?php echo $id; ?>" <p><b>Restaurant</b></p> <select name="restaurantid"> <?php include ('dbconnect.php'); $restaurants = mysqli_query( $conn, "SELECT id, title FROM restaurants"); while( $row = mysqli_fetch_array( $restaurants ) ) { echo '<option value="' . $row['id'] . '">' . $row['title'] . '</option>'; } ?> </select> <p>Title</p> <input type="text" name="title" placeholder="Write Tittle" required="" value="<?php echo $arr['title']; ?>"> <p>Type</p> <select name="type"> <option value="0">Drinks</option> <option value="1">Main course</option> <option value="2">Desert</option> <option value="3">Fast food</option> <option value="4">Set menu</option> </select> <p>Price</p> <input type="text" name="price" placeholder="Price" required="" value="<?php echo $arr['price']; ?>"> <p>Image</p> <input type="file" name="image"> <input type="submit" name="" value="Submit"> </form> </div> </body> </html><file_sep>/search_result.php <!DOCTYPE html> <html lang="en"> <head> <title>All Restaurant</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link href="css/allrast.css" rel="stylesheet" type="text/css"> </head> <body> <header> <!-- Navbar --> <div class="nav"> <ul> <li><a href="home.php">Home</a></li> <li><a href="aboutus.php">About</a></li> <li><a href="all_restaurant.php">Restaurants</a></li> <li><a href="contactus.php">Contact</a></li> <li><a href="login.php">Login</a></li> </ul> </div> <!-- banner --> <div class="title"> <h1><strong>FOODFUN</strong></h1> <h2><strong>Find A Food You Will Love</strong></h2> </div> <!-- title section --> <div class="box"> <form action="search_result.php" method="get"> <input type="text" name="query" placeholder="search by food" value="<?php echo htmlspecialchars( $_GET['query'] ) ?>"> <input type="submit" name="" value="Search"> </form> </div> </header> <!-- rastaurant list --> <div class="xop-section"> <ul class="xop-grid"> <?php include ('dbconnect.php'); $sql = "SELECT restaurants.id as restaurant_id, restaurants.title as restaurant_title, restaurants.address as restaurant_address, restaurants.phone as restaurant_phone, restaurants.email as restaurant_email, items.id, items.title FROM restaurants, items WHERE items.restaurant_id=restaurants.id AND "; $query_word = $_GET['query']; $br = explode( ' ', $query_word ); $i = 0; foreach( $br as $brs ) { if( $i > 0 ) $sql .= ' OR '; $sql .= "items.title LIKE " . trim( "'%" . $brs . "%'" ); $i++; } $res = mysqli_query( $conn, $sql ); while( $row = mysqli_fetch_array( $res ) ) { echo '<li>'; echo '<div class="xop-box xop-img-1" style="background: linear-gradient( rgba(0, 0, 0, 0.50), rgba(0, 0, 0, 0.10)), url(images/item_images/' . $row['id'] . '.jpg);">'; echo '<a href="restaurant_detail.php?id=' . $row['restaurant_id'] . '" target="_blank">'; echo '<div class="xop-info">'; echo '<h3>' . $row['title'] . '</h3>'; echo '<p><b>' . $row['restaurant_title'] . '</b> <b>Address:</b> ' . $row['restaurant_address'] . '<br><b>Phone:</b> ' . $row['restaurant_phone'] . '<br><b>Email:</b> ' . $row['restaurant_email']. '</p>'; echo '</div>'; echo '</a>'; echo '</div>'; echo '</li>'; } ?> </ul> </div> <!-- footer --> <div class="footer-main-div"> <div class="footer-social-icons"> <ul> <li><a href="#" target="_blank"><i class="fa fa-facebook"></i></a></li> <li><a href="#" target="_blank"><i class="fa fa-twitter"></i></a></li> <li><a href="#" target="_blank"><i class="fa fa-instagram"></i></a></li> </ul><br> </div> <div class="footer-menu-one"> <ul> <li><a href="#">About Us</a></li> <li><a href="#">Join Us</a></li> <li><a href="#">Contact Us</a></li> <li><a href="#">Terms of Use</a></li> <li><a href="#">Customer support</a></li> </ul><br> </div> <div class="footer-bottom"> <p>Design by: <a href="#">Online food</a></p> </div> </body> </html> <file_sep>/edit_restaurant.php <!DOCTYPE html> <html> <head> <title>Edit restaurant</title> <link rel="stylesheet" type="text/css" href="css/Reg.css"> </head> <body> <div class="loginbox"> <img src="images/site_images/avatar.png" class="avatar"> <h1>Edit Restaurant Here</h1> <?php if( isset( $_GET['error'] ) ) { if( $_GET['error'] == 'password_mismatch' ) echo '<p style="color: red">Password mismatch</p>'; } ?> <?php include ('dbconnect.php'); $id = $_GET['id']; $res = mysqli_query( $conn, "SELECT title, address, phone, email FROM restaurants WHERE id='$id'"); $arr = mysqli_fetch_array( $res ); ?> <form method="POST" action="update_restaurant.php" enctype="multipart/form-data"> <input type="hidden" name="id" value="<?php echo $id; ?>" <p>Title</p> <input type="text" name="title" placeholder="Write Tittle" required="" value="<?php echo $arr['title']; ?>"> <p>Address</p> <input type="text" name="address" placeholder="Write Address" required="" value="<?php echo $arr['address']; ?>"> <p>Phone</p> <input type="text" name="phone" placeholder="Enter Phone No" required="" value="<?php echo $arr['phone']; ?>"> <p>E-mail</p> <input type="text" name="email" placeholder="Enter E-mail" required="" value="<?php echo $arr['email']; ?>"> <p>Image</p> <input type="file" name="image"> <input type="submit" name="" value="Submit"> </form> </div> </body> </html>
61e8e4c676aa741d9bf04349ce8e6c246b20ffa7
[ "HTML", "PHP" ]
18
PHP
nisher07/online-food-delivery-system
b2ff849c993cafaedd98bc526f8932236c68a33c
6baccdf6613024dfce3bcc0286460be0e6d55a49
refs/heads/master
<file_sep>using System.Diagnostics; using Microsoft.AspNetCore.Mvc; using CSharpNetCoreWeb.Models; using Microsoft.AspNetCore.Authorization; using System; using Microsoft.Extensions.Configuration; using System.Collections.Generic; namespace CSharpNetCoreWeb.Controllers { //[Authorize] public class HomeController : Controller { private IConfiguration configuration { get; } private string connectionString = ""; public HomeController(IConfiguration configuration) { this.configuration = configuration; this.connectionString = configuration.GetConnectionString("DefaultConnection"); } public IActionResult Index(Persona p) { if (p == null) { p = new Persona(); } PersonaDb db = new PersonaDb(connectionString); ModelState.Clear(); p.list = db.GetAll(); return View(p); } public IActionResult Dettaglio(int? id) { if (id == null || id == 0) { return RedirectToAction("Index"); } PersonaDb db = new PersonaDb(connectionString); ModelState.Clear(); Persona p = db.GetDetails(id.GetValueOrDefault()); return View(p); } public ActionResult Modifica(int? id) { if (id == null || id == 0) { return RedirectToAction("Index"); } PersonaDb db = new PersonaDb(connectionString); ModelState.Clear(); Persona p = db.GetDetails(id.GetValueOrDefault()); return View(p); } [HttpPost] public ActionResult ModificaPersona(int id, Persona p) { if (ModelState.IsValid) { PersonaDb db = new PersonaDb(connectionString); if (db.ModificaPersona(id, p)) { ViewBag.Message = "Operazione eseguita"; } } return RedirectToAction("Index"); } [HttpPost] public ActionResult AddPersona(Persona p) { if (ModelState.IsValid) { PersonaDb db = new PersonaDb(connectionString); if (db.AddPersona(p)) { ViewBag.Message = "Record aggiunto con successo"; } } return RedirectToAction("Index"); } public ActionResult DeletePersona(int id) { if (ModelState.IsValid) { PersonaDb emprep = new PersonaDb(connectionString); if (emprep.DeletePersona(id)) { ViewBag.Message = "Record Deleted Successfully"; } } return RedirectToAction("Index"); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } } <file_sep>using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace CSharpNetCoreWeb.Models { public class Persona { [Key] public int ID { get; set; } [Required(ErrorMessage = "Email obbligatoria")] public string Email { get; set; } public bool Active { get; set; } public List<Persona> list { get; set; } } } <file_sep># NET-MVC-Core-Example .NET MVC Core Example Esempio di Codice in C#. All'interno anche la tabella da importare in SQL Server. Non ci sono le tabelle per l'autenticazione / registrazione; quelle conviene che le fate creare in fase di creazione di progetto da Visual Studio. <file_sep>using CSharpNetCoreWeb.Models; using Microsoft.Data.SqlClient; using System; using System.Collections.Generic; namespace CSharpNetCoreWeb { public class PersonaDb { private string connectionString; public PersonaDb(string connectionString) { this.connectionString = connectionString; } public List<Persona> GetAll() { var list = new List<Persona>(); using (var conn = new SqlConnection(connectionString)) { conn.Open(); string sql = "SELECT * FROM Persone"; using (var cmd = new SqlCommand(sql, conn)) { using (SqlDataReader dataReader = cmd.ExecuteReader()) { while (dataReader.Read()) { Persona persona = new Persona(); persona.ID = Convert.ToInt32(dataReader["PersonaId"]); persona.Email = dataReader["PersonaEmail"].ToString(); persona.Active = dataReader.GetBoolean(dataReader.GetOrdinal("PersonaAttivo")); list.Add(persona); } } conn.Close(); } } return list; } public bool AddPersona(Persona p) { bool result = false; string commandText = "INSERT INTO Persone (PersonaEmail, PersonaAttivo) VALUES(@email, @attivo)"; using (var conn = new SqlConnection(connectionString)) { using (var cmd = new SqlCommand(commandText, conn)) { cmd.Parameters.AddWithValue("@email", p.Email.Trim()); cmd.Parameters.AddWithValue("@attivo", p.Active); conn.Open(); int i = cmd.ExecuteNonQuery(); conn.Close(); if (i > 0) { result = true; } else { result = false; } } } return result; } public bool ModificaPersona(int id, Persona p) { bool result = false; string commandText = "UPDATE Persone SET PersonaEmail = @email, PersonaAttivo = @active WHERE PersonaId = @id"; using (var conn = new SqlConnection(connectionString)) { using (var cmd = new SqlCommand(commandText, conn)) { System.Diagnostics.Debug.WriteLine(id); cmd.Parameters.AddWithValue("@id", id); cmd.Parameters.AddWithValue("@email", p.Email.Trim()); cmd.Parameters.AddWithValue("@active", p.Active); conn.Open(); int i = cmd.ExecuteNonQuery(); conn.Close(); if (i > 0) { result = true; } else { result = false; } } } return result; } public Persona GetDetails(int id) { var persona = new Persona(); using (var conn = new SqlConnection(connectionString)) { conn.Open(); string sql = "SELECT * FROM Persone WHERE PersonaId = @id"; using (var cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddWithValue("@id", id); using (SqlDataReader dataReader = cmd.ExecuteReader()) { while (dataReader.Read()) { persona.ID = Convert.ToInt32(dataReader["PersonaId"]); persona.Email = dataReader["PersonaEmail"].ToString(); persona.Active = dataReader.GetBoolean(dataReader.GetOrdinal("PersonaAttivo")); } } conn.Close(); } } return persona; } public bool DeletePersona(int id) { bool result = false; string commandText = "DELETE FROM Persone WHERE PersonaId = @id"; using (var conn = new SqlConnection(connectionString)) { using (var cmd = new SqlCommand(commandText, conn)) { cmd.Parameters.AddWithValue("@id", id); conn.Open(); int i = cmd.ExecuteNonQuery(); conn.Close(); if (i > 0) { result = true; } else { result = false; } } } return result; } } }
973958556ce187fb7ece3336d95789b409711b38
[ "Markdown", "C#" ]
4
C#
mattepuffo/NET-MVC-Core-Example
71c3908838fb4ee58a5848cd9d9fe8ee968cd6a2
219b0fe7b0f149ff23560099e8967415f9a5028a
refs/heads/master
<file_sep># *OnlineCodingSolutions* - A repository containing all Code Chef Codes ### Generate codechef-dsa maven project using the following mvn command ------- > mvn archetype:generate -DgroupId=org.dhiren.codechef > -DartifactId=codechef-dsa > -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false <file_sep>package org.dhiren.codechef.weekOne.solutions; import java.util.Arrays; import java.util.Scanner; import java.util.regex.Pattern; public class Lapindromes { public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { while (scanner.hasNext()) { int num = scanner.nextInt(); for (int i = 0; i < num; i++) { testLaptindromes(scanner.next()); } return; } } } private static boolean containsSpecialCharacters(String test) { Pattern pattern = Pattern.compile("[a-zA-Z]*"); return pattern.matcher(test).matches(); } private static void sameFrequencyAndEqual(String str1, String str2) { char[] chars = str1.toCharArray(); char[] chars1 = str2.toCharArray(); Arrays.sort(chars); Arrays.sort(chars1); String first_half = new String(chars); String second_half = new String(chars1); System.out.println(first_half.contentEquals(second_half) ? "YES" : "NO"); } private static void testLaptindromes(String text) { String first_half, second_half; final int length = text.length(); if (containsSpecialCharacters(text)) { System.out.println("NO"); } else { if (length % 2 == 0) { first_half = text.substring(0, length / 2); second_half = text.substring(length / 2); } else { first_half = text.substring(0, length / 2); second_half = text.substring(length / 2 + 1); } sameFrequencyAndEqual(first_half, second_half); } } } <file_sep>>Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits. Example >Input: 1 2 88 42 99 >Output: 1 2 88 --- >If an Integer N, write a program to reverse the given number. Input: > The first line contains an integer T, total number of testcase. Then follow T lines, each line contains an integer N. Output > Display the reverse of the given number N. Constraints > 1 ≤ T ≤ 1000 > 1 ≤ N ≤ 1000000 Example >Input 4 12345 31203 2123 2300 >Output 54321 30213 3212 32 --- > Lapindrome is defined as a string which when split in the middle, gives two halves having the same characters and same frequency of each character. If there are odd number of characters in the string, we ignore the middle character and check for lapindrome. For example gaga is a lapindrome, since the two halves ga and ga have the same characters with same frequency. Also, abccab, rotor and xyzxy are a few examples of lapindromes. Note that abbaab is NOT a lapindrome. The two halves contain the same characters but their frequencies do not match. Your task is simple. Given a string, you need to tell if it is a lapindrome. Input: >First line of input contains a single integer T, the number of test cases. Each test is a single line containing a string S composed of only lowercase English alphabet. Output: >For each test case, output on a separate line: "YES" if the string is a lapindrome and "NO" if it is not. Constraints: 1 ≤ T ≤ 100 2 ≤ |S| ≤ 1000, where |S| denotes the length of S Example: >Input: 6 gaga abcde rotor xyzxy abbaab ababc > Output: YES NO YES YES NO NO
1358f9b1b50944c867d78bbc0bc79fe0343eb3da
[ "Markdown", "Java" ]
3
Markdown
dhirenpatra/OnlineCodingSolutions
41cd621381fbc329d6463aebc04671ac52e138b5
c653aab5ea789d93a4b09a4be55db807990cf5d0
refs/heads/master
<repo_name>tatianimeneghini/projeto-final-reprograma<file_sep>/src/routes/literaturaLGBTRouter.js const express = require("express"); const router = express.Router(); const controller = require("../controllers/literaturaLGBTController"); router.get("/", controller.getAll); router.get("/buscarPorTitulo/:titulo/", controller.getTitulo); router.get("/buscarPorAutoria/:autoria", controller.getAutoria); router.get("/buscarPorEstilo/:estiloNarrativo", controller.getEstiloNarrativo); router.get("/buscarPorGenero/:generoLiterario", controller.getGeneroLiteratura); router.post("/criar", controller.criarLivro); router.patch("/atualizar/:id", controller.atualizarLivro); router.delete("/remover/:id", controller.deletarLivro); module.exports = router;<file_sep>/README.md # Projeto Final Reprograma Projeto Final do Bootcamp de Backend da Reprograma, em parceria com a Accenture e o Facebook, desenvolvido por <NAME>. ## API Literatura LGBT :book: :rainbow: O projeto tem como nome **Literatura LGBT**, com o objetivo de disponibilizar aos usuários um Banco de Dados de livros e autores LGBTs (Lésbicas, Gays, Bissexuais e Transexuais). É a primeira iniciativa de criar um Banco de Dados colaborativo do tema, com acesso por API. ### Passo a passo pra criar a API: - *README.md* - `npm init` - `npm install express` - `npm install mongoose` - `npm install -D nodemon` - `npm install body-parser` - *.gitignore* com *node_modules* - criar *server.js* rodando o *app.js* com a porta escolhida (5005). - criar o *app.js* com o *express*, exportando o app. - `npm install dotenv-safe` e verificar a versão ^6.1.0 no *package.json*. ### Instalação Para clonar o repositório, acessar o *Git Bash* (Windows) ou terminal (Linux, MAC): `git clone https://github.com/tatianimeneghini/projeto-final-reprograma.git` Iniciar, após o diretório ser clonado, o pacote: `npm install` ### Objetivo A **API Literatura LGBT** cria um Banco de Dados de livros e disponbiliza seu acesso por título, autoria, editora, gênero literário, estilo narrativo, ano e acesso a *link* de pdf (não obrigatório). ### Requisitos - A API deve possuir CRUD (Create, Read, Update e Delete). - Cada livro deve possuir os seguintes campos: título, autoria, gênero literário, editora, ano de lançamento. - Diferenciar os títulos dos livros, para não possuir diferentes livros com o mesmo nome. - Links é opcional, para caso de livros que estejam disponíveis *online* em formato pdf. - O estilo literário é dividido em obras de ficção e não-ficção (sem acentuação). - Os gêneros literários são subdividos em: romance, contos, crônicas, poesia, ensaio, autobiografia. ### Endpoints Os endpoints criados são: - A rota GET /literatura-LGBT deve trazer a lista de todos livros. - A rota GET /buscarPorTitulo/:titulo deve retornar os livros pelo título. - A rota GET /buscaPorAutoria/:autoria deve retornar os livros pela autoria. - A rota GET /buscaPorEstilo/:estiloNarrativo deve retornar os livros pelo estilo narrativo. - A rota GET /buscaPorGenero/:generoLiterario deve retornar os livros pelo gênero literário. - A rota POST /criar deve receber no body o *titulo* do livro a ser adicionado no Banco de Dados, seguido de *autoria* e *generoLiterário* (requeridos), *estiloNarrativo*, *editora*, *anoDeLancamento* e *acessoLink* (opcionais). - A rota PATCH /atualizar/:id deve salvar as atualizações do livro através de seu id. - A rota DELETE /remover/:id deve remover o livro através de seu id. <file_sep>/src/controllers/literaturaLGBTController.js const literaturaLGBTCollection = require('../model/literaturaLGBTSchema'); exports.get = (request, response) => { console.log(request.url); response.status(200).send(livro) }; const getAll = (request, response) => { literaturaLGBTCollection.find((error, livro) => { if(error){ return response.status(500).send(error) } else { return response.status(200).send(livro) } }) }; const getTitulo = (request, response) => { const titulo = request.params.titulo; const regex = new RegExp(titulo, "i"); const tituloFiltrado = { "titulo": regex }; literaturaLGBTCollection.find(tituloFiltrado, (error, titulo) => { if(error){ return response.send("O livro não foi encontrado em nosso sistema. Inserir sem acento.") } else { return response.status(200).send(titulo) } }) }; const getAutoria = (request, response) => { const autoria = request.params.autoria; const regex = new RegExp(autoria, "i"); const autoriaFiltrada = { "autoria": regex }; literaturaLGBTCollection.find(autoriaFiltrada, (error, autoria) => { if(error){ return response.send("A autoria não está no nosso sistema.") } else { return response.status(200).send(autoria) } }) }; const getEstiloNarrativo = (request, response) => { const estiloNarrativo = request.params.estiloNarrativo; const regex = new RegExp(estiloNarrativo, "i"); const estiloNarrativoFiltrado = { "estiloNarrativo": regex }; literaturaLGBTCollection.find(estiloNarrativoFiltrado, (error, estiloNarrativo) => { if(error){ return response.status(404).send("Não possuimos nenhum estilo literário no Bando de Dados") } else { return response.status(200).send(estiloNarrativo) } }) }; const getGeneroLiteratura = (request, response) => { const generoLiterario = request.params.generoLiterario; const regex = new RegExp(generoLiterario, "i"); const generoLiterarioFiltrado = { "generoLiterario": regex }; literaturaLGBTCollection.find(generoLiterarioFiltrado, (error, generoLiterario) => { if(error){ return response.send("Nenhum cadastro do gênero literário solicitado.") } else { return response.status(200).send(generoLiterario) } }) }; const criarLivro = (request, response) => { const novoTitulo = request.body const livro = new literaturaLGBTCollection( novoTitulo ) livro.save((error) => { if(error){ return response.status(400).send(error) } else { return response.status(201).send(livro) } }) } const atualizarLivro = (request, response) => { const id = request.params.id; const atualizacaoLivro = request.body; const options = {new:true} literaturaLGBTCollection.findByIdAndUpdate(id, atualizacaoLivro, options, (error, livro) => { if(error){ return response.status(500).send("O livro não encontrado!") } else { return response.status(404).send(livro) } }) } const deletarLivro = (request, response) => { const id = request.params.id literaturaLGBTCollection.findByIdAndRemove(id, (error, livro) => { if(error){ return response.status(500).send(error) } else if(livro){ return response.status(200).send("Livro excluído.") } else { return response.sendStatus(404) } }) } module.exports = { getAll, getTitulo, getAutoria, getEstiloNarrativo, getGeneroLiteratura, criarLivro, atualizarLivro, deletarLivro }
f9c1591a51804b563dfedda3e4f1bf8085de0ff9
[ "JavaScript", "Markdown" ]
3
JavaScript
tatianimeneghini/projeto-final-reprograma
f94398fcfcb7010ed6af525129c85a0e824577c7
706d1354d834f6e9d23b28c4136dcf26056641c9
refs/heads/master
<repo_name>rvpandey99/practice<file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { AngularFireModule } from '@angular/fire'; import { AngularFirestoreModule } from '@angular/fire/firestore'; import { AngularFireDatabaseModule } from '@angular/fire/database'; import { AngularFireAuthModule } from '@angular/fire/auth'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { AppComponent } from './app.component'; import { environment } from 'src/environments/environment'; import { BsNavbarComponent } from './bs-navbar/bs-navbar.component'; import { LoginComponent } from './login/login.component'; import { HomeComponent } from './home/home.component'; import { DashbordComponent } from './admin/dashbord/dashbord.component'; import { BeautyComponent } from './categories/beauty/beauty.component'; import { FashionComponent } from './categories/fashion/fashion.component'; import { LifeComponent } from './categories/life/life.component'; import { SidebarComponent } from './sidebar/sidebar.component'; import { CreateBlogComponent } from './admin/create-blog/create-blog.component'; import { SelectedBlogComponent } from './selected-blog/selected-blog.component'; import { AboutUsComponent } from './about-us/about-us.component'; import { AuthService } from './auth.service'; import { AuthGuardService } from './auth-guard.service'; import { UserService } from './user.service'; @NgModule({ declarations: [ AppComponent, BsNavbarComponent, HomeComponent, DashbordComponent, BeautyComponent, FashionComponent, LifeComponent, SidebarComponent, CreateBlogComponent, SelectedBlogComponent, LoginComponent, AboutUsComponent ], imports: [ BrowserModule, AngularFireModule.initializeApp(environment.firebase), AngularFirestoreModule, AngularFireDatabaseModule, AngularFireAuthModule, NgbModule.forRoot(), RouterModule.forRoot([ {path: '', component: HomeComponent }, {path: 'beauty', component: BeautyComponent}, {path: 'fashion', component: FashionComponent}, {path: 'life', component: LifeComponent}, {path: 'about-us', component: AboutUsComponent}, {path: 'login', component: LoginComponent}, {path: 'admin', component: DashbordComponent, canActivate: [AuthGuardService]}, {path: 'admin/create', component: CreateBlogComponent} ]) ], providers: [ AuthService, AuthGuardService, UserService ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/environments/environment.prod.ts export const environment = { production: true, firebase: { apiKey: '<KEY>', authDomain: 'maqshineonly.firebaseapp.com', databaseURL: 'https://maqshineonly.firebaseio.com', projectId: 'maqshineonly', storageBucket: 'maqshineonly.appspot.com', messagingSenderId: '120877718436' } };
c89a9798162785d179481b33eb8a2c8da571d3a0
[ "TypeScript" ]
2
TypeScript
rvpandey99/practice
4a9e011665e7256b6340b42b5e19d77dc5cafa78
163c4c90f5d05cb81a58f3a1874cd30f65ad6128
refs/heads/master
<file_sep>'use strict' console.log('Arrow functions:') var sum = (x,y) => x+y var add1 = x => sum(x,1) console.log(add1(5))
0952b776ec334a9900017056e733ca53605d2223
[ "JavaScript" ]
1
JavaScript
iagolaguna/curso-reactjs-ninja-impl
5df2058201fabb9e0f00112861867e5125c74c2b
6c19ba2850c869f42b136dae78942d1d56ea68ac
refs/heads/master
<repo_name>jonathanCNITA/sort_algo_JS<file_sep>/js/algos.js // Converts from degrees to radians. Math.toRadians = function(degrees) { return degrees * Math.PI / 180; }; function distanceFromGrenoble(city) { console.log("implement me !"); var GrenobleLat = 45.166667; var GrenobleLong = 5.716667; let RayonDeLaPlaneteTerre = 6371e3; // metres var φ1 = Math.toRadians(GrenobleLat); var φ2 = Math.toRadians(city.latitude); var Δφ = Math.toRadians((city.latitude-GrenobleLat)); var Δλ = Math.toRadians((city.longitude-GrenobleLong)); var a = Math.sin(Δφ/2) * Math.sin(Δφ/2) + Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ/2) * Math.sin(Δλ/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = RayonDeLaPlaneteTerre * c; return Math.round(d/1000); } function swap(i,j) // Swap the values in csvDataay csvData { displayBuffer.push(['swap', i, j]); // Do not delete this line (for display) [csvData[i], csvData[j]] = [csvData[j], csvData[i]]; // let temp = csvData[i]; // csvData[i] = csvData[j]; // csvData[j] = temp; } function isLess(A,B) { displayBuffer.push(['compare', A, B]); // Do not delete this line (for display) let cityA = csvData[A]; let cityB = csvData[B]; return cityA.dist < cityB.dist; } function insertsort() { console.log("insert me !"); for (let i = 1; i < csvData.length; i++) { for (let k = i; k > 0 ; k--) { if(isLess(k, k-1)) { swap(k, k-1); } } } } function selectionsort() { console.log("selection sort !"); for (let i = 0; i < csvData.length; i++) { let k = i; for (let j = i+1; j < csvData.length; j++) { if (isLess(j,k)) { k = j; } } swap(i,k); } } function bubblesort() { console.log("bubble sort !"); for (let i = 0; i < csvData.length; i++) { let swapped = false; for (let j = csvData.length - 1; j >= i+1; j--) { if(isLess(j, j-1)) { swap(j, j-1); swapped = true; } } if(!swapped) { break; } } } function insertionForShell(gap, s) { for (let i = s + gap; i < csvData.length; i += gap) { if (isLess(i, i - gap)) { swap(i , i - gap); } } } function shellsort() { console.log("Shell sort !"); let gap = Math.floor(csvData.length / 3); while ( gap > 0 ) { for (let s = 0; s < gap; s++) { insertionForShell(gap, s); } gap--; } } function mergesort(data) { console.log("implement me !"); } function heapsort(data) { console.log("implement me !"); } function quickSort2(start, end) { if(end <= start) { return; } let indexPivot = start; let k = start; for (let i = start + 1; i <= end; i++) { if( isLess(i, indexPivot)) { swap(++k,i); } } swap(k, indexPivot); // quickSort2(start, k-1); // left side // quickSort2(k+1, end); // right side } function quicksort() { quickSort2(0, csvData.length-1); } function quick3sort(data) { console.log("implement me !"); } var algorithms = { 'insert': insertsort, 'select': selectionsort, 'bubble': bubblesort, 'shell': shellsort, 'merge': mergesort, 'heap': heapsort, 'quick': quicksort, 'quick3': quick3sort } function sort(algo) { if (!algorithms.hasOwnProperty(algo)) { throw 'Invalid algorithm ' + algo; } var sort_fn = algorithms[algo]; sort_fn(); }
ed6eb3a8e0eb87c1188550ae95d26d65103e4897
[ "JavaScript" ]
1
JavaScript
jonathanCNITA/sort_algo_JS
908b7ca7d89c19514cc833651a56ea4d6eaeb470
0d2203601dc1a94bdf82f1e339c8a5c3f39d1134
refs/heads/main
<repo_name>henrytan0705/interactive-algorithms<file_sep>/frontend/src/App.js import CodingProblem from "./components/CodingProblem"; function App() { return ( <div> <CodingProblem /> </div> ); } export default App; <file_sep>/frontend/src/components/CodingProblem.js import { React, Fragment, Component } from "react"; class CodingProblem extends Component { constructor(props) { super(props); // Refactor with props this.state = { questionTitle: "FizzBuzz", questionPrompt: `Write a program that outputs the string representation of numbers from 1 to n. But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. Example: n = 15, Return: [ "1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz" ]`, userInput: "", testCases: `testOutput(fizzBuzz(1), '1'); testOutput(fizzBuzz(2), '2'); testOutput(fizzBuzz(3), 'Fizz'); testOutput(fizzBuzz(5), 'Buzz'); testOutput(fizzBuzz(15), 'Fizz Buzz'); `, success: "" }; this.update = this.update.bind(this); this.runCode = this.runCode.bind(this); } // Use for testing // function fizzBuzz(num){ // if (num % 3 === 0 && num % 5 === 0) { // return "Fizz Buzz"; // } else if (num % 3 === 0) { // return "Fizz"; // } else if (num % 5 === 0) { // return "Buzz"; // } // return num.toString; // } update(field) { return e => { this.setState({ [field]: e.target.value }); }; } runCode(e) { e.preventDefault(); let concatenated = ` ${this.state.userInput} let successStatus = true; function testOutput(actual, expected) { console.log(actual === expected); if (actual !== expected) { successStatus = false; } } ${this.state.testCases} successStatus; `; let pass = eval(concatenated); if (pass) { this.setState({ success: "All test cases passed!" }); } else { this.setState({ success: "1 or more test cases failed." }); } } render() { return ( <Fragment> <div> <h1>Header</h1> </div> <div> <h1>Splash Content</h1> </div> <div> <div> <h1>Coding Question</h1> <h2>{this.state.questionTitle}</h2> <div>{this.state.questionPrompt}</div> </div> <div> <form> <h1>User Code</h1> <div> <textarea rows="15" cols="50" onChange={this.update("userInput")} ></textarea> <button onClick={this.runCode}>Submit</button> </div> </form> </div> </div> <div> <h2>Results: </h2> {this.state.success} </div> <div> <h1>Footer</h1> </div> </Fragment> ); } } export default CodingProblem;
8c678169e46c368766eb05c2b4da60197708d2d5
[ "JavaScript" ]
2
JavaScript
henrytan0705/interactive-algorithms
ff433664dec6b334b7f703e3f3315d884df501bc
6d45f4eac8456de801bad2031df8dd88caf6c9dd
refs/heads/master
<file_sep>/** * Created by amorimoto on 16/03/11. */ 'use strict'; const electron = require('electron'); const app = electron.app; // Module to control application life. const BrowserWindow = electron.BrowserWindow; // Module to create native browser window. const ipc = require("electron").ipcMain; const fs = require('fs'); // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. var mainWindow = null; // Quit when all windows are closed. app.on('window-all-closed', function () { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform != 'darwin') { app.quit(); } }); // This method will be called when Electron has finished // initialization and is ready to create browser windows. app.on('ready', function () { // Create the browser window. mainWindow = new BrowserWindow({width: 800, height: 600}); // and load the index.html of the app. mainWindow.loadURL('file://' + __dirname + '/index.html'); // Open the DevTools. mainWindow.webContents.openDevTools(); // Emitted when the window is closed. mainWindow.on('closed', function () { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null; }); }); ipc.on('async-cache-request', function (event, filename) { var cachePath = app.getPath('cache') + '/' + filename; fs.readFile(cachePath, (err, data) => { if (data) { event.sender.send('asynchronous-cache-request-reply', cachePath); return; } event.sender.send('asynchronous-cache-request-reply', ''); }); }); ipc.on('async-cache-save-request', function (event, filename, body) { var cachePath = app.getPath('cache') + '/' + filename; console.log(cachePath, body); fs.readFile(cachePath, (err, data) => { if (err) { fs.writeFile(cachePath, body, 'binary', (err) => { if (err) { event.sender.send('asynchronous-cache-request-reply', ''); } console.log('It\'s saved!'); event.sender.send('asynchronous-cache-request-reply', cachePath); }); } }); });<file_sep>## webpack ####getting started http://webpack.github.io/docs/tutorials/getting-started/ ####webpack.config.js この名前のファイルを設定ファイルと認識して読みに行く entry |_ エントリポイント output |_ path アウトプットの出力先パス |_ filename ファイル名 module |_ loaders 配列で指定する。 test: にファイルのマッチ条件を書くと満たしている場合loaderで変換される http://webpack.github.io/docs/configuration.html#module-loaders ##PostCSS https://github.com/postcss/postcss <file_sep># js-playground :raising_hand: <file_sep>## Electron + babel + es6 #### 導入 http://qiita.com/inuscript/items/a3822167604e5ad6c19b #### jQuery http://qiita.com/pirosikick/items/72d11a8578c5c3327069 #### es6でReactの注意点 http://stackoverflow.com/questions/30720620/reactjs-w-ecmascript-6 https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding
0e7239e37c29838c56941f9be325b83d35a009a9
[ "JavaScript", "Markdown" ]
4
JavaScript
moriiimo/js-playground
eb38750f240f6ee461e86a9a46b9e2894d72dc81
ab1165ed3c4325d1d821f6bd19f8c3c419b2f992
refs/heads/master
<file_sep>package steps; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; import io.restassured.response.Response; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.equalTo; public class GetPostSteps { @Given("I initiate the url") public void i_initiate_the_url() { // Write code here that turns the phrase above into concrete actions PerformPost(); } @When("I do a post") public void i_do_a_post() { // Write code here that turns the phrase above into concrete actions //throw new cucumber.api.PendingException(); } @Then("I get a response") public void i_get_a_response() { // Write code here that turns the phrase above into concrete actions // throw new cucumber.api.PendingException(); } public void PerformPost() { Response response = given() .get("http://parabank.parasoft.com/parabank/services/bank/customers/12212/"). then(). assertThat().body("customer.id", equalTo("12212")). and(). assertThat().body("customer.firstName", equalTo("John")). and(). assertThat().body("customer.lastName", equalTo("Smith")). extract().response(); System.out.println(response.body()); String responseBody = response.getBody().asString(); } }
a4af20d0ac78023830a767cc94f8d9f099f06a35
[ "Java" ]
1
Java
nikblackshaw/javarestassuredtestframework
c315f0b142c4c3ea732cd3019a8f6e81522bc3cb
b86512d679dcf39fc3daec9eb116176e6dc03ba7
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WpfTest { class Constants { public static string authUrl = "http://localhost:15536/oauth/authorize?client_id=b20033f1-af49-421f-81b9-5e32bc7f5149&redirect_uri=http%3a%2f%2flocalhost%3a49676%2ftoken&response_type=code&state=e4f2c78d-aac8-40ba-857a-a7f03eefb084"; } } <file_sep>using Newtonsoft.Json; using NopCommerce.Api.SampleApplication.Controllers; using NopCommerce.Api.SampleApplication.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using WpfTest.DTOs; namespace WpfTest { /// <summary> /// Interaction logic for AddProduct.xaml /// </summary> public partial class AddProduct : Window { private MainController _mainController; static HttpClient client = new HttpClient(); public AddProduct(MainController mainController) { _mainController = mainController; InitializeComponent(); } private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { } private void Button_Click(object sender, RoutedEventArgs e) { ProductDTO productDTO = new ProductDTO(); productDTO.name = ImeProizvoda.Text; productDTO.short_description = KratakOpis.Text; productDTO.full_description = KompletanOpis.Text; productDTO.sku = Sku.Text; productDTO.stock_quantity = Kolicina.Text; productDTO.price = Cena.Text; productDTO.old_price = StaraCena.Text; productDTO.weight = Tezina.Text; productDTO.length = Duzina.Text; productDTO.width = Sirina.Text; productDTO.height = Visina.Text; var convertedModel = JsonConvert.SerializeObject(productDTO); //CreateProductAsync(userAccessModel); new HttpClient().PostAsync("http://localhost:9388/addproduct", new StringContent(convertedModel, Encoding.UTF8, "application/json")); // new HttpClient().GetAsync("http://localhost:9388/getcustomers"); // _authorizationController.Submit(userAccessModel); } static async Task<Uri> CreateProductAsync(UserAccessModel userAccessModel) { HttpResponseMessage response = await client.PostAsJsonAsync( "http://localhost:9388/submit", userAccessModel); response.EnsureSuccessStatusCode(); // return URI of the created resource. return response.Headers.Location; } } } //http://localhost:15536/oauth/authorize?client_id=b20033f1-af49-421f-81b9-5e32bc7f5149 // &redirect_uri=http%3a%2f%2flocalhost%3a49676%2ftoken // &response_type=code&state=e4f2c78d-aac8-40ba-857a-a7f03eefb084 //http://localhost:15536/oauth/authorize?client_id=b20033f1-af49-421f-81b9-5e32bc7f5149 //&redirect_uri=http%3A%2F%2Flocalhost%3A9388%2Ftoken //&response_type=code&state=6545e277-5bd8-41d8-bf3c-6d417976c257" <file_sep>using System.Dynamic; using System.Linq; using Microsoft.AspNetCore.Http; //using System.Web.Mvc; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using NopCommerce.Api.AdapterLibrary; using NopCommerce.Api.SampleApplication.DTOs; //using NopCommerce.Api.SampleApplication.DTOs; namespace NopCommerce.Api.SampleApplication.Controllers { public class CustomersController : Controller { public ActionResult UpdateCustomer(int customerId) { var accessToken = (HttpContext.Session.GetString("accessToken") ?? TempData["accessToken"]).ToString(); var serverUrl = (HttpContext.Session.GetString("serverUrl") ?? TempData["serverUrl"]).ToString(); var nopApiClient = new ApiClient(accessToken, serverUrl); string jsonUrl = $"/api/customers/{customerId}"; // we use anonymous type as we want to update only the last_name of the customer // also the customer shoud be the cutomer property of a holder object as explained in the documentation // https://github.com/SevenSpikes/api-plugin-for-nopcommerce/blob/nopcommerce-3.80/Customers.md#update-details-for-a-customer // i.e: { customer : { last_name: "" } } var customerToUpdate = new { customer = new { last_name = "" } }; string customerJson = JsonConvert.SerializeObject(customerToUpdate); nopApiClient.Put(jsonUrl, customerJson); return RedirectToAction("GetCustomers"); } } }<file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WpfTest.DTOs { class CategoryPostDTO { [JsonProperty("category")] public CategoryDTO category { get; set; } } } <file_sep>using Newtonsoft.Json; using NopCommerce.Api.SampleApplication.DTOs; using NopCommerce.Api.SampleApplication.Models; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Windows; namespace WpfTest { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Loaded += MyWindow_Loaded; } private void MyWindow_Loaded(object sender, RoutedEventArgs e) { GetToken(); } private async void Window_Loaded(object sender, RoutedEventArgs e) { await HostBuilder.Start(); } private void AddProduct_Click(object sender, RoutedEventArgs e) { AddProduct addProduct = new AddProduct(new NopCommerce.Api.SampleApplication.Controllers.MainController()); addProduct.Show(); } private void AddCategory_Click(object sender, RoutedEventArgs e) { AddCategory addCategory = new AddCategory(); addCategory.Show(); } private void ViewCategory_Click(object sender, RoutedEventArgs e) { HttpClient httpClient = new HttpClient(); ViewCategory viewCategory = new ViewCategory(); viewCategory.Show(); string response = httpClient.GetAsync("http://localhost:9388/getcustomers").Result.Content.ReadAsStringAsync().Result; // CustomersRootObject customers = new CustomersRootObject(); CustomersRootObject customers = JsonConvert.DeserializeObject<CustomersRootObject>(response); } private void GetToken() { UserAccessModel userAccessModel = new UserAccessModel(); userAccessModel.ClientId = "b20033f1-af49-421f-81b9-5e32bc7f5149"; userAccessModel.ClientSecret = "<KEY>"; userAccessModel.RedirectUrl = "http://localhost:9388/token"; userAccessModel.ServerUrl = "http://localhost:15536"; var convertedModel = JsonConvert.SerializeObject(userAccessModel); //CreateProductAsync(userAccessModel); new HttpClient().PostAsync("http://localhost:9388/Submit", new StringContent(convertedModel, Encoding.UTF8, "application/json")); } private Task<HttpResponseMessage> GetCustomersAsync() { return new HttpClient().GetAsync("http://localhost:9388/getcustomers"); } private void ViewProduct_Click(object sender, RoutedEventArgs e) { ViewProduct viewProduct = new ViewProduct(); viewProduct.Show(); } private void Button_Click(object sender, RoutedEventArgs e) { AddCustomer addCustomer = new AddCustomer(); addCustomer.Show(); } } } <file_sep>using Newtonsoft.Json; using NopCommerce.Api.SampleApplication.DTOs; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WpfTest.DTOs { public class CustomerSendDTO { [JsonProperty("customer")] public CustomerCreateDTO customer { get; set; } } } <file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WpfTest.DTOs { public class CustomerCreateDTO { [JsonProperty("first_name")] public string FirstName { get; set; } [JsonProperty("last_name")] public string LastName { get; set; } [JsonProperty("date_of_birth")] public string DateOfBirth { get; set; } [JsonProperty("email")] public string Email { get; set; } [JsonProperty("role_ids")] public ICollection<int> CustomerRoles { get; set; } = new List<int>(); } } <file_sep>using System; using Newtonsoft.Json; using Microsoft.AspNetCore.Http; using NopCommerce.Api.SampleApplication.Models; using NopCommerce.Api.SampleApplication.Managers; using NopCommerce.Api.SampleApplication.Parameters; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using NopCommerce.Api.AdapterLibrary; using NopCommerce.Api.SampleApplication.DTOs; using System.Linq; using WpfTest.DTOs; using System.Collections.Generic; namespace NopCommerce.Api.SampleApplication.Controllers { public class MainController :Controller { [HttpPost("/submit")] [AllowAnonymous] //TODO: it is recommended to have an [Authorize] attribute set public ActionResult Submit([FromBody] UserAccessModel model) { if (ModelState.IsValid) { try { var nopAuthorizationManager = new AuthorizationManager(model.ClientId, model.ClientSecret, model.ServerUrl); var redirectUrl = Url.RouteUrl("GetAccessToken", null, HttpContext.Request.Scheme); // "http://localhost:9388/token"; if (redirectUrl != model.RedirectUrl) { return BadRequest(); } var convertedId = JsonConvert.SerializeObject(model.ClientId); var convertedSecret = JsonConvert.SerializeObject(model.ClientSecret); var convertedServerUrl = JsonConvert.SerializeObject(model.ServerUrl); var convertedredirectUrl = JsonConvert.SerializeObject(redirectUrl); //var convertedstate = JsonConvert.SerializeObject(state); // For demo purposes this data is kept into the current Session, but in production environment you should keep it in your database HttpContext.Session.SetString("clientId", model.ClientId); HttpContext.Session.SetString("clientSecret", model.ClientSecret); HttpContext.Session.SetString("serverUrl", model.ServerUrl); HttpContext.Session.SetString("redirectUrl", model.RedirectUrl); // This should not be saved anywhere. var state = Guid.NewGuid(); // var convertedstate = JsonConvert.SerializeObject(state); HttpContext.Session.SetString("state", state.ToString()); string authUrl = nopAuthorizationManager.BuildAuthUrl(redirectUrl, new string[] { }, state.ToString()); return Redirect(authUrl); } catch (Exception ex) { return BadRequest(ex.Message); } } return BadRequest(); } [HttpGet("/token", Name = "GetAccessToken")] [AllowAnonymous] public ActionResult GetAccessToken(string code, string state) { if (ModelState.IsValid && !string.IsNullOrEmpty(code) && !string.IsNullOrEmpty(state)) { if (state != HttpContext.Session.GetString("state")) { return BadRequest(); } var model = new AccessModel(); try { // TODO: Here you should get the authorization user data from the database instead from the current Session. string clientId = HttpContext.Session.GetString("clientId"); string clientSecret = HttpContext.Session.GetString("clientSecret"); string serverUrl = HttpContext.Session.GetString("serverUrl"); string redirectUrl = HttpContext.Session.GetString("redirectUrl"); var authParameters = new AuthParameters() { ClientId = clientId, ClientSecret = clientSecret, ServerUrl = serverUrl, RedirectUrl = redirectUrl, GrantType = "authorization_code", Code = code }; var nopAuthorizationManager = new AuthorizationManager(authParameters.ClientId, authParameters.ClientSecret, authParameters.ServerUrl); string responseJson = nopAuthorizationManager.GetAuthorizationData(authParameters); AuthorizationModel authorizationModel = JsonConvert.DeserializeObject<AuthorizationModel>(responseJson); model.AuthorizationModel = authorizationModel; model.UserAccessModel = new UserAccessModel() { ClientId = clientId, ClientSecret = clientSecret, ServerUrl = serverUrl, RedirectUrl = redirectUrl }; var authorizationModelConverted = JsonConvert.SerializeObject(authorizationModel.AccessToken); // TODO: Here you can save your access and refresh tokens in the database. For illustration purposes we will save them in the Session and show them in the view. HttpContext.Session.SetString("accessToken", authorizationModel.AccessToken); using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"auth.txt", true)) { file.WriteLine(authorizationModel.AccessToken); file.WriteLine(authParameters.ServerUrl); } TempData["accessToken"] = authorizationModel.AccessToken; TempData["serverUrl"] = serverUrl; } catch (Exception ex) { return BadRequest(ex.Message); } return View("~/Views/AccessToken.cshtml", model); } return BadRequest(); } [HttpGet] public IActionResult RefreshAccessToken(string refreshToken, string clientId, string clientSecret, string serverUrl) { string json = string.Empty; if (ModelState.IsValid && !string.IsNullOrEmpty(refreshToken) && !string.IsNullOrEmpty(clientId) && !string.IsNullOrEmpty(clientSecret) && !string.IsNullOrEmpty(serverUrl)) { var model = new AccessModel(); try { var authParameters = new AuthParameters() { ClientId = clientId, ClientSecret = clientSecret, ServerUrl = serverUrl, RefreshToken = refreshToken, GrantType = "refresh_token" }; var nopAuthorizationManager = new AuthorizationManager(authParameters.ClientId, authParameters.ClientSecret, authParameters.ServerUrl); string responseJson = nopAuthorizationManager.RefreshAuthorizationData(authParameters); AuthorizationModel authorizationModel = JsonConvert.DeserializeObject<AuthorizationModel>(responseJson); model.AuthorizationModel = authorizationModel; model.UserAccessModel = new UserAccessModel() { ClientId = clientId, ServerUrl = serverUrl }; // Here we use the temp data because this method is called via ajax and here we can't hold a session. // This is needed for the GetCustomers method in the CustomersController. TempData["accessToken"] = authorizationModel.AccessToken; TempData["serverUrl"] = serverUrl; } catch (Exception ex) { json = string.Format("error: '{0}'", ex.Message); return Ok(json); } json = JsonConvert.SerializeObject(model.AuthorizationModel); } else { json = "error: 'something went wrong'"; } return Ok(json); } [HttpGet("getcustomers", Name = "GetCustomers")] [AllowAnonymous] public ActionResult GetCustomers() { // TODO: Here you should get the data from your database instead of the current Session. // Note: This should not be done in the action! This is only for illustration purposes. string [] lines = System.IO.File.ReadAllLines(@"auth.txt"); var accessToken = lines[0]; //Settings.Default["accessToken"].ToString();//HttpContext.Session.GetString("accessToken"); var serverUrl = lines[1]; var nopApiClient = new ApiClient(accessToken, serverUrl); string jsonUrl = $"/api/customers?fields=id,first_name,last_name"; object customersData = nopApiClient.Get(jsonUrl); var customersRootObject = JsonConvert.DeserializeObject<CustomersRootObject>(customersData.ToString()); var customers = customersRootObject.Customers.Where( customer => !string.IsNullOrEmpty(customer.FirstName) || !string.IsNullOrEmpty(customer.LastName)); return Ok(customersRootObject); } [HttpGet("getproducts/{id}", Name = "GetProduct")] [AllowAnonymous] public ActionResult GetProduct(int id) { // TODO: Here you should get the data from your database instead of the current Session. // Note: This should not be done in the action! This is only for illustration purposes. string[] lines = System.IO.File.ReadAllLines(@"auth.txt"); var accessToken = lines[0]; //Settings.Default["accessToken"].ToString();//HttpContext.Session.GetString("accessToken"); var serverUrl = lines[1]; var nopApiClient = new ApiClient(accessToken, serverUrl); string jsonUrl = String.Format("/api/products/{0}",id);//$"/api/products?ids={}"; object customersData = nopApiClient.Get(jsonUrl); var productsRaw = JsonConvert.DeserializeObject<ProductsRootObject>(customersData.ToString()); //var customers = productsRaw.Products.Where( // customer => !string.IsNullOrEmpty(customer.FirstName) || !string.IsNullOrEmpty(customer.LastName)); return Ok(productsRaw); } [HttpDelete("deleteproducts/{id}", Name = "DeleteProduct")] [AllowAnonymous] public ActionResult DeleteProduct(int id) { // TODO: Here you should get the data from your database instead of the current Session. // Note: This should not be done in the action! This is only for illustration purposes. string[] lines = System.IO.File.ReadAllLines(@"auth.txt"); var accessToken = lines[0]; //Settings.Default["accessToken"].ToString();//HttpContext.Session.GetString("accessToken"); var serverUrl = lines[1]; var nopApiClient = new ApiClient(accessToken, serverUrl); string jsonUrl = String.Format("/api/products/{0}", id);//$"/api/products?ids={}"; object customersData = nopApiClient.Delete(jsonUrl); return Ok(); } [HttpDelete("deletecategories/{id}", Name = "DeleteCategory")] [AllowAnonymous] public ActionResult DeleteCategory(int id) { // TODO: Here you should get the data from your database instead of the current Session. // Note: This should not be done in the action! This is only for illustration purposes. string[] lines = System.IO.File.ReadAllLines(@"auth.txt"); var accessToken = lines[0]; //Settings.Default["accessToken"].ToString();//HttpContext.Session.GetString("accessToken"); var serverUrl = lines[1]; var nopApiClient = new ApiClient(accessToken, serverUrl); string jsonUrl = String.Format("/api/categories/{0}", id);//$"/api/products?ids={}"; object customersData = nopApiClient.Delete(jsonUrl); return Ok(); } [HttpGet("getproducts", Name = "GetProducts")] [AllowAnonymous] public ActionResult GetProducts() { // TODO: Here you should get the data from your database instead of the current Session. // Note: This should not be done in the action! This is only for illustration purposes. string[] lines = System.IO.File.ReadAllLines(@"auth.txt"); var accessToken = lines[0]; //Settings.Default["accessToken"].ToString();//HttpContext.Session.GetString("accessToken"); var serverUrl = lines[1]; var nopApiClient = new ApiClient(accessToken, serverUrl); string jsonUrl = $"/api/products?fields=id"; object productsData = nopApiClient.Get(jsonUrl); var productsRaw = JsonConvert.DeserializeObject<ProductsRootObject>(productsData.ToString()); //List<int> niz = new List<int>(); //foreach(ProductDTO prod in productsRaw.Products) //{ // niz.Add(prod.id); //} return Ok(productsRaw); } [HttpPost("/addproduct")] [AllowAnonymous] public ActionResult AddProduct([FromBody] ProductDTO product) { string[] lines = System.IO.File.ReadAllLines(@"auth.txt"); var accessToken = lines[0]; //Settings.Default["accessToken"].ToString();//HttpContext.Session.GetString("accessToken"); var serverUrl = lines[1]; ProductSendDTO productSendDTO = new ProductSendDTO(); productSendDTO.product = product; var nopApiClient = new ApiClient(accessToken, serverUrl); var convertedModel = JsonConvert.SerializeObject(productSendDTO, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); string jsonUrl = $"/api/products"; object productsData = nopApiClient.Post(jsonUrl, convertedModel); return Ok(); } [HttpPost("/updateproduct")] [AllowAnonymous] public ActionResult UpdateProduct([FromBody] ProductDTO product) { string[] lines = System.IO.File.ReadAllLines(@"auth.txt"); var accessToken = lines[0]; //Settings.Default["accessToken"].ToString();//HttpContext.Session.GetString("accessToken"); var serverUrl = lines[1]; ProductSendDTO productSendDTO = new ProductSendDTO(); productSendDTO.product = product; var nopApiClient = new ApiClient(accessToken, serverUrl); var convertedModel = JsonConvert.SerializeObject(productSendDTO, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); string jsonUrl = String.Format("/api/products/{0}", product.id); object productsData = nopApiClient.Put(jsonUrl, convertedModel); return Ok(); } [HttpPost("/addcategory")] [AllowAnonymous] public ActionResult AddCategory([FromBody] CategoryDTO category) { string[] lines = System.IO.File.ReadAllLines(@"auth.txt"); var accessToken = lines[0]; //Settings.Default["accessToken"].ToString();//HttpContext.Session.GetString("accessToken"); var serverUrl = lines[1]; CategoryPostDTO categoryPostDTO = new CategoryPostDTO(); categoryPostDTO.category = category; var nopApiClient = new ApiClient(accessToken, serverUrl); var convertedModel = JsonConvert.SerializeObject(categoryPostDTO, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); string jsonUrl = $"/api/categories"; object productsData = nopApiClient.Post(jsonUrl, convertedModel); return Ok(); } [HttpPost("/updatecategory")] [AllowAnonymous] public ActionResult UpdateCategory([FromBody] CategoryUpdateDTO category) { string[] lines = System.IO.File.ReadAllLines(@"auth.txt"); var accessToken = lines[0]; //Settings.Default["accessToken"].ToString();//HttpContext.Session.GetString("accessToken"); var serverUrl = lines[1]; CategoryDTO categoryDTO = new CategoryDTO(); categoryDTO.name = category.name; categoryDTO.description = category.description; CategoryPostDTO categoryPostDTO = new CategoryPostDTO(); categoryPostDTO.category = categoryDTO; var nopApiClient = new ApiClient(accessToken, serverUrl); var convertedModel = JsonConvert.SerializeObject(categoryPostDTO, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); string jsonUrl = String.Format("/api/categories/{0}", category.id); object productsData = nopApiClient.Put(jsonUrl, convertedModel); return Ok(); } [HttpGet("getcategories", Name = "GetCategories")] [AllowAnonymous] public ActionResult GetCategories() { // TODO: Here you should get the data from your database instead of the current Session. // Note: This should not be done in the action! This is only for illustration purposes. string[] lines = System.IO.File.ReadAllLines(@"auth.txt"); var accessToken = lines[0]; //Settings.Default["accessToken"].ToString();//HttpContext.Session.GetString("accessToken"); var serverUrl = lines[1]; var nopApiClient = new ApiClient(accessToken, serverUrl); string jsonUrl = $"/api/categories?fields=id"; object productsData = nopApiClient.Get(jsonUrl); var productsRaw = JsonConvert.DeserializeObject<CategoriesRootObject>(productsData.ToString()); return Ok(productsRaw); } [HttpGet("getcategories/{id}", Name = "GetCategory")] [AllowAnonymous] public ActionResult GetCategory(int id) { // TODO: Here you should get the data from your database instead of the current Session. // Note: This should not be done in the action! This is only for illustration purposes. string[] lines = System.IO.File.ReadAllLines(@"auth.txt"); var accessToken = lines[0]; //Settings.Default["accessToken"].ToString();//HttpContext.Session.GetString("accessToken"); var serverUrl = lines[1]; var nopApiClient = new ApiClient(accessToken, serverUrl); string jsonUrl = String.Format("/api/categories/{0}", id); object productsData = nopApiClient.Get(jsonUrl); var productsRaw = JsonConvert.DeserializeObject<CategoriesRootObject>(productsData.ToString()); //List<int> niz = new List<int>(); //foreach(ProductDTO prod in productsRaw.Products) //{ // niz.Add(prod.id); //} return Ok(productsRaw); } [HttpPost("/addcustomer")] [AllowAnonymous] public ActionResult AddCustomer([FromBody] CustomerCreateDTO customer) { string[] lines = System.IO.File.ReadAllLines(@"auth.txt"); var accessToken = lines[0]; //Settings.Default["accessToken"].ToString();//HttpContext.Session.GetString("accessToken"); var serverUrl = lines[1]; CustomerSendDTO customerSendDTO = new CustomerSendDTO(); customerSendDTO.customer= customer; var nopApiClient = new ApiClient(accessToken, serverUrl); var convertedModel = JsonConvert.SerializeObject(customerSendDTO, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); string jsonUrl = $"/api/customers"; object productsData = nopApiClient.Post(jsonUrl, convertedModel); return Ok(); } private IActionResult BadRequestMsg(string message = "Bad Request") { return BadRequest(message); } } }<file_sep>using Newtonsoft.Json; using NopCommerce.Api.SampleApplication.DTOs; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using WpfTest.DTOs; namespace WpfTest { /// <summary> /// Interaction logic for AddCustomer.xaml /// </summary> public partial class AddCustomer : Window { private string role; public AddCustomer() { InitializeComponent(); } private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { ComboBox cmb = sender as ComboBox; role = cmb.SelectedItem.ToString().Split(':')[1]; } private void Button_Click(object sender, RoutedEventArgs e) { CustomerCreateDTO customerDTO = new CustomerCreateDTO(); customerDTO.FirstName = ImeKorisnika.Text; customerDTO.LastName = PrezimeKorisnika.Text; customerDTO.Email = Email.Text; customerDTO.CustomerRoles.Add(3); var convertedModel = JsonConvert.SerializeObject(customerDTO); //CreateProductAsync(userAccessModel); new HttpClient().PostAsync("http://localhost:9388/addcustomer", new StringContent(convertedModel, Encoding.UTF8, "application/json")); } } } <file_sep>using System; using System.Collections.Generic; using Newtonsoft.Json; namespace WpfTest.DTOs { public class ProductsRootObject { [JsonProperty("products")] public List<ProductDTO> Products { get; set; } } } <file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WpfTest.DTOs { public class ProductDTO { [JsonProperty("id")] public int id { get; set; } [JsonProperty("name")] public string name { get; set; } [JsonProperty("short_description")] public string short_description { get; set; } [JsonProperty("full_description")] public string full_description { get; set; } [JsonProperty("show_on_home_page")] public string show_on_home_page { get; set; } [JsonProperty("sku")] public string sku { get; set; } [JsonProperty("price")] public string price { get; set; } [JsonProperty("weight")] public string weight { get; set; } [JsonProperty("length")] public string length { get; set; } [JsonProperty("height")] public string height { get; set; } [JsonProperty("width")] public string width { get; set; } [JsonProperty("stock_quantity")] public string stock_quantity { get; set; } [JsonProperty("old_price")] public string old_price { get; set; } [JsonProperty("special_price")] public string special_price { get; set; } [JsonProperty("special_price_start_date_time_utc")] public string special_price_start_date_time_utc { get; set; } [JsonProperty("special_price_end_date_time_utc")] public string special_price_end_date_time_utc { get; set; } } } <file_sep>using System.Collections.Generic; using Newtonsoft.Json; namespace NopCommerce.Api.SampleApplication.DTOs { public class CustomersRootObject { [JsonProperty("customers")] public List<CustomerDTO> Customers { get; set; } } }<file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using WpfTest.DTOs; namespace WpfTest { /// <summary> /// Interaction logic for AddCategory.xaml /// </summary> public partial class AddCategory : Window { public AddCategory() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { CategoryDTO categoryDTO = new CategoryDTO(); categoryDTO.name = ImeKategorije.Text; categoryDTO.description = Opis.Text; var convertedModel = JsonConvert.SerializeObject(categoryDTO); //CreateProductAsync(userAccessModel); new HttpClient().PostAsync("http://localhost:9388/addcategory", new StringContent(convertedModel, Encoding.UTF8, "application/json")); } } } <file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WpfTest.DTOs { class CategoriesRootObject { [JsonProperty("categories")] public List<CategoryFullDTO> Categories { get; set; } } } <file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using WpfTest.DTOs; namespace WpfTest { /// <summary> /// Interaction logic for ViewCategory.xaml /// </summary> public partial class ViewCategory : Window { private int num; private List<int> ids = new List<int>(); private string no; public ViewCategory() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { CategoryUpdateDTO categoryDTO = new CategoryUpdateDTO(); categoryDTO.id = Convert.ToInt32(no); categoryDTO.name = NazivKategorije.Text; categoryDTO.description = OpisKategorije.Text; var convertedModel = JsonConvert.SerializeObject(categoryDTO); //CreateProductAsync(userAccessModel); new HttpClient().PostAsync("http://localhost:9388/updatecategory", new StringContent(convertedModel, Encoding.UTF8, "application/json")); } private void Category_Loaded(object sender, RoutedEventArgs e) { Intialize(); } private void Intialize() { HttpClient httpClient = new HttpClient(); HttpResponseMessage response = httpClient.GetAsync("http://localhost:9388/getcategories").Result; var res = response.Content.ReadAsStringAsync().Result; var lista = JsonConvert.DeserializeObject<CategoriesRootObject>(res); num = lista.Categories.ToArray().Length; foreach (CategoryFullDTO categoryDTO in lista.Categories) { ids.Add(categoryDTO.id); categoriesCombo.Items.Add(categoryDTO.id); } } private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { ComboBox cmb = sender as ComboBox; no = cmb.SelectedItem.ToString(); HttpClient httpClient = new HttpClient(); string response = httpClient.GetAsync("http://localhost:9388/getcategories/" + no).Result.Content.ReadAsStringAsync().Result; var categoriesRoot = JsonConvert.DeserializeObject<CategoriesRootObject>(response); var categories = categoriesRoot.Categories; foreach (var category in categories) { NazivKategorije.Text = category.name; OpisKategorije.Text = category.description; } } private void Button_Click_1(object sender, RoutedEventArgs e) { HttpClient httpClient = new HttpClient(); HttpResponseMessage response = httpClient.DeleteAsync("http://localhost:9388/deletecategories/" + no).Result; var res = response.Content.ReadAsStringAsync().Result; } } } <file_sep>using Newtonsoft.Json; using System.Collections.Generic; namespace NopCommerce.Api.SampleApplication.DTOs { // Simplified Customer dto object with only the first and last name public class CustomerDTO { [JsonProperty("id")] public int Id { get; set; } [JsonProperty("first_name")] public string FirstName { get; set; } [JsonProperty("last_name")] public string LastName { get; set; } [JsonProperty("date_of_birth")] public string DateOfBirth { get; set; } [JsonProperty("email")] public string Email { get; set; } [JsonProperty("role_ids")] public List<int> CustomerRoles { get; set; } = new List<int>(); } }<file_sep> using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WpfTest { public class SessionIndexer { private ISession Session; public SessionIndexer(ISession Session) { this.Session = Session; } public byte[] this[string key] { set { Session.Set(key, value); } get { return Session.Get(key); } } } } <file_sep> using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using WpfTest.DTOs; namespace WpfTest { /// <summary> /// Interaction logic for ViewProduct.xaml /// </summary> public partial class ViewProduct : Window { private int num = 0; private List<int> ids = new List<int>(); private string no; //private List<int> ids = new List<int>(); public ViewProduct() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { ProductDTO productDTO = new ProductDTO(); productDTO.id = Convert.ToInt32(no); productDTO.name = ImeProizvoda.Text; productDTO.short_description = KratakOpis.Text; productDTO.full_description = KompletanOpis.Text; productDTO.sku = Sku.Text; productDTO.stock_quantity = Kolicina.Text; productDTO.price = Cena.Text; productDTO.old_price = StaraCena.Text; productDTO.weight = Tezina.Text; productDTO.length = Duzina.Text; productDTO.width = Sirina.Text; productDTO.height = Visina.Text; var convertedModel = JsonConvert.SerializeObject(productDTO); //CreateProductAsync(userAccessModel); new HttpClient().PostAsync("http://localhost:9388/updateproduct", new StringContent(convertedModel, Encoding.UTF8, "application/json")); } private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { ComboBox cmb = sender as ComboBox; no = cmb.SelectedItem.ToString(); HttpClient httpClient = new HttpClient(); string response = httpClient.GetAsync("http://localhost:9388/getproducts/" + no).Result.Content.ReadAsStringAsync().Result; var productRoot = JsonConvert.DeserializeObject<ProductsRootObject>(response); var product = productRoot.Products; foreach (var prod in product) { ImeProizvoda.Text = prod.name; KratakOpis.Text = prod.full_description; Sku.Text = prod.sku; Kolicina.Text = prod.stock_quantity; Cena.Text = prod.price; StaraCena.Text = prod.old_price; Tezina.Text = prod.weight; Duzina.Text = prod.length; Sirina.Text = prod.width; Visina.Text = prod.height; } } private void Product_Loaded(object sender, RoutedEventArgs e) { Intialize(); } private void Intialize() { HttpClient httpClient = new HttpClient(); HttpResponseMessage response = httpClient.GetAsync("http://localhost:9388/getproducts").Result; var res = response.Content.ReadAsStringAsync().Result; var lista = JsonConvert.DeserializeObject<ProductsRootObject>(res); num = lista.Products.ToArray().Length; foreach (ProductDTO productDTO in lista.Products) { ids.Add(productDTO.id); comboProducts.Items.Add(productDTO.id); } } private void Button_Click_1(object sender, RoutedEventArgs e) { HttpClient httpClient = new HttpClient(); string response = httpClient.DeleteAsync("http://localhost:9388/deleteproducts/" + no).Result.StatusCode.ToString(); if(response.Equals("OK")) MessageBox.Show("Obrisano !", "My App"); } } }
3084c2c0a304a1e7be5645a9ed28d83657897bed
[ "C#" ]
18
C#
Phillipposs/ProductManagerApp
ff7924899bed7d4987405b9acb59b9cc45f47658
370caf8a04258c5c5ce38368b746a2b9c954ce71
refs/heads/main
<file_sep>package com.security.location import android.content.Context import android.content.DialogInterface import android.content.Intent import android.content.pm.PackageManager import android.location.* import android.os.Bundle import android.provider.Settings import android.view.View import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import java.io.IOException import java.util.* class MainActivity : AppCompatActivity(),LocationListener{ lateinit var locationManager:LocationManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) grantPermission() checkLocationIsEnabledOrNot() } private fun getLocation() { try { val locationManager:LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 500, 5f, (this as LocationListener) ) }catch (e:SecurityException){ e.printStackTrace() } } private fun checkLocationIsEnabledOrNot() { val lm:LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager var gpsEnabled=false var networkEnabled=false try { gpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER) }catch (e:Exception){ e.printStackTrace() } try { networkEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER) }catch (e:Exception){ e.printStackTrace() } if(!gpsEnabled && !networkEnabled){ AlertDialog.Builder(this) .setTitle("Enable GPS Service") .setCancelable(false) .setPositiveButton("Enable",DialogInterface.OnClickListener { dialog, id -> startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)) }).setNegativeButton("Cancel",null) .show() } } override fun onLocationChanged(location: Location) { try { val geocoder= Geocoder(applicationContext, Locale.getDefault()) val address: List<Address> = geocoder.getFromLocation( location.latitude, location.longitude, 1 ) Toast.makeText(this,"${address.get(0).countryCode}----${address[0].adminArea}" + "----${address[0].locality}----${address[0].postalCode}" + "----${address[0].getAddressLine(0)}",Toast.LENGTH_LONG).show() }catch (e:IOException){ e.printStackTrace() } } fun grantPermission(){ if(ContextCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(applicationContext,android.Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION),100) } } fun LocationButton(view: View) { getLocation() } }
3e6329e34b32066e7d3ea6e5071bf03ec0c19a0d
[ "Kotlin" ]
1
Kotlin
Vivekdembla/LocationTracker
49025b60a5a8b41567bef2f25b6fffcd4fd237ea
efed21d88d0000b4b86d158453395d5de7d4d5b1
refs/heads/master
<file_sep>// // MusicItem.swift // inf_musicGallery_ios // // Created by <NAME> on 25.04.2017. // Copyright © 2017 Kamajabu. All rights reserved. // import Foundation class MusicItem { var fileName: String var itemImage: String var title: String var artist: String init(dataDictionary:Dictionary<String,String>) { fileName = dataDictionary["fileName"]! artist = dataDictionary["artist"]! title = dataDictionary["title"]! itemImage = dataDictionary["itemImage"]! } class func newGalleryItem(_ dataDictionary:Dictionary<String,String>) -> GalleryItem { return GalleryItem(dataDictionary: dataDictionary) } } <file_sep>// // CollectionViewCell.swift // Example // // Created by <NAME> on 2016-12-28. // Copyright © 2016 <NAME>. // import UIKit protocol CollectionViewCellDelegate: class { func cellDelegateCloseController(sender: AnyObject) } class FullScreenCollectionViewCell: UICollectionViewCell { weak var closeDelegate: CollectionViewCellDelegate? @IBOutlet weak var itemImage: UIImageView! func setGalleryItem(_ item:MusicItem) { itemImage.image = UIImage(named: item.itemImage) } } <file_sep> import UIKit import AVFoundation class PlayerViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { @IBOutlet var collectionView: UICollectionView! @IBOutlet weak var progressView: UIProgressView! @IBOutlet weak var songTitleLabel: UILabel! @IBOutlet weak var artistLabel: UILabel! @IBOutlet weak var shuffle: UISwitch! @IBOutlet weak var nextSong: UIBarButtonItem! @IBOutlet weak var rewindForward: UIBarButtonItem! @IBOutlet weak var previousSong: UIBarButtonItem! @IBOutlet weak var rewindBack: UIBarButtonItem! @IBOutlet weak var playPause: UIButton! var isFirstStart = true var imageIndex: IndexPath? var musicItems: [MusicItem] = [] var trackId: Int = 0 var audioPlayer: AVAudioPlayer! override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = self collectionView.delegate = self chooseImageTitleArtist(trackId) loadMp3(trackId) } override func viewDidLayoutSubviews() { if (isFirstStart) { self.collectionView?.scrollToItem(at: imageIndex!, at: .centeredHorizontally, animated: false) self.collectionView.reloadData() isFirstStart = false } } @IBAction func backButtonDidTouch(_ sender: Any) { dismiss(animated: true, completion: nil) } override func viewWillDisappear(_ animated: Bool) { audioPlayer.stop() } @objc func updateProgressView(){ if audioPlayer.isPlaying { progressView.setProgress(Float(audioPlayer.currentTime/audioPlayer.duration), animated: true) } } @IBAction func playAction(_ sender: AnyObject) { if !audioPlayer.isPlaying { audioPlayer.play() if let image = UIImage(named: "pause") { UIView.transition(with: playPause, duration: 0.4, options: .transitionFlipFromRight, animations: { sender.setImage(image, for: .normal) }, completion: nil) } } else { audioPlayer.pause() if let image = UIImage(named:"circled_play") { UIView.transition(with: playPause, duration: 0.4, options: .transitionFlipFromRight, animations: { sender.setImage(image, for: .normal) }, completion: nil) } } } func stopAction(_ sender: AnyObject) { audioPlayer.stop() audioPlayer.currentTime = 0 progressView.progress = 0 } @IBAction func pauseAction(_ sender: AnyObject) { audioPlayer.pause() } @IBAction func fastForwardAction(_ sender: AnyObject) { var time: TimeInterval = audioPlayer.currentTime time += 5.0 if time > audioPlayer.duration { stopAction(self) } else { audioPlayer.currentTime = time } } @IBAction func rewindAction(_ sender: AnyObject) { var time: TimeInterval = audioPlayer.currentTime time -= 5.0 if time < 0 { stopAction(self) }else { audioPlayer.currentTime = time } } @IBAction func previousAction(_ sender: AnyObject) { if shuffle.isOn { trackId = Int(arc4random_uniform(UInt32(musicItems.count))) } else if trackId > 0 { trackId -= 1 } else { trackId = 11 } audioPlayer.currentTime = 0 progressView.progress = 0 chooseImageTitleArtist(trackId) loadMp3(trackId) } @IBAction func nextAction(_ sender: AnyObject) { if shuffle.isOn { trackId = Int(arc4random_uniform(UInt32(musicItems.count))) } else if trackId < (musicItems.count - 1) { trackId += 1 } else { trackId = 0 } audioPlayer.currentTime = 0 progressView.progress = 0 chooseImageTitleArtist(trackId) loadMp3(trackId) } func chooseImageTitleArtist(_ trackId: Int) { self.collectionView?.scrollToItem(at: IndexPath(item: trackId, section: 0), at: .centeredHorizontally, animated: true) self.collectionView.reloadData() songTitleLabel.text = musicItems[trackId].title artistLabel.text = musicItems[trackId].artist } func loadMp3(_ trackId: Int) { let path = Bundle.main.path(forResource: "\(musicItems[trackId].fileName)", ofType: "mp3") if let path = path { let mp3URL = URL(fileURLWithPath: path) do { audioPlayer = try AVAudioPlayer(contentsOf: mp3URL) audioPlayer.play() Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(PlayerViewController.updateProgressView), userInfo: nil, repeats: true) progressView.setProgress(Float(audioPlayer.currentTime/audioPlayer.duration), animated: false) } catch let error as NSError { print(error.localizedDescription) } } } } <file_sep>// // ViewController.swift // UICollectionView_p1_Swift // // Created by olxios on 20/11/14. // Copyright (c) 2014 olxios. All rights reserved. // import UIKit class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { @IBOutlet var collectionView: UICollectionView! var musicItems: [MusicItem] = [] var selectedItem: IndexPath? override func viewDidLoad() { super.viewDidLoad() initGalleryItems() } override func viewDidAppear(_ animated: Bool) { collectionView.reloadData() NotificationCenter.default.addObserver(self, selector: #selector(ViewController.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } fileprivate func initGalleryItems() { var items = [MusicItem]() let inputFile = Bundle.main.path(forResource: "audioList", ofType: "plist") let inputDataArray = NSArray(contentsOfFile: inputFile!) for inputItem in inputDataArray as! [Dictionary<String, String>] { let musicItem = MusicItem(dataDictionary: inputItem) items.append(musicItem) } musicItems = items } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return musicItems.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: "GalleryItemCollectionViewCell", for: indexPath) as! GalleryItemCollectionViewCell cell.setGalleryItem(musicItems[indexPath.row]) return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { selectedItem = indexPath self.performSegue(withIdentifier: "fullscreenSegue", sender: self) } func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { perform(#selector(self.actionOnFinishedScrolling), with: nil, afterDelay: Double(velocity.y)) } @objc func actionOnFinishedScrolling() { let visibleCells = collectionView.visibleCells let sorted = visibleCells.sorted(){ $0.center.y < $1.center.y } self.collectionView?.scrollToItem(at: collectionView.indexPath(for: sorted.last!)!, at: .bottom, animated: true) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else { return CGSize() } let heightAvailbleForAllItems = (collectionView.frame.height - flowLayout.sectionInset.top - flowLayout.sectionInset.bottom) let widthAvailbleForAllItems = (collectionView.frame.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right) let widthForOneItem = widthAvailbleForAllItems / 2 - flowLayout.minimumInteritemSpacing let heightForOneItem = heightAvailbleForAllItems / 4 - flowLayout.minimumInteritemSpacing return CGSize(width: CGFloat(widthForOneItem), height: CGFloat(heightForOneItem)) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "fullscreenSegue" { let playerVC = segue.destination as! PlayerViewController playerVC.trackId = (selectedItem?.row)! playerVC.musicItems = musicItems playerVC.imageIndex = selectedItem } } @objc func rotated() { collectionView.reloadData() } override func viewWillDisappear(_ animated: Bool) { NotificationCenter.default.removeObserver(self) } } <file_sep>// // UIImageView+Extensions.swift // infGalleryIOS // // Created by <NAME> on 29.03.2017. // Copyright © 2017 Kamajabu. All rights reserved. // import Foundation import UIKit extension UIImageView { func addBlurEffect() { let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = self.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // for supporting device rotation self.addSubview(blurEffectView) } } <file_sep>// // FullScreenCollectionViewController.swift // infGalleryIOS // // Created by <NAME> on 29.03.2017. // Copyright © 2017 Kamajabu. All rights reserved. // import UIKit private let reuseIdentifier = "CollectionViewCell" extension PlayerViewController: CollectionViewCellDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return musicItems.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! FullScreenCollectionViewCell let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: cell.frame.width, height: cell.frame.height))) let item = musicItems[indexPath.row] let image = UIImage(named: item.itemImage) imageView.image = image imageView.addBlurEffect() cell.backgroundView = UIView() cell.backgroundView!.addSubview(imageView) cell.setGalleryItem(musicItems[indexPath.row]) cell.closeDelegate = self return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.frame.width , height: collectionView.frame.height ) } func cellDelegateCloseController(sender: AnyObject){ dismiss(animated: true, completion: nil) } func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { perform(#selector(self.actionOnFinishedScrolling), with: nil, afterDelay: Double(velocity.y)) } @objc func actionOnFinishedScrolling() { if let visibleCell = collectionView.visibleCells.last { trackId = collectionView.indexPath(for: visibleCell)!.row } audioPlayer.currentTime = 0 progressView.progress = 0 chooseImageTitleArtist(trackId) loadMp3(trackId) } }
9dfc0c54146474a0bf47a695e61818f0a2656118
[ "Swift" ]
6
Swift
Kamajabu/inf_musicGallery_ios
221c2945436920170bc044fe78e1ea0766494831
e207481092d34fc2466cb57991c5d1d9aef0193a
refs/heads/master
<file_sep><?php echo "Hello"; echo "我是淋榕"; echo "我是宜軒"; echo "我是超酷魔王 我超酷"; ?>
b2d47d0a19631976895fba9e60fa0804e7c7cfa2
[ "PHP" ]
1
PHP
1106137204/108D
6d796cf803d4ceecc5da4de8130b262088a5b6f0
8dcb1ac35e9253837ec4a769bf3d0f714bcb8530
refs/heads/master
<file_sep># getting started ## description this tool can generate a random conversation using a json type data and write it to a doc file this tool is made for a vn simulation game made with renpy it can also generate a random character with a gender relative to the story made there is also a script that can write the story in renpy ## Prerequisites ``` Python3 interpreter ``` ``` renpy, to test the script ``` ## Installing just click on : [story_gen.py](https://gitlab.com/alaeessaki/the_actual_plana_tool_project/blob/master/story_gen.py) - the main function # Built With [python3] (https://www.python.org/) # Authors * **<NAME>** - *Story generater tool* - [Alaeessaki](https://github.com/alaeessaki) * **<NAME>** - *the integration scripts* - [YassineOsip](https://gitlab.com/YassineOsip) # License this project is made with a cooperation between capgemini and Youcode<file_sep>import random import json #you can learn how this tool works in client class's comments #this class works exactly like the client class class agent() : def __init__(self): self.greeting = None #this method generate the greeting conversation def hello (self): #reading json file with open('assets/data/data.json',"r") as f: s= f.read() data = json.loads(s) #pick a random greeting word w = [] for i in data['hello']['hi']: w.append(i) self.hi = random.choice(w) #write in file with open("stories/story.doc","a") as f: f.write("agent " + "\"" + self.hi + "\"" + "\n") def tk (self): with open('assets/data/data.json',"r") as f: s= f.read() data = json.loads(s) w = [] for i in data['tk']['tk1']: w.append(i) self.ty = random.choice(w) with open("stories/story.doc","a") as f: f.write("agent " + "\"" + self.ty + "\""+"\n") def qt1(self, r, k, q): with open('assets/data/data.json',"r") as f: s= f.read() data = json.loads(s) w = [] for i in data['qt']['qt1'][r][k][q]: w.append(i) self.cv1 = random.choice(w) with open("stories/story.doc","a") as f: f.write("agent " + "\"" + self.cv1 + "\"" + "\n") def qt2(self, r, k): with open('assets/data/data.json',"r") as f: s= f.read() data = json.loads(s) w = [] x = [] if r == "afi": if "car" in k: l = "car" elif "motorcycle" in k : l = "motorcycle" elif "truck" in k : l = "truck" for i in data['qt']['qt2'][r][l]: w.append(i) convos = random.choice(w) self.convos = convos for i in data['qt']['qt2'][r][l][convos]: x.append(i) self.convo = x elif r == "aai": for i in data['qt']['qt2'][r][k]: w.append(i) convos = random.choice(w) self.convos = convos for i in data['qt']['qt2'][r][k][convos]: x.append(i) self.convo = x elif r == "dat": if "fee" in k : l = "paying insurance fee" else : l = "check out" for i in data['qt']['qt2'][r][l]: w.append(i) convos = random.choice(w) self.convos = convos for i in data['qt']['qt2'][r][l][convos]: x.append(i) self.convo = x <file_sep>import random import sys import os import shutil #P >> program #T >> theme #I >> Image #Images manipulation #initial Lists ImagesPathList = [] ImagesList = [] #intial data data = [] char1 = sys.argv[1] data.append(char1) char2 = sys.argv[2] data.append(char2) scriptFile = sys.argv[3] data.append(scriptFile) #Structure The Script.rpy (with 3 choices ) # here !!! # manipulation functions def moveFileFunc(src,dest): shutil.move(src , dest) def changeDirFunc(dir): os.chdir(dir) def joinPathFunc(pathDer): cwd = os.getcwd() path = os.path.join(cwd , pathDer) return path def getListOfFilesFunc(dirName): for dir , subDir , files in os.walk(dirName): ImagesPathList.append(dir) for subF in files : ImagesList.append(subF) def Main(): #reading scene file scene = open(data[2] , "r+") scene1 = scene.read() sceneRen = open("script.rpy", "w") #Init Characters #moveFileFunc(joinPathFunc("Characters") , joinPathFunc("images") ) changeDirFunc(joinPathFunc("images")) dirName = os.getcwd() print(getListOfFilesFunc(dirName)) #Structure The Script.rpy (without choices) char1 = 'define client = Character("{}")\n'.format(data[0]) char2 = 'define agent = Character("{}")\n'.format(data[1]) selectedImg = random.choice(ImagesList) img = 'image eileen happy = "{}"\n'.format(selectedImg) startP = "label start :\n" sceneT = "scene bg room\n" sceneI = "show eileen happy with dissolve:\n xzoom 0.5 yzoom 0.5\n" exe_c = "\nreturn" sceneRen.write(char1) sceneRen.write(char2) sceneRen.write(img) sceneRen.write(startP) sceneRen.write(sceneT) sceneRen.write(sceneI) sceneRen.write(str(scene1)) sceneRen.write(exe_c) #close files scene.close() sceneRen.close() if __name__ == "__main__": Main() <file_sep>from assets.actors.client import client from assets.actors.agent import agent def story(): client1 = client() agent1 = agent() client1.hello() agent1.hello() client1.hwd() agent1.tk() client1.tk() client1.qt1() agent1.qt1(client1.r, client1.k, client1.cv1) agent1.qt2(client1.r, client1.k) client1.qt2(client1.r, client1.k, agent1.convos, agent1.convo) k = 0 with open("stories/story.doc","a") as f: #checking the topic if client1.r == "afi" : #checking the gender to use it later to choose the character man = ["david","jon","Liam","Noah"] #to do : use a loop to check the name without knowing which line he is in for i in man: # you can use for i in man : # if i in client1.convo2[0]: ## while m<len(client.convo2): gender = "man" # if i in client.convo2[m]: break # gender = "man" else: # break gender = "woman" # else : # gender = "woman" #this loop write the respond of each agent's question while k<len(agent1.convo) : f.write("agent " + "\"" + agent1.convo[k] + "\"" + "\n" + "client " + "\"" + client1.convo2[k] + "\"" + "\n") k+=1 f.write("gender:"+ gender +"\n") elif client1.r == "aai" : while k<len(agent1.convo) : f.write("agent " + "\""+ agent1.convo[k] + "\""+ "\n" + "client " + "\""+ client1.convo2[k] +"\""+ "\n") k+=1 else : if "fee" in client1.k: man = ["david","jon","Liam","Noah"] for i in man: if i in client1.convo2[0]: gender = "man" break else: gender = "woman" while k<len(agent1.convo) : f.write("agent " + "\"" + agent1.convo[k] + "\"" + "\n" + "client " + "\"" + client1.convo2[k] + "\"" + "\n") k+=1 f.write("gender:"+ gender +"\n") else : while k<len(agent1.convo): f.write("agent " + "\"" + agent1.convo[k] + "\"" + "\n" + "client " + "\"" + client1.convo2[k] + "\"" + "\n") k+=1 f.close() print("you'll find the stroy in the the stories directory!") story() <file_sep>import random import json class client() : def __init__(self): self.greeting = None #this method generate the greeting conversation def hello (self): #reading json file with open("assets/data/data.json","r") as f: s= f.read() data = json.loads(s) #pick a random greeting word w = [] for i in data['hello']['hi']: w.append(i) self.hi = random.choice(w) #write in file with open("stories/story.doc","a") as f: f.write("\n" + "client " + "\"" + self.hi + "\"" + "\n") #this method generate the first conversation like : "how are you doing..." def hwd (self): #open json file with open('assets/data/data.json',"r") as f: s= f.read() data = json.loads(s) #pick a random sentense w = [] for i in data['hwd']['hwd']: w.append(i) self.hwrd = random.choice(w) #write in file with open("stories/story.doc","a") as f: f.write("client " + "\"" + self.hwrd + "\"" + "\n") #this method generate a thanking sentense def tk(self): #read the json file with open('assets/data/data.json',"r") as f: s= f.read() data = json.loads(s) #generate a random sentense w = [] for i in data['tk']['tk2']: w.append(i) self.ty = random.choice(w) #write in file with open("stories/story.doc","a") as f: f.write("client " + "\"" + self.ty + "\"" + "\n") #this methode generate the first question def qt1(self): #open json file with open('assets/data/data.json',"r") as f: s = f.read() data = json.loads(s) w = [] x = [] y = [] #generate a random topic for i in data['qt']['qt1']: w.append(i) r = random.choice(w) self.r = r #self.r will get a value of a topic #generate a random topic relative to the first topic for i in data['qt']['qt1'][r]: x.append(i) k = random.choice(x) self.k = k #self.k will get a value of a topic #generate a random topic relative to the first and the second topic for i in data['qt']['qt1'][r][k]: y.append(i) self.cv1 = random.choice(y) #self.cv1 gets the first question #write in file with open("stories/story.doc","a") as f: f.write("client " + "\"" + self.cv1 + "\"" +"\n") #this method generate the other conversations def qt2(self,r, k, convos, w): ##################################################### # r values : # # "afi" : "asking for insurance" # # "aai" : "asking about insurance" # # "dat" : "declare a statement" # # k values : # # client.k # # convos values # # agent.convos : the number of the conversation # # w value: # # agent.convo : the agent questions # ##################################################### #read json file with open('assets/data/data.json',"r") as f: s = f.read() data = json.loads(s) m = [] t = 0 #the first topic if r == "afi": if "car" in k: l = "car" elif "motorcycle" in k : l = "motorcycle" elif "truck" in k : l = "truck" #this loup stock the responds of agent questions in a list called m and affect it in self.convo2 while t<len(w): m.append(random.choice(data['qt']['qt2'][r][l][convos][w[t]])) t+=1 self.convo2 = m #the second topic elif r == "aai": #this loup stock the responds of agent questions in a list called m and affect it in self.convo2 while t<len(w): m.append(random.choice(data['qt']['qt2'][r][k][convos][w[t]])) t+=1 self.convo2 = m #the third topic elif r == "dat": if "fee" in k : l = "paying insurance fee" elif "checking-out" in k: l = "check out" #this loup stock the responds of agent questions in a list called m and affect it in self.convo2 while t<len(w): m.append(random.choice(data['qt']['qt2'][r][l][convos][w[t]])) t+=1 self.convo2 = m
0405fce8b3fb2337ca069098b7316bd784e268e7
[ "Markdown", "Python" ]
5
Markdown
alaeessaki/insureFAQ
b3a1eb1e6802df360c8814c9ede841bb52556fdf
0610e96fcaa046a197d72208c5c204517816c4ef
refs/heads/master
<repo_name>Rasmuskilp/airport_excericise<file_sep>/README.md Passengers as a user I can create a Passanger It can be created with name and passport number I can create '<NAME>' with the Passport number 'B343123' I can create '<NAME>' with the Passport number 'B13927' If I try to create a user with out a name or a passport number I get an error Plane As a User I can create a Plane with a plane number Flight_trip As a user I can create a flight with no specific information as a user I can add a plane as a User I can add a destination As a user I can add a origin As a user I can add a Passanger to the list of passangers Passanger list is a list of objct that are Passanger<file_sep>/sql_db_connection.py import pyodbc class MSDBConnection(): def __init__(self): self.server = 'localhost,1433' self.database = 'homework_db' self.username = 'SA' self.password = '<PASSWORD>' self.docker_Northwind = pyodbc.connect( 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=' + self.server + ';DATABASE=' + self.database + ';UID=' + self.username + ';PWD=' + self.password) self.cursor = self.docker_Northwind.cursor() def __sql_query(self,sql_query): # Makes it private return self.cursor.execute(sql_query) # cursor.execute("SELECT * FROM Passengers WHERE name LIKE 'Jessica'") def insert_to(self): query = "INSERT INTO Passengers (name , passport) VALUES ('Tom', 'A152521')" query2 = 'SELECT * FROM Passengers' item = self.__sql_query(query) item2 = self.__sql_query(query2) # record = item.fetchall() print(item2.fetchall()) def select_from(self): query = 'SELECT * FROM Flight_trip' item = self.__sql_query(query) print( item.fetchall()) def add_to(self): query = "INSERT INTO Flight_trip (passenger) VALUES ('Jess')" item = self.__sql_query(query) query2 = "SELECT * FROM Flight_trip" item2 = self.__sql_query(query2) print(item2.fetchall()) airport = MSDBConnection() print(airport.insert_to()) print(airport.select_from()) print(airport.add_to()) <file_sep>/flight_trip.py # As a user I can create a flight with no specific information # as a user I can add a plane # as a User I can add a destination # As a user I can add a origin # As a user I can add a Passanger to the list of passangers # Passanger list is a list of objct that are Passanger class Flight_trip(): def __init__(self,plane = None,destination = None,origin = None,passenger = None,passenger_list = 0): self.plane = plane self.destination = destination self.origin = origin self.passenger = passenger self.passenger_list = [] def add_plane(self,plane): self.plane = plane return self.plane def add_destination(self,destination): self.destination = destination return self.destination def add_origin(self,origin): self.origin = origin return self.origin def add_passenger_list(self,passenger): self.passenger = passenger self.passenger_list.append(passenger) return self.passenger, self.passenger_list def return_list(self): return self.passenger_list <file_sep>/plane.py # Plane # As a User I can create a Plane with a plane number class Plane(): def __init__(self,flight_number): self.flight_number = flight_number<file_sep>/test_airport.py #here are the tests8 from passenger import * from plane import * from flight_trip import * import pytest def test_create_passenger_test(): assert Passenger('<NAME>','B13927').name == '<NAME>' assert Passenger('<NAME>','B13927').passport == 'B13927' assert Passenger('<NAME>','B343123').name =='<NAME>' assert Passenger('<NAME>','B343123').passport == 'B343123' with pytest.raises(TypeError): Passenger() def test_plane_test(): assert Plane('a1515252').flight_number == 'a1515252' # def flight_trip_test(): # assert Flight_trip def test_flight(): te_flight = Flight_trip() assert te_flight.plane == None assert te_flight.passenger == None assert te_flight.origin == None assert te_flight.destination == None # create an objct new_test = Flight_trip('a1521','Majorca','London','Charlie') # then call the method # assert new_test.add_plane('a15215') == 'a15215' assert new_test.add_destination('Palma',) == 'Palma' assert new_test.add_origin('Paris') == 'Paris' assert 'Bob' in new_test.add_passenger_list('Bob') <file_sep>/while_loop.py from flight_trip import * from passenger import * from plane import * while True: count = 0 print('1 - if you wish to add passenger details') print('2 - if you wish to add plane details') print('3 - if you wish to add flight_trip details') details = input('enter the correct number:') if '1' in details: pass_name = input('add passenger details:') passport_details = input('add passport number:') new_name = Passenger(pass_name,passport_details) elif '2' in details: plane_num = input('add plane number:') plane_num = Plane(plane_num) elif '3' in details: planes_num = input('add plane number') dest_det = input('add destination') origin_det = input('add origin') passeng_num = input('add passenger') origin_det = Flight_trip(planes_num,dest_det,origin_det,passeng_num,[]) origin_det.passenger_list.append(passeng_num) count += 1 else: print('you did not input a correct number!') exit()<file_sep>/passenger.py # Passengers # as a user I can create a Passanger # It can be created with name and passport number # I can create '<NAME>' with the Passport number 'B343123' # I can create '<NAME>' with the Passport number 'B13927' # If I try to create a user with out a name or a passport number I get an error # Plane class Passenger(): def __init__(self,name,passport): self.name = name self.passport = passport # def create_passenger(self,name,passport):
328175c85c46f1a31ded505ad06ee25e14e475ee
[ "Markdown", "Python" ]
7
Markdown
Rasmuskilp/airport_excericise
641986129d5c192e7df8290ed166574477de3870
b9078ad9b65545f927fdbd4b9a1537369e1cf5e1
refs/heads/master
<file_sep>#include <stdio.h> #include <cs50.h> int main(void) { int minutes; printf("Enter number of minutes\n"); //prompt user to enter input minutes = get_int(); if (minutes > 0) { int bottles = minutes * 12; printf("Minutes: %i\nBottles: %i\n", minutes, bottles); } } <file_sep>#include <stdio.h> #include <cs50.h> #include <ctype.h> #include <string.h> int main(void) { string name; //char initials[10]; //int j = 0; printf("Whaddup gimme yo name\n"); name = get_string(); if (name != NULL) //Check that the string input is valid { printf("%c", toupper(name[0])); //straight up print the first letter/char of the entered string for(int i = 0; i < strlen(name); i++) //no. of iterations equals the length of the string or no. of chars in a string { do { if(name[i] == ' ') //if the ith character in the string is a space.... { printf("%c", toupper(name[i+1])); } } while(name[i] == '\0'); } printf("\n"); } } <file_sep>#include <stdio.h> #include <stdlib.h> void createFileName(); //unsigned char buffer[512]; // One "block" contains 512 bytes char filename[7]; // ###.jpg int i = 0; //unsigned int size; FILE *jpeg = NULL; int main (int argc, char *argv[]) { unsigned char buffer[512]; // Ensure proper usage if(argc != 2) { fprintf(stderr, "Usage: ./recover image\n"); return 1; } // remember memory card file name char *infile = argv[1]; // open the memory card file FILE *inptr = fopen(infile, "r"); if(inptr == NULL) { fprintf(stderr, "File %s could not be opened.\n", infile); return 2; } // read in first chunk/block while((fread(buffer, 512, 1, inptr)) == 1) // As long as the block read in is 512 Bytes { //FIND START OF JPEG if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0) //good ol' bitmasking { if(i != 0) //have we found a jpeg already? { //yes fclose(jpeg); //close the previous jpeg } // now if we hadn't found a jpeg already, you'd be creating the first ever jpeg file. // if we had found one already, no worries. We closed the previous file up there^^^ // and now you're safe to open newest file, go girl createFileName(); jpeg = fopen(filename, "a"); if (jpeg == NULL) { fclose(inptr); fprintf(stderr, "File %s could not be created.\n", filename); return 3; } // fwrite stuff into that jpeg file fwrite(buffer, 512, 1, jpeg); // cardfseek(inptr, 512, SEEK_CUR); //Shift the pointer to next block } // Didn't find the start of jpeg else if(i != 0) //have we found a jpeg already? { //yes, then this means that the current chunk of 512 bytes belongs to the ongoing jpeg file. fwrite(buffer, 512, 1, jpeg); } // size = fread(buffer, 1, 512, inptr); //Read in the next chunk, update size in case we're reaching the end of file } fclose(jpeg); fclose(inptr); // If successful return 0; } void createFileName() { /*********** NAMING THE JPEGS ***********/ sprintf(filename,"%03i.jpg", i); //printf("%s\n", filename); i++; } <file_sep>#include <stdio.h> #include <cs50.h> #include <math.h> int main(void) { float change, change2; int counter = 0; do { printf("O hai! How much change is owed?\n"); change = get_float(); change2 = round(100 * change); } while (change < 0.0); while (change2 >= 25) { change2 = change2 - 25; counter++; } while (change2 >= 10) { change2 = change2 - 10; counter++; } while (change2 >= 5) { change2 = change2 - 5; counter++; } while (change2 >= 1) { change2 = change2 - 1; counter++; } printf("%i\n", counter); } <file_sep>import cs50 while True: print("O hai! How much change is owed?") change = cs50.get_float() change2 = round(100*change) counter = 0 if change<0.0: break while change2 >= 25: change2 = change2 - 25 counter+=1 while change2 >= 10: change2 = change2 - 10 counter+=1 while change2 >= 5: change2 = change2 - 5 counter+=1 while change2 >= 1: change2 = change2 - 1 counter+=1 print("{}".format(counter)) <file_sep>/** * generate.c * * Generates pseudorandom numbers in [0,LIMIT), one per line. * * Usage: generate n [s] * * where n is number of pseudorandom numbers to print * and s is an optional seed */ #define _XOPEN_SOURCE #include <cs50.h> #include <stdio.h> #include <stdlib.h> #include <time.h> // upper limit on range of integers that can be generated #define LIMIT 65536 int main(int argc, string argv[]) { // TODO: if the number of arguments entered is not 2 OR 3, return an error /* argc!=2 argc!=3 if() argc = 1 | 1 | 1 | 1 2 | 0 | 1 | 0 3 | 1 | 0 | 0 4 | 1 | 1 | 1 */ if (argc != 2 && argc != 3) { printf("Usage: ./generate n [s]\n"); return 1; } // TODO: turn the string entered as an argument, change it to type int and store it in n int n = atoi(argv[1]); // TODO: if a seed value was entered at start of program execution, convert it from string to int within the srand48 function // that seeds drand48. // if a seed value wasn't entered, use time(NULL) to seed it if (argc == 3) { srand48((long) atoi(argv[2])); } else { srand48((long) time(NULL)); } // TODO: Once all the seeding is done, generate n random numbers // drand48 generates double numbers between [0.0, 1.0). so when you multiply it by LIMIT, // you are changing the range to [0, LIMIT) for (int i = 0; i < n; i++) { printf("%i\n", (int) (drand48() * LIMIT)); } // success return 0; } <file_sep># CS50-Projects This repository contains all my work from the CS50 online course through Harvard edX. CS50 (Computer Science 50) is an on-campus and online introductory course on computer science from Harvard. The course material is available for free on HarvadX with a range of certificates available for a fee. Other courses on HarvardX can be found here: https://www.edx.org/school/harvardx ## Syllabus Introduction to the intellectual enterprises of computer science and the art of programming. This course teaches students how to think algorithmically and solve problems efficiently. Topics include abstraction, algorithms, data structures, encapsulation, resource management, security, software engineering, and web development. Languages include C, Python, SQL, and JavaScript plus CSS and HTML. Problem sets inspired by real-world domains of biology, cryptography, finance, forensics, and gaming. Designed for majors and non-majors alike, with or without prior programming experience. ## Wesbite https://cs50.edx.org/ ## Lectures Week 0 - Scratch Week 1 - C Week 2 - Arrays Week 3 - Algorithms Week 4 - Memory Week 5 - Data Structures Week 6 - HTTP Week 7 - Machine Learning Week 8 - Python Week 9 - SQL Week 10 - JavaScript Week 11 - The End ## Problem Sets Problem Set 0 - Scratch | Language - Scratch Problem Set 1 - C | Language - C Problem Set 2 - Crypto | Language C Problem Set 3 - Game of Fifteen | Language - C Problem Set 4 - Forensics | Language - C Problem Set 5 - Mispellings | Language - C Problem Set 6 - Sentimental | Language - Python Problem Set 7 - C$50 Finance | Language - Python, SQL Problem Set 8 - Mashup | Language - JavaScript <file_sep>#include <stdio.h> #include <cs50.h> #include <string.h> #include <stdlib.h> #include <ctype.h> int main(int argc, string argv[]) { if(argc != 2) //we only want two arguments: the keyword and ./vigenere { printf("Usage: ./caesar k\n"); return 1; } char k[strlen(argv[1])]; for(int i = 0; i<strlen(argv[1]); i++) { if(isupper(argv[1][i])) //if the ith character in the keyword is uppercase { k[i] = argv[1][i] - 65; //printf("%i\n", k[i]); } else if(islower(argv[1][i])) ////if the ith character in the keyword is lowercase { k[i] = argv[1][i] - 97; //printf("%i\n", k[i]); } else { printf("Usage: ./caesar k\n"); return 1; } } string plaintext; int ciphertext; int j = 0; printf("plaintext: "); plaintext = get_string(); printf("ciphertext: "); for(int i = 0; i < strlen(plaintext); i++) { do { if(isalpha(plaintext[i])) { if(j > (strlen(argv[1]) - 1)) { j = 0; } ciphertext = (int) plaintext[i] + k[j]; //k was constant in caesar. In vigenere is changes based on the p[i] j++; if (islower(plaintext[i]) && ciphertext > 122) { ciphertext = ciphertext - 26; } if (isupper(plaintext[i]) && ciphertext > 90) { ciphertext = ciphertext - 26; } printf("%c", (char) ciphertext); } else { printf("%c", plaintext[i]); } } while (plaintext[i] == '\0'); } printf("\n"); }<file_sep>/* <NAME> */ #include <stdio.h> #include <cs50.h> int main(void) { int height, width, col; do { printf("Enter a height value between 0 and 23\n"); height = get_int(); } while (height < 0 || height > 23); width = height + 1; for (int i = 0; i < height ; i++) //eg. height = 0, 1, 2, 3 (or row) { //now in rows 0, 1, 2, 3 for (col = i; col < (height - 1) ; col++) //1st: (height - 1) = 3; col = 0, 1, 2 { //2nd: (3 - 1) = 2; col = 0, 1 printf(" "); //3rd: (2 - 1) = 1; col = 0 } for (col = (height - 1 - i); col < width; col++) //col = 3, 4 { printf("#"); } printf("\n"); } } <file_sep>import nltk #nltk.download() from nltk.tokenize import TweetTokenizer class Analyzer(): """Implements sentiment analysis.""" def __init__(self, positives, negatives): """Initialize Analyzer. Load positive and negative words into memory so that analyze can access them""" # TODO self.positives = set() self.negatives = set() file = open("positive-words.txt", "r") for line in file: if not line.startswith(";"): self.positives.add(line.rstrip("\n")) file.close() file = open("negative-words.txt", "r") for line in file: if not line.startswith(";"): self.negatives.add(line.rstrip("\n")) file.close() def analyze(self, text): """Analyze text for sentiment, returning its score.""" score = 0 #tokens = nltk.word_tokenize(text) tokenizer = nltk.tokenize.TweetTokenizer() tokens = tokenizer.tokenize(text) for token in tokens: if token.lower() in self.positives: score+=1 elif token.lower() in self.negatives: score-=1 return score <file_sep>from cs50 import SQL from flask import Flask, flash, redirect, render_template, request, session, url_for from flask_session import Session from passlib.apps import custom_app_context as pwd_context from tempfile import mkdtemp from passlib.context import CryptContext from helpers import * # configure application app = Flask(__name__) # ensure responses aren't cached if app.config["DEBUG"]: @app.after_request def after_request(response): response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" response.headers["Expires"] = 0 response.headers["Pragma"] = "no-cache" return response # custom filter app.jinja_env.filters["usd"] = usd #a function to format values as US dollars # configure session to use filesystem (instead of signed cookies) app.config["SESSION_FILE_DIR"] = mkdtemp() app.config["SESSION_PERMANENT"] = False app.config["SESSION_TYPE"] = "filesystem" Session(app) # configure CS50 Library to use SQLite database db = SQL("sqlite:///finance.db") ###################################################################################################################### INDEX ####### @app.route("/") @login_required def index(): stocks = [] t = 0 un = db.execute("SELECT username FROM users WHERE id = :id", id = session["user_id"]) un = un[0]["username"] hold = db.execute("""SELECT stock_name, symbol, Sum(quantity) AS quantity FROM transactions WHERE username=:uname AND t_type = 'BUY' GROUP BY stock_name, symbol ORDER BY stock_name""", uname = un) # subtract the quantity of shares SOLD for i in hold: hold2 = db.execute("""SELECT Sum(quantity) AS quantity FROM transactions WHERE username=:uname AND t_type = 'SELL' AND symbol = :sym""", uname = un, sym = i["symbol"]) # hold2 = {quan2} if hold2[0]["quantity"] != None: q1 = i["quantity"] q2 = hold2[0]["quantity"] q = abs(q1 - int(q2)) i["quantity"] = q cash = db.execute("SELECT cash FROM users WHERE id = :id", id = session["user_id"]) cash = round(float(cash[0]["cash"]), 2) # get current price for dict in hold: name = str(dict["stock_name"]) symbol = str(dict["symbol"]) quantity = int(dict["quantity"]) # change quantity to reflect difference in buy and sell cur_price = lookup(symbol) cur_price = cur_price['price'] total = quantity * cur_price t += total stockdict = {"name": name, "symbol": symbol, "quantity": quantity, "current": usd(cur_price), "total": usd(total)} stocks.append(stockdict) grand = cash + t return render_template("index.html", stocks = stocks, cash = cash, grand = usd(grand)) ######################################################################################################################## BUY ####### @app.route("/buy", methods=["GET", "POST"]) @login_required def buy(): """Buy shares of stock.""" if request.method == "POST": stock = lookup(request.form.get("symbol")) quant = int(request.form.get("quantity")) if stock == None: return apology("Invalid symbol") nam = stock['name'] price = stock['price'] sym = stock['symbol'] # get current cash balance cash = db.execute("SELECT cash FROM users WHERE id = :id", id = session["user_id"]) cash = cash[0]["cash"] # check to see if there's enough cash to make the purchase total_price = quant * price if total_price > float(cash): return apology("You're too broke to make this purchase") un = db.execute("SELECT username FROM users WHERE id = :id", id = session["user_id"]) db.execute("""INSERT INTO transactions (username, stock_name, symbol, price, quantity, t_type) VALUES(:username, :stockname, :symbol,:price, :quantity, 'BUY')""", username=un[0]["username"], stockname = nam, symbol = sym, price = usd(price), quantity= quant) # update cash balance db.execute("UPDATE users SET cash = :balance WHERE id = :id", balance = float(cash) - total_price, id = session["user_id"]) return redirect(url_for("index")) else: return render_template("buy.html") #################################################################################################################### HISTORY ####### @app.route("/history") @login_required def history(): """Show history of transactions.""" un = db.execute("SELECT username FROM users WHERE id = :id", id = session["user_id"]) un = un[0]["username"] # pull the relevant data from transactions table data = db.execute("SELECT stock_name, symbol, price, quantity, t_type, timestamp FROM transactions WHERE username=:un", un = un) # add it to a list called stocks stocks = [] for dict in data: name = str(dict["stock_name"]) symbol = str(dict["symbol"]) quantity = int(dict["quantity"]) price = dict["price"] t_type = str(dict["t_type"]) dt = dict["timestamp"] stockdict = {"name": name, "symbol": symbol, "quantity": quantity, "price": price, "type": t_type, "dt": dt} stocks.append(stockdict) return render_template("history.html", stocks = stocks) ###################################################################################################################### LOGIN ####### @app.route("/login", methods=["GET", "POST"]) def login(): """Log user in.""" # forget any user_id session.clear() # if user reached route via POST (as by submitting a form via POST) if request.method == "POST": # ensure username was submitted if not request.form.get("username"): return apology("must provide username") # ensure password was submitted elif not request.form.get("password"): return apology("must provide password") # query database for username rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username")) # ensure username exists and password is correct if len(rows) != 1 or not pwd_context.verify(request.form.get("password"), rows[0]["hash"]): return apology("invalid username and/or password") # remember which user has logged in session["user_id"] = rows[0]["id"] # redirect user to home page return redirect(url_for("index")) # else if user reached route via GET (as by clicking a link or via redirect) else: return render_template("login.html") ##################################################################################################################### LOGOUT ####### @app.route("/logout") def logout(): """Log user out.""" # forget any user_id session.clear() # redirect user to login form return redirect(url_for("login")) ###################################################################################################################### QUOTE ####### @app.route("/quote", methods=["GET", "POST"]) @login_required def quote(): """Get stock quote.""" if request.method == "POST": stock = lookup(request.form.get("symbol")) if stock == None: return apology("Invalid symbol") nam = stock['name'] pri = stock['price'] sym = stock['symbol'] return render_template("quoted.html", name = nam, price = usd(pri), symbol = sym) else: return render_template("quote.html") ################################################################################################################### REGISTER ####### @app.route("/register", methods=["GET", "POST"]) def register(): """Register user.""" if request.method == "POST": # ensure username was submitted if not request.form.get("username"): return apology("must provide username") # ensure password was submitted elif not request.form.get("password"): return apology("must provide password") # ensure password was typed again elif not request.form.get("confirm password"): return apology("must confirm password") # do the passwords match? if request.form.get("password") != request.form.get("confirm password"): return apology("passwords do not match!") else: #if all the information is entered correctly # hash the password (using version 1.6 of Passlib) hash = pwd_context.encrypt(request.form.get("password")) # Version 1.7 method: hash = myctx.hash(request.form.get("password")) # query database to create field result = db.execute("INSERT INTO users (username, hash) VALUES(:username, :hash)", username=request.form.get("username"), hash=hash) # check for failure in username creation if not result: return apology("username already exists!") # # store the user id # session["user_id"] = result # redirect user to home page return redirect(url_for("login")) else: return render_template("register.html") ####################################################################################################################### SELL ####### @app.route("/sell", methods=["GET", "POST"]) @login_required def sell(): """Sell shares of stock.""" if request.method == "POST": # lookup current stock price and get the quantity user entered stock = lookup(request.form.get("symbol")) quant = int(request.form.get("quantity")) st = db.execute("SELECT * FROM transactions WHERE symbol=:sym", sym = request.form.get("symbol")) # ensure stock exists in portfolio if len(st) != 1: return apology("No such stocks found") # ensure symbol is valid if stock == None: return apology("Invalid symbol") # get necessary information regarding stock nam = stock['name'] price = stock['price'] sym = stock['symbol'] # get user's name un = db.execute("SELECT username FROM users WHERE id = :id", id = session["user_id"]) un = un[0]["username"] # get current number of stock owned own = db.execute("SELECT SUM(quantity) as quantity FROM transactions WHERE username=:un AND symbol = :sym", un =un, sym = sym) own = own[0]["quantity"] # get current cash balance cash = db.execute("SELECT cash FROM users WHERE id = :id", id = session["user_id"]) cash = cash[0]["cash"] # check to see if there's enough stocks to sell if own < quant: return apology("You don't have enough stocks to sell") # make sale if there're enough stocks db.execute("""INSERT INTO transactions (username, stock_name, symbol, price, quantity, t_type) VALUES(:username, :stockname, :symbol, :price, :quantity, 'SELL')""", username=un, stockname = nam, symbol = sym, price = price, quantity= quant) # calculate the total of the sale total_price = quant * price # update cash balance db.execute("UPDATE users SET cash = :balance WHERE id = :id", balance = float(cash) + total_price, id = session["user_id"]) return redirect(url_for("index")) else: return render_template("sell.html") #################################################################################################################### BALANCE ####### @app.route("/balance", methods=["GET", "POST"]) @login_required def balance(): if request.method == "POST": # get current cash balance cash = db.execute("SELECT cash FROM users WHERE id = :id", id = session["user_id"]) cash = cash[0]["cash"] # get amount amount = float(request.form.get("amount")) # add it to current balance cash = float(amount) + float(cash) # update cash balance db.execute("UPDATE users SET cash = :balance WHERE id = :id", balance = cash, id = session["user_id"]) return render_template("balance.html", cb = cash) else: return render_template("balance.html") <file_sep># # Makefile: this file tells your what commands are execute when each of the following are "made" # i.e., make find, make all, make generate, make clean. # if you type 'make all' I think it'll be the same as saying 'make find' and 'make generate' except in a single command # CS50 # all: find generate find: find.c helpers.c helpers.h clang -ggdb3 -O0 -std=c11 -Wall -Werror -o find find.c helpers.c -lcs50 -lm generate: generate.c clang -ggdb3 -O0 -std=c11 -Wall -Werror -o generate generate.c clean: rm -f *.o a.out core find generate <file_sep>## Problem Set 6: ### Python Port certain prior assignments from C to Python. ### Sentiments 1. Implement a program that categorizes a word as positive or negative. 2. Implement a program that categorizes a user’s tweets as positive or negative. 3. Implement a website that generates a pie chart categorizing a user’s tweets. ![alt text](https://i.imgur.com/ke5MKzA.jpg) In order to classify the tweets, we utilized lists of 2006 positive words and 4783 negative words that Dr. <NAME> and Prof. <NAME> of the University of Illinois at Chicago kindly put together a few years back. <file_sep>#chr(97) returns the string 'a' #ord('a') returns the integer 97 import cs50 import sys if len(sys.argv) != 2: print("Usage: python caesar.py k") exit(1) k = int(sys.argv[1]) while k>26: k = k -26 plaintext = input("plaintext: ") print("ciphertext: ", end="") for char in plaintext: if char.isalpha(): if char.islower(): ciphertext = ord(char) + k if ciphertext > 122: ciphertext = ciphertext - 26 print(chr(ciphertext), end="") elif char.isupper(): ciphertext = ord(char) + k if ciphertext > 90: ciphertext = ciphertext - 26 print(chr(ciphertext), end="") else: print(char, end="") print() <file_sep>/** * helpers.c * * Helper functions for Problem Set 3. */ #include <cs50.h> #include "helpers.h" #include <stdio.h> #include <math.h> /********************************************** FUNCTION: SEARCH *********************************************/ /* Returns true if value is in array of n values, else false. 1. The implementation must return false immediately if n is non-positive. 2. The implementation must return true if value is in values and false if value is not in values. 3. The running time of your implementation must be in O(log n). */ bool search(int value, int values[], int n) //28, {27,28,29}, 3 { // TODO: implement a searching algorithm int first, last, middle; int size; first = 0; //[0] last = n-1; //3-1 = [2] middle = floor((first + last) /2); //[1] size = last - first + 1; //3 while(size > 0) { if(values[middle] == value) { return true; } if(values[middle] > value) { last = middle - 1; middle = floor((last + first)/2); } if(values[middle] < value) { first = middle + 1; middle = floor((last + first)/2); } size = last - first + 1; } return false; /*Simple version: */ // if(n < 0) // { // return false; // } // for(int i = 0; i<n; i++) // { // if(values[i] == value) // { // return true; // } // } } /*********************************************** FUNCTION: SORT **********************************************/ /* Sorts array of n values. 1. Your implemenation must sort, from smallest to largest, the array of numbers that it’s passed. 2. The running time of your implementation must be in O(n2), where n is the array’s size. */ void sort(int values[], int n) { // TODO: implement a sorting algorithm int min, min_index, temp; /*INSERT SORTING ALGORITHM*/ for(int i = 0; i<(n - 1); i++) //2 { min = values[i]; //20 for(int k = (i+1); k<(n); k++) //3 to 7 { if(min > values[k]) { min = values[k]; min_index = k; temp = values[i]; values[i] = values[min_index]; values[min_index] = temp; } } } // for(int j = 0; j< n; j++) // { // printf("%i, ", values[j]); // } // printf("\n"); return; } <file_sep>## Problem Set 7: C$50 Finance Implement C$50 Finance, a web app via which one can manage portfolios of stocks. Not only will this tool allow the user to check real stocks' actual prices and portfolios' values, it will also let the user make mock purchases and sales of stocks by querying Yahoo Finance for stocks' prices. <file_sep>import cs50 while True: print("Height: ") height = cs50.get_int() if height < 0 or height > 23: break width = height + 1 for i in range(height): for col in range(i, height-1): print(" ", end="") for col in range(height - i - 1, width): print("#", end="") print() <file_sep>#include <stdio.h> #include <cs50.h> #include <string.h> #include <stdlib.h> #include <ctype.h> int main(int argc, string argv[]) //argv[0] = ./caesar, argv[1] = k { if(argc != 2) { printf("Usage: ./caesar k\n"); return 1; } int k; k = atoi(argv[1]); while(k>26) { k = k - 26; } string plaintext; int ciphertext; printf("plaintext: "); plaintext = get_string(); printf("ciphertext: "); for(int i = 0; i < strlen(plaintext); i++) { do { if(isalpha(plaintext[i])) { if(islower(plaintext[i])) { ciphertext = (int) plaintext[i] + k; if (ciphertext > 122) { ciphertext = ciphertext - 26; } printf("%c", (char) ciphertext); } else if(isupper(plaintext[i])) { ciphertext = (int) plaintext[i] + k; if (ciphertext > 90) { ciphertext = ciphertext - 26; } printf("%c", (char) ciphertext); } } else { printf("%c", plaintext[i]); } } while (plaintext[i] == '\0'); } printf("\n"); }<file_sep>/** * Resize a BMP image bit by bit */ #include <stdio.h> #include <stdlib.h> #include "bmp.h" int main(int argc, char *argv[]) { // ensure proper usage if (argc != 4) { fprintf(stderr, "Usage: ./resize n infile outfile\n"); return 1; } // ensure n is within bounds int n; n = atoi(argv[1]); if(n < 1 || n > 100) { fprintf(stderr, "n must be between 1 and 100, inclusive\n"); return 1; } // remember filenames char *infile = argv[2]; char *outfile = argv[3]; // open input file FILE *inptr = fopen(infile, "r"); //If successful, fopen will return a pointer to the file. Otherwise, it will return NULL if (inptr == NULL) { fprintf(stderr, "Could not open %s.\n", infile); return 2; } // create/open output file FILE *outptr = fopen(outfile, "w"); if (outptr == NULL) { fclose(inptr); fprintf(stderr, "Could not create %s.\n", outfile); return 3; } // read infile's BITMAPFILEHEADER BITMAPFILEHEADER bf; fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr); // read infile's BITMAPINFOHEADER BITMAPINFOHEADER bi; fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr); // ensure infile is (likely) a 24-bit uncompressed BMP 4.0 if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 || bi.biBitCount != 24 || bi.biCompression != 0) { fclose(outptr); fclose(inptr); fprintf(stderr, "Unsupported file format.\n"); return 4; } /***************************************************** OUTFILE HEADER SHIT ********************************************************/ long oldWidth, oldHeight; // save it oldWidth = bi.biWidth; oldHeight = bi.biHeight; int oldPadding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4; // change it bi.biWidth = bi.biWidth * n; bi.biHeight = bi.biHeight * n; // determine new padding for output file int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4; //sizeof(RGBTRIPLE) = 3 // caculate new things bi.biSizeImage = ((sizeof(RGBTRIPLE) * bi.biWidth) + padding) * abs(bi.biHeight); bf.bfSize = bi.biSizeImage + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); // write outfile's BITMAPFILEHEADER fwrite(&bf, sizeof(BITMAPFILEHEADER), 1, outptr); // write outfile's BITMAPINFOHEADER fwrite(&bi, sizeof(BITMAPINFOHEADER), 1, outptr); /**********************************************************************************************************************************/ /***************************************************** RESIZING STARTS HERE *******************************************************/ RGBTRIPLE array[bi.biWidth]; //Pixel-storing array. It'll store the stretched out row // iterate over infile's scanlines, i.e. EACH ROW for (int i = 0, biHeight = labs(oldHeight); i < biHeight; i++) { int m = 0; //Pixel-storing array's index // iterate over pixels in scanline, i.e. EACH PIXEL for (int j = 0; j < oldWidth; j++) { // temporary storage RGBTRIPLE triple; // read RGB triple from infile fread(&triple, sizeof(RGBTRIPLE), 1, inptr); for(int k = 0; k<n; k++) { // For each pixel at [i,j] WRITE TO ARRAY N TIMES array[m] = triple; m++; //Increment the index and store the same pixel again } } for (int k = 0; k<n; k++) { // WRITE ARRAY TO OUTFILE fwrite(&array, sizeof(array), 1, outptr); //Write the stretched out row n times // ADD PADDING, IF ANY for (int l = 0; l < padding; l++) { fputc(0x00, outptr); } } // skip over padding, if any fseek(inptr, oldPadding, SEEK_CUR); } /**********************************************************************************************************************************/ // close infile fclose(inptr); // close outfile fclose(outptr); // success return 0; }
220e5ceeace7028e35d291a03ca4568622530601
[ "Markdown", "C", "Python", "Makefile" ]
19
C
scumulder/CS50-Projects
ccf73a1d3d86d4102df1775e259f33c1dcab209f
3164836a98925480b0dfbf4ef4741131825657b9
refs/heads/master
<repo_name>fmuiin14/laravel_basic<file_sep>/app/Http/routes.php <?php Route::get('/', function () { return view('welcome'); }); Route::get('/create-customer', 'CustomerController@create'); Route::post('/create-customer', 'CustomerController@create_post');<file_sep>/routes/routes.php <?php // Application routes // Here is where you can register all of the routes for an application. // It's a breeze. Simply tell Laravel the url's it should respond to // and give it the controller to call when that URL is requested. Route::get('/', function() { return view('welcome'); }); Route::get('/create-customer', 'CustomerController@create'); Route::post('/create-customer', 'CustomerController@create_post');<file_sep>/app/Http/Controllers/CustomerController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; use App\Customer; class CustomerController extends Controller { public function index() { } public function create() { return view('create_customer'); } public function create_post(Request $request) { $customer = new Customer; $customer->name = $request["name"]; $customer->email = $request["email"]; $customer->occupation = $request["occupation"]; return view('view_customer', ['customer' => $customer]); } }
ffd1ac17058c1a588690278f6c2aac673eb8f2b2
[ "PHP" ]
3
PHP
fmuiin14/laravel_basic
a4cf9b0f63be32eaa671cf92a85940d570d79526
395e5af27b16bf24e4e282057dd929967b2e2bfa
refs/heads/master
<repo_name>Megadeus/BFT-on-Hadoop<file_sep>/src/finalyearproject/JobTrackerNonSpecMapper.java package finalyearproject; import java.io.IOException; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.MapReduceBase; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reporter; public class JobTrackerNonSpecMapper extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> { public static int start_year = 0, End_year; public void map(LongWritable ran, Text line, OutputCollector<Text, IntWritable> out, Reporter arg3) throws IOException { try { if (line != null) { String sep_line = line.toString(); String year = sep_line.substring(start_year, End_year); String Temp = sep_line.substring(End_year); IntWritable temp_int = new IntWritable(); temp_int.set(Integer.parseInt(Temp.trim())); if (temp_int != null && year != null) out.collect(new Text(year), temp_int); } } catch (Exception e) { e.printStackTrace(); } } } <file_sep>/src/finalyearproject/ForecastReducer.java package finalyearproject; import java.io.IOException; import java.util.Iterator; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.MapReduceBase; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; public class ForecastReducer extends MapReduceBase implements Reducer<Text, IntWritable, Text, DoubleWritable> { boolean error_code; public ForecastReducer() { if (Math.random() > 0.8) { error_code = true; } } public void reduce(Text year, Iterator<IntWritable> temp, OutputCollector<Text, DoubleWritable> out, Reporter arg3) throws IOException { long sum = 0; double avg = 0.0; int count = 0; try { while (temp.hasNext()) { sum += temp.next().get(); count++; } avg = sum / count; // introducing error if (error_code) { avg += 12; } out.collect(year, new DoubleWritable(avg)); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>/src/finalyearproject/JobTrackerNonSpecDriver.java package finalyearproject; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Scanner; public class JobTrackerNonSpecDriver { private static final String tempnsmresult = "/home/hduser/workspace/newfinalyearproject/tempnsmresult"; private static final String tempnsinput = "/home/hduser/workspace/newfinalyearproject/tempnsinput"; private final static String tempnsrresult = "/home/hduser/workspace/newfinalyearproject/tempnsrresult"; public void run(Class mapperclass, Class reducerclass, String input_dir, String output_dir, int fault_index) { // running the map int i; StartMapperClass.StartMapperClass1(mapperclass, finalyearproject.JobTrackerNonSpecReducer.class, input_dir, tempnsmresult + "/temp"); Thread t[] = new Thread[50]; for (i = 0; i <= fault_index; i++) { StartMapperClass ob = new StartMapperClass(); t[i] = new Thread(ob); t[i].start(); } boolean isalive = true; while (isalive) { for (int j = 0; j < i; j++) { isalive = false; if (t[j].isAlive() == true) { isalive = true; break; } } } // checking the error // reiterate try { while (true) { if (test(tempnsmresult, tempnsinput, fault_index + 1) == 1) { break; } StartMapperClass ob = new StartMapperClass(); Thread k = new Thread(ob); k.start(); while (k.isAlive()); } } catch (Exception e) { e.printStackTrace(); } // running the reduce // checking the error and reiterate // produce the output StartReducerClass.StartReducerClass1( finalyearproject.JobTrackerNonSpecMapper.class, reducerclass, tempnsinput, tempnsrresult + "/temp"); for (i = 0; i <= fault_index; i++) { StartReducerClass ob1 = new StartReducerClass(); t[i] = new Thread(ob1); t[i].start(); } isalive = true; while (isalive) { for (int j = 0; j < i; j++) { isalive = false; if (t[j].isAlive() == true) { isalive = true; break; } } } // checking the error // reiterate try { while (true) { if (test(tempnsrresult, output_dir, fault_index + 1) == 1) { break; } StartReducerClass ob = new StartReducerClass(); Thread k = new Thread(ob); k.start(); while (k.isAlive()); } } catch (Exception e) { e.printStackTrace(); } } public static int test(String In, String Out1, int fault) throws Exception { Out1 = Out1 + "/new"; File folder = new File(In); File[] listOfFiles = folder.listFiles(); int i = 0; Scanner s[] = new Scanner[100]; for (File file : listOfFiles) { s[i] = new Scanner(new File(file.getAbsolutePath() + "/part-00000")); i++; } File f2 = new File(Out1); List<String> l = new LinkedList<String>(); while (s[0].hasNext() && s[1].hasNext() && s[2].hasNext()) { HashMap<String, Integer> out = new HashMap<String, Integer>(); for (int k = 0; k < i; k++) { String g = s[k].nextLine(); if (!out.containsKey(g)) out.put(g, 1); else out.put(g, out.get(g) + 1); } Iterator it = out.entrySet().iterator(); int counter = 0; while (it.hasNext()) { Map.Entry<String, Integer> pairs = (Map.Entry<String, Integer>) it.next(); // to print all if (pairs.getValue() >= fault) { l.add(pairs.getKey()); counter++; break; } } if (counter == 0) { return 0; } } if (!f2.isAbsolute()) { f2.createNewFile(); } FileWriter fw = new FileWriter(f2.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); for (String n : l) { bw.write(n + System.lineSeparator()); } bw.close(); return 1; } } <file_sep>/README.md Byzantine Fault Tolerance ALgorithm implemented on Apache Hadoop platform. Visit us on to know more about project http://megadeus.github.io/BFT-on-Hadoop/ Watch video of our Running project in youtube https://www.youtube.com/watch?v=zJkAGoCAccI <file_sep>/src/finalyearproject/AppletClass.java package finalyearproject; import java.awt.GridLayout; import java.io.BufferedWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import javax.swing.ButtonGroup; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; public class AppletClass extends JApplet { private static final long serialVersionUID = 1L; public final JTextArea ta = new JTextArea(); public static boolean finished = false; public void init() { this.setLayout(new GridLayout(4, 1)); this.setSize(600, 300); JPanel panel1,panel2,panel3,panel4; panel1 = new JPanel(); panel2 = new JPanel(); panel3 = new JPanel(); panel4 = new JPanel(); JLabel l1,l2,l3; l1 = new JLabel("Method"); l2 = new JLabel("Algorithm Type"); l3 = new JLabel("Fault Index"); JTextField fault = new JTextField(10); JRadioButton m1,m2,m3; m1 = new JRadioButton("Daily"); m2 = new JRadioButton("Monthly"); m3 = new JRadioButton("Yearly"); JRadioButton a1,a2; a1 = new JRadioButton("Speculative"); a2 = new JRadioButton("Non Speculative"); ButtonGroup method , algorithm_g; method = new ButtonGroup(); method.add(m1); method.add(m2); method.add(m3); algorithm_g = new ButtonGroup(); algorithm_g.add(a1); algorithm_g.add(a2); panel1.setSize(this.WIDTH, 100); panel3.setSize(this.WIDTH, 100); panel2.setSize(this.WIDTH, 100); panel2.add(l2); panel1.add(l1); panel3.add(l3); panel2.add(a1); panel2.add(a2); panel1.add(m3); panel1.add(m2); panel1.add(m1); panel3.add(fault); panel4.add(new JButton("Start")); this.add(panel1); this.add(panel2); this.add(panel3); this.add(panel4); int type = Integer.parseInt(this.getParameter("type")); int algorithm = Integer.parseInt(this.getParameter("algorithm")); int fault_index = Integer.parseInt(this.getParameter("fault_index")); ByzantineFaultSystem ob = null; try { ob = new ByzantineFaultSystem("mapper_class", "reducer_class", "IN", "OUT", false , 2); ob.run(); } catch (Exception e) { e.printStackTrace(); } finished = true; System.out.println("Finished!"); super.init(); } public void start() { super.start(); } public void repaint() { super.repaint(); } public void destroy() { super.destroy(); } public void stop() { super.stop(); } }
c41aa87c8a60dae473f5d79470aa9588cf1ce686
[ "Markdown", "Java" ]
5
Java
Megadeus/BFT-on-Hadoop
d667677686a278dfa223c51bb2861523d515aad4
524da68c65693dd41b5bd3501f2390fff50b8b2c
refs/heads/main
<file_sep>import React, { useEffect } from "react"; import AOS from "aos"; import "./aos.css"; import "./Page1.css"; const Page1 = () => { useEffect(() => { AOS.init({ duration: 1000, }); }); return ( <> <div> <div className="greeting__first" data-aos="fade-in" data-aos-offset="200" data-aos-easing="ease-in-sine" data-aos-duration="1200" > <span className="greeting__hello">HELLO</span> <span className="greeting__xinchao">Xin chào</span> </div> <div className="greeting__second" data-aos="fade-in" data-aos-offset="200" data-aos-easing="ease-in-sine" data-aos-duration="1500" > <div className="greeting__gutentag">Guten Tag</div> </div> <div className="greeting__third" data-aos="fade-in" data-aos-offset="400" data-aos-easing="ease-in-sine" data-aos-duration="2500" > <span className="greeting__hi">你好</span> <p className="greeting__korean">안녕하세요</p> <span className="greeting__bonjour">Bonjour</span> </div> <div className="greeting__fourth" data-aos="fade-in" data-aos-offset="200" data-aos-easing="ease-in-sine" data-aos-duration="750" > <div className="greeting__hola">¡Hola</div> <div className="greeting__goni">こんにちは</div> </div> <div className="greeting__fifth" data-aos="fade-in" data-aos-offset="50" data-aos-easing="ease-in-sine" data-aos-duration="900" > <div className="greeting__sawa">สวัสดีครับ</div> </div> </div> </> ); }; export default Page1; <file_sep># <NAME> - 한가희 - 한양대학교 중어중문학과 16학번 - 특징 : 안드로이드 개발자로 취업했으며 복싱을 재미있게 배우는 중. - Add another line - And another line for testing account - lklkjlklkjlkjl<file_sep>### 김진호 ! - feat1 <file_sep>import React from "react"; import "./App.css"; import Page1 from "./component/Page1/Page1"; function App() { return <Page1 />; } export default App; <file_sep>import React, { useEffect } from "react"; import AOS from "aos"; import "./aos.css"; const Page1 = () => { const boxStyle = { width: "40%", height: "200px", fontSize: "30px", lineHeight: "200px", background: "black", color: "white", textAlign: "center", }; useEffect(() => { AOS.init({ duration: 1000, }); }); return ( <> <div> <div> <p data-aos="fade-up">AOS 테스트1</p> </div> <div style={{ height: "500px" }} /> <div style={boxStyle}> <p data-aos="fade-up">AOS 테스트2</p> </div> <div style={{ height: "500px" }} /> <div style={boxStyle} data-aos="fade-up"> <p>AOS 테스트3</p> </div> <div style={{ height: "500px" }} /> </div> </> ); }; export default Page1;
690c8d71d3a4d82649e1e63022061e09ae7df016
[ "JavaScript", "Markdown" ]
5
JavaScript
hangeul-project/hangeul-react-web
61681cb9e82ee859d2160191d5d48a2fd1f5792b
adc63f35fdb997f18aa4ca05edd5d043a27212e5
refs/heads/master
<file_sep> <!DOCTYPE html> <html lang="en"> <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>SantoshSharmaa.com | About Wing Commander Santosh Sharma</title> <meta name="keywords" content="online astrology prediction free , best astrologer in south india,free horoscope online, rudra center, free online horoscope,rudraksha ratna bangalore, free rudraksha consultation,free online numerology, best numerologist in india, best numerology,hypnosis bangalore, hypnotism bangalore"/> <meta name="description" content="Santosh Sharmaa free horoscopes,Vedic astrology (JYOTISH) readings assume the law of karma and past births. That is why, in our horoscopes we find mention of “Dasha Bhukti balance." /> <meta name="copyright" content="2016 <NAME>" /> <meta name="content-language" content="EN" /> <meta name="author" content="<NAME>" /> <meta name="distribution" content="GLOBAL" /> <meta name="robots" content="ALL" /> <meta name="pragma" content="no-cache" /> <meta name="revisit-after" content="7 day" /> <meta name="classification" content="Santosh Sharma,bangalore Horoscopes,About Wing Commander Santosh Sharma, Spiritual hypnotherapist" /> <?php include 'header.php' ?> <!-- <div class="home-main-banner"> <img src="images/testimonials-rudra.jpg" alt="main banner" class="main-banner-wd"> </div> --> <div class="home-main-banner-jyotish"> <div class="img-gif"> <img src="images/light.gif" alt="main banner" class="gif-round-img"> </div> </div> <div class="container"> <div class="row main-content"> <div class="col-md-8"> <h4>Jyoti means light. Jyotish means Light is God. Light is a form of energy. </h4> <p>The whole universe is filled with energies of different forms. Energy can neither be created nor destroyed. We talk of soul in terms of energy which is indestructible and eternal.</p> <p> Astrology, which we call Jyotish, is a science of soul’s journey. We are born with a life journey map. This map is our chart or kundali. We are born with these charts based on our past karmas.</p> <p>Kundali means potential energy in a coiled form, which unravels itself as the individual’s life progresses.</p> <p>Kundali or chart is like a hard disk with a programming of an OS. A person thinks, behaves and reacts to situations in pre-programmed ways.</p> </div> <div class="col-md-4"> <div class="row"> <div class="col-md-12 my-inner-form"> <h4>Enquiry Form</h4> <form name="contact" id="contact" action="thankyou-inner.php" method="post" onsubmit="return validateForm()"> <div class="form-group"> <label for="name">Full Name:</label> <input type="text" class="form-control" id="name" name="name" placeholder="<NAME>" maxlength="22" required> </div> <div class="form-group"> <label for="mobile">Mobile Number:</label> <input type="text" class="form-control" id="mobile" name="mobile" placeholder="Mobile Number" maxlength="22" required> </div> <div class="form-group"> <label for="email">Email:</label> <input type="text" class="form-control" id="email" name="email" placeholder="Email" maxlength="22" required> </div> <input type="submit" value="Submit" class="btn btn-primary btn-lg"> </form> </div> </div> </div> </div> </div> <!-- container / --> <?php include 'footer.php' ?><file_sep> <!DOCTYPE html> <html lang="en"> <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>SantoshSharmaa.com | About Wing Commander Santosh Sharma</title> <meta name="keywords" content="Santosh Sharma,bangalore Horoscopes,About Wing Commander Santosh Sharma, Spiritual hypnotherapist,astrology,horoscopes,online horoscopes,Rudraksh,original Rudraksha"/> <meta name="description" content="Santosh Sharmaa free horoscopes,Vedic astrology (JYOTISH) readings assume the law of karma and past births. That is why, in our horoscopes we find mention of “Dasha Bhukti balance." /> <meta name="copyright" content="2016 Santosh Sharmaa" /> <meta name="content-language" content="EN" /> <meta name="author" content="<NAME>" /> <meta name="distribution" content="GLOBAL" /> <meta name="robots" content="ALL" /> <meta name="pragma" content="no-cache" /> <meta name="revisit-after" content="7 day" /> <meta name="classification" content="Santosh Sharma,bangalore Horoscopes,About Wing Commander Santosh Sharma, Spiritual hypnotherapist" /> <?php include 'header.php' ?> <div class="home-main-banner"> <img src="images/about-us-banner.jpg" alt="main banner" class="main-banner-wd"> </div> <div class="container"> <div class="row"> <div class="col-md-12 col-xs-12 main-content"> <h1 class="title-h1">About Wing Commander Santosh Sharma</h1> <p>Wing Commander Santosh Sharma is a third generation astrologer, A Healer of vast experience, SUJOK master and Spiritual hypnotherapist. He is at Bangalore, capital of Karnataka, India since last two decades</p> <p>He is adept in Energy equalization, Emotional Detoxification, past life regression, marital conflict resolution, Fear/phobia/pain dissolution, de-addiction and smoking cessation etc.</p> <p>He has been honoured with umpteen awards and facilitations. Nelson Mandela International Peace award, Global Achievers award in Astrology and Indian Achievers award in social service and Health education are some of many. </p> <h2 class="title-h1"> Our Mission</h2> <ul class="Chakra-list"> <li> We are dedicated to help drive away sin, suffering and pain worldwide. </li> <li> We are committed to transformation of humanity through self-awareness, leading to inner bliss and living enlightenment. </li> <li> We are committed to supplying best quality blessed items for for path of spiritual enlightenment.</li> <li> We keep prices reasonable for the benefit of the humanity. </li> <li> We promote further research in this path so that the knowledge may be used for the benefit of all. </li> </ul> <h3 class="title-h1">Achievement Awards</h3> <div class="rudraksha-photo"> <ul class="rudraksha-ul"> <li class="rudraksha-list" data-toggle="modal" data-target="#rudraksha0"><img src="images/achievement-0.jpg" alt="Achievement Awards"/> </li> <li class="rudraksha-list" data-toggle="modal" data-target="#rudraksha1"><img src="images/achievement-1.jpg" alt="Achievement Awards"/> </li> <li class="rudraksha-list" data-toggle="modal" data-target="#rudraksha2"><img src="images/achievement-2.jpg" alt="Achievement Awards"/> </li> <li class="rudraksha-list" data-toggle="modal" data-target="#rudraksha3"><img src="images/achievement-3.jpg" alt="Achievement Awards"/> </li> <li class="rudraksha-list" data-toggle="modal" data-target="#rudraksha4"><img src="images/achievement-4.jpg" alt="Achievement Awards"/> </li> <li class="rudraksha-list" data-toggle="modal" data-target="#rudraksha5"><img src="images/achievement-5.jpg" alt="Achievement Awards"/> </li> <li class="rudraksha-list" data-toggle="modal" data-target="#rudraksha6"><img src="images/achievement-6.jpg" alt="Achievement Awards"/> </li> </ul> </div> </div> </div> </div> <!-- container / --> <!-- Modal popup start--> <div class="modal fade" id="rudraksha0" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Achievement Awards</h4> </div> <div class="modal-body"> <img src="images/achievement-0-zoom.jpg" alt="rudraksh" class="img-responsive" /> </div> <div class="modal-footer"> </div> </div> </div> </div> <!-- Modal popup start--> <div class="modal fade" id="rudraksha1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Achievement Awards</h4> </div> <div class="modal-body"> <img src="images/achievement-1-zoom.jpg" alt="rudraksh" class="img-responsive" /> </div> <div class="modal-footer"> </div> </div> </div> </div> <!-- Modal popup start--> <div class="modal fade" id="rudraksha2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Achievement Awards</h4> </div> <div class="modal-body"> <img src="images/achievement-2-zoom.jpg" alt="rudraksh" class="img-responsive" /> </div> <div class="modal-footer"> </div> </div> </div> </div> <!-- Modal popup start--> <div class="modal fade" id="rudraksha3" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Achievement Awards</h4> </div> <div class="modal-body"> <img src="images/achievement-3-zoom.jpg" alt="rudraksh" class="img-responsive" /> </div> <div class="modal-footer"> </div> </div> </div> </div> <!-- Modal popup start--> <div class="modal fade" id="rudraksha4" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Achievement Awards</h4> </div> <div class="modal-body"> <img src="images/achievement-4-zoom.jpg" alt="rudraksh" class="img-responsive" /> </div> <div class="modal-footer"> </div> </div> </div> </div> <!-- Modal popup start--> <div class="modal fade" id="rudraksha5" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Achievement Awards</h4> </div> <div class="modal-body"> <img src="images/achievement-5-zoom.jpg" alt="rudraksh" class="img-responsive" /> </div> <div class="modal-footer"> </div> </div> </div> </div> <!-- Modal popup start--> <div class="modal fade" id="rudraksha6" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Achievement Awards</h4> </div> <div class="modal-body"> <img src="images/achievement-6-zoom.jpg" alt="rudraksh" class="img-responsive" /> </div> <div class="modal-footer"> </div> </div> </div> </div> <?php include 'footer.php' ?><file_sep><?php ob_start(); include 'header.php'; /*error_reporting(E_ALL); ini_set('display_errors', 1); echo "<pre>"; print_r($_POST); die;*/ if(isset($_REQUEST['msg']) && ($_REQUEST['msg'] == 'sent')) { echo "<div class='container'><div class='thankyou-email'><h1 class='title-h1'>Thankyou for your information, one of our counsellor will get back to you.</h1> </div></div>"; header('Refresh:3;url=index.php'); } else { if(empty($_POST['name']) || empty($_POST['mobile']) || empty($_POST['email']) || empty($_POST['month']) || empty($_POST['date']) || empty($_POST['year']) || empty($_POST['state']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) { echo "Please fill all the required fields!"; return false; } $name = $_POST['name']; $phone = $_POST['mobile']; $email_address = $_POST['email']; $month = $_POST['month']; $date = $_POST['date']; $year = $_POST['year']; $state = $_POST['state']; // create email body and send it $to = '<EMAIL>'; $email_subject = "Santosh Sharmaa enquiry from: $name"; $email_body = "You have received a new message from contact form.<br><br>". "The details are as follows:<br>Name: $name<br>Phone: $phone<br>Email: $email_address<br>Date of Birth: $month-$date-$year <br>State: $state"; $headers = "From: <EMAIL>\r\n"; $headers .= "BCC: <EMAIL>\r\n"; $headers .= "BCC: <EMAIL>\r\n"; $headers .= "Content-type: text/html\r\n"; mail($to,$email_subject,$email_body,$headers); header("Location:thankyou.php?msg=sent"); } ?> <?php include "footer.php";?><file_sep><!DOCTYPE html> <html lang="en"> <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>santoshsharmaa.com | Chakra Analysis,Aura Analysis </title> <meta name="keywords" content="chakra balancing,chakras test,chakra analysis,Chakra Yog workshops,Aura Analysis,online astrology prediction free,best astrologer in south india,free horoscope online, free online horoscope,rudraksha ratna bangalore" /> <meta name="description" content="The rudra Center is a nurturing place where people come to find balance, heal, and transform through the foundational teachings of yoga, Aura Analysis, Chakra Analysis. Founded by santosh sharma bangalore." /> <meta name="copyright" content="2016 <NAME>" /> <meta name="content-language" content="EN" /> <meta name="author" content="<NAME>" /> <meta name="distribution" content="GLOBAL" /> <meta name="robots" content="ALL" /> <meta name="pragma" content="no-cache" /> <meta name="revisit-after" content="7 day" /> <meta name="classification" content="hypnosis training,bangalore hypnosis training,bangalore Hypnosis,free Hypnosis" /> <!-- header include --> <?php include 'header.php' ?> <div class="home-main-banner"> <img src="images/chakras-banner.jpg" alt="main banner" class="main-banner-wd"> </div> <div class="container"> <div class="row"> <div class="col-xs-12 col-md-12 main-content"> The word "chakra" means "wheel or disk". These energy vortexes/wheels are the channels through which energy flows in & out. Chakras are “entry gates” of the aura ( energy field that surrounds our physical body). Chakras constantly rotate and vibrate. The activities in the chakras influence our body shape, glandular processes, physical/mental ailments, emotions and behavior. When one or more of the chakras are blocked, the energy does not flow harmoniously, or if they are too open, it will result in energy imbalance. </div> </div> <div class="row"> <!-- Chakra Analysis start --> <div class="col-xs-12 col-md-4 rudr-img-wd"> <img src="images/Chakras-inner-banner.jpg" alt="Chakras inner banner" class="img-responsive"> </div> <div class="col-xs-12 col-md-8"> <h1 class="title-h1">Chakra Analysis</h1> <p class="chakra-p">Through Chakra Yog workshops, you can achieve following:</p> <ul class="Chakra-list"> <li>Understand life, its lessons and your unique life purpose</li> <li>Learn quick and effective meditation techniques</li> <li> Promote physical healing of many diseases and conditions</li> <li>Develop the ability to accomplish life goals</li> <li>Establish a deeper connection with your inner self</li> <li>Clear mental blocks and strengthen mental capacities</li> <li>Achieve success in every sphere of life</li> <li>Assist and provide individual tools to make their life more meaningful and fulfilling.</li> </ul> </div> </div> <!-- Chakra Analysis end --> <div class="row"> <!-- Chakra Analysis start --> <div class="col-xs-12 col-md-8 "> <h1 class="title-h1">Aura Analysis</h1> <p class="chakra-p">Aura can get punctured under following circumstances:</p> <ul class="Chakra-list"> <li>Under high influence of liquor where consciousness has moved out of body.</li> <li>During GA (General Anesthesia) when consciousness is absent.</li> <li>During heavy menstrual cycles, when aura is open Spirits / foreign energies and dark forces can enter through holes in aura and create block in chakras and/or enter physical body and start interfering in day-to-day life. One feels tired, demotivated, depressed and worth less due to depletion of energy through the punctured aura.</li> </ul> </div> <div class="col-xs-12 col-md-4"> <img src="images/chakras-inner-aura-color.jpg" alt="Chakras inner banner" class="img-responsive"> </div> </div> <!-- Chakra Analysis end --> </div> <!-- container / --> <?php include 'footer.php' ?><file_sep><!DOCTYPE html> <html lang="en"> <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>santoshsharmaa.com | Hypnosis Training Center</title> <meta name="keywords" content="best numerology,hypnosis bangalore,hypnotism bangalore,online hypnosis training,hypnosis training,bangalore hypnosis training,bangalore Hypnosis,free Hypnosis course,best Hypnosis Training Center" /> <meta name="description" content="Hypnosis under clinical conditions, is a great wonderful tool to deal with trauma, behavioral issues, relationship issues, anxiety, depression, diabetes, BP etc." /> <meta name="copyright" content="2016 <NAME>" /> <meta name="content-language" content="EN" /> <meta name="author" content="<NAME>" /> <meta name="distribution" content="GLOBAL" /> <meta name="robots" content="ALL" /> <meta name="pragma" content="no-cache" /> <meta name="revisit-after" content="7 day" /> <meta name="classification" content="online hypnosis training,bangalore hypnosis training,bangalore Hypnosis,free Hypnosis" /> <!-- header include --> <?php include 'header.php' ?> <div class="home-main-banner"> <img src="images/hypnosis-banner.jpg" alt="main banner" class="main-banner-wd"> </div> <div class="container"> <div class="row main-content"> <!-- Chakra Analysis start --> <div class="col-xs-12 col-md-4 hypnosis-inner-bg "> <div class="row"> <!-- Chakra Analysis start --> <div class="col-xs-12 col-md-12 main-logo-place"> <img src="images/hypnosis-inner-banner.jpg" alt="Chakras inner banner" class="img-responsive"> </div> </div> </div> <div class="col-xs-12 col-md-8 "> <h1 class="title-h1">At Rudra Center</h1> <p>Hypnosis under clinical conditions, is a great wonderful tool to deal with trauma, behavioral issues, relationship issues, anxiety, depression, insomnia, skin rashes,lack of motivation, examination phobia, fear of rejection/ flying/height/sea/pregnancy/intimacy, allergies, PCOD, headache, acidity, diabetes, BP etc. Under hypnosis, body is fully relaxed and the mind is at a very high state of alertness.It is extremely safe and highly effective. Great results in attracting love in life, dealing with sexual dysfunction, low energy, tiredness, low self esteem, attracting luck, creating wealth and developing leadership qualities.</p> <h2 class="title-h1">Results</h2> <p>Great results in attracting love in life, dealing with sexual dysfunction, low energy, tiredness, low self esteem, attracting luck, creating wealth and developing leadership qualities. Past life regression ferrets out hidden reasons for blockages in progress in present life and sufferings getting manifested again and again. Your unhealed Inner Child has the capacity to create many obstacles in your present life. Self hypnosis is a wonderful tool to help yourself to lead a happy balanced life.</p> </div> </div> <!-- Chakra Analysis end --> </div> <!-- container / --> <?php include 'footer.php' ?><file_sep> <!DOCTYPE html> <html lang="en"> <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>SantoshSharmaa.com | About Wing Commander <NAME></title> <meta name="keywords" content="online astrology prediction free , best astrologer in south india,free horoscope online, free online horoscope,rudraksha ratna bangalore, free rudraksha consultation,free online numerology, best numerologist in india, best numerology,hypnosis bangalore, hypnotism bangalore"/> <meta name="description" content="Santosh Sharmaa free horoscopes,Vedic astrology (JYOTISH) readings assume the law of karma and past births. That is why, in our horoscopes we find mention of “Dasha Bhukti balance." /> <meta name="copyright" content="2016 <NAME>" /> <meta name="content-language" content="EN" /> <meta name="author" content="<NAME>" /> <meta name="distribution" content="GLOBAL" /> <meta name="robots" content="ALL" /> <meta name="pragma" content="no-cache" /> <meta name="revisit-after" content="7 day" /> <meta name="classification" content="Santosh Sharma,bangalore Horoscopes,About Wing Commander Santosh Sharma, Spiritual hypnotherapist" /> <?php include 'header.php' ?> <div class="home-main-banner"> <img src="images/youtube-video.jpg" alt="main banner" class="main-banner-wd"> </div> <div class="container"> <div class="row"> <div class="col-xs-12 col-md-12 main-content"> <h2>Our Youtube channel</h2> <br> </div> </div> <div class="row"> <div class="col-xs-12 col-md-4"> <div class="row"> <iframe width="320" height="215" class="embed-responsive-item" src="https://www.youtube.com/embed/YVlAbtQPBa4" frameborder="0" allowfullscreen></iframe> </div> </div> <div class="col-xs-12 col-md-4"> <div class="row"> <iframe width="320" height="215" class="embed-responsive-item" src="https://www.youtube.com/embed/MbDndJdRi1o" frameborder="0" allowfullscreen></iframe> </div> </div> <div class="col-xs-12 col-md-4"> <iframe width="320" height="215" class="embed-responsive-item" src="https://www.youtube.com/embed/UhycF5SL5a4" frameborder="0" allowfullscreen></iframe> </div> </div> <br><br> <div class="row"> <div class="col-xs-12 col-md-4"> <div class="row"> <iframe width="320" height="215" class="embed-responsive-item" src="https://www.youtube.com/embed/dcsazjs-m7I" frameborder="0" allowfullscreen></iframe> </div> </div> <div class="col-xs-12 col-md-4"> <div class="row"> <iframe width="320" height="215" class="embed-responsive-item" src="https://www.youtube.com/embed/kokszu86viQ" frameborder="0" allowfullscreen></iframe> </div> </div> </div> </div> <!-- container / --> <?php include 'footer.php' ?><file_sep> <!DOCTYPE html> <html lang="en"> <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>SantoshSharmaa.com | About Wing Commander Santo<NAME></title> <meta name="keywords" content="online astrology prediction free , best astrologer in south india,free horoscope online, free online horoscope,rudraksha ratna bangalore, free rudraksha consultation,free online numerology, best numerologist in india, best numerology,hypnosis bangalore, hypnotism bangalore"/> <meta name="description" content="Santosh Sharmaa free horoscopes,Vedic astrology (JYOTISH) readings assume the law of karma and past births. That is why, in our horoscopes we find mention of “Dasha Bhukti balance." /> <meta name="copyright" content="2016 <NAME>" /> <meta name="content-language" content="EN" /> <meta name="author" content="<NAME>" /> <meta name="distribution" content="GLOBAL" /> <meta name="robots" content="ALL" /> <meta name="pragma" content="no-cache" /> <meta name="revisit-after" content="7 day" /> <meta name="classification" content="Santosh Sharma,bangalore Horoscopes,About Wing Commander Santosh Sharma, Spiritual hypnotherapist" /> <?php include 'header.php' ?> <div class="home-main-banner"> <img src="images/testimonials-rudra.jpg" alt="main banner" class="main-banner-wd"> </div> <div class="heightfix"></div> <div class="heightfix"></div> <div class="container"> <div class="row"> <div class="col-md-8"> <div class="row"> <div class="col-md-2"> <img width="300" height="300" src="images/testimonial.png" class="img-responsive" alt="testimonial"> </div> <div class="col-md-10"> <h4><NAME></h4> <p>Career Astrology,Vastu Services, Rudraksha today had been truly energizing. So thanks to you for all this.</p> </div> </div> <hr> <div class="row"> <div class="col-md-2"> <img width="300" height="300" src="images/testimonial.png" class="img-responsive" alt="testimonial"> </div> <div class="col-md-10"> <h4> <NAME></h4> <p>A very thorough cleansing was done. So many issues surfaced. I have amazing clarity through the sessions.Thank you and God Bless!</p> </div> </div> <hr> <div class="row"> <div class="col-md-2"> <img width="300" height="300" src="images/user.png" class="img-responsive" alt="testimonial"> </div> <div class="col-md-10"> <h4><NAME></h4> <p>I stand here two and a half years later after successfully completing medical school and passing my licensing exams. I had guidance all along the way and so precise that it helped me confidently pass in the periods he suggested. What I like when I meet with him is he is frank and tells the truth which was not always easy to hear but when it came out correct it gave me the strength to handle it and move on and get to where I am today. I am definitely a believer and look forward to guidance in my future endeavors. Thank you Mr. <NAME>.</p> </div> </div> <hr> <div class="row"> <div class="col-md-2"> <img width="300" height="300" src="images/testimonial.png" class="img-responsive" alt="testimonial"> </div> <div class="col-md-10"> <h4><NAME></h4> <p>After going to seek advice from <NAME> I was very pleased with the guidance I received especially since it was at a very complex and difficult time during my medical school and career. I was very nervous and felt like I had no direction. Mr. Sharma always spoke honestly and gave me clarity and hope to move on through my exam hurdles.</p> </div> </div> <hr> <div class="row"> <div class="col-md-2"> <img width="300" height="300" src="images/testimonial.png" class="img-responsive" alt="testimonial"> </div> <div class="col-md-10"> <h4><NAME></h4> <p>Dear Mr. <NAME>, It was very nice meeting you. You predicted that,  Aug 2015 onwards, there will be good opportunities & there will be career growth. You also told me that i will get a chance to work with a well known and large scale company, and yes! I got a job offer from one of the best companies in India in mid Aug 2015 and now I am working with them. Thank you very much for your support and suggestions. I can definitely say that your prediction turned out accurate.</p> </div> </div> <hr> <div class="row"> <div class="col-md-2"> <img width="300" height="300" src="images/testimonial.png" class="img-responsive" alt="testimonial"> </div> <div class="col-md-10"> <h4> <NAME></h4> <p>I had a great experience with "online astrology prediction free ". I was feeling very depressed due to problems in my love life. Then I searched the Internet and found "online astrology prediction free" and believe me from the time I had called them they provided great suggestions and helped me in resolving my problems. Now I am married and from that day I regularly use their consultancy services and they never charged for any kind of consultancy services. I recommend "online astrologer prediction free" to friends and relatives.</p> </div> </div> <hr> <div class="row"> <div class="col-md-2"> <img width="300" height="300" src="images/user.png" class="img-responsive" alt="testimonial"> </div> <div class="col-md-10"> <h4> <NAME></h4> <p>Words cannot begin to describe what I was exposed to. I came by myself to a Spouses Intensive with the understanding of how much damage I was responsible for in my marriage. I was physically, mentally, and emotionally done! We have been separated already and headed for divorce. There were constant fights and quarrels in my life everyday for which my whole family has been involved. I was very stressed and in pain until I came to know the most accurate and highly productive astrologer Santosh Sharma who was from bangalore. He has transformed my life from stress to peace and happiness and all these possible for his wisdom and knowledge. I feel deeply grateful to astrologer Santosh Sharma for resolving all problems and hindrances and made my life happy and colorful.</p> </div> </div> <hr> <div class="row"> <div class="col-md-2"> <img width="300" height="300" src="images/user.png" class="img-responsive" alt="testimonial"> </div> <div class="col-md-10"> <h4><NAME></h4> <p>I know Santo<NAME> since 2 years. He has helped me in all spheres of life. For me he is like God to me and without him I would not have survived in this world. I was facing some grim money & business problems which were banished from my life after I started following <NAME>’s guidance. I’ve been his follower for more than a decade now and he is the only person I turn to in times of tribulations. Under his charisma, I never feel stressed now. He makes life easy and fruitful. With warm and very high regards for my Guru</p> </div> </div> <hr> <div class="row"> <div class="col-md-2"> <img width="300" height="300" src="images/testimonial.png" class="img-responsive" alt="testimonial"> </div> <div class="col-md-10"> <h4> <NAME></h4> <p>We are both from a different caste and in love. We wanted to be married but our families did not allow us. Thus we contacted pandit ji to solve our marriage problem solution and he has surprised us in making it all happen with great perfection and satisfaction. Today we are a happy couple all because of him. Thank you Mr. <NAME>.</p> </div> </div> <hr> <div class="row"> <div class="col-md-2"> <img width="300" height="300" src="images/testimonial.png" class="img-responsive" alt="testimonial"> </div> <div class="col-md-10"> <h4> <NAME></h4> <p>I tried this finance report for the first time. I never knew that these guys can predict the complete year of my finances so well and correctly. They also guided me how to save money and take advantage of the good times my year. It’s really very helpful and people more into money matters should try...</p> </div> </div> </div> <div class="col-md-4"> <div class="row"> <div class="col-md-12"> <iframe width="320" height="215" class="embed-responsive-item" src="https://www.youtube.com/embed/YVlAbtQPBa4" frameborder="0" allowfullscreen></iframe> </div> </div> <div class="heightfix"></div> <div class="row"> <div class="col-md-12"> <iframe width="320" height="215" class="embed-responsive-item" src="https://www.youtube.com/embed/MbDndJdRi1o" frameborder="0" allowfullscreen></iframe> </div> </div> <div class="heightfix"></div> <div class="row"> <div class="col-md-12"> <iframe width="320" height="215" class="embed-responsive-item" src="https://www.youtube.com/embed/UhycF5SL5a4" frameborder="0" allowfullscreen></iframe> </div> </div> <div class="heightfix"></div> <div class="row"> <div class="col-md-12"> <iframe width="320" height="215" class="embed-responsive-item" src="https://www.youtube.com/embed/dcsazjs-m7I" frameborder="0" allowfullscreen></iframe> </div> </div> <div class="heightfix"></div> <div class="row"> <div class="col-md-12"> <div class="fb-page" data-href="https://www.facebook.com/Santoshsharmaacom-1671819039756775/" data-tabs="timeline" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true"></div> </div> </div> </div> </div> </div> <!-- container / --> <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.6"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <?php include 'footer.php' ?><file_sep><!DOCTYPE html> <html lang="en"> <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><NAME> - Horoscopes,Rudraksha,Chakra Analysis</title> <meta name="keywords" content="<NAME>,Bangalore Horoscopes,Bangalore free astrology,online astrology prediction free,best astrologer in south india,free horoscope online, free online horoscope,rudraksha ratna bangalore, free rudraksha consultation,free online numerology,best numerologist in india,rudra center" /> <meta name="description" content="<NAME> online astrology prediction free in Bangalore,Vedic astrology (JYOTISH) readings assume the law of karma and past births. That is why, in our horoscopes we find mention of “Dasha Bhukti balance.There are resonance relationships between the planets, colors and other phenomena. Each planet is resonant with specific frequencies of the color spectrum." /> <meta name="copyright" content="2016 <NAME>" /> <meta name="content-language" content="EN" /> <meta name="author" content="<NAME>" /> <meta name="distribution" content="GLOBAL" /> <meta name="robots" content="ALL" /> <meta name="pragma" content="no-cache" /> <meta name="revisit-after" content="7 day" /> <meta name="classification" content="Santosh Sharma,Bangalore astrology,Bangalore horoscopes,Bangalore online horoscopes,Bangalore Rudraksh,Bangalore original Rudraksha" /> <?php include 'header.php' ?> <div class="home-main-banner"> <a href="javascript:void(0)" data-toggle="modal" data-target="#myModalbanner"> <img src="images/banner-home.jpg" alt="main banner" class="main-banner-wd"> </a> </div> <div class="container"> <div class="row"> <div class="col-xs-12 col-lg-4 col-sm-12 col-md-4 middle-Astrology"> <a href="jyotish.php"><img src="images/vedic-astrology.jpg" alt="Vedic Astrology"></a> <p class="astrology-subtext"> Vedic astrology (JYOTISH) readings assume the law of karma and past births. That is why, in our horoscopes we find mention of “Dasha Bhukti balance”. </p> </div> <div class="col-xs-12 col-lg-4 col-sm-12 col-md-4 middle-Astrology"> <a href="gem-stones.php"><img src="images/2.jpg" alt="Gems"></a> <p class="astrology-subtext"> There are resonance relationships between the planets, colors, gemstones, digital sequences, and other phenomena. Each planet is resonant with specific frequencies of the color spectrum. </p> </div> <div class="col-xs-12 col-lg-4 col-sm-12 col-md-4 middle-Astrology"> <a href="astrology.php"><img src="images/1.jpg" alt="Gems"></a> <p class="astrology-subtext"> Tavizs: These are filled with certain tree roots and herbs used generally by tribals in states like Odisha, Assam and Chhattisgarh to pacify grahas. </p> </div> </div> <div class="heightfix"></div> <div class="row"> <h3 class="title-h2 sk-our-services">Our Services</h3> <div class="col-md-12"> <div id="slider"> <a href="javascript:void(0)" class="control_next">></a> <a href="javascript:void(0)" class="control_prev"><</a> <a href="javascript:void(0)" data-toggle="modal" data-target="#myModalbanner"> <ul class="slider-list-item"> <li> <p class="services-title">Ask a Question, Get an Answer</p><img src="images/ask-question.jpg" class="img-responsive" alt="ask question"> </li> <li> <p class="services-title">Business Problem</p> <img src="images/business-problem.jpg" class="img-responsive" alt="business problem"> </li> <li> <p class="services-title">Career</p> <img src="images/career.jpg" class="img-responsive" alt="career"> </li> <li> <p class="services-title"> Husband & Wife Problem</p> <img src ="images/divorce.jpg" class="img-responsive" alt="Divorce"> </li> <li> <p class="services-title"> Education</p> <img src ="images/education.jpg" class="img-responsive" alt="education"> </li> <li> <p class="services-title"> Health Issue</p> <img src ="images/health-&-fitness.jpg" class="img-responsive" alt="health-&-fitness"> </li> <li> <p class="services-title"> Horoscope</p> <img src ="images/horoscope.jpg" class="img-responsive" alt="horoscope"> </li> <li> <p class="services-title"> Kundli</p> <img src ="images/kundli.jpg" class="img-responsive" alt="kundli"> </li> <li> <p class="services-title"> Marriage</p> <img src ="images/marriage.jpg" class="img-responsive" alt="marriage"> </li> <li> <p class="services-title"> Rudrashka</p> <img src ="images/rudrashka.jpg" class="img-responsive" alt="rudrashka"> </li> </ul> </a> </div> </div> </div> <div class="heightfix"></div> <div class="row workshop-event"> <div class="col-md-10"> <h3 class="title-h2">Workshop Event Updates</h3> <marquee behavior="scroll" direction="left" onmouseover="this.stop();" onmouseout="this.start();"> <!-- <span>Every Sunday Chakra yoga workshop 10.30AM to 12.30PM.</span> --> <span>Coming Soon...</span> </marquee> </div> </div> <div class="heightfix"></div> <div class="row"> <div class="col-md-12"> <h3 class="title-h2">Our Expertise</h3> </div> </div> <div class="row"> <div class="col-md-4"> <div class="row"> <div class="col-md-4"> <ul class="list-group"> <li class="list-group-item"><span class="glyphicon glyphicon glyphicon-hand-right hand-width" aria-hidden="true"></span></li> <li class="list-group-item list-group-item-chakra">Chakra</li> </ul> </div> <div class="col-md-8"> <a href="chakra.php"><img src="images/rudra-center-1.gif" class="img-responsive" alt="rudra-center"> </a> <p class="home-img-title"></p> </div> </div> </div> <div class="col-md-4"> <div class="row"> <div class="col-md-4"> <ul class="list-group"> <li class="list-group-item"><span class="glyphicon glyphicon glyphicon-hand-right hand-width" aria-hidden="true"></span></li> <li class="list-group-item list-group-item-chakra">Rudraksha</li> </ul> </div> <div class="col-md-8"> <a href="rudraksha.php"><img src="images/rudraksha-home-banner.jpg" class="img-responsive" alt="rudra-center"> </a> </div> </div> </div> <div class="col-md-4"> <div class="row"> <div class="col-md-4"> <ul class="list-group"> <li class="list-group-item"><span class="glyphicon glyphicon glyphicon-hand-right hand-width" aria-hidden="true"></span></li> <li class="list-group-item list-group-item-chakra">Hypnosis</li> </ul> </div> <div class="col-md-8"> <a href="hypnosis.php"><img src="images/rudra-hypnotic.gif" class="img-responsive" style="width: 150px;" alt="hypnotic"> </a> </div> </div> </div> </div> <div class="heightfix"></div> <div class="row"> <div class="col-md-12 col-xs-12"> <h4 class="title-h2"><a href="testimonials.php" style="color: red;">What people say about us</a></h4> </div> </div> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> <div class="carousel-inner testimonial" role="listbox"> <div class="item active"> <div class="testimonial-text-home"> <a href="testimonials.php"><img width="100" height="100" src="images/testimonial.png" class="img-responsive" alt="testimonial"></a> Career Astrology,Vastu Services, Rudraksha today had been truly energizing... <span > <a href="testimonials.php" class="read-more">Read more...</a></span> </div> </div> <div class="item"> <div class="testimonial-text-home"> <a href="testimonials.php"><img width="100" height="100" src="images/testimonial.png" class="img-responsive" alt="testimonial"></a> Career Astrology,Vastu Services, Rudraksha today had been truly energizing. <span class="read-more"><a href="testimonials.php" class="read-more">Read more...</a></span> </div> </div> <div class="item"> <div class="testimonial-text-home"> <a href="testimonials.php"><img width="100" height="100" src="images/user.png" class="img-responsive" alt="testimonial"></a> I know <NAME> since 2 years. He has helped me in all spheres of life. For me he is like God to me and without him... <span class="read-more"><a href="testimonials.php" class="read-more">Read more...</a></span> </div> </div> <div class="item"> <div class="testimonial-text-home"> <a href="testimonials.php"> <img width="100" height="100" src="images/testimonial.png" class="img-responsive" alt="testimonial"></a> Words cannot begin to describe what I was exposed to. I came by myself to a Spouses Intensive with the understanding of how much damage <a href="testimonials.php" class="read-more">Read more...</a> </div> </div> <div class="item"> <div class="testimonial-text-home"> <a href="testimonials.php"><img width="100" height="100" src="images/testimonial.png" class="img-responsive" alt="testimonial"></a> I know <NAME> since 2 years. He has helped me in all spheres of life. For me he is like God to me and without him <a href="testimonials.php" class="read-more">Read more...</a> </div> </div> <div class="item"> <div class="testimonial-text-home"> <a href="testimonials.php"> <img width="100" height="100" src="images/testimonial.png" class="img-responsive" alt="testimonial"></a> It was very nice meeting you. You predicted that, Aug 2013 onwards, there will be good opportunities <a href="testimonials.php" class="read-more">Read more...</a> </div> </div> </div> <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> <h5 class="pull-right"><a href="testimonials.php" class="read-more">View More...</a></h5> <div class="heightfix"></div> <div class="row"> <div class="col-md-12 col-xs-12"> <h4 class="title-h2" ><a href="videos.php" style="color: red;">Our Videos</a></h4> </div> </div> <div class="row"> <div class="col-xs-12 col-md-4"> <div class="row"> <iframe width="320" height="215" src="https://www.youtube.com/embed/YVlAbtQPBa4" frameborder="0" allowfullscreen></iframe> </div> </div> <div class="col-xs-12 col-md-4"> <div class="row"> <iframe width="320" height="215" src="https://www.youtube.com/embed/MbDndJdRi1o" frameborder="0" allowfullscreen></iframe> </div> </div> <div class="col-xs-12 col-md-4"> <iframe width="320" height="215" src="https://www.youtube.com/embed/UhycF5SL5a4" frameborder="0" allowfullscreen></iframe> </div> <h5 class="pull-right"><a href="videos.php" class="read-more">View More...</a></h5> </div> </div> <!-- container / --> <?php include 'footer.php' ?> <script type="text/javascript"> $(document).ready(function ($) { setInterval(function () { moveRight(); }, 3000); var slideCount = $('#slider ul li').length; var slideWidth = $('#slider ul li').width(); var slideHeight = $('#slider ul li').height(); var sliderUlWidth = slideCount * slideWidth; $('#slider').css({ width: slideWidth, height: slideHeight }); $('#slider ul').css({ width: sliderUlWidth, marginLeft: - slideWidth }); $('#slider ul li:last-child').prependTo('#slider ul'); function moveLeft() { $('#slider ul').animate({ left: + slideWidth }, 200, function () { $('#slider ul li:last-child').prependTo('#slider ul'); $('#slider ul').css('left', ''); }); }; function moveRight() { $('#slider ul').animate({ left: - slideWidth }, 200, function () { $('#slider ul li:first-child').appendTo('#slider ul'); $('#slider ul').css('left', ''); }); }; $('a.control_prev').click(function () { moveLeft(); }); $('a.control_next').click(function () { moveRight(); }); }); </script><file_sep><!DOCTYPE html> <html lang="en"> <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>santoshsharmaa.com | Rudraksha, Rudraksha Beads from Nepal, Original Rudraksha </title> <meta name="keywords" content="Bangalore Rudraksha,original Rudraksha,online astrology prediction free,best astrologer in south india,free horoscope online,free online horoscope,rudraksha ratna bangalore,free rudraksha consultation" /> <meta name="description" content="Natural and authentic Rudraksha Beads from Nepal, you will find Rudraksha Beads of all types such as from Nepal Beads for wearing purposes." /> <meta name="copyright" content="2016 <NAME>" /> <meta name="content-language" content="EN" /> <meta name="author" content="<NAME>" /> <meta name="distribution" content="GLOBAL" /> <meta name="robots" content="ALL" /> <meta name="pragma" content="no-cache" /> <meta name="revisit-after" content="7 day" /> <meta name="classification" content="Online Rudraksha,Bangalore Rudraksha,Original Rudraksha,Rudraksha,Rudraksh,Bangalore Rudraksha" /> <!-- header include --> <?php include 'header.php' ?> <div class="home-main-banner"> <img src="images/rudraksha-banner.jpg" alt="main banner" class="main-banner-wd"> </div> <div class="container"> <div class="row"> <div class="col-xs-12 col-md-12 main-content"> Destruction is the beginning of Creation in a cyclic fashion. Shiva is the Destroyer and Rudraksh is related to him. Like Shiva, rudraksh beads destroy all negatives and brings balance in our psycho-somatic energy body. </div> </div> <div class="row"> <!-- Chakra Analysis start --> <div class="col-xs-12 col-md-4 rudr-img-wd"> <img src="images/rudraksha-inner-banner.jpg" alt="Chakras inner banner" class="img-responsive"> <br> <h2 class="title-h1">Visit Us</h1> <a href="http://www.karnataka.chakrayog.com/Web/Home.aspx" target="_blank"> <p>Our online consultation andpurchase of Rudraksha,Gemstones,Vastu N Pooja items. Click here.</p> </a> </div> <div class="col-xs-12 col-md-8"> <br> <p> Our mother earth is a big electro-magnetic field and we have bio-electricity and electro-magnetic fields in our physical and auric body. Rudraksha with its Dynamic polarities changes its properties of poles to bring balance in electro-magnetic fields of our body. It also has bio-electricity akin to our nervous system. Rudraksh works as an automatic balancer and reservoir. It helps us keep our chakra (vortex energy generators) balanced by creating requisite neuro paths and memory muscles.</p> <p><NAME> narrations about usage of rudraksh and feedback from innumerable users have proven time and again about efficacy of rudraksh in different combinations.</p> <p>One should wear rudraksh after consulting an expert who understand about fake and genuine ones and who can guide how to wear it, based on Yin /Yang energy flows in naadis. Wrong usage does not generate full results. Precautions for storage and correct usage are advised.</p> <h2 class="title-h1">Experience power of original Rudraksha</h2> <div class="rudraksha-photo"> <ul class="rudraksha-ul"> <li class="rudraksha-list" data-toggle="modal" data-target="#rudraksha1"><img src="images/rudraksha-1.jpg" alt="rudraksha"/> </li> <li class="rudraksha-list" data-toggle="modal" data-target="#rudraksha2"><img src="images/rudraksha-2.jpg" alt="rudraksha"/> </li> <li class="rudraksha-list" data-toggle="modal" data-target="#rudraksha3"><img src="images/rudraksha-3.jpg" alt="rudraksha"/> </li> <li class="rudraksha-list" data-toggle="modal" data-target="#rudraksha4"><img src="images/rudraksha-4.jpg" alt="rudraksha"/> </li> <li class="rudraksha-list" data-toggle="modal" data-target="#rudraksha5"><img src="images/rudraksha-5.jpg" alt="rudraksha"/> </li> </ul> </div> </div> </div> <!-- Chakra Analysis end --> </div> <!-- container / --> <!-- Modal popup start--> <div class="modal fade" id="rudraksha1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Career Success</h4> </div> <div class="modal-body"> <img src="images/rudraksh-zoom-11.jpg" alt="rudraksh" class="img-responsive" /> </div> <div class="modal-footer"> </div> </div> </div> </div> <!-- Modal popup start--> <div class="modal fade" id="rudraksha2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Study Success</h4> </div> <div class="modal-body"> <img src="images/rudraksh-zoom-22.jpg" alt="rudraksh" class="img-responsive" /> </div> <div class="modal-footer"> </div> </div> </div> </div> <!-- Modal popup start--> <div class="modal fade" id="rudraksha3" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Ek Mukhi in Gold</h4> </div> <div class="modal-body"> <img src="images/rudraksh-zoom-33.jpg" alt="rudraksh" class="img-responsive" /> </div> <div class="modal-footer"> </div> </div> </div> </div> <!-- Modal popup start--> <div class="modal fade" id="rudraksha4" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Wealth n Protection</h4> </div> <div class="modal-body"> <img src="images/rudraksh-zoom-44.jpg" alt="rudraksh" class="img-responsive" /> </div> <div class="modal-footer"> </div> </div> </div> </div> <!-- Modal popup start--> <div class="modal fade" id="rudraksha5" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Surya kavach</h4> </div> <div class="modal-body"> <img src="images/rudraksh-zoom-55.jpg" alt="rudraksh" class="img-responsive" /> </div> <div class="modal-footer"> </div> </div> </div> </div> <?php include 'footer.php' ?><file_sep> <!DOCTYPE html> <html lang="en"> <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>SantoshSharmaa.com | About Wing Commander <NAME></title> <meta name="keywords" content="online astrology prediction free,best astrologer in south india,free horoscope online, free online horoscope,rudraksha ratna bangalore, free rudraksha consultation,free online numerology, best numerologist in india, best numerology,hypnosis bangalore, hypnotism bangalore"/> <meta name="description" content="Santosh Sharmaa free horoscopes,Vedic astrology (JYOTISH) readings assume the law of karma and past births. That is why, in our horoscopes we find mention of “Dasha Bhukti balance." /> <meta name="copyright" content="2016 <NAME>" /> <meta name="content-language" content="EN" /> <meta name="author" content="<NAME>" /> <meta name="distribution" content="GLOBAL" /> <meta name="robots" content="ALL" /> <meta name="pragma" content="no-cache" /> <meta name="revisit-after" content="7 day" /> <meta name="classification" content="Santosh Sharma,bangalore Horoscopes,About Wing Commander Santosh Sharma, Spiritual hypnotherapist" /> <?php include 'header.php' ?> <div class="home-main-banner-testimonials"> <div class="img-gif"> <img src="images/gemstone.gif" alt="main banner" class="gif-round-img-gem"> </div> </div> <div class="container"> <div class="row main-content"> <div class="col-md-8"> <p>We human beings exist in a spectrum of light of VIBGYOR. Infra-red and Ultra-violet are basically two nodes called Rahu and Ketu. Between these two are all seven colors which are the Grahas (moon is also considered as a graha because of it’s impact on our emotion). Each one is associated with a colour, like Saturn is blue and Jupiter is yellow etc.. </p> <p>Earth has a frequency, our body has a frequency and each graha has it’s own frequency. When we say Saturn is Vakri (retrograde) it means that the frequency of blue colour energy is deficient or in dissonance with our body frequency. </p> <p>All gem stones have radioactive properties. These stones reflect, refract, absorb and radiate ions. These ions react with electrolytes in our blood plasma and work as catalysts in our neuro paths and alter chemical secretions in glands. For example, when we wear a blue sapphire, the deficient blue colour energy frequency in our body gets balanced.</p> <p>As per Garud puran and other scriptures, gem stones should NOT be heated or treated. Gem stones lose its astrological properties if heated or treated with artificial colours. Proper study and analysis of horoscope are strongly recommended to determine usage. </p> </div> <div class="col-md-4"> <div class="row"> <div class="col-md-12 my-inner-form"> <h4>Enquiry Form</h4> <form name="contact" id="contact" action="thankyou-inner.php" method="post" onsubmit="return validateForm()"> <div class="form-group"> <label for="name">Full Name:</label> <input type="text" class="form-control" id="name" name="name" placeholder="<NAME>" maxlength="22" required> </div> <div class="form-group"> <label for="mobile">Mobile Number:</label> <input type="text" class="form-control" id="mobile" name="mobile" placeholder="Mobile Number" maxlength="22" required> </div> <div class="form-group"> <label for="email">Email:</label> <input type="text" class="form-control" id="email" name="email" placeholder="Email" maxlength="22" required> </div> <input type="submit" value="Submit" class="btn btn-primary btn-lg"> </form> </div> </div> </div> </div> </div> <!-- container / --> <?php include 'footer.php' ?><file_sep><!DOCTYPE html> <html lang="en"> <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><NAME> - Horoscopes,Rudraksha,Chakra Analysis</title> <meta name="keywords" content="Santosh Sharma,online astrology prediction free,best astrologer in south india,free horoscope online,free online horoscope,rudraksha ratna bangalore,free rudraksha consultation,free online numerology,best numerologist in india,best numerology,hypnosis bangalore,hypnotism bangalore" /> <meta name="description" content="Santosh Sharmaa free horoscopes,Vedic astrology (JYOTISH) readings assume the law of karma and past births. That is why, in our horoscopes we find mention of “Dasha Bhukti balance." /> <meta name="copyright" content="2016 <NAME>" /> <meta name="content-language" content="EN" /> <meta name="author" content="<NAME>" /> <meta name="distribution" content="GLOBAL" /> <meta name="robots" content="ALL" /> <meta name="pragma" content="no-cache" /> <meta name="revisit-after" content="7 day" /> <meta name="classification" content="Santosh Sharma,Santosh Sharmaa, astrology,horoscopes,online horoscopes,Rudraksh,original Rudraksha" /> <?php include 'header.php' ?> <div class="home-main-banner"> <img src="images/appoitnment-banner.jpg" alt="main banner" class="main-banner-wd"> </div> <div class="container avg-bg"> <div class="astro-form"> <div class="row"> <div class="col-md-12"> <form name="contact" id="contact" action="thankyou-inner.php" method="post" onsubmit="return validateForm()"> <div class="form-group"> <label for="name">Full Name:</label> <input type="text" class="form-control" id="name" name="name" placeholder="<NAME>" maxlength="32" required> </div> <div class="form-group"> <label for="mobile">Mobile Number:</label> <input type="text" class="form-control" id="mobile" name="mobile" placeholder="Mobile Number" maxlength="32" required> </div> <div class="form-group"> <label for="email">Email:</label> <input type="text" class="form-control" id="email" name="email" placeholder="Email" maxlength="32" required> </div> <input type="submit" value="Submit" class="btn btn-primary btn-lg"> <!-- <input type="submit" class="btn btn-primary btn-lg"> --> </form> </div> </div> </div> </div> <!-- container / --> <?php include 'footer.php' ?>
1f0d18ccbbc08d0f36a70a28e43a014019d247fd
[ "PHP" ]
11
PHP
rahulyhg/sk.com
6b2e525ed7c104f310f52df2be7f5eaf0839158b
24afce7bfaaa95a5a7ef81066f6353efafcbc125
refs/heads/master
<repo_name>brunetto/ambrogio<file_sep>/main.go package main import ( "log" "net/http" "strings" "os/exec" "os" ) func main () { http.HandleFunc("/it", handler) err := http.ListenAndServe(":8787", nil) log.Fatal(err) } func handler (resp http.ResponseWriter, req *http.Request) { resp.Write([]byte("<script>window.open('','_parent',''); window.close();</script>")) script := `tell application "iTerm2" set newWindow to (create window with default profile) tell current session of newWindow write text "COMMAND" end tell end tell` input := req.URL.Query() script = strings.Replace(script, "COMMAND", input["q"][0], -1) cmd := *exec.Command("osascript") cmd.Stdin = strings.NewReader(script) cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout err := cmd.Start() if err != nil{ log.Fatal(err) } err = cmd.Wait() if err != nil { log.Fatal(err) } } <file_sep>/README.md # Ambrogio Little webservice to run bash command from Alfred. Mac-only. Run with `./ambrogio &`, it will listen for call to `http://localhost:8787/it?q={query}`, with space ancoded as `+`. See also the [java version](https://github.com/mfalcier/lurch) by [@Marco](https://github.com/mfalcier)
7c6e7a9303e39f29c9b13db1ebed40cd4cb015b7
[ "Markdown", "Go" ]
2
Go
brunetto/ambrogio
d897033a762b93837eafbf9aec8d0df5cf3511d6
81b054afb5e93ba2b2757d5312dee3917a2d2ef7
refs/heads/master
<file_sep>(function () { if (typeof Asteroids === "undefined"){ window.Asteroids = {}; } var GameView = Asteroids.GameView = function(game, ctx) { this.game = game; this.ctx = ctx; }; GameView.prototype.start = function() { setInterval(function () { this.game.draw(this.ctx); }, 30); var asteroidIntervalId = setInterval(function(){ var asteroid = new Asteroids.Asteroid({ pos: this.game.randomPosition(), game: this.game }) this.game.allObjects.push(asteroid); this.game.asteroids.push(asteroid); }, 2000) //setInterval(this.game.moveObjects.bind(this.game), 10); setInterval(this.game.step.bind(this.game), 10); this.bindKeyHandlers(); } GameView.prototype.bindKeyHandlers = function () { var game = this.game; var ctx = this.ctx; key('up',function (event) { event.preventDefault(); var direction = Asteroids.Util.prototype.unitVec(game.ship.angle) game.ship.power([direction[0],direction[1]]) }); key('down', function (event) { event.preventDefault(); var direction = Asteroids.Util.prototype.unitVec(game.ship.angle) game.ship.power([-1*direction[0], -1*direction[1]]) // game.ship.power([0,0.5]) }); key('left', function (event) { event.preventDefault(); game.ship.left(); // game.ship.power([-0.5,0]) }); key('right', function (event) { event.preventDefault(); game.ship.right() // game.ship.power([0.5,0]) }); key('space', function (event) { event.preventDefault(); game.ship.fireBullet(game); }); key('esc', function(event){ location.reload(true) // ctx.clearRect(0, 0, game.dim_x, game.dim_y); // game.gameOver = false; // gameView.start(); }); }; })();<file_sep>(function () { if (typeof Asteroids === "undefined"){ window.Asteroids = {}; } var Asteroid = Asteroids.Asteroid = function(passedHash){ var COLOR = 'white'; var RADIUS = 20; this.color = COLOR; this.radius = RADIUS; this.pos = passedHash['pos']; this.vel = [Asteroids.Util.prototype.randomVec(5), Asteroids.Util.prototype.randomVec(5)]; this.game = passedHash['game']; this.isWrappable = true; this.imgSrc = "lib/asteroid.png" this.size = 100; } Asteroids.Util.prototype.inherits(Asteroids.Asteroid, Asteroids.MovingObject); })();<file_sep>(function () { if (typeof Asteroids === "undefined"){ window.Asteroids = {}; } var Util = Asteroids.Util = function () {}; Util.prototype.inherits = function (child, base) { function Surrogate () {}; Surrogate.prototype = base.prototype; child.prototype = new Surrogate(); } Util.prototype.randomVec = function(length){ return (Math.random(length) * 2 - Math.random(length)); } Util.prototype.unitVec = function (angle) { return [Math.cos(angle), Math.sin(angle)] }; })(); <file_sep># Asteroids # My version of the famous Atari game built using Canvas and Javascript following object-oriented principles. Try it out at: panchammehrunkar.com/Asteroids<file_sep>// var asteroids = window.Asteroids || {} (function () { if (typeof Asteroids === "undefined"){ window.Asteroids = {}; } var MovingObject = Asteroids.MovingObject = function(passedHash) { this.pos = passedHash['pos']; this.vel = passedHash['vel']; this.radius = passedHash['radius']; this.color = passedHash['color']; this.game = passedHash['game']; this.isWrappable = true; this.imgSrc = ""; this.size = 75; this.angle = 0; this.load = false }; MovingObject.prototype.draw = function(ctx){ var obj = this; var img = new Image(); if (obj instanceof Asteroids.Ship) { ctx.save(); ctx.translate(obj.pos[0], obj.pos[1]); ctx.rotate(obj.angle); img.src = this.imgSrc; ctx.drawImage(img, -20, -20, 50, 50); ctx.restore(); }else{ var img = new Image(); var load = false; img.onload = function () { load = true ctx.drawImage(img, obj.pos[0], obj.pos[1], obj.size, obj.size); }; img.src = this.imgSrc; } }; MovingObject.prototype.move = function(ctx) { this.pos = this.game.wrap(this, this.pos); // if (this instanceof Asteroids.Ship){ // this.pos[0] += direction[0]; // this.pos[1] += direction[1]; // }else{ this.pos[0] += this.vel[0]; this.pos[1] += this.vel[1]; // } }; MovingObject.prototype.relocate = function (game) { this.pos = game.randomPosition(); this.vel = [0,0] this.angle = 0; }; MovingObject.prototype.power = function(impulse){ this.vel[0] += impulse[0]; this.vel[1] += impulse[1]; }; MovingObject.prototype.fireBullet = function (game) { var direction = Asteroids.Util.prototype.unitVec(this.angle) var bullet = new Asteroids.Bullet({ pos: [game.ship.pos[0], game.ship.pos[1]], game: game, vel: [direction[0]*10, direction[1]*10] }); game.allObjects.push(bullet); }; MovingObject.prototype.left = function () { this.angle -= (Math.PI)/4 }; MovingObject.prototype.right = function () { this.angle += (Math.PI)/4 }; MovingObject.prototype.isCollidedWith = function(otherObject) { var x1 = this.pos[0]; var x2 = otherObject.pos[0]; var y1 = this.pos[1]; var y2 = otherObject.pos[1]; var dist = Math.sqrt(Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2)); if (dist < (this.size)) { return true; } else{ return false; } } MovingObject.prototype.collidedWith = function (otherObject) { var game = this.game; if (this instanceof Asteroids.Asteroid) { if (otherObject instanceof Asteroids.Ship){ otherObject.relocate(game); game.remove(this) game.lives--; }else if (otherObject instanceof Asteroids.Bullet){ game.remove(this); game.remove(otherObject); game.score += 10; } } }; })();<file_sep>(function () { if (typeof Asteroids === "undefined"){ window.Asteroids = {}; } var Game = Asteroids.Game = function () { NUM_ASTEROIDS = 8; DIM_X = 1000; DIM_Y = 700; this.dim_x = DIM_X; this.dim_y = DIM_Y; this.numAst = NUM_ASTEROIDS; this.asteroids = this.addAsteroids(); this.ship = this.addShip(); this.allObjects = this.allObjects(); this.score = 0; this.lives = 5; this.gameOver = false; } Game.prototype.addAsteroids = function () { var asteroids = []; for(var i = 0; i < this.numAst; i++){ asteroids.push(new Asteroids.Asteroid({ pos: this.randomPosition(), game: this})); } return asteroids; } Game.prototype.addShip = function() { var ship = new Asteroids.Ship({ pos: this.randomPosition(), game: this }); return ship; }; Game.prototype.randomPosition = function() { var ast_pos = [Math.random() * this.dim_x, Math.random() * this.dim_y]; return ast_pos; } Game.prototype.moveObjects = function(ctx){ for (var i = 0; i < this.allObjects.length; i++) { this.allObjects[i].move(ctx); this.checkCollisions(); } } Game.prototype.draw = function(ctx) { ctx.clearRect(0, 0, this.dim_x, this.dim_y); if (this.gameOver){ ctx.font="100px Verdana"; ctx.fillStyle = 'yellow' ctx.fillText("GAME OVER!",150,300); ctx.font="50px Verdana"; ctx.fillText("Press escape to play again!",150,400); return; } //this.ship.draw(ctx) for (var i = 0; i < this.allObjects.length; i++) { ctx.font="30px Verdana"; ctx.fillStyle = 'yellow' ctx.fillText("Score:",10,50); ctx.fillText(this.score,110,50) ctx.fillText("Lives:",10,90); ctx.fillText(this.lives,110,90) this.allObjects[i].draw(ctx); } } Game.prototype.wrap = function(obj, pos) { if (obj.isWrappable){ if (pos[0] < 0){ pos[0] = this.dim_x; } else if (pos[1] < 0) { pos[1] = this.dim_y; } else if (pos[0] > this.dim_x) { pos[0] = 0; } else if (pos[1] > this.dim_y) { pos[1] = 0; } } return pos; } Game.prototype.checkCollisions = function(){ for (var i = 0; i < this.asteroids.length; i++) { for (var j = 0; j < this.allObjects.length; j++) { if (this.asteroids[i].isCollidedWith(this.allObjects[j])) { this.asteroids[i].collidedWith(this.allObjects[j]); } } } } Game.prototype.remove = function (object) { // body... if (object instanceof Asteroids.Asteroid || object instanceof Asteroids.Bullet) { var index = this.allObjects.indexOf(object) this.allObjects.splice(index,1) if (object instanceof Asteroids.Asteroid){ var indexA = this.asteroids.indexOf(object) this.asteroids.splice(indexA,1) } } else if (object instanceof Asteroids.Ship) { var index = this.allObjects.indexOf(object) object.relocate(this) } }; Game.prototype.step = function(){ this.moveObjects(); this.checkCollisions(); this.checkGameOver(); } Game.prototype.allObjects = function() { return this.asteroids.concat(this.ship) //return this.asteroids } Game.prototype.checkGameOver = function () { if (this.lives <= 0) { this.gameOver = true } }; // Game.prototype.addBullets = function () { // var bullet = new Asteroids.Bullet({ pos: this.randomPosition(), game: this, vel: this.ship.vel }); // return bullet; // }; })(); // Asteriods = { Game: function() {} } // Asteriods = { Game: function() {}, Bullet: function () {} }
de1595a274a8c1f0958743d3d2c8ba0f61a5bd48
[ "JavaScript", "Markdown" ]
6
JavaScript
pancham348/Asteroids
1cb000de92460f9e55db4ba41655c08fa94f9c76
ad976a5c18d2b5addc211db00b3a853aeec521bf
refs/heads/master
<repo_name>Rimer79/homework1<file_sep>/profunk.js // JavaScript File var finish ; finihs = myFun('abc','ert','rty', 'bar' ,function(str){ return str.toUpperCase(); }); console.log (finihs); function myFun(...args) { var posl = arguments.length-1, fan = arguments[posl], result = []; for (var i=0; i<posl ;i++){ result[i]= fan (args[i]); } return result; }<file_sep>/polindrom.js var fraza = prompt("напишите любую фразу , \n мы проверим ее на полиндром."); // приводим к нижнему регистру fraza = fraza.toLowerCase(); // alert(fraza); fraza = fraza.split(''); //alert(fraza); for (var i=0 ; i<fraza.length ; i++) { if ( fraza[i]===' '){ fraza.splice(i,1); } } alert ('фраза бeз пробелов' +fraza); function sravnenie( fraza) { var palindrom = true; var bukaff = fraza.length ; for (var i = 0 ; i<bukaff/2 ; i++){ if (fraza[i]!== fraza[bukaff-1-i]){ palindrom = false; break ; } } return palindrom ; } var result = sravnenie(fraza); if (result) { alert('фраза полиндром'); } else { alert ('Фраза не полиндром'); }
f075ac9932f11e3042d651f11f4f72b57460a829
[ "JavaScript" ]
2
JavaScript
Rimer79/homework1
38db7ba8b1d4443e30ca6ce40c5d709575be83ab
d8b5a568b0d601605975fe0eb89d7946edf75c95
refs/heads/master
<file_sep><?php session_start(); if(empty($_POST['hospede'])){ header("Location: ../index.php"); } //puxando o arquivo classe reservas require_once 'reservas.class.php'; //estanciando o obj reservas $reserva = new Reservas(); //pegando os valores indo do ajax por post $dados["hospede"] = $_POST['hospede']; $dados["checkin"] = $_POST['checkin']; $dados["checkout"] = $_POST['checkout']; $dados["apto"] = $_POST['apto']; $dados['id_funcionario'] = $_SESSION['idFunc']; //chamando o metodo para cadastrar reserva $retorno = $reserva->addReserva($dados); //devolvendo resposta para o ajax echo json_encode($retorno);<file_sep><?php if(empty($_GET['cpf'])){ header("Location: ../index.php"); } //puxando o arquivo classe hospede require_once 'hospede.class.php'; //estanciando o obj hospede $hospede = new Hospede(); //pegando o CPF do ajax $CPF = intval($_GET['cpf']); //verificando se o CPF está cadastrado no banco de dados if($hospede->existeCPF($CPF)){ $retorno['existe'] = true; $retorno['mensagem'] = "CPF esta cadastrado no banco de dados!"; echo json_encode($retorno); }else{ $retorno['existe'] = false; $retorno['mensagem'] = "CPF nao esta cadastrado no banco de dados!"; echo json_encode($retorno); } <file_sep><?php if(empty($_POST['emailFunc'])){ header("Location: ../index.php"); } require_once 'funcionario.class.php'; $funcionario = new Funcionario(); $dados['nome'] = $_POST['nomeFunc']; $dados['email'] = $_POST['emailFunc']; $dados['senha'] = $_POST['senhaFunc']; $retorno = $funcionario->inserirFuncionario($dados); echo json_encode($retorno); <file_sep><?php session_start(); if(!isset($_SESSION['idFunc'])){ header('Location: login-funcionario.php'); } require_once 'header.php'; require_once 'server/reservas.class.php'; $reservas = new Reservas(); ?> <div class="container"> <a href="cadastrar-reserva.php">Nova Reserva</a> <div class="lista-reservas"> <table> <tr> <th>Nº</th> <th>Hóspede</th> <th>Apto</th> <th>Data</th> <th class="lastCol">Check-in</th> <th class="lastCol">Check-out</th> </tr> <?php $listaReservas = $reservas->getReservas(); foreach($listaReservas as $valor): ?> <tr> <td><?php echo $valor['id']; ?></td> <td><a href="detalhes-reserva.php?idReserv=<?php echo $valor['id']; ?>"><?php echo $valor['nome_completo']; ?></a></td> <td><?php echo $valor['numero']; ?></td> <td><?php echo date("d/m/y", strtotime($valor['dataCadastro'])); ?></td> <td class="lastCol"><?php echo date("d/m/y H:m", strtotime($valor['data_entrada'])); ?></td> <td class="lastCol"><?php echo date("d/m/y H:m", strtotime($valor['data_saida'])); ?></td> </tr> <?php endforeach; ?> </table> </div> </div> <?php require_once 'footer.php'; ?><file_sep>const urlHostServer = 'http://localhost/Projeto-Gestao-Hoteleira/'; //selecinando os td da tabela detalhes-hospede const objNomeTd = document.querySelector('#tdNome'); const objCPFTd = document.querySelector('#tdCPF'); const objEmailTd = document.querySelector('#tdEmail'); const objTelefoneTd = document.querySelector('#tdTelefone'); const objCelularTd = document.querySelector('#tdCelular'); //selecionando os input do formulario form_cadastrar_hospede const objfnome = document.querySelector('#fnome_completo'); const objfCPF = document.querySelector('#fCPF'); const objfemail = document.querySelector('#femail'); const objfcelular = document.querySelector('#fcelular'); const objftelefone = document.querySelector('#ftelefone'); const botaoCadastrar = document.querySelector('#botaoCadastrar'); //span para avisar algum erro no formulario form_cadastrar_hospede const spanfCPF = document.querySelector('#spancpf'); const spanfNome = document.querySelector('#spannome'); const spanfEmail = document.querySelector('#spanemail'); const spanfCelular = document.querySelector('#spancelular'); const spanfTelefone = document.querySelector('#spantelefone'); //selecionando os inputs formulario cadastrar funcionario const nomeFuncionario = document.querySelector('#nomeFunc'); const emailFuncionario = document.querySelector('#emailFunc'); const senhaFuncionario = document.querySelector('#senhaFunc'); //selecionando os inpts do formulario de login do funcionario const emailLogin = document.querySelector('#emailLogin'); const senhaLogin = document.querySelector('#senhaLogin'); //selecionando os inputs do formulario cadastrar reserva const titularReserva = document.querySelector('#titular-reserva'); const dataEntrada = document.querySelector('#data-entrada'); const dataSaida = document.querySelector('#data-saida'); const horarioEntrada = document.querySelector('#horario-entrada'); const apartamento = document.querySelector('#apartamento'); //validando input nome no formulario form_cadastrar_hospede function validarNome(){ if(objfnome.value == ''){ objfnome.style.borderColor = '#f00'; objfnome.focus(); botaoCadastrar.disabled = true; spanfNome.innerHTML = ' O campo Nome não pode estar vazio'; }else if(objfnome.value.length < 10){ objfnome.style.borderColor = '#f00'; objfnome.focus(); botaoCadastrar.disabled = true; spanfNome.innerHTML = ' Digite seu Nome completo'; }else{ botaoCadastrar.disabled = false; objfnome.style.borderColor = '#F8F8FF'; spanfNome.innerHTML = ''; } } //testando CPF válido function testaCPF(strCPF){ let Soma; let Resto; Soma = 0; if (strCPF == "00000000000") return false; for (i=1; i<=9; i++) Soma = Soma + parseInt(strCPF.substring(i-1, i)) * (11 - i); Resto = (Soma * 10) % 11; if ((Resto == 10) || (Resto == 11)) Resto = 0; if (Resto != parseInt(strCPF.substring(9, 10)) ) return false; Soma = 0; for (i = 1; i <= 10; i++) Soma = Soma + parseInt(strCPF.substring(i-1, i)) * (12 - i); Resto = (Soma * 10) % 11; if ((Resto == 10) || (Resto == 11)) Resto = 0; if (Resto != parseInt(strCPF.substring(10, 11) ) ) return false; return true; } //validando input CPF no formulario form_cadastrar_hospede function validarCPF(){ //verificando se o CPF já existe no banco de dados function existeCPF(strCPF){ if(window.XMLHttpRequest){ var ajax = new XMLHttpRequest(); }else{ var ajax = new ActiveXObject("Microsoft.XMLHTTP"); } ajax.onreadystatechange = function(){ if(this.readyState == 4 && this.status == 200){ var resposta = JSON.parse(this.response); if(resposta.existe){ spanfCPF.innerHTML = ' '+resposta.mensagem; objfCPF.style.borderColor = '#f00'; objfCPF.focus(); botaoCadastrar.disabled = true; }else{ spanfCPF.innerHTML = ''; botaoCadastrar.disabled = false; objfCPF.style.borderColor = '#F8F8FF'; } } }; ajax.open('GET', 'server/existe-cpf.php?cpf='+strCPF, true); ajax.send(); } //validando CPF if(objfCPF.value == ''){ objfCPF.style.borderColor = '#f00'; objfCPF.focus(); spanfCPF.innerHTML = ' O campo CPF não pode estar vazio'; botaoCadastrar.disabled = true; }else if(!testaCPF(objfCPF.value)){ objfCPF.style.borderColor = '#f00'; objfCPF.focus(); spanfCPF.innerHTML =' CPF inválido'; botaoCadastrar.disabled = true; }else{ existeCPF(objfCPF.value); } } //validando input Email function validarEmail(){ //verificando se e-mail ja está cadastrado no banco function existeEmail(strEmail){ if(window.XMLHttpRequest){ var ajax = new XMLHttpRequest(); }else{ var ajax = new ActiveXObject("Microsoft.XMLHTTP"); } ajax.onreadystatechange = function(){ if(this.readyState == 4 && this.status == 200){ var resposta = JSON.parse(this.response); if(resposta.existe){ spanfEmail.innerHTML = ' '+resposta.mensagem; objfemail.style.borderColor = '#f00'; objfemail.focus(); botaoCadastrar.disabled = true; }else{ spanfEmail.innerHTML = ''; botaoCadastrar.disabled = false; objfemail.style.borderColor = '#F8F8FF'; } } }; ajax.open('GET', 'server/existe-email.php?email='+strEmail, true); ajax.send(); } //validando email if(objfemail.value == ""){ objfemail.style.borderColor = '#f00'; spanfEmail.innerHTML = " O campo E-mail não pode estar vazio!"; botaoCadastrar.disabled = true; }else if(objfemail.value.indexOf('@')==-1 || objfemail.value.indexOf('.')==-1){ objfemail.style.borderColor = '#f00'; objfemail.focus(); spanfEmail.innerHTML = " Preencha campo E-mail corretamente!"; botaoCadastrar.disabled = true; }else{ existeEmail(objfemail.value); } } //validando celular function validarCelular(){ if(objfcelular.value == ''){ objfcelular.style.borderColor = '#f00'; objfcelular.focus(); spanfCelular.innerHTML = ' O campo Celular não pode estar vazio'; botaoCadastrar.disabled = true; }else if(objfcelular.value.length != 11){ objfcelular.style.borderColor = '#f00'; objfcelular.focus(); spanfCelular.innerHTML = ' Preencha o campo celular corretamente com o DDD'; botaoCadastrar.disabled = true; }else{ objfcelular.style.borderColor = '#F8F8FF'; spanfCelular.innerHTML = ''; botaoCadastrar.disabled = false; } } //validando celular function validarTelefone(){ if(objftelefone.value == ''){ objftelefone.style.borderColor = '#f00'; objftelefone.focus(); spanfTelefone.innerHTML = ' O campo Telefone não pode estar vazio'; botaoCadastrar.disabled = true; }else if(objftelefone.value.length != 10){ objftelefone.style.borderColor = '#f00'; objftelefone.focus(); spanfTelefone.innerHTML = ' Preencha o campo Telefone corretamente com o DDD'; botaoCadastrar.disabled = true; }else{ objftelefone.style.borderColor = '#F8F8FF'; spanfTelefone.innerHTML = ''; botaoCadastrar.disabled = false; } } //criando cadastro de hospede function cadastrarHospede(){ const fnome = objfnome.value; const fCPF = objfCPF.value; const femail = objfemail.value; const fcelular = objfcelular.value; const ftelefone = objftelefone.value; if(fnome == '' || fCPF == '' || femail == '' || fcelular == '' || ftelefone == ''){ validarNome(); validarCPF(); validarEmail(); validarCelular(); validarTelefone(); return false; } if(window.XMLHttpRequest){ var ajax = new XMLHttpRequest(); }else{ var ajax = new ActiveXObject("Microsoft.XMLHTTP"); } ajax.open('POST', 'server/cadastrar-hospede-submit.php', true); ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); ajax.onreadystatechange = function(){ if(this.readyState == 4 && this.status == 200){ var resposta = JSON.parse(this.response); if(resposta.deucerto){ alert(resposta.mensagem); window.location.href = urlHostServer+'detalhes-hospede.php?id='+resposta.idHosped; }else{ alert(resposta.mensagem); } } }; ajax.send('nome='+fnome+'&cpf='+fCPF+'&email='+femail+'&telefone='+ftelefone+'&celular='+fcelular); } //Esta função edita as informações do hospede da tabela detalhes do hospede function editarHospede(id){ //pegando os valores hospede na tabela detalhes-hospede const nome = objNomeTd.innerHTML; const CPF = objCPFTd.innerHTML; const email = objEmailTd.innerHTML; const telefone = objTelefoneTd.innerHTML; const celular = objCelularTd.innerHTML; //deixando a tabela detalhes do hospede editavel objNomeTd.innerHTML = '<input class="input-td" type="text" name="nome_completo" value="'+nome+'">'; objCPFTd.innerHTML = '<input class="input-td" type="text" name="CPF" value="'+CPF+'">'; objEmailTd.innerHTML = '<input class="input-td" type="email" name="email" value="'+email+'">'; objTelefoneTd.innerHTML = '<input class="input-td" type="text" name="telefone" value="'+telefone+'">'; objCelularTd.innerHTML = '<input class="input-td" type="text" name="celular" value="'+celular+'">'; //escondendo os botoes editar e excluir da tabela detalhes do hospede document.getElementById('editarHospede').style.display = 'none'; document.getElementById('excluirHospede').style.display = 'none'; //criando o botao salvar na tabela detalhes do hospede const botaoSalvar = document.createElement('button'); botaoSalvar.innerHTML = 'Salvar'; var atributoClass = document.createAttribute("class"); atributoClass.value = "BotaoSalvarEdit"; botaoSalvar .setAttributeNode(atributoClass); var tabela = document.getElementsByClassName('detalhes-hospede')[0]; tabela.insertBefore(botaoSalvar , tabela.childNodes[2]); //criando botao cancelar na tabela detalhes do hospede const botaoCancelar = document.createElement('button'); botaoCancelar.innerHTML = 'Cancel'; var atributoClass = document.createAttribute("class"); atributoClass.value = "BotaoSalvarEdit"; botaoCancelar.setAttributeNode(atributoClass); var tabela = document.getElementsByClassName('detalhes-hospede')[0]; tabela.insertBefore(botaoCancelar, tabela.childNodes[2]); //carregando a pagina após clicar em cancelar edição da tabela detalhes do hospede botaoCancelar.onclick = function(){ location.reload(); } //salvando alterações na tabela detalhes do hospede botaoSalvar.onclick = function(){ const tdValor = document.getElementsByClassName('input-td'); const novoNome = tdValor[0].value; const novoCPF = tdValor[1].value; const novoEmail = tdValor[2].value; const novoTelefone = tdValor[3].value; const novoCelular = tdValor[4].value; const resposta = confirm("Deseja salvar alterações?"); //verificando se o CPF é valido if(!testaCPF(novoCPF)){ alert('CPF inválido'); tdValor[1].style.borderColor = '#F00'; return false; } //verificando se o e-mail é válido if(novoEmail.indexOf('@')==-1 || novoEmail.indexOf('.')==-1){ alert('Email inválido'); tdValor[2].style.borderColor = '#F00'; return false; } if(resposta == true){ if(window.XMLHttpRequest){ var ajax = new XMLHttpRequest(); }else{ var ajax = new ActiveXObject("Microsoft.XMLHTTP"); } ajax.open('POST', 'server/editar-hospede-submit.php', true); ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); ajax.onreadystatechange = function(){ if(this.readyState == 4 && this.status == 200){ var resposta = JSON.parse(this.response); if(resposta.deucerto){ alert(resposta.mensagem); location.reload(); }else{ alert(resposta.mensagem); } } }; ajax.send( 'id='+id+'&nome='+novoNome+ '&cpf='+novoCPF+ '&email='+novoEmail+ '&telefone='+novoTelefone+ '&celular='+novoCelular ); }else{ alert('Alterações cancelada'); location.reload(); } } } //Esta função desativa o hospede para não ser mostrado mais na lista de hospedes function excluirHospede(id){ var resposta = confirm("Deseja excluir este hospede?"); if(resposta == true){ if(window.XMLHttpRequest){ var ajax = new XMLHttpRequest(); }else{ var ajax = new ActiveXObject("Microsoft.XMLHTTP"); } ajax.open('POST', 'server/excluir-hospede-submit.php', true); ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajax.onreadystatechange = function(){ if(this.readyState == 4 && this.status == 200){ var resposta = JSON.parse(this.response); if(resposta.deucerto){ alert(resposta.mensagem); window.location.href = urlHostServer+'lista-hospedes.php'; }else{ alert(resposta.mensagem); } } }; ajax.send('id='+id); }else{ alert('Exclusão cancelada'); } } //Função para cadastrar funcionario function cadastrarFuncionario(){ if(nomeFuncionario.value == '' || nomeFuncionario.value.length < 10){ alert('Digite nome completo!'); return false; } if(emailFuncionario.value == '' || emailFuncionario.value.indexOf('@')==-1 || emailFuncionario.value.indexOf('.')==-1){ alert('Digite o email corretamente!'); return false; } if(senhaFuncionario.value.length < 6){ alert('Senha tem que ter no minimo 6 caractere!'); return false; } if(window.XMLHttpRequest){ var ajax = new XMLHttpRequest(); }else{ var ajax = new ActiveXObject("Microsoft.XMLHTTP"); } ajax.open('POST', 'server/cadastrar-funcionario-submit.php', true); ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); ajax.onreadystatechange = function(){ if(this.readyState == 4 && this.status == 200){ var resposta = JSON.parse(this.response); if(resposta.deucerto){ alert(resposta.mensagem); }else{ alert(resposta.mensagem); } } }; ajax.send( 'nomeFunc='+nomeFuncionario.value+ '&emailFunc='+emailFuncionario.value+ '&senhaFunc='+senhaFuncionario.value ); } //login funcionario function logarFuncionario(){ if(emailLogin.value == ''){ alert('Digite seu email!'); return false; } if(senhaLogin.value == ''){ alert('Digite sua senha!'); return false; } if(window.XMLHttpRequest){ var ajax = new XMLHttpRequest(); }else{ var ajax = new ActiveXObject("Microsoft.XMLHTTP"); } ajax.onreadystatechange = function(){ if(this.readyState == 4 && this.status == 200){ var resposta = JSON.parse(this.response); if(resposta.deucerto){ window.location.href = urlHostServer+'index.php?func='+resposta.idFunc; }else{ alert(resposta.mensagem); } } }; ajax.open('GET', 'server/logar-funcionario.php?emailFunc='+emailLogin.value+ '&senhaFunc='+senhaLogin.value, true); ajax.send(); } //cadastrar reserva function cadastrarReserva(){ let horaEntrada; let horaSaida; switch(horarioEntrada.value){ case 'hora1': horaEntrada = '14:00:00'; horaSaida = '12:00:00'; break; case 'hora2': horaEntrada = '18:00:00'; horaSaida = '16:00:00'; break; default: horaEntrada = ''; horaSaida = ''; } if(titularReserva.value == '' || dataEntrada.value == '' || dataSaida.value == '' || apartamento.value == '' || horaEntrada == '' || horaSaida == ''){ alert("Selecione todos os campos"); return false; } let hospede = titularReserva.value; let checkin = dataEntrada.value + ' ' + horaEntrada; let checkout = dataSaida.value + ' ' + horaSaida; let apto = apartamento.value; if(window.XMLHttpRequest){ var ajax = new XMLHttpRequest(); }else{ var ajax = new ActiveXObject("Microsoft.XMLHTTP"); } ajax.open('POST', 'server/cadastrar-reserva-submit.php', true); ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); ajax.onreadystatechange = function(){ if(this.readyState == 4 && this.status == 200){ var resposta = JSON.parse(this.response); if(resposta.deucerto){ console.log(resposta); window.location.href = urlHostServer+'detalhes-reserva.php?idReserv='+resposta.idReserv; }else{ alert(resposta.mensagem); } } }; ajax.send( 'hospede='+hospede+ '&checkin='+checkin+ '&checkout='+checkout+ '&apto='+apto ); } <file_sep><?php session_start(); if(!isset($_SESSION['idFunc'])){ header('Location: login-funcionario.php'); } require_once 'header.php'; require_once 'server/apartamentos.class.php'; require_once 'server/hospede.class.php'; $hospede = new Hospede(); $listaHospede = $hospede->listarHospedes(); $apartamento = new Apartamentos(); $listaApartamento = $apartamento->getApartamentos(); ?> <div class="container"> <button><a href="javascript:history.back()">Voltar</a></button> <div class="cadastrar-reserva"> <h1>Adicionar reserva</h1> Hospede: <select id="titular-reserva"> <option value="">selecione o hospede titular</option> <?php foreach($listaHospede as $hospede): ?> <option value="<?php echo $hospede['id']; ?>"><?php echo $hospede['nome_completo']; ?></option> <?php endforeach; ?> </select><br><br> Data de entrada:<br> <input type="date" name="data-entrada" id="data-entrada"><br><br> Data de saída:<br> <input type="date" name="data-saida" id="data-saida"><br><br> Horarios:<br> <select id="horario-entrada"> <option value="hora1">check-in 14:00 | check-out 12:00</option> <option value="hora2">check-in 18:00 | check-out 16:00</option> </select><br><br> Apartamento: <select id="apartamento"> <option value="">selecione o apartamento</option> <?php foreach($listaApartamento as $apto): ?> <option value="<?php echo $apto['id']; ?>"><?php echo $apto['numero'].' | '.$apto['camas']; ?></option> <?php endforeach; ?> </select><br><br> <button onclick="cadastrarReserva()">Reservar</button> </div> </div> <?php require_once 'footer.php'; ?> <file_sep># Projeto-Gestao-Hoteleira<file_sep><?php require_once 'conexao.class.php'; class Reservas extends Conexao{ private $hospede; private $checkin; private $checkout; private $apto; private $funcionario; private $dataCadastro; public function addReserva($dados){ $this->hospede = $this->filtraEntrada($dados['hospede']); $this->checkin = $this->filtraEntrada($dados['checkin']); $this->checkout = $this->filtraEntrada($dados['checkout']); $this->apto = $this->filtraEntrada($dados['apto']); $this->funcionario = $dados["id_funcionario"]; $this->dataCadastro = $this->dataAtual(); try{ $sql = "INSERT INTO reservas (id_hospede, data_entrada, data_saida, id_apartamento, id_funcionario, dataCadastro) VALUES (:id_hospede, :data_entrada, :data_saida, :id_apartamento, :id_funcionario, :dataCadastro)"; $sql = $this->pdo->prepare($sql); $sql->bindValue(":id_hospede", $this->hospede); $sql->bindValue(":data_entrada", $this->checkin); $sql->bindValue(":data_saida", $this->checkout); $sql->bindValue(":id_apartamento", $this->apto); $sql->bindValue(":id_funcionario", $this->funcionario); $sql->bindValue(":dataCadastro", $this->dataCadastro); $sql->execute(); if($sql->rowCount() > 0){ $retorno['deucerto'] = true; $retorno['mensagem'] = "Reserva cadastrada com sucesso!"; $retorno['idReserv'] = $this->pdo->lastInsertId(); return $retorno; }else{ $retorno['deucerto'] = false; $retorno['mensagem'] = "Erro! nao cadastrado"; return $retorno; } }catch(PDOException $e){ $retorno['deucerto'] = false; $retorno['mensagem'] = "Erro no servidor"; return $retorno; } } public function getReservas(){ $array = array(); $sql = "SELECT hospedes.id, hospedes.nome_completo, apartamentos.numero, reservas.*, funcionarios.nome FROM hospedes JOIN reservas ON hospedes.id = reservas.id_hospede JOIN apartamentos ON apartamentos.id = reservas.id_apartamento JOIN funcionarios ON funcionarios.id = hospedes.id_funcionario"; $sql = $this->pdo->query($sql); if($sql->rowCount() > 0){ $array = $sql->fetchAll(); } return $array; } public function getReservasDaSemana(){ $array = array(); $sql = "SELECT hospedes.id, hospedes.nome_completo, apartamentos.numero, reservas.*, funcionarios.nome FROM hospedes JOIN reservas ON hospedes.id = reservas.id_hospede JOIN apartamentos ON apartamentos.id = reservas.id_apartamento JOIN funcionarios ON funcionarios.id = hospedes.id_funcionario"; $sql = $this->pdo->query($sql); if($sql->rowCount() > 0){ $array = $sql->fetchAll(); } return $array; } } /* FIM CLASSE Reservas*/<file_sep><?php require_once 'conexao.class.php'; class Funcionario extends Conexao{ private $nome; private $email; private $senha; private $idFuncionario; private $dataCadastro; public function __set($atributo, $valor){ $this->$atributo = $valor; } public function __get($atributo){ return $this->$atributo; } public function inserirFuncionario($dados){ $this->nome = $this->filtraEntrada($dados['nome']); $this->email = $this->filtraEntrada($dados['email']); $this->senha = $this->filtraEntrada(sha1($dados['senha'])); $this->dataCadastro = $this->dataAtual(); try{ $sql = "INSERT INTO funcionarios (nome, email, senha, dataCadastro) values (:nome, :email, :senha, :dataCadastro)"; $sql = $this->pdo->prepare($sql); $sql->bindValue(":nome", $this->nome); $sql->bindValue(":email", $this->email); $sql->bindValue(":senha", $this->senha); $sql->bindValue(":dataCadastro", $this->dataCadastro); $sql->execute(); if($sql->rowCount() > 0){ $retorno['deucerto'] = true; $retorno['mensagem'] = "funcionário cadastrado com sucesso!"; return $retorno; }else{ $retorno['deucerto'] = false; $retorno['mensagem'] = "Erro! nao cadastrado"; return $retorno; } }catch(PDOException $e){ $retorno['deucerto'] = false; $retorno['mensagem'] = "Erro no servidor"; return $retorno; } } public function listarFuncionarios(){ try{ $sql = "SELECT * FROM funcionarios"; $sql = $this->pdo->prepare($sql); $sql->execute(); return $sql->fetchAll(); }catch(PDOException $e){ return "Erro! ".$e->getMessage(); } } public function selecionarFuncionario($dados){ $this->idFuncionario = $this->filtraEntrada($dados['id']); try{ $sql = "SELECT * FROM funcionarios WHERE id = :id"; $sql = $this->pdo->prepare($sql); $sql->bindValue(":id", $this->idFuncionario); $sql->execute(); return $sql->fetch(); }catch(PDOException $e){ return "Erro! ".$e->getMessage(); } } public function atualizarFuncionario($dados){ $this->idFuncionario = $this->filtraEntrada($dados['id']); $this->nome = $this->filtraEntrada($dados['nome']); $this->email = $this->filtraEntrada($dados['email']); $this->senha = $this->filtraEntrada(sha1($dados['senha'])); $this->dataCadastro = $this->dataAtual(); try{ $sql = "UPDATE funcionarios SET nome = :nome, email = :email, senha = :senha WHERE id = :id"; $sql = $this->pdo->prepare($sql); $sql->bindValue(":id", $this->idFuncionario); $sql->bindValue(":nome", $this->nome); $sql->bindValue(":email", $this->email); $sql->bindValue(":senha", $this->senha); $sql->execute(); if($sql->rowCount() > 0){ $retorno['deucerto'] = true; $retorno['mensagem'] = "funcionário editado com sucesso!"; return $retorno; }else{ $retorno['deucerto'] = false; $retorno['mensagem'] = "Não alterado!"; return $retorno; } }catch(PDOException $e){ $retorno['deucerto'] = false; $retorno['mensagem'] = "Erro no servidor!"; return $retorno; } } public function deletarFuncionario($dados){ $this->idFuncionario = $dados['id']; try{ $sql = "DELETE FROM funcionarios WHERE id = :id"; $sql = $this->pdo->prepare($sql); $sql->bindValue(":id", $this->idFuncionario); $sql->execute(); if($sql->rowCount() > 0){ $retorno['deucerto'] = true; $retorno['mensagem'] = "funcionário excluído com sucesso!"; return $retorno; }else{ $retorno['deucerto'] = false; $retorno['mensagem'] = "Não excluído"; return $retorno; } }catch(PDOException $e){ $retorno['deucerto'] = false; $retorno['mensagem'] = "Erro no servidor"; return $retorno; } } public function logarFuncionario($dados){ $this->email = $dados['email']; $this->senha = sha1($dados['senha']); try{ $sql = "SELECT * FROM funcionarios WHERE email = :email and senha = :senha"; $sql = $this->pdo->prepare($sql); $sql->bindValue(":email", $this->email); $sql->bindValue(":senha", $this->senha); $sql->execute(); if($sql->rowCount() > 0){ $sql = $sql->fetch(); $retorno['deucerto'] = true; $retorno['idFunc'] = $sql['id']; session_start(); $_SESSION['idFunc'] = $sql['id']; $_SESSION['nomeFunc'] = $sql['nome']; $_SESSION['emailFunc'] = $sql['email']; return $retorno; }else{ $retorno['deucerto'] = false; $retorno['mensagem'] = "E-mail ou senha inválidos!"; return $retorno; } }catch(PDOException $e){ $retorno['deucerto'] = false; $retorno['mensagem'] = "Erro no servidor!"; return $retorno; } } }/*FIM CLASSE Funcionario */<file_sep><?php abstract class Conexao{ private $dbname; private $host; private $dbuser; private $dbpass; protected $pdo; private $status; public function __construct(){ $this->dbname = 'gestao-hoteleira'; $this->host = 'localhost'; $this->dbuser = 'root'; $this->dbpass = ''; try{ $this->pdo = new PDO("mysql:host=".$this->host.";dbname=".$this->dbname, $this->dbuser, $this->dbpass); $this->setStatus("Conectado!"); }catch(PDOException $e){ $this->setStatus("Não conectado!"); } } /* * MÉTODO PARA PARA RETORNAR O STATUS DA CONEXAO COM BANCO DE DADOS * @return RETORNA O STATUS DA CONEXAO * @author WILLIAN <<EMAIL>> */ public function getStatus(){ return $this->status; } /* * MÉTODO PARA PARA SETAR O STATUS DA CONEXAO COM BANCO DE DADOS * @param RECEBE O STATUS * @author WILLIAN <<EMAIL>> */ public function setStatus($s){ $this->status = $s; } /* * MÉTODO PARA PEGAR A DATA E HORA ATUAL * @return DATA E HORA ATUAL EM FORMATO PARA BANCO DE DADOS * @author WILLIAN <<EMAIL>> */ protected function dataAtual(){ date_default_timezone_set('America/Sao_Paulo'); return date("Y-m-d H:i:s"); } /* * MÉTODO PARA PROTEJER O BANCO DE DADOS DE SQL INJECTION * @param DADO A FILTRAR * @return DADO FILTRADO * @author WILLIAN <<EMAIL>> */ protected function filtraEntrada($campo){ // remove espaços no início e no final $campo = trim($campo); // remove tags html $campo = strip_tags($campo); // adiciona caractere de escape nas aspas e apostófros $campo = addslashes($campo); return $campo; } }/*FIM CLASSE Conexao*/ <file_sep>-- phpMyAdmin SQL Dump -- version 4.7.9 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1:3306 -- Generation Time: 13-Maio-2019 às 06:17 -- Versão do servidor: 5.7.21 -- PHP Version: 7.2.4 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: `gestao-hoteleira` -- -- -------------------------------------------------------- -- -- Estrutura da tabela `funcionarios` -- DROP TABLE IF EXISTS `funcionarios`; CREATE TABLE IF NOT EXISTS `funcionarios` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nome` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `senha` varchar(64) NOT NULL, `dataCadastro` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; -- -- Extraindo dados da tabela `funcionarios` -- INSERT INTO `funcionarios` (`id`, `nome`, `email`, `senha`, `dataCadastro`) VALUES (1, 'Willian', '<EMAIL>', '<PASSWORD>8d09ca3762af<PASSWORD>0<PASSWORD>6<PASSWORD>', '2019-05-10 01:58:02'), (6, 'Felipe', '<EMAIL>', '40bd001563085fc35165329ea1ff5c5ecbdbbeef', '2019-05-12 02:33:42'); -- -------------------------------------------------------- -- -- Estrutura da tabela `hospedes` -- DROP TABLE IF EXISTS `hospedes`; CREATE TABLE IF NOT EXISTS `hospedes` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nome_completo` varchar(255) NOT NULL, `CPF` varchar(11) NOT NULL, `email` varchar(255) NOT NULL, `celular` varchar(11) NOT NULL, `telefone` varchar(10) DEFAULT NULL, `status` tinyint(11) DEFAULT '1', `dataCadastro` datetime DEFAULT NULL, `autor` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`), UNIQUE KEY `CPF` (`CPF`), KEY `CPF_2` (`CPF`), KEY `autor` (`autor`) ) ENGINE=MyISAM AUTO_INCREMENT=39 DEFAULT CHARSET=utf8; -- -- Extraindo dados da tabela `hospedes` -- INSERT INTO `hospedes` (`id`, `nome_completo`, `CPF`, `email`, `celular`, `telefone`, `status`, `dataCadastro`, `autor`) VALUES (2, '<NAME> ', '14536585985', '<EMAIL>', '12997865656', '1238833040', 0, NULL, '1'), (3, 'Rebeca Lorraine ', '32145698721', '<EMAIL>', '12998785667', '1238833040', 0, NULL, '1'), (4, '<NAME>', '93158942437', '<EMAIL>', '12345678912', '1234567891', 1, NULL, '1'), (5, '<NAME>', '92780017244', '<EMAIL>', '12788523655', '38834030', 1, NULL, '6'), (6, '<NAME>', '81220936049', '<EMAIL>', '12345678910', '1238833040', 1, NULL, '6'), (7, '<NAME>', '12345678910', '<EMAIL>', '11996528999', '1238833040', 1, NULL, '6'), (8, '<NAME>', '35715945652', '<EMAIL>', '13985661478', '1238833040', 1, NULL, '6'), (9, '<NAME> ', '74598256587', '<EMAIL>', '15996417887', '1238833040', 1, NULL, '1'), (10, '<NAME>', '12536578952', '<EMAIL>', '15996417887', '1238833040', 1, NULL, '1'), (11, '<NAME>', '8597455265', '<EMAIL>', '15996417887', '1238833040', 1, NULL, '1'), (12, '<NAME> ', '12332145625', '<EMAIL>', '12345678910', '1238833040', 1, NULL, '6'), (13, '<NAME>', '26702344880', '<EMAIL>', '123', '123', 1, NULL, '6'), (15, '<NAME> ', '47789952256', '<EMAIL>', '12996417887', '1238833040', 1, NULL, '6'), (16, '<NAME> ', '15975382545', '<EMAIL>', '12996417887', '1238833040', 1, NULL, '6'), (33, '<NAME>', '43593584824', '<EMAIL>', '12996417887', '1238834030', 1, '2019-05-10 01:43:38', '1'), (17, '<NAME> ', '14778963125', '<EMAIL>', '12996417887', '1238833040', 1, NULL, '1'), (18, '<NAME>', '41782556556', '<EMAIL>', '12996417887', '1238833040', 1, NULL, '1'), (19, '<NAME>', '12132345625', '<EMAIL>', '12996417878', '38834030', 0, NULL, '6'), (34, '<NAME>', '62782890166', '<EMAIL>', '12996417878', '1238834030', 1, '2019-05-10 02:58:01', '6'), (35, '<NAME>', '33778177788', '<EMAIL>', '12996417878', '1238834030', 1, '2019-05-10 03:34:51', '1'), (36, '<NAME>', '78548960116', '<EMAIL>', '12996417887', '1238833040', 1, '2019-05-12 03:23:00', '1'), (37, '<NAME>', '20957982526', '<EMAIL>', '12996417878', '1238834030', 1, '2019-05-12 04:13:35', '1'), (38, '<NAME>', '61150678550', '<EMAIL>', '12996417878', '1238839090', 1, '2019-05-12 04:16:32', '6'); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php session_start(); if(!isset($_SESSION['idFunc'])){ header('Location: login-funcionario.php'); } require_once 'server/hospede.class.php'; $hospede = new Hospede(); $listaHospede = $hospede->listarHospedes(); require_once 'header.php'; ?> <div class="container"> <a href="cadastrar-hospede.php">Novo Hóspede</a> <div class="lista-hospedes"> <table> <tr> <th>Nome do Hóspede</th> <th>CPF</th> <th class="lastCol">E-Mail</th> </tr> <?php foreach($listaHospede as $valor): ?> <tr> <td><a href="detalhes-hospede.php?id=<?php echo $valor['id']; ?>"><?php echo $valor['nome_completo']; ?></a></td> <td><?php echo $valor['CPF']; ?></td> <td class="lastCol"><?php echo $valor['email']; ?></td> </tr> <?php endforeach; ?> </table><!--lista-hospedes--> </div><!--tabela-hospedes--> </div><!--container--> <?php require_once 'footer.php'; ?> <file_sep><?php if(empty($_POST['id'])){ header("Location: ../index.php"); } //puxando o arquivo classe hospede require_once 'hospede.class.php'; //estanciando o obj hospede $hospede = new Hospede(); //pegando o id do ajax $id = intval($_POST['id']); //chamando o metodo para excluir $retorno = $hospede->excluirHospede($id); //devolvendo resposta para o ajax echo json_encode($retorno); <file_sep><?php require_once 'conexao.class.php'; class Apartamentos extends Conexao{ public function getApartamentos(){ $array = array(); $sql = "SELECT * FROM apartamentos order by numero"; $sql = $this->pdo->query($sql); if($sql->rowCount() > 0){ $array = $sql->fetchAll(); } return $array; } } ?><file_sep><?php if(empty($_GET['email'])){ header("Location: ../index.php"); } //puxando o arquivo classe hospede require_once 'hospede.class.php'; //estanciando o obj hospede $hospede = new Hospede(); //pegando o email do ajax $email = $_GET['email']; //verificando se o email está cadastrado no banco de dados if($hospede->existeEmail($email)){ $retorno['existe'] = true; $retorno['mensagem'] = "E-mail esta cadastrado no banco de dados!"; echo json_encode($retorno); }else{ $retorno['existe'] = false; $retorno['mensagem'] = "E-mail nao esta cadastrado no banco de dados!"; echo json_encode($retorno); } <file_sep><?php session_start(); if(!isset($_SESSION['idFunc'])){ header('Location: login-funcionario.php'); } require_once 'header.php'; require_once 'calendario.php'; require_once 'server/apartamentos.class.php'; $apartamentos = new Apartamentos(); $listaApartamentos = $apartamentos->getApartamentos(); $data = date("Y-m-d"); $data = new DateTime($data); // Pega a data de hoje $diaN = date( "w", strtotime($data->format('Y-m-d'))); // Dia da semana, começa em 0 com domingo, 1 para segunda... $data->modify('-' . $diaN . ' day'); $diasSemana = []; for($i=0;$i<=7;$i++) { array_push($diasSemana, $data->format('d/m/y')); $data->modify('+1 day'); } ?> <div class="container"> <div class="reservas-calendario"> <table class="calendario"> <tr> <th>APTO</th> <th><p>SEG</p><p class="dias-semana"><?php echo $diasSemana[1]?></p></th> <th><p>TER</p><p class="dias-semana"><?php echo $diasSemana[2]?></p></th> <th><p>QUA</p><p class="dias-semana"><?php echo $diasSemana[3]?></p></th> <th><p>QUI</p><p class="dias-semana"><?php echo $diasSemana[4]?></p></th> <th><p>SEX</p><p class="dias-semana"><?php echo $diasSemana[5]?></p></th> <th><p>SAB</p><p class="dias-semana"><?php echo $diasSemana[6]?></p></th> <th><p>DOM</p><p class="dias-semana"><?php echo $diasSemana[7]?></p></th> </tr> <?php foreach($listaApartamentos as $value): ?> <tr> <td class="num-apto"><?php echo $value['numero']; ?></td> <td></td> <td></td> <td></td> <td><div class="item-reserva">Willian Sales</div></td> <td></td> <td></td> <td></td> </tr> <?php endforeach; ?> </table> </div> </div> <?php require_once 'footer.php'; ?><file_sep>-- phpMyAdmin SQL Dump -- version 4.7.9 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1:3306 -- Generation Time: 03-Maio-2019 às 08:15 -- Versão do servidor: 5.7.21 -- PHP Version: 7.2.4 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: `gestao-hoteleira` -- -- -------------------------------------------------------- -- -- Estrutura da tabela `hospedes` -- DROP TABLE IF EXISTS `hospedes`; CREATE TABLE IF NOT EXISTS `hospedes` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nome_completo` varchar(255) NOT NULL, `CPF` varchar(11) NOT NULL, `email` varchar(255) NOT NULL, `celular` varchar(11) NOT NULL, `telefone` varchar(10) DEFAULT NULL, `status` tinyint(11) DEFAULT '1', PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`), UNIQUE KEY `CPF` (`CPF`) ) ENGINE=MyISAM AUTO_INCREMENT=18 DEFAULT CHARSET=utf8; -- -- Extraindo dados da tabela `hospedes` -- INSERT INTO `hospedes` (`id`, `nome_completo`, `CPF`, `email`, `celular`, `telefone`, `status`) VALUES (1, '<NAME> ', '43593584824', 'williansalesgab<EMAIL>', '12996417887', '1238833040', 0), (2, '<NAME> ', '14536585985', '<EMAIL>', '12997865656', '1238833040', 1), (3, '<NAME> ', '71782893956', '<EMAIL>', '12998785667', NULL, 1), (4, '<NAME>', '45612378925', '<EMAIL>', '12996568554', NULL, 1), (5, '<NAME>', '12345678985', '<EMAIL>', '12788523655', NULL, 1), (6, '<NAME> ', '78958265417', '<EMAIL>', '12345678910', '1238833040', 1), (7, '<NAME>', '15935745612', '<EMAIL>', '11996528999', '1238833040', 1), (8, '<NAME>', '35715945652', '<EMAIL>', '13985661478', '1238833040', 1), (9, '<NAME> ', '74598256587', '<EMAIL>', '15996417887', '1238833040', 1), (10, '<NAME>', '12536578952', '<EMAIL>', '15996417887', '1238833040', 1), (11, '<NAME>', '8597455265', '<EMAIL>', '15996417887', '1238833040', 1), (12, '<NAME> ', '12332145625', '<EMAIL>', '12345678910', '1238833040', 1), (13, '<NAME> ', '75315985225', '<EMAIL>', '123', '123', 1), (14, '<NAME> ', '14743595256', '<EMAIL>', '12996417887', '1238833040', 1), (15, '<NAME> ', '47789952256', '<EMAIL>', '12996417887', '1238833040', 1), (16, '<NAME> ', '15975382545', '<EMAIL>', '12996417887', '1238833040', 1), (17, '<NAME> ', '14778963125', '<EMAIL>', '12996417887', '1238833040', 1); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php require_once 'header.php'; ?> <div class="container"> <div class="loguin-funcionario"> Email:<br> <input type="email" name="email" id="emailLogin"/><br><br> Senha:<br> <input type="<PASSWORD>" name="senha" id="senhaLogin"/><br><br> <button id="botaoLogin" onclick="logarFuncionario()">Cadastrar</button> </div> </div> <?php require_once 'footer.php'; ?><file_sep><?php session_start(); if(empty($_POST['email'])){ header("Location: ../index.php"); } //puxando o arquivo classe hospede require_once 'hospede.class.php'; //estanciando o obj hospede $hospede = new Hospede(); //pegando os valores do ajax $dados["novoNome"] = $_POST['nome']; $dados["novoCPF"] = $_POST['cpf']; $dados["novoEmail"] = $_POST['email']; $dados["novoTelefone"] = $_POST['telefone']; $dados["novoCelular"] = $_POST['celular']; $dados['id_funcionario'] = $_SESSION['idFunc']; //chamando o metoto para alteração $retorno = $hospede->cadastrarHospede($dados); //devolvendo resposta para o ajax echo json_encode($retorno); <file_sep><?php require_once 'conexao.class.php'; /* * CLASSE PARA HOSPEDES * ESTA CLASSE CRIA, LÊ, ATUALIZA E DELETA HOSPEDES * @package GESTÃO HOTELEIRA * @author WILLIAN <<EMAIL>> */ class Hospede extends Conexao{ /* * MÉTODO CONSTRUTOR PARA CONECTAR COM O BANCO DE DADOS *@param RECEBE A VARIAVEL $PDO VINDO DO ARQUIVO CONEXAO.PHP * @author WILLIAN <<EMAIL>> */ /* * MÉTODO PARA CADASTRAR HOSPEDES NO BANCO DE DADOS * @param DADOS DO HOSPEDE A SER CADASTRADO * @return ARRAY BOOLEAN E MENSAGEM DE STATUS * @author WILLIAN <<EMAIL>> */ public function cadastrarHospede($dados){ //aplicando segurança nas entradas $nome_completo = $this->filtraEntrada($dados["novoNome"]); $CPF = $this->filtraEntrada($dados["novoCPF"]); $email = $this->filtraEntrada($dados["novoEmail"]); $celular = $this->filtraEntrada($dados["novoCelular"]); $telefone = $this->filtraEntrada($dados["novoTelefone"]); $dataCadastro = $this->dataAtual(); $funcionario = $dados["id_funcionario"]; //verificando se alguns dos campos estão vazios if($nome_completo == '' or $CPF == '' or $email == '' or $celular == '' or $telefone == ''){ $retorno['deucerto'] = false; $retorno['mensagem'] = "Erro! os campos não podem estar vazio!"; return $retorno; } //verificando se o email já esta cadastrado if($this->existeEmail($email)){ $retorno['deucerto'] = false; $retorno['mensagem'] = "Erro! E-mail já esta em uso em outro registro!"; return $retorno; } //verificando se o cpf ja esta cadastrado if($this->existeCPF($CPF)){ $retorno['deucerto'] = false; $retorno['mensagem'] = "Erro! CPF já está em uso em outro registro!"; return $retorno; } try{ $sql = "INSERT INTO hospedes (nome_completo, CPF, email, celular, telefone, dataCadastro, id_funcionario) VALUES (:nome_completo, :CPF, :email, :celular, :telefone, :dataCadastro, :funcionario)"; $sql = $this->pdo->prepare($sql); $sql->bindValue(":nome_completo", $nome_completo); $sql->bindValue(":CPF", $CPF); $sql->bindValue(":email", $email); $sql->bindValue(":celular", $celular); $sql->bindValue(":telefone", $telefone); $sql->bindValue(":dataCadastro", $dataCadastro); $sql->bindValue(":funcionario", $funcionario); $sql->execute(); if($sql->rowCount() > 0){ $retorno['deucerto'] = true; $retorno['mensagem'] = "hóspede cadastrado com sucesso!"; $retorno['idHosped'] = $this->infoHospedePorEmail($email)['id']; return $retorno; }else{ $retorno['deucerto'] = false; $retorno['mensagem'] = "Erro! nao cadastrado"; return $retorno; } }catch(PDOException $e){ $retorno['deucerto'] = false; $retorno['mensagem'] = "Erro no servidor"; return $retorno; } } /* * MÉTODO PARA LISTAR HOSPEDES CADASTRADOS COM STATUS 1(ATIVO) * @return ARRAY COM TODOS OS REGISTROS * @author WILLIAN <<EMAIL>> */ public function listarHospedes(){ $sql = "SELECT * FROM hospedes WHERE status = 1 order by nome_completo"; $sql = $this->pdo->query($sql); if($sql->rowCount() > 0){ return $sql->fetchAll(); }else{ return array(); } } /* * MÉTODO PARA BUSCAR INFORMAÇÕES DE UM HOSPEDE * @param ID IDENTIFICADOR DO HOSPEDE * @return ARRAY COM UM REGISTRO * @author WILLIAN <<EMAIL>> */ public function infoHospede($id){ $sql = "select hospedes.*, funcionarios.nome from hospedes join funcionarios on funcionarios.id = hospedes.id_funcionario where hospedes.id = :id"; $sql = $this->pdo->prepare($sql); $sql->bindValue(":id", $id); $sql->execute(); if($sql->rowCount() > 0){ return $sql->fetch(); }else{ return array(); } } /* * MÉTODO PARA BUSCAR INFORMAÇÕES DE UM HÓSPEDE * @param EMAIL IDENTIFICADOR DO HOSPEDE * @return ARRAY COM UM REGISTRO * @author WILLIAN <<EMAIL>> */ public function infoHospedePorEmail($email){ $sql = "SELECT * FROM hospedes WHERE email = :email"; $sql = $this->pdo->prepare($sql); $sql->bindValue(":email", $email); $sql->execute(); if($sql->rowCount() > 0){ return $sql->fetch(); }else{ return array(); } } /* * MÉTODO PARA UTUALIZAR INFORMAÇÕES DE UM HÓSPEDE * @param DADOS DO HÓSPEDE A SER ATUALIZADOS * @return ARRAY COM UM REGISTRO * @author WILLIAN <<EMAIL>> */ public function editarHospede($dados){ //aplicando segurança nas entradas $id = $this->filtraEntrada($dados["id"]); $nome_completo = $this->filtraEntrada($dados["novoNome"]); $CPF = $this->filtraEntrada($dados["novoCPF"]); $email = $this->filtraEntrada($dados["novoEmail"]); $celular = $this->filtraEntrada($dados["novoCelular"]); $telefone = $this->filtraEntrada($dados["novoTelefone"]); //verificando se alguns dos campos estão vazios if($nome_completo == '' or $CPF == '' or $email == '' or $celular == '' or $telefone == ''){ $retorno['deucerto'] = false; $retorno['mensagem'] = "Erro! os campos não podem estar vazio!"; return $retorno; } //verificando se o email já esta cadastrado if($this->existeEmail($email, $id)){ $retorno['deucerto'] = false; $retorno['mensagem'] = "Erro! E-mail já está em uso em outro registro!"; return $retorno; } //verificando se o cpf ja esta cadastrado if($this->existeCPF($CPF, $id)){ $retorno['deucerto'] = false; $retorno['mensagem'] = "Erro! CPF já está em uso em outro registro!"; return $retorno; } try{ $sql = "UPDATE hospedes SET nome_completo = :nome_completo, CPF = :CPF, email = :email, celular = :celular, telefone = :telefone WHERE id = :id"; $sql = $this->pdo->prepare($sql); $sql->bindValue(":id", $id); $sql->bindValue(":nome_completo", $nome_completo); $sql->bindValue(":CPF", $CPF); $sql->bindValue(":email", $email); $sql->bindValue(":celular", $celular); $sql->bindValue(":telefone", $telefone); $sql->execute(); if($sql->rowCount() > 0){ $retorno['deucerto'] = true; $retorno['mensagem'] = "hóspede editado com sucesso!"; return $retorno; }else{ $retorno['deucerto'] = false; $retorno['mensagem'] = "Não Alterado"; return $retorno; } }catch(PDOException $e){ $retorno['deucerto'] = false; $retorno['mensagem'] = "Erro no servidor"; return $retorno; } } /* * MÉTODO PARA DESATIVAR O HOSPEDE * @param ID IDENTIFICADOR DO HOSPEDE * @return ARRAY COM BOOLEAN E MENSAGEM * @author WILLIAN <<EMAIL>> */ public function excluirHospede($id){ $id = $this->filtraEntrada($id); $sql = "UPDATE hospedes SET status = '0' WHERE id = :id"; $sql = $this->pdo->prepare($sql); $sql->bindValue(":id", $id); $sql->execute(); if($sql->rowCount() > 0){ $retorno['deucerto'] = true; $retorno['mensagem'] = "Hóspede excluído!"; return $retorno; }else{ $retorno['deucerto'] = false; $retorno['mensagem'] = "Erro no servidor!"; return $retorno; } } /* * MÉTODO PARA VERIFICAR EXISTENCIA DE EMAIL DO HOSPEDE * @param EMAIL E ID IDENTIFICADOR DO HOSPEDE * @return BOOLEAN * @author WILLIAN <<EMAIL>> */ public function existeEmail($email, $id=''){ if($id == ''){ $email = $this->filtraEntrada($email); $sql = "SELECT * FROM hospedes WHERE email = :email"; $sql = $this->pdo->prepare($sql); $sql->bindValue(":email", $email); }else{ $email = $this->filtraEntrada($email); $id = $this->filtraEntrada($id); $sql = "SELECT * FROM hospedes WHERE email = :email and id != :id"; $sql = $this->pdo->prepare($sql); $sql->bindValue(":email", $email); $sql->bindValue(":id", $id); } $sql->execute(); if($sql->rowCount() > 0){ return true; }else{ return false; } } /* * MÉTODO PARA VERIFICAR EXISTENCIA DE CPF DO HOSPEDE * @param CPF E ID IDENTIFICADOR DO HOSPEDE * @return BOOLEAN * @author WILLIAN <<EMAIL>> */ public function existeCPF($CPF, $id=''){ if($id == ''){ $CPF = $this->filtraEntrada($CPF); $sql = "SELECT * FROM hospedes WHERE CPF = :CPF"; $sql = $this->pdo->prepare($sql); $sql->bindValue(":CPF", $CPF); }else{ $CPF = $this->filtraEntrada($CPF); $id = $this->filtraEntrada($id); $sql = "SELECT * FROM hospedes WHERE CPF = :CPF and id != :id"; $sql = $this->pdo->prepare($sql); $sql->bindValue(":CPF", $CPF); $sql->bindValue(":id", $id); } $sql->execute(); if($sql->rowCount() > 0){ return true; }else{ return false; } } }/*FIM DA CLASSE HOSPEDE*/<file_sep><?php if(empty($_GET['emailFunc'])){ header("Location: ../index.php"); } require_once 'funcionario.class.php'; $funcionario = new Funcionario(); // var_dump($funcionario); $dados["email"] = $_GET['emailFunc']; $dados["senha"] = $_GET['senhaFunc']; $retorno = $funcionario->logarFuncionario($dados); echo json_encode($retorno); <file_sep><?php session_start(); if(!isset($_SESSION['idFunc'])){ header('Location: login-funcionario.php'); } require_once 'header.php'; ?> <div class="container"> <button><a href="javascript:history.back()">Voltar</a></button> <div> <h2>Cadastrar Funcionário</h2> Nome Completo:<br> <input type="text" id="nomeFunc" name="nomeFunc" /><span id="spannome"></span> <br><br> E-mail:<br> <input type="email" id="emailFunc" name="emailFunc" /><span id="spanemail"></span> <br><br> Senha:<br> <input type="password" id="senhaFunc" name="senhaFunc" /><span id="spansenha"></span> <br><br> <button id="botaoCadastrarFunc" onclick="cadastrarFuncionario()">Cadastrar</button> </div> </div> <?php require_once 'footer.php'; ?><file_sep><?php session_start(); if(!isset($_SESSION['idFunc'])){ header('Location: login-funcionario.php'); } require_once 'header.php'; ?> <div class="container"> <button><a href="javascript:history.back()">Voltar</a></button> <div class="form_cadastrar_hospede"> <h2>Cadastrar Hóspede</h2> Nome Completo:<br> <input onfocusout="validarNome()" type="text" id="fnome_completo" name="nome_completo" required/><span id="spannome"></span> <br><br> CPF:<br> <input onfocusout="validarCPF()" type="text" id="fCPF" name="CPF" required/><span id="spancpf"></span> <br><br> E-mail:<br> <input onfocusout="validarEmail()" type="email" id="femail" name="email" required/><span id="spanemail"></span> <br><br> Celular:<br> <input onfocusout="validarCelular()" type="tel" id="fcelular" name="celular" required/><span id="spancelular"></span> <br><br> Telefone:<br> <input onfocusout="validarTelefone()" type="tel" id="ftelefone" name="telefone" required/><span id="spantelefone"></span> <br><br> <button id="botaoCadastrar" onclick="cadastrarHospede()">Cadastrar</button> </div> </div> <?php require_once 'footer.php'; ?><file_sep><?php session_start(); if(!isset($_SESSION['idFunc'])){ header('Location: login-funcionario.php'); } require_once 'server/hospede.class.php'; $hospede = new Hospede(); if(isset($_GET['id']) and !empty($_GET['id'])){ $id = $_GET['id']; $info = $hospede->infoHospede($id); }else{ header("Location: lista-hospedes.php"); } require_once 'header.php'; ?> <div class="container"> <button><a href="javascript:history.back()">Voltar</a></button> <div class="detalhes-hospede"> <h2>Detalhes do Hospede</h2> <i id="excluirHospede" onclick="excluirHospede(<?php echo $info['id']; ?>)" class="fas fa-trash-alt"></i> <i id="editarHospede" onclick="editarHospede(<?php echo $info['id']; ?>)" class="fas fa-user-edit"></i> <table id="tabela-info-hospede"> <tr> <th>Nome</th> <td id="tdNome"><?php echo $info['nome_completo']; ?></td> </tr> <tr> <th>CPF</th> <td id="tdCPF"><?php echo $info['CPF']; ?></td> </tr> <tr> <th>Email</th> <td id="tdEmail"><?php echo $info['email']; ?></td> </tr> <tr> <th>Telefone</th> <td id="tdTelefone"><?php echo $info['telefone']; ?></td> </tr> <tr> <th>Celular</th> <td id="tdCelular"><?php echo $info['celular']; ?></td> </tr> <tr> <th>Cadastrado</th> <td id="tdCelular"><?php echo date('d/m/y H:i', strtotime($info['dataCadastro'])).' - '.$info['nome']; ?></td> </tr> </table><!--info-hospede--> </div><!--tabela-detalhes-hospede--> </div><!--container--> <?php require_once 'footer.php'; ?>
c4ea4c13dc4178e0f6a6bc7f681cb60aa08107c9
[ "JavaScript", "SQL", "Markdown", "PHP" ]
24
PHP
willian1996/Projeto-Gestao-Hoteleira
1b11f8bc39480e2b06af2145ae9ce414a4aa94e0
4de518aff71cdc1f93d93e6092fe4bda33b3f768
refs/heads/master
<repo_name>gridface/gfHome<file_sep>/js/home-trans.js $(function(){ (function homeTransition() { var homePageTransition = function() { $('#home-header').removeClass('before'); $('img.logo.powerbi').attr('style', 'top:0;-webkit-transition: top 1.2s ease;transition: top 1.2s ease;') } var setInitialPowerBiTop = function() { var header = $('#home-header'); var headerHeight = $(header).outerHeight(); var content = $('.header-content-wrapper'); var contentHeight = $(content).outerHeight(); var top = 190; if ($(window).outerWidth() < 600 && ($(window).outerHeight() > 1024)) { top = (headerHeight/2)-(contentHeight/2)-30; } else if (($(window).outerWidth() > 992)) { top = (headerHeight/2)-(contentHeight/2)+70; } else if (($(window).outerHeight() > 1024)) { top = (headerHeight/2)-(contentHeight/2)-10; } else if ($(window).outerWidth() < 600) { top = 160; } var logo = $('img.logo.powerbi'); $(logo).attr('style', 'opacity:1;top:'+top+'px;'); } var setHeaderContentMarginTop = function() { var content = $('.header-content-wrapper'); var contentHeight = $(content).outerHeight(); var marginTop = (contentHeight/2)-155; $(content).attr('style', 'margin-top: -'+marginTop+'px;'); } var takeTransOffButton = function() { var button = $('#home-page-email-input-top input[type="submit"]'); $(button).addClass('no-trans'); } setHeaderContentMarginTop(); $(window).resize(function() { setHeaderContentMarginTop(); }); setInitialPowerBiTop(); setTimeout(function(){ homePageTransition(); }, 1500); setTimeout(function(){ takeTransOffButton(); }, 3200); //make user scroll to top on page load //this is so animation starts in correct spot // $(window).on('beforeunload', function() { // $(window).scrollTop(0); //set browser scroll to top to override where user might have been before refresh // }); }()); }); <file_sep>/README.md # gfHome public source code for the original single page site at www.gridfacesolutions.com. Archived.
8562eebbe07056d0c08b273e3c321e0090618638
[ "JavaScript", "Markdown" ]
2
JavaScript
gridface/gfHome
eb9e9045e20e2c2817b3db84c1d6a622affca8d3
67aa02789a90839ce79a6c4a43cb98246a00b2b6
refs/heads/master
<file_sep>define(['jquery'], function () { return { fixZero: function (num, length) { var str = "" + num; var len = str.length; var s = ""; for (var i = length; i-- > len;) { s += "0"; } return s + str; }, formatDate: function (now) { var now = new Date(now * 1000); var year = now.getFullYear(); var month = now.getMonth() + 1; var date = now.getDate(); var hour = now.getHours(); var minute = now.getMinutes(); var second = now.getSeconds(); return year + "/" + this.fixZero(month, 2) + "/" + this.fixZero(date, 2) + "/" + this.fixZero(hour, 2) + ":" + this.fixZero(minute, 2) + ":" + this.fixZero(second, 2); } } });<file_sep># requirejs-config RequireJS是一个JavaScript模块加载器,使用RequireJS加载模块化脚本将提高代码的加载速度和质量。 For any questions, please leave a email to <EMAIL> Thank you :)
c4d6c8fb8dd67c11809dd6c8f23a8aba5e7c641d
[ "JavaScript", "Markdown" ]
2
JavaScript
oOBobbyOo/requirejs-config
a30f799360c7d2e759f777fa2559be2319657036
2bb88ab03fba9745962e3e86bbdf837cd9f4790b
refs/heads/master
<repo_name>Fishermanzi/threads-alura<file_sep>/src/br/com/alura/threads/Lista.java package br.com.alura.threads; public class Lista { private Object[] elementos; private int index; private int size; public Lista(int size) { this.size = size; elementos = new Object[size]; index = 0; } public synchronized void add(Object obj) { elementos[index] = obj; this.index++; Sleep.sleep(10); if (this.index == this.size()) { System.out.println(index + " lista tá cheia, notificando"); this.notify(); } } public int size() { return size; } public Object get(int i) { return elementos[i]; } public void replace(int i, Object obj) { elementos[i] = obj; } } <file_sep>/src/br/com/alura/banco/TarefaAcessarBancoProcedimento.java package br.com.alura.banco; public class TarefaAcessarBancoProcedimento implements Runnable { private GerenciadorDeTransacao tx; private PoolDeConexao pool; public TarefaAcessarBancoProcedimento(PoolDeConexao pool,GerenciadorDeTransacao tx) { this.pool = pool; this.tx = tx; } @Override public void run() { synchronized (tx) { System.out.println("comecando a tx"); tx.begin(); synchronized (pool) { System.out.println("pegando a conexão"); pool.getConnection(); } } } } <file_sep>/src/br/com/alura/threads/TarefaAdicionarElemento.java package br.com.alura.threads; public class TarefaAdicionarElemento implements Runnable { private Lista lista; private int threadNumero; private static int count = 0; public TarefaAdicionarElemento(Lista lista) { count++; this.lista = lista; this.threadNumero = count; } @Override public void run() { for(int i = 0; i < 100;i++) { lista.add(String.format("Thread %1$s - %2$s",threadNumero,i)); } } }
c35ca9f4d76f4a6b7348a6839cf1c581bb6a9432
[ "Java" ]
3
Java
Fishermanzi/threads-alura
1667edc06d137fb5cb00373055db512fba234666
25c9452f3eaef8875c247b6dd5bdc217109ca77e
refs/heads/master
<repo_name>ikawashima41/ConnpassClient-Android<file_sep>/app/src/main/java/com/iichirokawashima/conpassclient/Entity/Events.kt package com.iichirokawashima.conpassclient.Entity data class Events ( val renderedBody: String, val body: String, val coediting: Boolean, val commentsCount: Long, val createdAt: String, val group: Any? = null, val id: String, val likesCount: Long, val private: Boolean, val reactionsCount: Long, val tags: List<Tag>, val title: String, val updatedAt: String, val url: String, val user: User, val pageViewsCount: Any? = null ) data class Tag ( val name: String, val versions: List<Any?> ) data class User ( val description: String, val facebookID: String, val followeesCount: Long, val followersCount: Long, val githubLoginName: String, val id: String, val itemsCount: Long, val linkedinID: String, val location: String, val name: String, val organization: String, val permanentID: Long, val profileImageURL: String, val teamOnly: Boolean, val twitterScreenName: String, val websiteURL: String )<file_sep>/app/src/test/java/com/iichirokawashima/conpassclient/ApiClientBuilderTest.kt package com.iichirokawashima.conpassclient import com.iichirokawashima.conpassclient.API.ApiClientBuilder import com.iichirokawashima.conpassclient.API.ApiClientInterface import com.iichirokawashima.conpassclient.Entity.Events import org.junit.Test import org.junit.Assert.* import retrofit2.Call import retrofit2.Response // https://dev.to/paulodhiambo/kotlin-and-retrofit-network-calls-2353 class ApiClientBuilderTest { @Test fun buildService() { val request = ApiClientBuilder.buildService( ApiClientInterface::class.java).fetchEvents(query = "swift") request.enqueue(object : retrofit2.Callback<List<Events>>{ override fun onResponse(call: Call<List<Events>>, response: Response<List<Events>>) { if (response.isSuccessful){ assertNotNull(response.body()) } } override fun onFailure(call: Call<List<Events>>, t: Throwable) { assertNotNull(null) } }) } }<file_sep>/app/src/main/java/com/iichirokawashima/conpassclient/API/ApiClient.kt package com.iichirokawashima.conpassclient.API import com.iichirokawashima.conpassclient.Entity.Events import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Query interface ApiClientInterface { @GET("api/v2/items?page=1&per_page=20") fun fetchEvents( @Query("query") query: String ): retrofit2.Call<List<Events>> } object ApiClientBuilder { private val baseApiUrl = "https://qiita.com/" private val client = OkHttpClient.Builder().build() private val retrofit = Retrofit.Builder() .baseUrl(baseApiUrl) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build() fun <T> buildService(service: Class<T>): T { return retrofit.create(service) } }<file_sep>/settings.gradle include ':app' rootProject.name = "ConpassClient"
ac598b92a09f2506c58e92a0cd4116200edc86b9
[ "Kotlin", "Gradle" ]
4
Kotlin
ikawashima41/ConnpassClient-Android
9d9d90dee1cb04c1538e1b2c2fbc50df7e944a45
b18bbe74eb8229f9d8d9650e61d9a04660ab653b
refs/heads/master
<file_sep>package com.icc.web.controller; public class CommonController { } <file_sep>package com.icc.web.netty.protobuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import java.util.Random; public class NettyClientHandler extends SimpleChannelInboundHandler<DataInfo.MessageType> { @Override protected void channelRead0(ChannelHandlerContext ctx, DataInfo.MessageType msg) throws Exception { } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { int randomInt = new Random().nextInt(3); System.out.println(randomInt); DataInfo.MessageType messageType = null; if(randomInt == 0) { messageType = DataInfo.MessageType.newBuilder().setDataType(DataInfo.MessageType.DataType.PersonType) .setPerson(DataInfo.Person.newBuilder().setId(1).setName("Perion").setAge("ze").build()) .build(); }else if(randomInt == 1) { messageType = DataInfo.MessageType.newBuilder().setDataType(DataInfo.MessageType.DataType.ChildType) .setChild(DataInfo.Child.newBuilder().setId(1).setName("Child").setAge("ze").build()) .build(); }else { messageType = DataInfo.MessageType.newBuilder().setDataType(DataInfo.MessageType.DataType.StudentType) .setStudent(DataInfo.Student.newBuilder().setId(1).setName("Student").setAge("ze").build()) .build(); } ctx.channel().writeAndFlush(messageType); } } <file_sep>package com.icc.web.thrift; import com.icc.web.thrift.generated.DataService; import com.icc.web.thrift.impl.PersionService; import org.apache.thrift.TProcessorFactory; import org.apache.thrift.protocol.TCompactProtocol; import org.apache.thrift.server.THsHaServer; import org.apache.thrift.server.TServer; import org.apache.thrift.transport.TFastFramedTransport; import org.apache.thrift.transport.TNonblockingServerSocket; import org.apache.thrift.transport.TTransportFactory; public class ThriftServer { public static void main(String[] args) throws Exception{ TNonblockingServerSocket socket = new TNonblockingServerSocket(8899); THsHaServer.Args targ = new THsHaServer.Args(socket).minWorkerThreads(2).maxWorkerThreads(4); DataService.Processor<PersionService> processor = new DataService.Processor<>(new PersionService()); //传送格式(协议) targ.protocolFactory(new TCompactProtocol.Factory()); //传输方式 targ.transportFactory(new TFastFramedTransport.Factory()); targ.processorFactory(new TProcessorFactory(processor)); System.out.println("server start"); TServer server = new THsHaServer(targ); server.serve(); } } <file_sep>package com.icc.web.netty.protobuf; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.protobuf.*; public class ServerInitializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new ProtobufDecoder(DataInfo.MessageType.getDefaultInstance())); pipeline.addLast(new ProtobufEncoder()); // pipeline.addLast(new ProtobufDecoderNano()); // pipeline.addLast(new ProtobufEncoderNano()); pipeline.addLast(new ProtobufVarint32FrameDecoder()); pipeline.addLast(new ProtobufVarint32LengthFieldPrepender()); pipeline.addLast(new NettyServerHandler()); } } <file_sep>package com.icc.web.Nio; import java.nio.IntBuffer; import java.security.SecureRandom; public class Test { public static void main(String[] args) { // IntBuffer ib = IntBuffer.allocate(10); // for (int i = 0;i<10;i++) { // Integer random = new SecureRandom().nextInt(); // ib.put(random); // } // ib.flip(); // System.out.println(ib.position()); // ib.get(); // System.out.println(ib.position()); // ib.limit(); // System.out.println(ib.position()); // ib.get(4); // System.out.println(ib.position()); // ib.asReadOnlyBuffer(); new Thread(new Runnable() { @Override public void run() { System.out.println(".."); } }).start(); } } <file_sep>package com.icc.web.design.decorator; public class ComPonent { public void work() { System.out.println("worka"); } } <file_sep>package com.icc.web.Nio.thread; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class Call { } <file_sep>package com.icc.web.common; import java.util.concurrent.CountDownLatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.icc.abstractClass.ZookeeperLook; public class Order implements Runnable { static CountDownLatch countDownLatch = new CountDownLatch(60); private static OrderCodeGenerator ong = new OrderCodeGenerator(); private Logger logger = LoggerFactory.getLogger(Order.class); private ZookeeperLook lock = new ZkLook(); @Override public void run() { try { countDownLatch.await(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } createOrder(); } private void createOrder() { lock.lock("/dubbo/lock"); logger.info("msg:"+ong.getOrderCode()); lock.unlock("/dubbo/lock"); } public static void main(String[] args) { for (int i = 1; i <= 60; i++) { // 按照线程数迭代实例化线程 new Thread(new Order()).start(); // 创建一个线程,倒计数器减1 countDownLatch.countDown(); } } } <file_sep>package com.icc.web.Nio; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; public class Test2 { public static void main(String[] args) throws Exception { RandomAccessFile file = new RandomAccessFile("input.txt","rw"); System.out.println(); FileChannel channel = file.getChannel(); MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE, 0, 5); map.put(0,(byte)'a'); map.put(1,(byte)'b'); System.out.println((char) map.get(0)); file.close(); } } <file_sep>package com.icc.web.Nio.thread; public class Connection { }<file_sep>package com.icc.web.Nio.thread; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.Queue; import java.util.concurrent.BlockingDeque; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.LinkedBlockingDeque; /** * Created by */ public class Server { //server启动标志 public static boolean running = true; public static int LIMIT = 64 * 1024; //缓存 -> server 数据 private static BlockingDeque<Call> readQeque = new LinkedBlockingDeque<Call>(); //缓存 <- server 数据 private static Queue<Call> writeQeque = new ConcurrentLinkedQueue<Call>(); public static void main(String[] args) throws Exception { Server server = new Server(); server.start(); } public static int readChannel(SocketChannel channel, ByteBuffer buffer) throws Exception{ return buffer.remaining() < LIMIT ? channel.read(buffer) : channelIO(channel , null , buffer); } public static int writeChannel(SocketChannel channel, ByteBuffer buffer) throws Exception{ return buffer.remaining() < LIMIT ? channel.read(buffer) : channelIO(null , channel , buffer); } private static int channelIO(SocketChannel read , SocketChannel write, ByteBuffer buffer) throws Exception{ int remining = buffer.remaining(); int ret = 0; while (buffer.remaining() > 0) { int size = Math.min(buffer.remaining() , LIMIT); buffer.limit(buffer.position() + size); ret = read == null ? write.write(buffer) : read.read(buffer); } return (remining - buffer.remaining() ) > 0 ? (remining - buffer.remaining() ) : ret; } private void start() throws Exception { Listener listener = new Listener(15000); } }<file_sep>package com.icc.web.Nio; import io.netty.util.CharsetUtil; import java.nio.charset.Charset; import java.util.Map; import java.util.Set; public class Test4 { public static void main(String[] args) { Set<Map.Entry<String, Charset>> entries = Charset.availableCharsets().entrySet(); for (Map.Entry<String, Charset> map:entries) { System.out.println("key: " + map.getKey() + ", value: "+ map.getValue()); } } } <file_sep>spring.profiles.active=pro server.context-path= server.timeout=30 spring.dubbo.application.id=icc-application-provider spring.dubbo.application.name=icc-application-provider spring.dubbo.protocol.id=dubbo spring.dubbo.protocol.name=dubbo spring.dubbo.protocol.port=2080 spring.dubbo.registry.id=icc-application-provider-registry spring.dubbo.registry.address=zookeeper://192.168.0.103:2181 spring.dubbo.application.registries.timeout=10000 spring.dubbo.application.registries.session=100000 spring.dubbo.scan=com.icc.application.service kafka.consumer.zookeeper.connect=192.168.0.103:2181 kafka.consumer.servers=192.168.0.103:9092 kafka.consumer.enable.auto.commit=true kafka.consumer.session.timeout=6000 kafka.consumer.auto.commit.interval=100 kafka.consumer.auto.offset.reset=latest kafka.consumer.topic=test kafka.consumer.group.id=test-consumer-group kafka.consumer.concurrency=10 kafka.producer.servers=192.168.0.103:9092 kafka.producer.retries=0 kafka.producer.batch.size=4096 kafka.producer.linger=1 kafka.producer.buffer.memory=40960 <file_sep>package com.icc.web.netty.gprc.protobuf; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.stub.StreamObserver; import java.util.Iterator; import java.util.concurrent.TimeUnit; public class GrpcClient { public static void main(String[] args) throws Exception{ ManagedChannel channel = ManagedChannelBuilder. forAddress("localhost",8899).usePlaintext().build(); /*PersonServiceGrpc.PersonServiceBlockingStub stub = PersonServiceGrpc.newBlockingStub(channel); ResponseHeader response = stub.find(RequestHeader.newBuilder().setId(31).build()); System.out.println("client message:" + response.getId()); channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);*/ System.out.println("--------------------------------"); /*PersonServiceGrpc.PersonServiceBlockingStub stubResponse = PersonServiceGrpc.newBlockingStub(channel); Iterator<ResponseHeader> i = stubResponse.findResponseStream(RequestHeader.newBuilder().setId(41).build()); while (i.hasNext()){ System.out.println(i.next()); } channel.shutdown().awaitTermination(5,TimeUnit.SECONDS);*/ /* System.out.println("--------------------------------"); //服务端返回数据监听 StreamObserver<ResponseHeaderList> observer = new StreamObserver<ResponseHeaderList>() { @Override public void onNext(ResponseHeaderList value) { for (ResponseHeader o:value.getResponseList()) { System.out.println("id:" + o.getId()); } } @Override public void onError(Throwable throwable) { } @Override public void onCompleted() { System.out.println("Completed"); } }; //客户端发送数据 PersonServiceGrpc.PersonServiceStub stub = PersonServiceGrpc.newStub(channel); StreamObserver<RequestHeader> stream = stub.findRequestStream(observer); stream.onNext(RequestHeader.newBuilder().setId(101).build()); stream.onNext(RequestHeader.newBuilder().setId(102).build()); stream.onNext(RequestHeader.newBuilder().setId(103).build()); stream.onNext(RequestHeader.newBuilder().setId(104).build()); stream.onCompleted(); Thread.sleep(50000); channel.shutdown().awaitTermination(5,TimeUnit.SECONDS);*/ System.out.println("--------------------------------"); StreamObserver<ResponseHeader> observer = new StreamObserver<ResponseHeader>() { @Override public void onNext(ResponseHeader value) { System.out.println("id:" + value.getId()); } @Override public void onError(Throwable throwable) { } @Override public void onCompleted() { System.out.println("Completed"); } }; PersonServiceGrpc.PersonServiceStub stub = PersonServiceGrpc.newStub(channel); StreamObserver<RequestHeader> RR = stub.findReqResStream(observer); for(int i = 0;i<10;i++){ RR.onNext(RequestHeader.newBuilder().setId(20001).build()); Thread.sleep(1000); } } } <file_sep>spring.profiles.active=pro spring.dubbo.application.id=icc-web-consumer spring.dubbo.application.name=icc-web-consumer spring.dubbo.protocol.id=dubbo spring.dubbo.protocol.name=dubbo spring.dubbo.protocol.port=3080 spring.dubbo.registry.id = icc-web-consumer-registry spring.dubbo.registry.address=zookeeper://192.168.0.105:2181 spring.dubbo.application.registries.timeout=10000 spring.dubbo.application.registries.session=100000 spring.dubbo.scan=com.icc.web.controller kafka.consumer.zookeeper.connect=127.0.0.1:2181 kafka.consumer.servers=127.0.0.1:9093 kafka.consumer.enable.auto.commit=true kafka.consumer.session.timeout=6000 kafka.consumer.auto.commit.interval=100 kafka.consumer.auto.offset.reset=latest kafka.consumer.topic=test-0 kafka.consumer.group.id=test-consumer-group kafka.consumer.concurrency=10 kafka.producer.servers=127.0.0.1:9093 kafka.producer.retries=0 kafka.producer.batch.size=4096 kafka.producer.linger=1 kafka.producer.buffer.memory=40960 <file_sep>package com.icc.web.netty.protobuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; public class NettyServerHandler extends SimpleChannelInboundHandler<DataInfo.MessageType> { @Override protected void channelRead0(ChannelHandlerContext ctx, DataInfo.MessageType msg) throws Exception { System.out.println(msg.toString()); } } <file_sep>package com.icc.web.Nio.thread; //向客户端回写数据 public class Responder extends Thread { } <file_sep>package com.icc.web.common; import java.io.DataInput; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStream; public class Test { public static void main(String[] args) throws Exception{ DataInputStream stream = new DataInputStream(new FileInputStream("")); stream.readDouble(); } } <file_sep>package com.icc.web.Nio; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.channels.*; import java.util.Iterator; import java.util.Set; public class SelectorTest { public static void main(String[] args) throws Exception { int[] ports = new int[5]; ports[0] = 5000; ports[1] = 5001; ports[2] = 5002; ports[3] = 5003; ports[4] = 5004; Selector selector = Selector.open(); ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); ServerSocket socket = serverSocketChannel.socket(); socket.bind(new InetSocketAddress(5000)); System.out.println("监听端口: " + 5000); System.out.println("ipp: " + serverSocketChannel.hashCode()); while (true) { int numbers = selector.select(); System.out.println("numbers: " + numbers); System.out.println("keys: " + selector.keys().size()); System.out.println("skeys: " + selector.selectedKeys().size()); Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = selectionKeys.iterator(); while (iterator.hasNext()) { SelectionKey next = iterator.next(); for (SelectionKey k:selector.keys()) { System.out.println("ip: " + k.channel().hashCode()); } if(next.isAcceptable()){ ServerSocketChannel acceptChannel = (ServerSocketChannel) next.channel(); SocketChannel accept = acceptChannel.accept(); accept.configureBlocking(false); accept.register(selector,SelectionKey.OP_READ); iterator.remove(); System.out.println("新建连接 :" + acceptChannel); System.out.println("keys: " + selector.keys().size()); System.out.println("skeys: " + selector.selectedKeys().size()); }else if(next.isReadable()) { SocketChannel channel = (SocketChannel) next.channel(); int byteRead = 0; while (true) { ByteBuffer byteBuffer = ByteBuffer.allocate(512); byteBuffer.clear(); int reads = channel.read(byteBuffer); if(reads <= 0){ break; } byteBuffer.flip(); channel.write(byteBuffer); System.out.println(); byteRead += reads; } System.out.println("byteRead: " + byteRead); iterator.remove(); } } } } }
f387e73ba9d75c97f42b857c71bdd30f894d4aac
[ "Java", "INI" ]
19
Java
18511897960/icc
bf82a67e1645dfcfef021976635b8c67df34fabb
ba97ab95d23acf1e3a5400a776432529e0b52a81
refs/heads/master
<file_sep>/******************************************************************************* * gpiodemo.c * * A very simple demo of using the GPIO sysfs interface under Linux by using * gpiolib library from Technologic Systems. This can be applied generically to * any computer utilizing the GPIO sysfs interface. This specific code block was * written on a TS-7970, where gpio_pin #59 is connected to a breadboard LED. One * could also use `gcc -D CTL gpiolib.c -o gpioctl` or `make` to bypass the need * for this file and use ./gpioctl instead for scripting or use from the shell * (see gpioctl --help). * * Functions provided by gpiolib: * - int gpio_export(int gpio); * - int gpio_direction(int gpio, int dir); * - void gpio_unexport(int gpio); * - int gpio_read(int gpio); * - int gpio_write(int gpio, int val); * - int gpio_setedge(int gpio, int rising, int falling); * - int gpio_select(int gpio); * - int gpio_getfd(int gpio); * * Sources: * - https://github.com/embeddedarm/ts4900-utils/blob/master/src/gpiolib.h * - https://github.com/embeddedarm/ts4900-utils/blob/master/src/gpiolib.c * - http://wiki.embeddedarm.com/wiki/TS-7970#GPIO * - https://www.kernel.org/doc/Documentation/gpio/sysfs.txt * *******************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include "gpiolib.h" int main(int argc, char **argv) { int gpio_pin = 59; gpio_export(gpio_pin); gpio_direction(gpio_pin, 1); for(int i = 0; i < 5; i++) { printf(">> GPIO %d ON\n", gpio_pin); gpio_write(gpio_pin, 1); sleep(1); printf(">> GPIO %d OFF\n", gpio_pin); gpio_write(gpio_pin, 0); sleep(1); } return 0; } <file_sep>SRCS=gpiolib.c gpiodemo.c CFLAGS= CC=gcc INSTALL=/usr/local/bin/ all: gpioctl gpiodemo gpioctl: gpiolib.c $(CC) $(CFLAGS) -DCTL -o gpioctl gpiolib.c gpiodemo: gpiodemo.c $(CC) $(CFLAGS) -o gpiodemo gpiolib.c gpiodemo.c install: all install -m 4755 gpiodemo $(INSTALL) install -m 4755 gpioctl $(INSTALL) clean: -rm -f gpiodemo gpioctl
d0cd3514c38bdb0d89240c0f1e01565761a1860d
[ "C", "Makefile" ]
2
C
01-Life/gpio-sysfs-demo
59805fbe42536fe0a7c5487723d26e723be98d98
381494383898d7cdeeecfa3f0125189e9c7d6710
refs/heads/master
<repo_name>anhuipal/Slotted-Aloha<file_sep>/src/slottedAloha/Network.java package slottedAloha; import java.util.*; public class Network { private HashMap<String,Node> Network; private Set<Metrics> metrics; private int sucTrans; private int failTrans; private int iterations; private int nodes; private int sucTotalTrans; private double networkProb,incrimentProb; private Set<String> networkKeysSet; public Network(int nodes) { this.Network = new HashMap<String,Node>(); this.metrics = new HashSet<Metrics>(); this.networkKeysSet = new HashSet<String>(); this.sucTrans=0; this.failTrans=0; this.networkProb=0.05; this.nodes=nodes; this.iterations=1; }//end of default constructor public Network(double networkProb,int incrimentProb,int nodes) { this.Network = new HashMap<String,Node>(); this.metrics = new HashSet<Metrics>(); this.networkKeysSet = new HashSet<String>(); this.sucTrans=0; this.failTrans=0; this.networkProb=networkProb; this.incrimentProb=incrimentProb; this.nodes=nodes; this.iterations=1; this.sucTotalTrans = 0; }//end of constructor public void init(){ for(int i = 0; i<=nodes;i++){ Network.put(Character.toString(new Node(i).getName()),new Node(i)); } }//end of init() public void init(int nodes){ for(int i = 0; i<=nodes;i++){ Network.put(Character.toString(new Node(i).getName()),new Node(i)); } }//end of init() public void calculateProb(){ this.networkProb = this.networkProb + (double)(this.incrimentProb)/100*this.networkProb; //System.out.println(this.networkProb); }//end of calculateProb() public void testNetworkEfficiency(){ networkKeysSet = Network.keySet(); String [] networkKeys = networkKeysSet.toArray(new String[networkKeysSet.size()]); do{ for(int i = 0;i<10000;i++){ int transmiting = 0; //This loop set a random probability which refers to the propability of transmiting for(int j = 0 ;j<Network.size();j++){ Network.get(networkKeys[j]).setP(new Random().nextDouble()); if(Network.get(networkKeys[j]).getP()<=this.networkProb){ // Network.get(networkKeys[j]).setTrans(true); transmiting++; //System.out.println(Network.get(networkKeys[j]).getName() + " wants to Transimit!"); } } if(transmiting==1){ //System.out.println("Transmission Complete"); this.sucTrans++; } else{ //System.out.println("Transmission Failed"); this.failTrans++; } // } this.metrics.add(new Metrics(this.sucTrans,this.failTrans,this.networkProb,this.iterations,(double) this.sucTrans/(this.sucTrans + this.failTrans),(double)this.sucTrans/this.networkProb,this.nodes)); this.iterations++; this.calculateProb(); //This method incriments the propability of the network sucTotalTrans = sucTotalTrans + sucTrans; this.sucTrans = 0; this.failTrans = 0; }while(this.networkProb<1); } public void internalEfficiency(){ this.init(); this.testNetworkEfficiency(); } public void setNetwork(HashMap<String, Node> Network) { this.Network = Network; } public HashMap<String, Node> getNetwork() { return Network; } public int getSucTrans() { return sucTrans; } public int getFailTrans() { return failTrans; } public Set<Metrics> getMetrics() { return metrics; } public String printSet(){ String results = new String(); double maxProp = 0; int maxSuc = 0; for(Metrics m : metrics){ results += "Runtime: " + m.getNum() +" Propability: " + m.getP() + " Successes: " + m.getSuccesses() + " Failures: " + m.getFailures() + " Efficiency: " + m.getEfficiency() + " Plot1: " + m.getPlot1() + "\n"; if(m.getSuccesses()>maxSuc){ maxSuc = m.getSuccesses(); maxProp = m.getP(); } } results += "Total Successful Transmissions : " + this.getSucTotalTrans() + "\n"; results += "Highest Number of Successes : " + maxSuc + " at Probability : " + maxProp + "\n" ; return results; } public int getSucTotalTrans() { return sucTotalTrans; } public int getNodes() { return nodes; } }//end of class <file_sep>/src/slottedAloha/GuiFx.java package slottedAloha; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.geometry.Rectangle2D; import javafx.scene.Scene; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.stage.Screen; import javafx.stage.Stage; public class GuiFx extends Application { //Text area TextField probStartText = new TextField(); TextField probIncriment = new TextField(); TextField nodesText = new TextField(); TextArea testResults = new TextArea(); //Plots NumberAxis xAxisPlot1 = new NumberAxis(); NumberAxis yAxisPlot1 = new NumberAxis(); LineChart<Number, Number> lineChartPlot1 = new LineChart<Number, Number>( xAxisPlot1, yAxisPlot1); NumberAxis xAxisPlot2 = new NumberAxis(); NumberAxis yAxisPlot2 = new NumberAxis(); LineChart<Number, Number> lineChartPlot2 = new LineChart<Number, Number>( xAxisPlot2, yAxisPlot2); //Plot 2 Data XYChart.Series<Number, Number> seriesPlot2 = new XYChart.Series<Number, Number>(); //Network static Network network; Scene mainScene; Stage window; @Override public void start(Stage primaryStage) { //Stage window = primaryStage; window.setTitle("Slotted Aloha Procotol Simulator"); //Text Result testResults.setFont(Font.font("Verdana",16)); testResults.setText("Please fill out the above fields and press the " + "'" + "Start Simulation" + "'" + " button."); testResults.setEditable(false); //Menu Bar MenuBar menuBar = new MenuBar(); Menu view = new Menu("View"); MenuItem mainMenu = new MenuItem("Main Menu"); MenuItem plot1Menu = new MenuItem("Plot 1"); MenuItem plot2Menu = new MenuItem("Plot 2"); view.getItems().add(mainMenu); view.getItems().add(plot1Menu); view.getItems().add(plot2Menu); Menu operations = new Menu("Operations"); MenuItem exit = new MenuItem("Exit"); MenuItem restart = new MenuItem("Restart"); exit.setOnAction(e-> window.close() ); restart.setOnAction(e-> this.restartApp() ); operations.getItems().addAll(restart,exit); exit.setOnAction(e-> window.close()); menuBar.getMenus().add(view); menuBar.getMenus().add(operations); //Buttons Button btnStart = new Button("Start Simulation"); btnStart.setPrefWidth(300); Button btnPlot1 = new Button("Plot 1"); btnPlot1.setPrefWidth(300); Button btnPlot2 = new Button("Plot 2"); btnPlot2.setPrefWidth(300); Button mainMenuOp = new Button("Main Menu"); mainMenuOp.setPrefWidth(300); Button restartBtn = new Button("Restart App"); restartBtn.setPrefWidth(300); //Labels Label propStartTextL = new Label("Starting Propability : "); propStartTextL.setPrefWidth(500); Label propIncrimentL = new Label("Incriment of Propability as a % : "); propIncrimentL.setPrefWidth(500); Label nodesTextL = new Label("Number of Nodes : "); nodesTextL.setPrefWidth(500); //Main Scene layouts GridPane centerGrid = new GridPane(); centerGrid.setPadding(new Insets(40,10,10,10)); BorderPane mainSceneLayout = new BorderPane(); mainSceneLayout.setPadding(new Insets(5,5,5,5)); centerGrid.setHgap(8); centerGrid.setVgap(5); //TextPane probStartText.setPrefWidth(500); VBox textPane = new VBox(20); textPane.setPadding(new Insets(10,10,10,10)); textPane.setAlignment(Pos.CENTER); textPane.getChildren().addAll(probStartText,probIncriment,nodesText); //Labels Pane VBox labelsPane = new VBox(30); labelsPane.setPadding(new Insets(10,10,10,10)); labelsPane.setAlignment(Pos.CENTER); labelsPane.getChildren().addAll(propStartTextL,propIncrimentL,nodesTextL); //Grid Center Layout centerGrid.add(labelsPane, 0, 0); centerGrid.add(textPane,1,0); //Buttons Pane VBox btnPane = new VBox(20); btnPane.setPadding(new Insets(10,10,10,10)); btnPane.getChildren().addAll(btnStart,btnPlot1,btnPlot2,mainMenuOp,restartBtn); btnPane.setAlignment(Pos.BASELINE_CENTER); mainSceneLayout.setLeft(btnPane); mainSceneLayout.setCenter(centerGrid); mainSceneLayout.setTop(menuBar); mainSceneLayout.setBottom(testResults); //Plot1 xAxisPlot1.setLabel("Network Propability"); yAxisPlot1.setLabel("Successfull Transmitions"); lineChartPlot1.setTitle("Successfully Transmitions Over Network Propability"); //Plot2 xAxisPlot2.setLabel("Nodes"); yAxisPlot2.setLabel("Successfull Transmitions"); lineChartPlot2.setTitle("Successfully Transmitions Over the Number of Nodes"); //Set Menus plot1Menu.setOnAction(e -> mainSceneLayout.setCenter(lineChartPlot1)); plot2Menu.setOnAction(e -> mainSceneLayout.setCenter(lineChartPlot2)); mainMenu.setOnAction(e -> mainSceneLayout.setCenter(centerGrid)); //Set Buttons btnPlot1.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { // populating the series with data XYChart.Series<Number, Number> seriesPlot1 = new XYChart.Series<Number, Number>(); for(Metrics m: network.getMetrics()){ seriesPlot1.getData().add(new XYChart.Data<Number, Number>(m.getP(), m.getSuccesses())); } seriesPlot1.setName("For : " + nodesText.getText() + " Nodes;"); lineChartPlot1.getData().add(seriesPlot1); mainSceneLayout.setCenter(lineChartPlot1); } }); restartBtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { restartApp(); } }); btnPlot2.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { seriesPlot2.getData().add(new XYChart.Data<Number, Number>(network.getNodes(),network.getSucTotalTrans())); lineChartPlot2.getData().add(seriesPlot2); mainSceneLayout.setCenter(lineChartPlot2); } }); btnStart.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { testResults.setText(""); network = null; network = new Network(Double.parseDouble(probStartText.getText()),Integer.parseInt(probIncriment.getText()),Integer.parseInt(nodesText.getText())); network.init(); network.testNetworkEfficiency(); testResults.setText(network.printSet()); } }); mainMenuOp.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { mainSceneLayout.setCenter(centerGrid); } }); //MainScene mainScene = new Scene(mainSceneLayout,900,700); //Center Window Rectangle2D primScreenBounds = Screen.getPrimary().getVisualBounds(); window.setX((primScreenBounds.getWidth() - primaryStage.getWidth()) / 2); window.setY((primScreenBounds.getHeight() - primaryStage.getHeight()) / 2); //Render window mainScene.setRoot(mainSceneLayout); mainScene.getStylesheets().add("slottedAloha/style.css"); window.setScene(mainScene); window.show(); } public void restartApp(){ network = null; window.close(); lineChartPlot1.getData().clear(); lineChartPlot2.getData().clear(); this.probStartText.setText(""); this.probIncriment.setText(""); this.nodesText.setText(""); this.testResults.setText(""); window.show(); } public static void main(String[] args) { launch(args); } } <file_sep>/src/slottedAloha/Metrics.java package slottedAloha; public class Metrics implements Comparable { private int successes,failures,num,nodes,totalSuccesses; private double p,efficiency,plot1,plot2; public Metrics(int successes, int failures, double p,int num,double efficiency,double plot1,int nodes){ this.successes = successes; this.failures = failures; this.p = p; this.num = num; this.efficiency = efficiency; this.plot1 = plot1; this.nodes = nodes; } public void setSuccesses(int successes) { this.successes = successes; } public int getSuccesses() { return successes; } public void setFailures(int failures) { this.failures = failures; } public int getFailures() { return failures; } public void setP(double p) { this.p = p; } public double getP() { return p; } public int getNum() { return num; } public void setEfficiency(double efficiency) { this.efficiency = efficiency; } public double getEfficiency() { return efficiency; } public void setPlot1(double plot1) { this.plot1 = plot1; } public double getPlot1() { return plot1; } public void setPlot2(double plot2) { this.plot2 = plot2; } public double getPlot2() { return plot2; } public void setNodes(int nodes) { this.nodes = nodes; } public int getNodes() { return nodes; } public void setTotalSuccesses(int totalSuccesses) { this.totalSuccesses = totalSuccesses; } public int getTotalSuccesses() { return totalSuccesses; } @Override public int compareTo(Object o) { return 0; } }
ffa3206e186ffea9b7523a39dc2bd0be26d87480
[ "Java" ]
3
Java
anhuipal/Slotted-Aloha
ae68a019c8ac8c49173f077b21debf5b05cfcda8
06765ded65480f593ca1e441826f562e7b0171c4
refs/heads/master
<file_sep>from django.shortcuts import render, get_object_or_404, redirect from django.utils import timezone from .models import Blog from django.http import HttpResponse import random # Create your views here. def home(request): blogs = Blog.objects return render(request, 'blog/home.html', {'blogs': blogs}) def detail(request, blog_id): blog_detail = get_object_or_404(Blog, pk=blog_id) return render(request, 'blog/detail.html', {'blog': blog_detail}) def new(request): return render(request, 'blog/new.html') def create(request): blog = Blog() blog.title = request.GET['title'] blog.body = request.GET['body'] blog.pub_date = timezone.datetime.now() blog.save() return redirect('/blog/' + str(blog.id)) def fortune(request): fortuneRand = random.randrange(5) + 1 if fortuneRand == 1: return HttpResponse("\nYou will receive a large some of money.") elif fortuneRand == 2: return HttpResponse("\nSomething you lost will soon turn up.") elif fortuneRand == 3: return HttpResponse("\nYou will have bad luck for a week.") elif fortuneRand == 4: return HttpResponse("\nToday is your lucky day!") elif fortuneRand ==5: return HttpResponse("\nYou will meet Mr. and Mrs. Right in 2 days!")
81d98158acd645283142266a286e6d786d790684
[ "Python" ]
1
Python
dongooree/blogproject
2d40efffa822c82b96f3d0ef718173681a4f7f30
18de89d6b7c01a99ff51e819149edbca2483c5b2
refs/heads/master
<repo_name>herzenuni/sem3-assignment2-1-11217-Bolzuka<file_sep>/NOD/Test_NOD.py # Практичское задание NOD # <NAME>| ИВТ | 2 курс | 1 подгруппа # Задача NOD # # ЧАСТЬ 2 # # Напишите программу, которая реализует нахождение наибольшего общего делителя двух чисел A, B # Тесты оформите с помощью pytest или UnitTest. import pytest import nod def factory(a, b, c): def test(): assert nod.nod(a, b) == c return test test1 = factory(1, 11, 1) test2 = factory(5, 55, 5) test3 = factory(12345, 123, 3) <file_sep>/SORT/SORT.py # Практичское задание sort # <NAME>| ИВТ | 2 курс | 1 подгруппа # Задача sort # # ЧАСТЬ 1 # # Реализуйте два алгоритма сортировки: методом пузырька и быструю сортировку, # протестируйте их работу с использованием пакета hypothesis # (возможно использовать код из лекции по тестированию) и проанализируйте время # выполнения сортировки двумя методами с помощью модуля timeit (см. файл example_sort.py # Практичское задание sort # <NAME>| ИВТ | 2 курс | 1 подгруппа # Задача sort # # ЧАСТЬ 1 # # Реализуйте два алгоритма сортировки: методом пузырька и быструю сортировку, # протестируйте их работу с использованием пакета hypothesis # (возможно использовать код из лекции по тестированию) и проанализируйте время # выполнения сортировки двумя методами с помощью модуля timeit (см. файл example_sort.py) # Пузырьек def bubble_sort(arr): for i in range(len(arr)): for j in range(len(arr) - 1, i, -1): if arr[j] < arr[j - 1]: arr[j], arr[j - 1] = arr[j - 1], arr[j] return arr # Быстрая сортировка def quick_sort(arr): if arr: head, *tail = arr return quick_sort([x for x in tail if x <= head]) + \ [head] + \ quick_sort([x for x in tail if x > head]) return [] if __name__ == "__main__": pass import timeit print("TIMEIT") print("bubble_sort : ", end='') print(timeit.timeit("bubble_sort([1,2,3,4,5,6,7,8,9])", setup="from __main__ import bubble_sort", number=10)) print("quick_sort : ", end='') print(timeit.timeit("quick_sort([1,2,3,4,5,6,7,8,9])", setup="from __main__ import quick_sort", number=10))
873611db060b7b1535dabf855d9401c8ca562112
[ "Python" ]
2
Python
herzenuni/sem3-assignment2-1-11217-Bolzuka
054e55cc8fcdfe8c450f81f617ce348fb2e966a4
b51de3be1d8ff9c4307b3bd0aa7a9cf26824bc53
refs/heads/master
<repo_name>ccharles78/clickygame<file_sep>/src/App.js //imports dependencies and files import React, { Component } from "react"; import Navbar from "./components/Navbar"; import Jumbotron from "./components/Jumbotron"; import sharkCard from "./components/sharkCard"; import Footer from "./components/Footer"; import sharks from "./sharks.json"; import "./App.css"; //sets state to 0 or empty class App extends Component { state = { sharks, clickedsharks: [], score: 0 }; //when you click on a card ... the sharks is taken out of the array imageClick = event => { const currentsharks = event.target.alt; const sharksAlreadyClicked = this.state.clickedsharks.indexOf(currentsharks) > -1; //if you click on a sharks that has already been selected, the game is reset and cards reordered if (sharksAlreadyClicked) { this.setState({ sharks: this.state.sharks.sort(function(a, b) { return 0.5 - Math.random(); }), clickedsharks: [], score: 0 }); alert("You lose. Play again?"); //if you click on an available sharks, your score is increased and cards reordered } else { this.setState( { sharks: this.state.sharks.sort(function(a, b) { return 0.5 - Math.random(); }), clickedsharks: this.state.clickedsharks.concat( currentsharks ), score: this.state.score + 1 }, //if you get all 12 sharks corrent you get a congrats message and the game resets () => { if (this.state.score === 12) { alert("Yay! You Win!"); this.setState({ sharks: this.state.sharks.sort(function(a, b) { return 0.5 - Math.random(); }), clickedsharks: [], score: 0 }); } } ); } }; //the order of components to be rendered: navbar, jumbotron, sharkcard, footer render() { return ( <div> <Navbar score={this.state.score} /> <Jumbotron /> <div className="wrapper"> {this.state.sharks.map(sharks => ( <sharkCard imageClick={this.imageClick} id={sharks.id} key={sharks.id} image={sharks.image} /> ))} </div> <Footer /> </div> ); } } export default App;<file_sep>/src/components/Sharkcard/index.js export { default } from "./SharkCard";
538882ad5013eceaa0fd8cf9814db3277ae61558
[ "JavaScript" ]
2
JavaScript
ccharles78/clickygame
15932652e22b1b2c35cc61b6d23b4ea77366637f
1c29f4532a46be8f07e11ab0165f107a20edc3d9
refs/heads/master
<file_sep>package Modul1_Bab3; /** * * @author abdu_ */ public class Obat { String nama; int harga; Obat(int kode) { switch (kode) { case 1: nama = "OBH"; harga = 29000; break; case 2: nama = "Paracetamol"; harga = 2000; break; case 3: nama = "Probiotik"; harga = 15000; break; case 4: nama = "Ultraflu"; harga = 5000; break; case 5: nama = "Mylanta"; harga = 36000; break; default: nama = "Tidak tersedia"; harga = 0; } } }<file_sep>package Modul1_Bab3; /** * * @author abdu_ */ import java.util.Scanner; public class mainApotik { public static void main(String[] args) { Scanner in = new Scanner(System.in); String nama, alamat; int jml, kode; Obat[] daftar; System.out.print("Nama\t: "); nama = in.nextLine(); System.out.print("Alamat\t: "); alamat = in.nextLine(); Costumers c1 = new Costumers(nama, alamat); c1.display("Daftar Obat"); System.out.print("Jumlah obat yang dipilih : "); jml = in.nextInt(); daftar = new Obat[jml]; for (int i = 0; i < daftar.length; i++) { System.out.printf("Masukkan kode obat %d : ", (i + 1)); kode = in.nextInt(); daftar[i] = new Obat(kode); } System.out.println(""); Costumers c2 = new Costumers(nama, alamat, daftar); c2.display(); } }
5a790d7c171ca5052f7a02a2db2494e1ded285ec
[ "Java" ]
2
Java
Abdu97/tugas-3
9d5a2b3fbde338ab1b618f2c2df64338ab10b7be
e0e53955936de0d284ac4f6b5cf8806df9421938
refs/heads/master
<repo_name>nelsonkuang/pix2rem<file_sep>/src/js/pix2rem_v2.js (function () { function setMeta() { var isMobile = { UCBrowser: function () { return navigator.userAgent.match(/UCBrowser/i); }, MicroMessenger: function () { return navigator.userAgent.match(/MicroMessenger/i); }, Android: function () { return navigator.userAgent.match(/Android/i); }, BlackBerry: function () { return navigator.userAgent.match(/BlackBerry/i); }, iPad: function () { return navigator.userAgent.match(/iPad/i); }, iPhone: function () { return navigator.userAgent.match(/iPhone/i); }, iOS: function () { return navigator.userAgent.match(/iPhone|iPod|iPad/i); }, Opera: function () { return navigator.userAgent.match(/Opera Mini/i); }, Windows: function () { return navigator.userAgent.match(/IEMobile/i); }, any: function () { return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows()); } }; var windowW = window.innerWidth > window.screen.width ? window.innerWidth : window.screen.width, dpr = window.devicePixelRatio, rootEl = document.querySelector('html'), viewportEl = document.querySelector('meta[name=viewport]'); var scale = 1 / dpr; if (isMobile.any()) { if (isMobile.iPhone()) { windowW = window.screen.width * dpr; } rootEl.style.fontSize = windowW / 10 + 'px'; rootEl.setAttribute('data-dpr', dpr); viewportEl.setAttribute('content', 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no'); } else { rootEl.style.fontSize = '75px'; rootEl.setAttribute('data-dpr', 1); viewportEl.setAttribute('content', 'initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no'); } } setMeta(); window.onresize = function () { setMeta(); }; })(); <file_sep>/README.md 正在优化当中。。。 # pix2rem Use Gulp + Sass instead of Grunt + less, check the repos - [hiooyUI/pix2remjs](https://github.com/hiooyUI/pix2remjs), both are the same. a responsive design soluction for mobile web page [compatible with all popular mobile / appwebview browsers], meanwhile REM lives harmony with Pixel that means you can use 'px' and 'rem' at the same time. Version v2 is an alternative choice for fixing 1 pixel issue / Chrome mobile mode font-size issue (not supported less than 12px) 与[hiooyUI/pix2remjs](https://github.com/hiooyUI/pix2remjs)项目一样,只是实现方式不一样,这里用Gulp + Sass实现,而前者用Grunt + less实现。 一个几乎能适配所有手机端的非常简单易用的h5响应式设计解决方案[兼容所有流行的移动浏览器或者app内置浏览器], 移动端Rem解决方案, 与此同时,最方便之处是你可以同时使用REM单位或者px像素单位互不冲突,非常和谐,[如果觉得1像素问题/Chrome mobile模式下显示最小12px不好处理,可以选择**V2版本,但V2版本有个缺点,就是与px单位共用时不灵活,需要针对dpr进行额外处理**] Usage 使用方式 ---------------------------------------------- Use Gulp in Command line, run ```npm install``` and ```gulp``` Gulp环境命令行通过npm安装, 输入```npm install```和```gulp``` ``` npm install gulp ``` Showcase 谁在用 ---------------------------------------------- [海印优选](http://wx.hiooy.com/wap) [海印乐购](http://m.hiooy.cn/) <file_sep>/src/js/pix2rem.js (function () { function setMeta() { var isMobile = { UCBrowser: function () { return navigator.userAgent.match(/UCBrowser/i); }, MicroMessenger: function () { return navigator.userAgent.match(/MicroMessenger/i); }, Android: function () { return navigator.userAgent.match(/Android/i); }, BlackBerry: function () { return navigator.userAgent.match(/BlackBerry/i); }, iPad: function () { return navigator.userAgent.match(/iPad/i); }, iPhone: function () { return navigator.userAgent.match(/iPhone/i); }, iOS: function () { return navigator.userAgent.match(/iPhone|iPod|iPad/i); }, Opera: function () { return navigator.userAgent.match(/Opera Mini/i); }, Windows: function () { return navigator.userAgent.match(/IEMobile/i); }, any: function () { return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows()); } }; var screenW = window.screen.width, dpr = window.devicePixelRatio; if (isMobile.UCBrowser() || (isMobile.MicroMessenger() && !isMobile.iPhone())) {//UC if (screenW > 610) { document.querySelector('html').style.fontSize = screenW / dpr / 10 + 'px'; } else { document.querySelector('html').style.fontSize = screenW / 10 + 'px'; } if (!isMobile.any()) { document.querySelector('html').style.fontSize = 75 + 'px'; } } else if (isMobile.iPhone()) { //iphone document.querySelector('html').style.fontSize = screenW / 10 + 'px'; } else if (isMobile.iPad()) {//ipad document.querySelector('html').style.fontSize = 75 + 'px'; } else if (isMobile.any()) { if (screenW / 10 > 70) {//Mobile QQ document.querySelector('html').style.fontSize = screenW / dpr / 10 + 'px'; } else { document.querySelector('html').style.fontSize = screenW / 10 + 'px'; } } else { if (window.innerWidth <= 750) { document.querySelector('html').style.fontSize = window.innerWidth / 10 + 'px'; } else document.querySelector('html').style.fontSize = 75 + 'px'; } } setMeta(); window.onresize = function () { setMeta(); }; })();
e5e9f99cb6e68d7157f28a1a3dcaa06a7fd0cf5b
[ "JavaScript", "Markdown" ]
3
JavaScript
nelsonkuang/pix2rem
4fa2b60c4e6541d7c7e54b2e58fbf128d37b51b9
e9870a049fe5022c1fbf951dcc9dc007bf9758d7
refs/heads/master
<file_sep>Build ================================================================================ Request: A Windows system has VS2010 being installed. 1. Double click build.release.bat will started to use MSBUILD to compile solution and generate all assemlies, executeable and package under ./Output folder. 2. Or you can open Hibu.Sam.Concordance.sln file using VS2010 and build each project with different configuration as needed. Folder structure as below ================================================================================ |+Data - Testing data |+Docs - Instruction documents |+Hibu.Sam.Concordance.Client - Command line client tool project which can be used to post a file to RESTful interface and display returned JSON data |+Hibu.Sam.Concordance.Models - Common data model classes project |+Hibu.Sam.Concordance.Parsers - Parser class proejct which takes filestream as input and return extracted sentence and word information |+Hibu.Sam.Concordance.Utilities - Common utilites and helper class project |+Hibu.Sam.Concordance.Web - Web application project which exposes a concordance generator interface and a web page for submitting file to this interface |+Hibu.Sam.Concordance.WebApiServer - Self-host web api project which exposes a concordance generator interface |+Output - Folder contains compiled output when using build script |+packages - 3rd part NUGet packages Files under root folder ================================================================================ ./Hibu.Sam.Concordance.sln - VS2010 solution file contains all sub projects ./build.cleanup.bat - Script for cleanup compiled output under each proejcts for Debug and Release configuration ./build.release.bat - Script for compile self-host web api server, command line client tool, and web applicaiton package. Compiled result will be under Output folder ./solution cleanup.bat - Script for cleanup all Bin, Obj, Output subfolders ./web.deploy.ps1 - PowerShell script for deploying web application<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Text; namespace Hibu.Sam.Concordance.Client { class Program { const int BufferSize = 1024; const string ApiFormat = @"http://localhost:888/api/concordance/"; const string FileFormat = @"C:\code\The Raven.txt"; //" ConcordanceClient.exe "http://localhost:888/api/concordance" "C:\code\The Raven.txt" static void Main(string[] args) { if (args.Count() != 2) { DisplayUsageInfo(); return; } try { string uri = args[0]; string filename = args[1]; Console.WriteLine("Web api address: {0}", uri); Console.WriteLine("Local file path: {0}", filename); RunClient(uri, filename); } catch (Exception e) { Console.WriteLine("Error happens when trying to post file: {0}", e.GetBaseException().Message); } } private static void DisplayUsageInfo() { Console.WriteLine("Usage: ConcordanceClient.exe ApiAddress LocalFilePath\n"); Console.WriteLine("Sample as below:"); Console.WriteLine("ConcordanceClient.exe \"{0}\" \"{1}\"", ApiFormat, FileFormat); } private static void RunClient(string uri, string filename) { HttpClient client = new HttpClient(); client.Timeout = TimeSpan.FromMinutes(5); using (FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize)) { StreamContent content = new StreamContent(fileStream, BufferSize); Uri address = new Uri(uri); MultipartFormDataContent formData = new MultipartFormDataContent(); formData.Add(new StringContent("submit"), "sumitter"); formData.Add(content, "filename", filename); HttpResponseMessage response = client.PostAsync(address, formData).Result; Console.WriteLine("Response from server:\n{0}", response.Content.ReadAsStringAsync().Result); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Http.SelfHost; using System.ServiceModel; using System.Web.Http; namespace Hibu.Sam.Concordance.WebApiServer { class Program { const int BufferSize = 1024; const string BindingUrlFormat = "http://localhost:888/"; // ConcordanceWebApiServer.exe "http://localhost:888/" // mabye need command? netsh http add iplisten ipaddress=0.0.0.0:888 static void Main(string[] args) { if (args.Count() != 1) { DisplayUsageInfo(); return; } HttpSelfHostServer server = null; try { string uri = args[0]; HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(uri); config.HostNameComparisonMode = HostNameComparisonMode.Exact; config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.MaxReceivedMessageSize = 16L * 1024 * 1024 * 1024; config.ReceiveTimeout = TimeSpan.FromMinutes(5); config.TransferMode = TransferMode.StreamedRequest; server = new HttpSelfHostServer(config); server.OpenAsync().Wait(); Console.WriteLine("Listening on " + uri); Console.WriteLine("Hit ENTER to stop and exit..."); Console.ReadLine(); } catch (Exception e) { Console.WriteLine("Could not start server: {0}", e.GetBaseException().Message); DisplayUsageInfo(); Console.WriteLine(); Console.WriteLine("If you meet couldn't register URL error, pleases run this app with local administrator privilage or use command line like following format to register Reserved URL to system"); Console.WriteLine("netsh http add urlacl url=http://localhost:888/ user=\\everyone listen=yes"); } finally { if (server != null) { server.CloseAsync().Wait(); } } } private static void DisplayUsageInfo() { Console.WriteLine("Usage: ConcordanceWebApiServer.exe BindingUrl\n"); Console.WriteLine("Sample as below:"); Console.WriteLine("ConcordanceWebApiServer.exe \"{0}\"", BindingUrlFormat); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Hibu.Sam.Concordance.Parsers { public class EnglishParser { readonly char[] PunctuationChars = { '"', ',', '!', '?' }; //'\'', readonly char[] EndingChars = { ' ', '.', '!', '?', '/' }; readonly byte[] Utf8BomArr = new byte[3] { 239, 187, 191 }; private FileStream fileStream; private TextReader readFile; private string line; private int pointer; private int sentenceNumber; private List<ParserWord> words; public List<ParserWord> Words { get { return words; } } public EnglishParser(FileStream fileStream) { this.fileStream = fileStream; readFile = new StreamReader(this.fileStream); words = new List<ParserWord>(); byte[] headerArr = new byte[3]; fileStream.Read(headerArr, 0, 3); if (headerArr.SequenceEqual<byte>(Utf8BomArr)) { // this is a UTF-8 file } else { fileStream.Position = 0; } } ~EnglishParser() { if (readFile != null) { readFile.Close(); } if (fileStream != null) { fileStream.Close(); } } public ParserWord GetNextWord() { ParserWord word = null; if (string.IsNullOrEmpty(line) || pointer == line.Length) { //line = readFile.ReadLine(); //sentenceNumber++; //while (line != null && line.Length == 0) //{ // line = readFile.ReadLine(); // sentenceNumber++; //} line = GetNextSentence(); pointer = 0; } if (line != null) { line = line.ToLower().Trim(); line = line.Replace("--", " "); line = line.Replace("_", " "); line = line.Replace(" ", " "); line = line.Replace("*", " "); StringBuilder sb = new StringBuilder(); for (int i = pointer; i < line.Length; i++) { char c = line[pointer++]; if (EndingChars.Contains(c) || pointer == line.Length) { word = new ParserWord(); word.Letters = sb.ToString().Replace("'s", "").Replace("'", ""); word.SentenceNumber = sentenceNumber; break; } else { if (!PunctuationChars.Contains(c)) { sb.Append(c); } } } } return word; } private string GetNextSentence() { string line = null; line = readFile.ReadLine(); sentenceNumber++; while (line != null && line.Length == 0) { line = readFile.ReadLine(); sentenceNumber++; } // only keep one space for multiple space // replace \r\n //fileStream.ReadByte(); return line; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Hibu.Sam.Concordance.Models { public class Dict { private Node rootNode; public Dict() { rootNode = new Node(); } public void AddWord(string word, int sentenceNumber) { Node node = rootNode; Node newNode = null; for (int i = 0; i < word.Length; i++) { char c = word[i]; newNode = new Node() { Key = c }; var n = node.Children.Where(o => o.Key == c).FirstOrDefault(); if (n == null) { node.Children.Add(newNode); newNode.Parent = node; node = newNode; } else { node = n; }; } node.Times++; node.SentenceNumbers.Add(sentenceNumber); } public List<Word> GetWords() { List<Word> words = new List<Word>(); Queue<Node> queue = new Queue<Node>(); foreach (Node child in rootNode.Children) { queue.Enqueue(child); } while (queue.Count > 0) { Node node = queue.Dequeue(); if (node.Times > 0) { words.Add(new Word() { Letters = node.Letters, Times = node.Times, SentenceNumbers = node.SentenceNumbers }); } foreach (Node child in node.Children) { queue.Enqueue(child); } } return words; } public int MyProperty { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Hibu.Sam.Concordance.Parsers { class Sentence { } } <file_sep>using System.Web; using System.Web.Mvc; namespace Hibu.Sam.Concordance.Web { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Hibu.Sam.Concordance.Models { public class Word { public string Letters { get; set; } public int Times { get; set; } public List<int> SentenceNumbers { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Hibu.Sam.Concordance.Models { public class Node { public Char? Key { get; set; } public Node Parent { get; set; } public List<Node> Children { get; set; } public List<int> SentenceNumbers { get; set; } public int Times { get; set; } public string Letters { get { StringBuilder sb = new StringBuilder(); sb.Insert(0, Key); Node p = Parent; while (p != null) { sb.Insert(0, p.Key); p = p.Parent; } return sb.ToString(); } } public Node() { Key = null; Children = new List<Node>(); SentenceNumbers = new List<int>(); } } } <file_sep>using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Http; using Hibu.Sam.Concordance.Models; using Hibu.Sam.Concordance.Parsers; using Hibu.Sam.Concordance.Utilities; namespace Hibu.Sam.Concordance.Web.Controllers { public class ConcordanceController : ApiController { public Task<HttpResponseMessage> PostFormData() { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string rootPath = HttpContext.Current.Server.MapPath("~/App_Data"); MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(rootPath); var task = Request.Content.ReadAsMultipartAsync(provider). ContinueWith<HttpResponseMessage>(t => { if (t.IsFaulted || t.IsCanceled) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception); } MultipartFileData file = provider.FileData[0]; // interface only provide servcie to single file, otherwise we need to iterate colleciton and return file based colletion Trace.WriteLine(file.Headers.ContentDisposition.FileName); Trace.WriteLine("Server file path: " + file.LocalFileName); System.IO.FileStream fileStream = System.IO.File.Open(file.LocalFileName, System.IO.FileMode.Open); #region Parse file and return JSON string EnglishParser parser = new EnglishParser(fileStream); Dict dict = new Dict(); ParserWord word = null; while ((word = parser.GetNextWord()) != null) { dict.AddWord(word.Letters, word.SentenceNumber); } List<Word> words = dict.GetWords(); string json = Newtonsoft.Json.JsonConvert.SerializeObject(words); #endregion fileStream.Close(); try { System.IO.File.Delete(file.LocalFileName); } catch (System.Exception error) { //Do log, don't throw; Trace.WriteLine(error.Message); } HttpResponseMessage response = this.Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(json, Encoding.UTF8, "application/json"); return response; }); return task; } } } <file_sep>This folder will be used for uploading temp data. Temp data will be deleted by app <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Hibu.Sam.Concordance.Parsers { public class ParserWord { public string Letters { get; set; } public int SentenceNumber { get; set; } } } <file_sep>Please refer documents under Docs folder<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Hibu.Sam.Concordance.Utilities { public class Helper { public static string RootPath { get { return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); } } } }
9c1679b9801f6af0a3cca984acc53a5deb2d33ce
[ "Markdown", "C#", "Text" ]
14
Text
zhongxun/hibu
529180945895db3f45907cb0a245827e4ee66f82
05e4caadc6b4c685ac78b209bbdb8cb1add09be2
refs/heads/master
<file_sep>rootProject.name = 'loginregistration' <file_sep>/********************************************************************* * @purpose : Test the controller class * @author : <NAME> * @Date : 27/06/2020 *********************************************************************/ package com.loginregistration.controller; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.loginregistration.model.User; import com.loginregistration.service.IUserService; import org.junit.Assert; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; @WebMvcTest (UserController.class) public class UserControllerMockTest { @Autowired private MockMvc mockMvc; @MockBean IUserService userService; /**+ * * @param object * @return : Write data in JSON * @throws JsonProcessingException */ private String mapToJson(Object object) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(object); } //TC-1 -> Correct and not null Register data passed here @Test public void givenRegister_WhenUserBodyPassed_ShouldReturnUser() throws Exception { User user = new User("Aju", "<PASSWORD>", "<EMAIL>", "Mumbai"); String userJson = this.mapToJson(user); given(userService.register(any(User.class))).willReturn(user); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/register") .accept(MediaType.APPLICATION_JSON).content(userJson) .contentType(MediaType.APPLICATION_JSON); MvcResult mvcResult = this.mockMvc.perform(requestBuilder).andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); String outputInJson = response.getContentAsString(); Assert.assertEquals(outputInJson, userJson); } //TC-2 -> Null data is passed here @Test public void givenRegister_WhenUserBodyPassedNull_ShouldReturnFalse() throws Exception { User user = new User(); String userJson = this.mapToJson(user); given(userService.register(any(User.class))).willReturn(user); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/register") .accept(MediaType.APPLICATION_JSON).content(userJson) .contentType(MediaType.APPLICATION_JSON); MvcResult mvcResult = this.mockMvc.perform(requestBuilder).andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); String outputInJson = response.getContentAsString(); Assert.assertEquals(outputInJson, userJson); } }<file_sep>/********************************************************************* * @purpose : Test class for mock repository * @author : <NAME> * @Date : 27/06/2020 *********************************************************************/ package com.loginregistration.service; import com.loginregistration.model.User; import com.loginregistration.repository.IUserRepository; import org.junit.Assert; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; import java.util.ArrayList; import java.util.List; import static org.mockito.Mockito.when; @RunWith (SpringRunner.class) @SpringBootTest public class UserServiceMockTest { @Autowired IUserService userService; @MockBean IUserRepository userRepository; //TC-1 -> Test case for register user data @Test public void givenUser_WhenRegister_ShouldReturnUser() { User user = new User("Aju", "Aju@123", "<EMAIL>", "Mumbai"); when(userRepository.save(user)).thenReturn(user); User registeredUser = userService.register(user); Assert.assertEquals(registeredUser, user); } //TC-2 -> Test case when passed null data @Test public void givenUser_WhenRegisterPassedNullData_ShouldReturnFalse() { User user = new User(); when(userRepository.save(user)).thenReturn(user); User registeredUser = userService.register(user); Assert.assertEquals(registeredUser, user); } } <file_sep>"Welcome to login registration problem using mockito" <file_sep>/********************************************************************* * @purpose : Repository is used to performed CRUD operation * @author : <NAME> * @Date : 26/06/2020 *********************************************************************/ package com.loginregistration.repository; import com.loginregistration.model.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; public interface IUserRepository extends JpaRepository<User,Integer> { @Query("select u from User u where u.password=?1 and u.emailId=?2") User findUserByEmailIdAndPassword(String password, String emailId); }<file_sep>/********************************************************************* * @purpose : IUserService interface is used for managed service operation * @author : <NAME> * @Date : 26/06/2020 *********************************************************************/ package com.loginregistration.service; import com.loginregistration.model.User; public interface IUserService { User register(User user); User loginUserUsingEmailId(String password,String emailId); } <file_sep>/********************************************************************* * @purpose : UserSerive class implement the business logic * @author : <NAME> * @Date : 26/06/2020 *********************************************************************/ package com.loginregistration.service.implementors; import com.loginregistration.model.User; import com.loginregistration.repository.IUserRepository; import com.loginregistration.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.List; @Service public class UserService implements IUserService { @Autowired private IUserRepository userRepository; /**+ * * @purpose : Used to registerd user data * @param user * @return : Sava register data */ @Override public User register(User user) { user.setRegisterDate(LocalDateTime.now()); return userRepository.save(user); } /**+ * * @purpose : Used for check UserName and password mathches to the database entries or NOT * @param emailId * @param password * @return : UserName and Password */ @Override public User loginUserUsingEmailId(String password,String emailId) { return userRepository.findUserByEmailIdAndPassword(password,emailId); } }
732e358655c8d1365aeb9ee1c760511db38c5556
[ "Markdown", "Java", "Gradle" ]
7
Gradle
seema1611/LoginRegistration_WithMockito
4b5901c6dd6390b33275687e878c7bd74247b4b2
c158beb6de63a8358fcfcd867c0b2f39c2a3f93b
refs/heads/master
<repo_name>JJmaz/jenkins<file_sep>/src/classes/VoidClass.php <?php /** * @author matsuo * @todo ここにやることを書く * test * */ class VoidClass{ private function abc(){ return; } public function test(){ return ; } }<file_sep>/newfile.php <?php echo "a"; echo "a"; echo "a";<file_sep>/selenium/com/packt/webdriver/utility/ScreenShot.java package com.packt.webdriver.utility; import org.apache.commons.io.FileUtils; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.*; import java.io.*; public class ScreenShot { public void takeScreenShot(WebDriver driver,String filename) { File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); try{ FileUtils.copyFile(scrFile, new File(System.getProperty("user.dir") + "\\images\\"+filename+".png")); }catch(IOException e){ e.getStackTrace(); } } } <file_sep>/build.xml <?xml version="1.0" encoding="utf-8" ?> <!-- basedirは基準となるパス。パスはbuild.xmlのあるパス defaultで最初に見に行くターゲットをbuildにする --> <project name="Project Jenkins" basedir="." default="build"> <!-- propertyは変数を格納するとこ $は変数--> <property name="basedir" value="." /> <property name="appdir" value="${basedir}/application" /> <property name="datadir" value="${basedir}/data" /> <property name="logdir" value="${datadir}/logs" /> <!-- buildターゲットは、dependsで他のターゲットに依存しており、左のターゲットから順に実行する --> <target name="build" depends="clean,prepare,phpdoc,phpunit"> </target> <!-- 既存フォルダ削除する処理 --> <target name="clean" description="clean"> <delete dir="${logdir}" /> <delete dir="${datadir}/phpdoc" /> <delete dir="reports" includeemptydirs="true" /> </target> <!-- レポートなどを格納してフォルダ作成する処理--> <target name="prepare" description="prepare"> <mkdir dir="${logdir}" /> <mkdir dir="${datadir}/phpdoc" /> <mkdir dir="reports" /> </target> <!-- phpunitの実行 https://www.phing.info/docs/stable/hlpdf/manual.pdfの書き方が公式 aaaaaaaaa--> <target name="phpunit"> <phpunit haltonfailure="false" printsummary="true" pharlocation="/usr/local/bin/phpunit" bootstrap="src/autoload2.php"> <formatter todir="reports" type="xml" outfile="unitreport.xml" /> <batchtest> <fileset dir="tests"> <include name="**/*Test.php" /> </fileset> </batchtest> </phpunit> </target> <!-- phpdocの実行 公式による専用のタグがあったが、executable属性からコマンドを実行するようにした --> <target name="phpdoc" description="Generate Application Documentation using PHPDocumentor2"> <!-- 公式による専用のタグがあったが動かないのでコメントアウト--> <!-- <phpdoc2 title = "API Documentation" destdir = "doc" template = "responsive-twig"> <fileset dir = "src/classes"> <include name = "**/*.php" /> </fileset> </phpdoc2> コメントアウト --> <!-- executable属性からコマンドを実行するようにした --> <exec dir="${basedir}" executable="phpdoc" output="${logdir}/phpdoc.log"> <arg line="run" /> <arg line="-t ${datadir}/phpdoc" /> <arg line="-d src/classes" /> <arg line="-p" /> </exec> </target> </project><file_sep>/tests/HelloTest.php <?php //include 'Hello.php'; //include 'autoload2.php'; class HelloTest extends PHPUnit_Framework_TestCase{ function testprintHello() { $h = new Hello(); $this->assertEquals(1,1); } }<file_sep>/selenium/com/packt/webdriver/chapter1/SelecterTraningApp.java package com.packt.webdriver.chapter1; import org.openqa.selenium.WebDriver; //import org.openqa.selenium.WebElement; //import org.openqa.selenium.firefox.FirefoxDriver; //import org.openqa.selenium.By; public class SelecterTraningApp { public static void main(String[] args) { String url = "C:\\Users\\j\\Desktop\\Dropbox\\Programing\\java\\for_eclipse\\webdriver\\html\\sample.html"; SelecterTraning st = new SelecterTraning(url); WebDriver drv = SelecterTraning.DriverFactory("firefox"); drv.get(st.getUrl()); st.WritePtagToTextarea(drv); st.checkXpath(drv); } } <file_sep>/selenium/com/packt/webdriver/chapter3/CookieInfo.java package com.packt.webdriver.chapter3; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import org.openqa.selenium.By; import org.openqa.selenium.Cookie; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; /** * loadクッキーをすれば、アカウントにログインした状態になれるようにしたい * */ public class CookieInfo { public static void loadCookie(){ WebDriver driver = new FirefoxDriver(); //WebDriver driver = new ChromeDriver(); driver.get("http://www.facebook.com"); try{ String pa = System.getProperty("user.dir"); File f2 = new File(pa + "\\browser.data"); FileReader fr = new FileReader(f2); BufferedReader br = new BufferedReader(fr); String line; while((line=br.readLine())!=null){ StringTokenizer str = new StringTokenizer(line,";"); while(str.hasMoreTokens()){ String name = str.nextToken(); String value = str.nextToken(); String domain = str.nextToken(); String path = str.nextToken(); Date expiry = null; String dt; if(!(dt=str.nextToken()).equals("null")){ DateFormat date1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy",Locale.US); try { expiry = date1.parse(dt); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } boolean isSecure = new Boolean(str.nextToken()).booleanValue(); Cookie ck = new Cookie(name,value,domain,path,expiry,isSecure); driver.manage().addCookie(ck); } } br.close(); }catch(Exception ex){ ex.printStackTrace(); } driver.get("http://www.facebook.com"); } public void storeCookie(String... args) { WebDriver driver = new FirefoxDriver(); driver.get("http://www.facebook.com"); driver.findElement(By.name("email")).sendKeys("your mail"); driver.findElement(By.name("pass")).sendKeys("<PASSWORD>"); driver.findElement(By.id("u_0_x")).click(); //driver.findElement(By.name("pass")).submit(); //cookieの保存 File f = new File("browser.data"); try{ f.delete(); f.createNewFile(); FileWriter fos = new FileWriter(f); BufferedWriter bos = new BufferedWriter(fos); for(Cookie ck : driver.manage().getCookies()) { bos.write((ck.getName()+";"+ck.getValue()+";"+ck.getDomain() +";"+ck.getPath()+";"+ck.getExpiry()+";"+ck.isSecure())); bos.newLine(); } bos.flush(); bos.close(); fos.close(); }catch(Exception ex){ ex.printStackTrace(); } } } <file_sep>/src/Hello.php <?php class Hello{ function printHello(){ echo "good morning"; } } ?><file_sep>/info/bootstrap.sh #!/usr/bin/env bash yum -y install httpd service httpd start chkconfig httpd on yum install -y php php-pear php-mbstring php-xml php-devel php-mysqlnd php-opcache php-pecl-apcu php-pecl-xdebug php-gd php-mcrypt #phpunit インストール yum -y install wget wget https://phar.phpunit.de/phpunit.phar chmod +x phpunit.phar mv phpunit.phar /usr/local/bin/phpunit #phpunit-skelgen インストール wget https://phar.phpunit.de/phpunit-skelgen.phar chmod +x phpunit-skelgen.phar mv phpunit-skelgen.phar /usr/local/bin/phpunit #install Phing #phpcs,phpmd,phpcpd,phpDocumentor,phpunitを一括管理することができるツール yum install gcc ImageMagick ImageMagick-devel -y cp /vagrant_data/imagick.ini /etc/php.d/ #これは必要か不明 pecl channel-update pecl.php.net #pecl upgrade #これがないと、下のインストールでwarning unable to load imagick.soとでる pecl install imagick pear channel-discover pear.phing.info pear channel-discover pear.pdepend.org pear channel-discover pear.phpmd.org pear channel-discover pear.phpdoc.org pear channel-discover pear.symfony.com pear channel-discover pear.netpirates.net pear install -a --force phing/phing #git2.2.1 2015/06/21時点での最新版のインストール #インストール後、再ログインするとgit --versionで最新版が入ったことを確認できる #参考 http://pyoonn.hatenablog.com/entry/2015/01/07/095845 yum -y remove git yum -y install curl-devel expat-devel gettext-devel openssl-devel zlib-devel perl-ExtUtils-MakeMaker wget https://www.kernel.org/pub/software/scm/git/git-2.2.1.tar.gz tar zxvf git-2.2.1.tar.gz cd git-2.2.1 ./configure --prefix=/usr/local make prefix=/usr/local all make prefix=/usr/local install<file_sep>/selenium/com/packt/webdriver/chapter3/TakesScreaanShotExample.java package com.packt.webdriver.chapter3; import org.apache.commons.io.FileUtils; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.*; import java.io.*; public class TakesScreaanShotExample { public static void main(String args[]) { WebDriver driver = new FirefoxDriver(); driver.get("http://www.packtpub.com/"); File scrFile = ((TakesScreenshot)driver) .getScreenshotAs(OutputType.FILE); try{ FileUtils.copyFile(scrFile, new File(System.getProperty("user.dir") + "\\html\\images\\a.png")); }catch(IOException e){ e.getStackTrace(); } } } <file_sep>/selenium/com/packt/webdriver/chapter9/pageObjects/UseSampleUse.java package com.packt.webdriver.chapter9.pageObjects; import com.utility.URLConstants; import com.packt.webdriver.chapter9.pageObjects.*; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.PageFactory; public class UseSampleUse { public static void main(String[] args) { WebDriver drv = new FirefoxDriver(); SampleUse su = PageFactory.initElements(drv, SampleUse.class); su.test(); } } <file_sep>/selenium/com/packt/webdriver/chapter9/pageObjects/SampleUse.java package com.packt.webdriver.chapter9.pageObjects; import com.utility.URLConstants; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.PageFactory; public class SampleUse{ WebDriver driver; @FindBy(how=How.ID, using="p_3") WebElement p_tag; @FindBy(how=How.ID, using="aaa") WebElement div; // @FindBy(how=How.ID, using="wp-submit") // WebElement submit; public SampleUse(WebDriver driver){ this.driver = driver; driver.get(URLConstants.TEST); } public void test(){ System.out.println(p_tag.getText()); System.out.println(div.getTagName()); } } <file_sep>/selenium/selenium/modules/hp_schools/admin/UseSample.java package selenium.modules.hp_schools.admin; import java.sql.Time; import java.util.ArrayList; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.*; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.Sleeper; import selenium.modules.hp_schools.admin.Sample_page; import com.packt.webdriver.chapter8.UsingSeleniumGrid; import com.packt.webdriver.utility.PlatFormDTO; import com.packt.webdriver.utility.Recursive; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import org.junit.*; import static org.junit.Assert.assertThat; import static org.hamcrest.CoreMatchers.is; import com.packt.webdriver.utility.SeleniumTestWatcher; public class UseSample { private WebDriver driver; @Rule public SeleniumTestWatcher watcher = new SeleniumTestWatcher(); @Before public void setUp(){ //this.driver = watcher.getWebDriver(); } @Test public void goToGoogle() { PlatFormDTO platform = new PlatFormDTO("win7", "internet explorer"); RemoteWebDriver remote = new UsingSeleniumGrid().getRemoteWebDriver(platform); Sample_page su = PageFactory.initElements(remote, Sample_page.class); int size = su.getCheckboxSize(); ArrayList<String> al = new Recursive().getRecursive(1, size); remote.quit(); for (int i = 0; i < al.size(); i++) { Sample_page s = PageFactory.initElements(new UsingSeleniumGrid().getRemoteWebDriver(platform), Sample_page.class); s.getCheckboxtabname(al.get(i)); } assertThat(true, is(false)); } @After public void tearDown() { System.out.println("after"); } // public static void main(String[] args) { // Sample_page su = PageFactory.initElements(new FirefoxDriver(), Sample_page.class); // // int size = su.getCheckboxSize(); // ArrayList<String> al = new Recursive().getRecursive(1, size); // // for (int i = 0; i < al.size(); i++) { // Sample_page s = PageFactory.initElements(new FirefoxDriver(), Sample_page.class); // s.getCheckboxtabname(al.get(i)); // } // } } <file_sep>/selenium/selenium/modules/hp_schools/admin/UseSample2.java package selenium.modules.hp_schools.admin; import java.sql.Time; import java.util.ArrayList; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.*; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.Sleeper; import selenium.modules.hp_schools.admin.Sample_page; public class UseSample2 { public static void main(String[] args) { // Sample_page su = PageFactory.initElements(new FirefoxDriver(), Sample_page.class); // su.getCheckboxtabname(); UseSample2 us = new UseSample2(); ArrayList<String>al = us.getRecursive(1, 3); //桁数 値の幅 } public ArrayList<String> getRecursive(int exp_max,int digit_max){ int[] arr = new int[digit_max]; int exp_cnt = 0; int digit_cnt = 0; ArrayList<String> al = new ArrayList<String>(); while(exp_cnt <= exp_max){ recursive(exp_max,digit_max,exp_cnt,digit_cnt,arr,al); exp_cnt++; } int ab = al.size(); return al; } private void recursive(int exp_max,int digit_max,int exp_cnt,int digit_cnt,int[] arr,ArrayList<String> al){ arr[digit_cnt] = exp_cnt; if (digit_cnt+1 == digit_max){ StringBuffer sb = new StringBuffer(); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]); sb.append(arr[i]); } sb = null; }else{ exp_cnt = 0; while (exp_cnt <= exp_max) { this.recursive(exp_max,digit_max,exp_cnt,digit_cnt+1,arr,al); exp_cnt++; } } } } <file_sep>/selenium/com/packt/webdriver/chapter3/WebDriverNavigate.java package com.packt.webdriver.chapter3; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.*; public class WebDriverNavigate { public static void main(String args[]){ WebDriver driver = new FirefoxDriver(); driver.navigate().to("http://www.google.com"); WebElement searchBox = driver.findElement(By.name("q")); searchBox.sendKeys("Selenium WebDriver"); WebElement searchButton = driver.findElement(By.name("btnK")); searchButton.click(); searchBox = driver.findElement(By.id("lst-ib")); searchBox.clear(); searchBox.sendKeys("<NAME>"); searchButton = driver.findElement(By.name("btnG")); searchButton.click(); driver.navigate().back(); driver.navigate().forward(); driver.navigate().refresh(); } } <file_sep>/selenium/com/packt/webdriver/utility/Recursive.java package com.packt.webdriver.utility; import java.util.ArrayList; public class Recursive { /** * @param exp_max 1から9までの指定のexp_maxまでの数字パターンを作成する * @param digit_max 桁数の上限を設定 * */ public ArrayList<String> getRecursive(int exp_max,int digit_max){ //桁数は0~9までとする if(exp_max < 0 || 10 < exp_max){ System.out.println("invalid exp_max value"); } int[] arr = new int[digit_max]; int exp_cnt = 0; int digit_cnt = 0; ArrayList<String> al = new ArrayList<String>(); while(exp_cnt <= exp_max){ recursive(exp_max,digit_max,exp_cnt,digit_cnt,arr,al); exp_cnt++; } int ab = al.size(); return al; } private void recursive(int exp_max,int digit_max,int exp_cnt,int digit_cnt,int[] arr,ArrayList<String> al){ arr[digit_cnt] = exp_cnt; if (digit_cnt+1 == digit_max){ StringBuffer sb = new StringBuffer(); for (int i = 0; i < arr.length; i++) { sb.append(arr[i]); } al.add(sb.toString()); sb = null; }else{ exp_cnt = 0; while (exp_cnt <= exp_max) { this.recursive(exp_max,digit_max,exp_cnt,digit_cnt+1,arr,al); exp_cnt++; } } } } <file_sep>/src/autoload2.php <?php function registerClass($class){ @include_once __DIR__ .'/'.$class . '.php'; } spl_autoload_register("registerClass");<file_sep>/selenium/com/packt/webdriver/utility/PlatFormDTO.java package com.packt.webdriver.utility; import org.openqa.selenium.Platform; public class PlatFormDTO { private String browser; private Platform platform; /** * @param platform:win7/win8/win8.1/linux * @param browser:firefox/chrome/internet explorer */ public PlatFormDTO(String platform ,String browser) { switch (platform) { case "win7": this.platform = Platform.WINDOWS; break; case "win8": this.platform = Platform.WIN8; break; case "win8.1": this.platform = Platform.WIN8_1; break; case "linux": this.platform = Platform.LINUX; break; default: break; } this.browser = browser; } public String getBrowser(){return this.browser;} public Platform getPlatform(){return this.platform;} } <file_sep>/selenium/com/packt/webdriver/chapter1/GoogleSearch.java package com.packt.webdriver.chapter1; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class GoogleSearch { public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); //������URL�֑J�� driver.get("http://www.google.com"); //html���name�̒l��q�ł�����̂�WebElement�^�ŕԂ��B�����ł�google�̌����{�b�N�X������Ă��� WebElement searchBox = driver.findElement(By.name("q")); //�����̒l���e�L�X�g�{�b�N�X�֓����B searchBox.sendKeys("packt publishing"); //���M searchBox.submit(); } } <file_sep>/newfile1.php <?php echo "a"; echo "c";<file_sep>/src/newfile.php <?php function my_func($class){ echo $class; include '..//tests/' . $class . '.php'; } spl_autoload_register("my_func"); $abc = new HelloTest();
dfd32394e6a37b8f765d934b48384b21bc224ad8
[ "Ant Build System", "Java", "PHP", "Shell" ]
21
PHP
JJmaz/jenkins
17b40f78634e338c1bb700e056ec6c773c279158
6024037c8a088fb80cb4e6eb74f9b211d97bd639
refs/heads/master
<repo_name>RykAlex/betterdocs<file_sep>/javascripts/main.js (function(window, document, classie) { 'use strict'; var topButton = document.getElementsByClassName('top-button')[0]; function scrollFunction() { if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) { topButton.style.display = 'block'; } else { topButton.style.display = 'none'; } } function topFunction() { document.body.scrollTop = 0; document.documentElement.scrollTop = 0; } window.topFunction = topFunction; window.onscroll = function() { scrollFunction(); }; var sidebarMenu = document.getElementsByClassName('menu')[0], openMenuCtrl = document.querySelector('.action--open'), closeMenuCtrl = document.querySelector('.action--close'); function openMenu() { classie.add(sidebarMenu, 'menu--open'); } function closeMenu() { classie.remove(sidebarMenu, 'menu--open'); } openMenuCtrl.addEventListener('click', openMenu); closeMenuCtrl.addEventListener('click', closeMenu); })(window, window.document, window.classie);
cd09657b4f06f9392cb496d80e9b67499fad56f2
[ "JavaScript" ]
1
JavaScript
RykAlex/betterdocs
d8dc3dc7d9abccbd168a594dcc03cb1135d90c46
12797af624dcc736d322c9978ec95c32006d59c6
refs/heads/master
<repo_name>DogoBot/-OLD-DogoBridge<file_sep>/src/main/kotlin/cf/dogo/server/bridge/Server.kt package cf.dogo.server.bridge import org.json.JSONObject import java.io.BufferedReader import java.io.InputStreamReader import java.io.PrintStream import java.net.ServerSocket import java.net.Socket import java.net.SocketException import kotlin.collections.ArrayList abstract class Server constructor(val port : Int = 4676, val name : String, var logger : PrintStream = System.out) { var socket = ServerSocket(port) var connections = ArrayList<Socket>() val connectionListener = ConnectionListener(this) val inputListener = InputListener(this) class ConnectionListener(val srv : Server) : Thread("${srv.name} ConnectionListener") { override fun run() { super.run() while(true) { var s = srv.socket.accept() if(!srv.connections.contains(s)){ srv.logger.println("[${this.name}] Connection Received! From ${s.remoteSocketAddress}") srv.connections.add(s) } for(s2 in srv.connections){ if(s2.isClosed || !s2.isConnected) srv.connections.remove(s2) } } } } class InputListener(val srv : Server) : Thread("${srv.name} InputListener") { override fun run() { super.run() while(true){ for(sck in srv.connections){ try { if (!sck.isClosed && sck.isConnected) { val scan = BufferedReader(InputStreamReader(sck.getInputStream())) val content = scan.readLine() if (content != null) { val json = JSONObject(content) val response = JSONObject() .put( "data", srv.onRequest(json.getInt("id"), json.getJSONObject("data"), sck) ) .put("id", json.getInt("id")) PrintStream(sck.getOutputStream()).println(response.toString()) } } }catch (ex : SocketException){ srv.connections.remove(sck) } } } } } abstract fun onRequest(reqid : Int, data : JSONObject, sck : Socket) : JSONObject fun start(){ connectionListener.start() inputListener.start() } fun stop(){ connectionListener.stop() inputListener.stop() connections.forEach { c -> c.close() } connections.clear() } }<file_sep>/src/main/kotlin/cf/dogo/server/bridge/Client.kt package cf.dogo.server.bridge import org.json.JSONObject import java.io.PrintStream import java.net.Socket import java.util.* import kotlin.collections.HashMap open class Client constructor(ip : String, port : Int, name : String){ private val requests = HashMap<Int, Request>() val name = name val ip = ip val port = port var socket : Socket? = null var input : Scanner? = null var output : PrintStream? = null val listener = InputListener(this) fun connect(){ for (i in 1..3){ println("Trying to connect to server...") try{ this.socket = Socket(ip, port) this.input = Scanner(this.socket?.getInputStream()) this.output = PrintStream(socket?.getOutputStream()) listener.start() println("Connected!") break } catch (ex : Exception) { println("Connection Failed!") } } } fun isAvailabe() = socket != null && socket?.isConnected as Boolean && !(socket?.isClosed as Boolean) fun request(request : JSONObject) : JSONObject { return if(isAvailabe()){ val req = Request() requests[req.id] = req output?.println(JSONObject().put("id", req.id).put("data", request)) val start = System.currentTimeMillis() while(req.response == null){ if((System.currentTimeMillis() - start) <= 12000) { Thread.sleep(100) } else { requests.remove(req.id) return JSONObject().put("desc", "time out").put("status", 408) } } req.response as JSONObject } else { JSONObject().put("desc", "socket is disconnected").put("status", 503) } } class InputListener(val con : Client) : Thread("${con.name} InputListener"){ override fun run() { while (true) { if(con.isAvailabe() && con.input?.hasNextLine() as Boolean){ val json = JSONObject(con.input?.nextLine()) if(json.has("id")) { val req = con.requests[json.getInt("id")] if (req != null) { req.response = json.getJSONObject("data") } } } } } } }<file_sep>/src/main/kotlin/cf/dogo/server/bridge/Request.kt package cf.dogo.server.bridge import org.json.JSONObject import java.util.* class Request { val id = Random().nextInt() var response : JSONObject? = null }<file_sep>/settings.gradle rootProject.name = 'DogoBridge' <file_sep>/build.gradle buildscript { ext.kotlinVersion = '1.2.50' repositories { mavenCentral() jcenter() } dependencies { classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}") classpath("org.jetbrains.kotlin:kotlin-allopen:${kotlinVersion}") } } apply plugin: 'kotlin' group 'cf.dogo.server.bridge' version '1.0-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() jcenter() } dependencies { compile 'org.json:json:20160810' compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlinVersion" } compileKotlin { kotlinOptions { freeCompilerArgs = ["-Xjsr305=strict"] jvmTarget = "1.8" } } compileTestKotlin { kotlinOptions { freeCompilerArgs = ["-Xjsr305=strict"] jvmTarget = "1.8" } } jar { enabled = true //from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } }
0fa0de11316cb50ba7af21f6851a57f4ec07325d
[ "Kotlin", "Gradle" ]
5
Kotlin
DogoBot/-OLD-DogoBridge
e11ba1a42cdceee9cf089bee71baa1cd6491360b
af4344ec6961855ebc661030b4d16ccb135a3811
refs/heads/master
<file_sep>var http = require("http"); //like include the module http //Cntrl+shift+C http.createServer(function(request,response){ var body = "<NAME>"; var len = body.length; response.writeHead(200,{ "Content-Type":'text/plain', "Content-Length":len }); response.end(body); }).listen(3000); console.log("Sever is running .The port is 3000");<file_sep>//for custom modules use ./name of file var hello = require('./hello.js') console.log(hello.sayHelloEng()) console.log(hello.sayHelloFrench())<file_sep>//for exporting it to other file // exports.sayHelloEng = function(){ // return "Hello Khushboo. This is exported"; // } // exports.sayHelloFrench = function(){ // return "French Khushboo. This is exported"; // } module.exports={ sayHelloEng :function(){ return "Hello Khushboo. This is exported"; }, sayHelloFrench :function(){ return "French Khushboo. This is exported"; }};
af9016d92d210a51672e50fc691dbe448e2f0eb0
[ "JavaScript" ]
3
JavaScript
khushboogithub/NodeJsPractice
9a9e8ccf6d4cba4411c63676c10d404f6e37666f
d5f5b62d2bb91518c76c28f7df4210a813b94714
refs/heads/master
<repo_name>ogormanm2/javaspringcontactmaint<file_sep>/src/net/ogormanm/spring3/controller/ContactController.java package net.ogormanm.spring3.controller; import java.util.ArrayList; import java.util.List; import net.ogormanm.spring3.form.Contact; import net.ogormanm.spring3.form.ContactForm; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.DriverManager; import java.sql.PreparedStatement; //import javax.naming.Context; //import javax.naming.InitialContext; //import javax.sql.DataSource; @Controller public class ContactController { private static Connection conn = null; private static Statement st = null; private static ResultSet rs = null; // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/ogormanm"; // Database credentials static final String USER = "springtest"; static final String PASS = "<PASSWORD>"; private static List<Contact> contacts = new ArrayList<Contact>(); static { //contacts.add(new Contact("Barack", "Obama", "<EMAIL>", "147-852-965")); //contacts.add(new Contact("George", "Bush", "<EMAIL>", "785-985-652")); //contacts.add(new Contact("Bill", "Clinton", "<EMAIL>", "236-587-412")); //contacts.add(new Contact("Ronald", "Reagan", "<EMAIL>", "369-852-452")); // Pull in the the DB contact dynamically try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(DB_URL, USER, PASS); st = conn.createStatement(); rs = st.executeQuery("SELECT * FROM contacts"); while (rs.next()) { int contact_id = rs.getInt("contact_id"); String firstName = rs.getString("firstname"); String lastName = rs.getString("lastname"); String email = rs.getString("email"); String phone = rs.getString("phone"); contacts.add(new Contact(contact_id, firstName, lastName, email, phone)); } } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } @RequestMapping(value = "/get", method = RequestMethod.GET) public ModelAndView get() { ContactForm contactForm = new ContactForm(); contactForm.setContacts(contacts); return new ModelAndView("add_contact" , "contactForm", contactForm); } @RequestMapping(value = "/save", method = RequestMethod.POST) public ModelAndView save(@ModelAttribute("contactForm") ContactForm contactForm) { System.out.println(contactForm); System.out.println(contactForm.getContacts()); List<Contact> contacts = contactForm.getContacts(); if(null != contacts && contacts.size() > 0) { ContactController.contacts = contacts; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(DB_URL, USER, PASS); st = conn.createStatement(); for (Contact contact : contacts) { System.out.printf("%s \t %s \n", contact.getFirstname(), contact.getLastname()); // Save contact update code here String query = "UPDATE contacts SET firstname=?,lastname=?,email=?," + "phone=? WHERE contact_id=?"; PreparedStatement preparedStmt = conn.prepareStatement(query); preparedStmt.setString(1, contact.getFirstname()); preparedStmt.setString(2, contact.getLastname()); preparedStmt.setString(3, contact.getEmail()); preparedStmt.setString(4, contact.getPhone()); preparedStmt.setInt(5, contact.getContact_id()); // execute the java preparedstatement preparedStmt.executeUpdate(); } } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return new ModelAndView("show_contact", "contactForm", contactForm); } } <file_sep>/README.md # javaspringcontactmaint <file_sep>/ogormanm.sql CREATE table contacts( contact_id INT NOT NULL AUTO_INCREMENT, firstname VARCHAR(100) NOT NULL, lastname VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL, phone VARCHAR(40) NOT NULL, submission_date DATE, PRIMARY KEY ( contact_id ) );
768dde60280bbc2323f94e3d589e09fc55331ad3
[ "Markdown", "Java", "SQL" ]
3
Java
ogormanm2/javaspringcontactmaint
eb53a23f04c62a108586168a0f6583ba57981a14
daad5984c1633a3a3fc9b0ee16e7621dfd51a1d0
refs/heads/master
<file_sep># Maintainer: <NAME> <<EMAIL>> # Taken from https://aur.archlinux.org/packages/mspds pkgname=mspds pkgver=3.5.0.1 pkgrel=1 pkgdesc="MSP430 Debug Stack. Contains a dynamic link library as well as embedded firmware that runs on the MSP-FET430UIF or the eZ430 emulators." arch=('i686' 'x86_64') url="http://processors.wiki.ti.com/index.php/MSPDS_Open_Source_Package" license=('custom:TI Open Source') group=('msp430') depends=('hidapi' 'boost') makedepends=('unzip' 'dos2unix') optdepends=('mspdebug-git') noextract=('slac460.zip') source=('http://www-s.ti.com/sc/techzip/slac460.zip' 'https://raw.githubusercontent.com/greigdp/msp430-mspds/master/v3.5.0.001.patch') prepare() { unzip slac460.zip find ./MSPDebugStack_OS_Package/ -type f -exec dos2unix -q '{}' \; patch -p1 -d MSPDebugStack_OS_Package < ../v3.5.0.001.patch } build() { cd "$srcdir/MSPDebugStack_OS_Package" make } package() { install -Dm644 "$srcdir/MSPDebugStack_OS_Package/libmsp430.so" "$pkgdir/usr/lib/libmsp430.so" } sha256sums=('5aa34a1ecea324c404dae0e71b1e552b4cd5536678beac4dacaffbad5ea5eae2' '564298885eb4cb13b647e1ef9a35be0369e6243b4f00750304de4c75b1d7a8c2')
5fc019a04040407c24934ddb8a7777c80e86b48e
[ "Shell" ]
1
Shell
greigdp/msp430-mspds
737454af043321797720d8baf7eb03b920e55f16
37736534ffcd367866cc23d3422cd05b35ee9b16
refs/heads/master
<file_sep>require 'YAML' module Configuration CONFIG_FILE = 'data/config.yml' def Configuration.load_configuration YAML::load_file CONFIG_FILE end end <file_sep>require 'dashing/dashboard' require 'test/unit' class TestDashboard < Test::Unit::TestCase def test_validate_integer assert_raise ArgumentError do Dashboard.validate_integer :test, nil end assert_raise ArgumentError do Dashboard.validate_integer :test, 'not_integer' end assert_equal 5, Dashboard.validate_integer(:test, 5), 'Successful call to validate_integer should return value' end def test_validate_layout config = {'rows' => 3, 'columns' => 0, 'width' => 1440, 'height' => 900, 'margin' => 10, 'dashes' => {'test' => {'row' => 0, 'column' => 0, 'width' => 2, 'height' => 2}}} assert_raise ArgumentError do Dashboard::Board.new config end config['columns'] = 3 dashboard = Dashboard::Board.new config assert_nothing_raised Dashboard::LayoutError do Dashboard.validate_layout dashboard end dash = {'row' => 0, 'column' => 2, 'width' => 1, 'height' => 3} dashboard.dashes << (Dashboard::Dash.new 'test_2', dash) assert_nothing_raised Dashboard::LayoutError do Dashboard.validate_layout dashboard end dashboard.dashes[1].width = 2 assert_raise Dashboard::LayoutError do Dashboard.validate_layout dashboard end dashboard.dashes[1].width = 1 dashboard.dashes[1].height = 4 assert_raise Dashboard::LayoutError do Dashboard.validate_layout dashboard end dashboard.dashes[1].height = 0 assert_raise Dashboard::LayoutError do Dashboard.validate_layout dashboard end dashboard.dashes[1].height = 3 dash = {'row' => 2, 'column' => 0, 'width' => 2, 'height' => 1} dashboard.dashes << (Dashboard::Dash.new 'test_3', dash) assert_nothing_raised Dashboard::LayoutError do Dashboard.validate_layout dashboard end dashboard.rows = 0 assert_raise Dashboard::LayoutError do Dashboard.validate_layout dashboard end end def test_initialization config = {'rows' => 2, 'columns' => 4, 'width' => 1440, 'height' => 900, 'margin' => 10} assert_raise ArgumentError do Dashboard::Board.new config end config['dashes'] = {'test' => {'row' => 1, 'column' => 1, 'width' => 2, 'height' => 2, 'data' => {'key' => 'value'}, 'color' => 'green'}} dashboard = Dashboard::Board.new config assert_equal 2, dashboard.rows assert_equal 4, dashboard.columns assert_equal 1440, dashboard.width assert_equal 900, dashboard.height assert_equal 10, dashboard.margin assert_nil dashboard.color, 'Did not specify dashboard color, should be nil' assert_equal 'Dashboard', dashboard.title, 'Did not specify dashboard title, should default to "Dashboard"' dashes = dashboard.dashes assert_equal 1, dashes.length, 'Should be only one dash in the dashboard list of dashes' dash = dashes[0] assert_equal 'test', dash.name assert_equal 'green', dash.color assert_equal 1, dash.row assert_equal 1, dash.column assert_equal 2, dash.width assert_equal 2, dash.height assert_nil dash.refresh_rate, 'Did not specify refresh rate, should be nil' dash_data = dash.data assert_equal 1, dash_data.length, 'Should be only one key-value data pair for the dash' assert_equal 'value', dash_data['key'] end end <file_sep>require File.join(File.dirname(__FILE__), %w[.. dash]) class Lister include Dash def self.get_erb_locals(data) Dash.validate_none_nil 'Lister', data, ['title', 'list'] data['ordered'] ||= false { :title => data['title'], :ordered => data['ordered'], :list => data['list'] } end end <file_sep>require 'dashing/dash' require 'dashing/dash/lister' require 'test/unit' class TestLister < Test::Unit::TestCase def test_get_erb_locals data = {'title' => 'Test List'} lister = Lister.new assert_raise Dash::DashConfigurationError do lister.get_erb_locals data end data['list'] = ['Item 1', 'Item 2', 'Item 3'] assert_nothing_raised Dash::DashConfigurationError do locals = lister.get_erb_locals data assert_equal 'Test List', locals[:title] assert_equal 3, locals[:list].length assert_equal false, locals[:ordered] end data['ordered'] = true assert_nothing_raised Dash::DashConfigurationError do locals = lister.get_erb_locals data assert_equal 'Test List', locals[:title] assert_equal 3, locals[:list].size assert_equal true, locals[:ordered] end end end <file_sep>module Dashboard class LayoutError < ArgumentError end def Dashboard.validate_integer(name, value) raise(ArgumentError, "Value for dashboard parameter #{name} was nil", caller) if value.nil? raise(ArgumentError, "Value for dashboard parameter #{name} was not an integer", caller) if !value.is_a? Integer value end def Dashboard.validate_layout(board) layout = Hash.new('') for param in ['rows', 'columns', 'width', 'height'] do if eval("board.#{param}") < 1 raise LayoutError, "Value '#{param}' for board invalid: less than 1", caller end end board.dashes.each do |dash| for param in ['row', 'column', 'width', 'height'] do threshold = 1 if param.eql? 'row' or param.eql? 'column' threshold = 0 end if eval("dash.#{param}") < threshold raise LayoutError, "Value '#{param}' for dash #{dash.name} invalid: less than #{threshold}", caller end end if dash.row + dash.height > board.rows raise LayoutError, "Dash #{dash.name} has too great of a height", caller end if dash.column + dash.width > board.columns raise LayoutError, "Dash #{dash.name} has too great of a width", caller end dash.row.upto(dash.row + dash.height - 1) do |i| dash.column.upto(dash.column + dash.width - 1) do |j| if !''.eql? layout[[i,j]] raise LayoutError, "Dash #{dash.name} overlaps with dash #{layout[[i,j]]} at row #{i} and column #{j}", caller else layout[[i, j]] = dash.name end end end end end class Board def initialize(params) @rows = Dashboard.validate_integer 'rows', params['rows'] @columns = Dashboard.validate_integer 'columns', params['columns'] @width = Dashboard.validate_integer 'width', params['width'] @height = Dashboard.validate_integer 'height', params['height'] @margin = Dashboard.validate_integer 'margin', params['margin'] @color = params['color'] params['title'] ||= 'Dashboard' @title = params['title'] if @rows < 1 or @columns < 1 or @height < 1 or @width < 1 raise ArgumentError, "None of row count, column count, height or width for board can be less than 1", caller end raise(ArgumentError, 'Configured board contained no dashes', caller) if params['dashes'].nil? @dashes = params['dashes'].keys.map do |dash| Dash.new dash, params['dashes'][dash] end @row_height = (@height - ((@rows - 1) * @margin)) / @rows @column_width = (@width - ((@columns - 1) * @margin)) / @columns end attr_accessor :rows, :columns, :width, :height, :margin, :color, :title, :dashes, :row_height, :column_width end class Dash def initialize(name, params) @name = name @type = params['type'] @row = Dashboard.validate_integer 'row', params['row'] @column = Dashboard.validate_integer 'column', params['column'] @width = Dashboard.validate_integer 'width', params['width'] @height = Dashboard.validate_integer 'height', params['height'] @refresh_rate = params['refresh_rate'] @data = params['data'] @color = params['color'] end attr_accessor :name, :type, :row, :column, :width, :height, :refresh_rate, :data, :color end end <file_sep>module Dash class DashConfigurationError < ArgumentError end def Dash.validate_none_nil(dash_name, data, fields) fields.each do |field| raise(DashConfigurationError, "Dash '#{dash_name}' missing field #{field}", caller) if data[field].nil? end end end <file_sep>#!/usr/bin/env ruby $LOAD_PATH << File.join(File.dirname(__FILE__), 'dashing') require 'configuration' require 'dashboard' require 'sinatra' require 'active_support/all' Dir[File.join(File.dirname(__FILE__), 'dashing', 'dash', '*.rb')].each { |file| require file } set :views, settings.root + '/../views' set :public_folder, File.dirname(__FILE__) + '/../public' configuration = Configuration.load_configuration dashboard = Dashboard::Board.new configuration Dashboard.validate_layout dashboard get '/dashboard' do erb :dashboard, :locals => { :board => dashboard } end dashboard.dashes.each do |dash| get "/dash/#{dash.name}" do locals = Object.const_get("#{dash.type.camelize}").send('get_erb_locals', dash.data) erb :"dashes/#{dash.type}", :locals => locals end end <file_sep>require 'dashing/dash' require 'test/unit' class TestDash < Test::Unit::TestCase def test_validate_none_nil data = {'key' => 'value', 'anotherKey' => 5} fields = ['key', 'anotherKey'] assert_nothing_raised Dash::DashConfigurationError do Dash.validate_none_nil 'dash', data, fields end data['oneMoreKey'] = nil assert_nothing_raised Dash::DashConfigurationError do Dash.validate_none_nil 'dash', data, fields end fields << 'oneMoreKey' assert_raise Dash::DashConfigurationError do Dash.validate_none_nil 'dash', data, fields end end end
5d51146cf9357dd686175f35f53264aa37598f10
[ "Ruby" ]
8
Ruby
jessex/dashing
a683130b27058369042bcf52806e9dd3daf75cd1
631eebd65c10aec1c98053db6866f4acfd54af8e
refs/heads/master
<file_sep>/* global $, jQuery, alerts */ $(function() { 'use strict'; // ======================================================================== // Is to toggle between forms (login - signup) when the user click on title // ======================================================================== $('.ls-page h1 span').click(function() { $(this).addClass('selected').siblings().removeClass('selected') $('.ls-page form').hide() $('.' + $(this).data('class')).fadeIn(200) }); });
a2359764a19f7e5a1c56e06c452909fb4382020a
[ "JavaScript" ]
1
JavaScript
AbdlrahmanSaberAbdo/Toggle-Form
91a7afd87fabe535d65d2e71cd33ab5c610ec04a
05377a1e49ff70903c66d61f899a37914d34759d
refs/heads/master
<repo_name>loudou140806/three<file_sep>/gulpfile.js var gulp = require('gulp'), del = require('del'), rename = require('gulp-rename'), less = require('gulp-less'), cssmin = require('gulp-cssmin'), prefix = require('gulp-autoprefixer'), jsmin = require('gulp-jsmin'), imgmin = require('gulp-imagemin'), juicer = require('gulp-juicer-js'), server = require('gulp-devserver'), essi = require('essi'), yargs = require('yargs').argv, htmlmin = require('gulp-htmlmin'); /** * 清除bulid目录 */ gulp.task('clean', function() { del(['bulid']); }); /** * CSS任务,less,加前缀,压缩 */ gulp.task('css', function() { gulp.src('src/**/*.less') .pipe(less()) .pipe(prefix()) .pipe(cssmin()) .pipe(rename(function( path ){ path.extname = '.css'; })) .pipe(gulp.dest('bulid/')); console.log('css编译成功'); }); /** * js任务 */ gulp.task('js', function() { gulp.src('src/**/*.js') .pipe(jsmin()) .pipe(gulp.dest('build/')); console.log('js编译成功'); }); /** * html 压缩 */ gulp.task('html', function() { gulp.src('src/**/*.html') .pipe(htmlmin('')) .pipe(gulp.dest('build/')); console.log('html编译成功'); }); gulp.task('default',['clean', 'css', 'js', 'html']); <file_sep>/src/home/index.js define('home/index', function(require, exports, moudle){ var instance = { init: function(){ alert(1); //创建渲染器 var render = new THREE.WebGLRenderer(); //设置canvans的大小为400*300 render.setSize(400, 300); //添加到body中 document.querySelector('body').appendChild(render.domElement); //设置背景颜色 render.setClearColor(0x000000); //创建场景 var scene = new THREE.Scene(); //创建照相机 var camera = new THREE.PerspectiveCamera( 45, 4 / 3, 1, 1000 ); camera.position.set(0, 0, 5); scene.add(camera); //创建长方体 var cube = new THREE.Mesh( new THREE.CubeGeometry( 1, 2, 3 ), new THREE.MeshBasicMaterial({ color: 0xff0000 }) ); scene.add(cube); render.render(scene, camera); } } instance.init(); })
33ab9e4affbad83217e09dd40c24c92bfc0a7d64
[ "JavaScript" ]
2
JavaScript
loudou140806/three
0150e50dba63142ccd353807ee905db237eade76
c192afc37320152ae03d591da4eb240407901e50
refs/heads/master
<repo_name>theoDELAS/Laravel_Game<file_sep>/Laravel_Game/database/migrations/2019_11_15_163908_create_personnages_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePersonnagesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('personnages', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('pseudo')->unique(); $table->integer('lvl_perso'); $table->integer('hp_base'); $table->integer('hp_current'); $table->integer('hp_max'); $table->integer('degats_base'); $table->integer('degats_current'); $table->integer('degats_max'); $table->integer('defense_base'); $table->integer('defense_current'); $table->integer('defense_max'); $table->integer('esquive_base'); $table->integer('esquive_current'); $table->integer('esquive_max'); $table->integer('histoire_completed'); $table->timestamps(); }); Schema::create('personnage_user', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('user_id'); $table->unsignedBigInteger('personnage_id'); $table->timestamps(); $table->unique(['user_id', 'personnage_id']); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->foreign('personnage_id')->references('id')->on('personnages')->onDelete('cascade'); }); Schema::create('classe_personnage', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('classe_id'); $table->unsignedBigInteger('personnage_id'); $table->timestamps(); $table->unique(['classe_id', 'personnage_id']); $table->foreign('classe_id')->references('id')->on('classe')->onDelete('cascade'); $table->foreign('personnage_id')->references('id')->on('personnages')->onDelete('cascade'); }); Schema::create('inventaire_personnage', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('inventaire_id'); $table->unsignedBigInteger('personnage_id'); $table->timestamps(); $table->unique(['inventaire_id', 'personnage_id']); $table->foreign('inventaire_id')->references('id')->on('inventaires')->onDelete('cascade'); $table->foreign('personnage_id')->references('id')->on('personnages')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('personnages'); } } <file_sep>/Laravel_Game/resources/docs/1.0/jeu.md # Nakarik ## Jeux sur navigateur style "Livre dont vous êtes le héros" - Création d'un compte - Création d'un personnage avec choix de sa classe - Choix de l'histoire = debut jeu ### Menu principal (hors connexion) : - Formulaire de connexion à son compte - Formulaire d'inscription - Leaderboard avec les meilleurs personnages ### Menu principal (connecté) : **Première connexion** * Vue la mise en place du monde (Full texte, une ou plusieurs pages) * Bouton qui amène au choix de la classe **Prochaine connexion** * Vue avec ses personnages créés (chaque personnage est unique) * Profil du personnage (pseudo, voir les items présents dans l'inventaire, voir son level) * Choix du personnage avec lequel on veut jouer * Choix de l'histoire à débuter ### Caractéristiques du jeu : - Système de leveling - Durant l'histoire, bouton faisant apparaitre un menu récapitulant la fiche du personnage - Histoire finie = level up dans le but d'un leaderboard - A chaque fin de page, une ou plusieurs page sont proposées ### Page admin - CRUD Equipement - CRUD Item - CRUD Classe ### Pour aller plus loin : - Système de difficulté de jeu avec différentes histoires, certaines réalisable avec un level minimum requis pour réussir - Gain d'xp à la fin d'évenements (à déterminer) - Feuille du personnage avec son avancement - Changement de background en fonction du type de page - Système d'achievement - Modification image compte - CRUD Histoire <file_sep>/CreationBDD.sql CREATE TABLE `classes` ( `id` int PRIMARY KEY AUTO_INCREMENT, `name` varchar(255), `hp` int, `degats` int, `defense` int, `esquive` int, `histoire` longtext, `created_at` timestamp ); CREATE TABLE `classe_personnage` ( `id` int PRIMARY KEY AUTO_INCREMENT, `classe_id` int, `personnage_id` int ); CREATE TABLE `equipements` ( `id` int PRIMARY KEY AUTO_INCREMENT, `personnage_id` int ); CREATE TABLE `inventaires` ( `id` int PRIMARY KEY AUTO_INCREMENT, `nombre_slot` id, `nombre_item` id ); CREATE TABLE `inventaire_items` ( `id` int PRIMARY KEY AUTO_INCREMENT, `item_id` int, `inventaire_id` int ); CREATE TABLE `inventaire_personnage` ( `id` int PRIMARY KEY AUTO_INCREMENT, `inventaire_id` int, `personnage_id` int ); CREATE TABLE `items` ( `id` int PRIMARY KEY AUTO_INCREMENT, `name` varchar(255), `quantite` int, `hp` int, `degats` int, `defense` int, `esquive` int ); CREATE TABLE `monstres` ( `id` int PRIMARY KEY AUTO_INCREMENT, `name` varchar(255), `hp` int, `degats` int, `defense` int, `esquive` int ); CREATE TABLE `personnages` ( `id` int PRIMARY KEY AUTO_INCREMENT, `pseudo` varchar(255), `lvl_perso` int, `hp_base` int, `hp_current` int, `hp_max` int, `degats_base` int, `degats_current` int, `degats_max` int, `defense_base` int, `defense_current` int, `defense_max` int, `esquive_base` int, `esquive_current` int, `esquive_max` int, `histoire_completed` int ); CREATE TABLE `personnage_user` ( `id` int PRIMARY KEY AUTO_INCREMENT, `user_id` int, `personnage_id` int ); CREATE TABLE `roles` ( `id` int PRIMARY KEY AUTO_INCREMENT, `name` varchar(255) ); CREATE TABLE `roles_user` ( `id` int PRIMARY KEY AUTO_INCREMENT, `role_id` int, `user_id` int ); CREATE TABLE `users` ( `id` int PRIMARY KEY AUTO_INCREMENT, `name` varchar(255), `email` email, `password` varchar(255) ); ALTER TABLE `users` ADD FOREIGN KEY (`id`) REFERENCES `personnages` (`id`); ALTER TABLE `users` ADD FOREIGN KEY (`id`) REFERENCES `roles` (`id`); ALTER TABLE `personnages` ADD FOREIGN KEY (`id`) REFERENCES `inventaires` (`id`); ALTER TABLE `classes` ADD FOREIGN KEY (`id`) REFERENCES `personnages` (`id`); ALTER TABLE `inventaires` ADD FOREIGN KEY (`id`) REFERENCES `items` (`id`); ALTER TABLE `personnages` ADD FOREIGN KEY (`id`) REFERENCES `classe_personnage` (`personnage_id`); ALTER TABLE `classes` ADD FOREIGN KEY (`id`) REFERENCES `classe_personnage` (`classe_id`); ALTER TABLE `items` ADD FOREIGN KEY (`id`) REFERENCES `inventaire_items` (`item_id`); ALTER TABLE `inventaires` ADD FOREIGN KEY (`id`) REFERENCES `inventaire_items` (`inventaire_id`); ALTER TABLE `personnages` ADD FOREIGN KEY (`id`) REFERENCES `inventaire_personnage` (`personnage_id`); ALTER TABLE `inventaires` ADD FOREIGN KEY (`id`) REFERENCES `inventaire_personnage` (`inventaire_id`); ALTER TABLE `personnages` ADD FOREIGN KEY (`id`) REFERENCES `personnage_user` (`personnage_id`); ALTER TABLE `users` ADD FOREIGN KEY (`id`) REFERENCES `personnage_user` (`user_id`); ALTER TABLE `roles` ADD FOREIGN KEY (`id`) REFERENCES `roles_user` (`role_id`); ALTER TABLE `users` ADD FOREIGN KEY (`id`) REFERENCES `roles_user` (`user_id`); ALTER TABLE `personnages` ADD FOREIGN KEY (`id`) REFERENCES `equipements` (`id`); <file_sep>/Laravel_Game/database/seeds/MonstresTableSeeder.php <?php use App\Monstre; use Illuminate\Database\Seeder; class MonstresTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Monstre::truncate(); Monstre::create([ 'name' => 'Loup', 'hp' => 150, 'degats' => 10, 'defense' => 12, 'esquive' => 8, ]); Monstre::create([ 'name' => 'Dragon', 'hp' => 100, 'degats' => 12, 'defense' => 10, 'esquive' => 10, ]); Monstre::create([ 'name' => 'Soldat', 'hp' => 80, 'degats' => 13, 'defense' => 8, 'esquive' => 10, ]); } } <file_sep>/Laravel_Game/app/Monstre.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Monstre extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name','hp', 'degats', 'defense', 'esquive' ]; } <file_sep>/Laravel_Game/app/Http/Controllers/PersonnageController.php <?php namespace App\Http\Controllers; use App\Classe; use App\Inventaire; use App\Item; use App\Monstre; use App\Personnage; use App\User; use Exception; use Illuminate\Contracts\View\Factory; use Illuminate\Http\Request; use Gate; use Illuminate\Http\Response; use Illuminate\View\View; class PersonnageController extends Controller { /** * Display a listing of the resource. * * @return Factory|View */ public function index() { // retourne la vue home avec comme parametres mon personnage stocké dans la variable $personnage return view('home'); } /** * Show the form for creating a new resource. * * @return Factory|View */ public function create() { // Selectionne mes classe $classes = Classe::all(); // retourne ma vue de création de personnage avec comme parametre mes classe stockées dans la variable $classe return view ('personnages.create')->with('classes', $classes); } /** * Store a newly created resource in storage. * * @return Response */ public function store() { // ma requete a besoin d'un pseudo pour etre valide request()->validate([ 'pseudo' => 'required', ]); $classe = Classe::get()->where('name', request('classe'))->first(); // crée mon personnage avec les valeurs de ma requete $personnage = Personnage::create([ 'pseudo' => request('pseudo'), // un personnage commence toujours lvl 0 'lvl_perso' => 0, // un personnage a complété 0 histoire à la création 'histoire_completed' => 0, // a le nombre de hp de base de sa classe 'hp_base' => $classe->hp, 'hp_current' => $classe->hp, 'hp_max' => $classe->hp, // a le nombre de degats de base de sa classe 'degats_base' => $classe->degats, 'degats_current' => $classe->degats, 'degats_max' => $classe->degats, // a le nombre de defense de base de sa classe 'defense_base' => $classe->defense, 'defense_current' => $classe->defense, 'defense_max' => $classe->defense, // a le nombre d'esquive de base de sa classe 'esquive_base' => $classe->esquive, 'esquive_current' => $classe->esquive, 'esquive_max' => $classe->esquive, ]); // Crée un inventaire $inventaire = Inventaire::create([ // nombre de slot disponnible 'nombre_slot' => 10, // l'inventaire est vide 'nombre_item' => 0, ]); // sauvegarde le personnage créé et envoie les infos dans la bdd $personnage->save(); // Selectionne l'user qui vient de créer ce personnage $user = User::select('id')->where('name', auth()->user()->name)->first(); // Assigne au personnage créé son utilisateur $personnage->user()->attach($user); // Selectionne la classe du personnage créé $classe = Classe::select('id')->where('name', request('classe'))->first(); // Assigne au personnage, sa classe $personnage->classe()->attach($classe); // Selectionne l'inventaire créé (le dernier) $newInventaire = Inventaire::select('id')->get()->last(); // Assigne au personnage, son inventaire $personnage->inventaire()->attach($newInventaire); // Si n'a pas le role 'first-users' if (Gate::denies('first-users')) { // alors il est redirigé vers la page home return redirect(route('home')); } // Selectionne tous les users $users = User::all(); // redirige vers la page 1 du tuto avec comme parametres mes users stockés dans la variable $users avec comme mot clé 'users' return redirect('tuto/debut')->with('users', $users); } /** * Display the specified resource. * * @param int $id * @return void */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return void */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param Request $request * @param int $id * @return void */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param Personnage $personnage * @return void * @throws Exception */ public function destroy(Personnage $personnage) { // Supprime le personnage $personnage->delete(); // Supprime la liaison entre le personnage et l'utilisateur à qui il appartient $personnage->user()->detach(); // Supprime l'inventaire du personnage $personnage->inventaire()->delete(); // Supprime la liaison entre l'inventaire et le personnage $personnage->inventaire()->detach(); // Supprime la liaison entre le personnage et sa classe $personnage->classe()->detach(); return redirect()->route('home'); } public function getItem() { $personnage = Personnage::get()->where('pseudo', request('pseudo'))->first(); $item = Item::get()->where('name', request('name'))->first(); $inventaire = Inventaire::get()->last(); $persoInventaire = $personnage->inventaire()->get()->first(); $itemsInventaire = $persoInventaire->items()->get()->all(); $personnage->update([ 'hp_current' => ($personnage->hp_current + $item->hp), 'hp_max' => ($personnage->hp_max + $item->hp), 'degats_current' => ($personnage->degats_current + $item->degats), 'degats_max' => ($personnage->degats_max + $item->degats), 'defense_current' => ($personnage->defense_current + $item->defense), 'defense_max' => ($personnage->defense_max + $item->defense), 'esquive_current' => ($personnage->esquive_current + $item->esquive), 'esquive_max' => ($personnage->esquive_max + $item->esquive), ]); $inventaire->update([ 'nombre_slot' => ($inventaire->nombre_slot - 1), 'nombre_item' => ($inventaire->nombre_item + 1), ]); $inventaire->items()->attach($item); $msg = [ 'success' => 'Objet équipé. Vos statistiques viennent d\'être modifiées' ]; return redirect()->back()->with($msg); } public function lancerCombat() { $monstre = Monstre::get()->where('name', request('name'))->first(); // Créé une nouvelle instance du monstre attaqué $newMob = new Monstre([ 'name' => $monstre->name, 'hp' => $monstre->hp, 'degats' => $monstre->degats, 'defense' => $monstre->defense, 'esquive' => $monstre->esquive, ]); $newMob->save(); // Récupère le personnage du joueur $personnage = Personnage::get()->where('pseudo', request('pseudo'))->first(); $nbTours = 1; $win = false; // Boucle du combat, chaque tour le personnage et le monstre se donne 1 coup while ($personnage->hp_current > 0 && $newMob->hp > 0 ) { // Si la defense du perso est inférieur aux degats du monstre, le personnage perd la soustraction des dégats du monstre moins sa defense if ($personnage->defense_current < $newMob->degats) { $personnage->update([ 'hp_current' => $personnage->hp_current - ($newMob->degats - $personnage->defense_current) ]); } // Same if ($newMob->defense < $personnage->degats_current) { $newMob->update([ 'hp' => $newMob->hp - ($personnage->degats_current - $newMob->defense) ]); } $nbTours++; } if ($personnage->hp_current <= 0) { $newMob->delete(); $msg = [ 'error' => 'Vous avez été vaincu. Votre adversaire a ' . $newMob->hp . '/' . $monstre->hp . ' PV. Il a gagné en ' . $nbTours . ' tours' ]; return redirect()->back()->with($msg); } elseif ($newMob->hp <= 0) { $newMob->delete(); $win = true; $msg = [ 'success' => 'Vous avez vaincu votre adversaire. Il vous reste ' . $personnage->hp_current . '/' . $personnage->hp_max . ' PV. Vous avez gagné en ' . $nbTours . ' tours' ]; return redirect()->back()->with($msg); } } } <file_sep>/Laravel_Game/resources/docs/1.0/overview.md # Laravel Game ## Contexte Ce --- - [Mise en place](#Mise_en_place) - [Prérequis](#Prérequis) <a name="Mise_en_place"></a> ## Mise en place <a name="Prérequis"></a> ### Prérequis * Installer: * Php * Comment vérifier si on a php: `php -v` * [Installation php](https://www.php.net/downloads.php) * Composer * [Installation composer](https://getcomposer.org/download/) * Npm * Comment vérifier si on a npm: `npm -v` * [Installation npm](https://nodejs.org/en/) * Laravel * [Installation laravel](https://laravel.com/docs/5.8/installation) * Un serveur avec une base de donnée * Ex: Wamp (windows) / Xampp (linux) / Mamp (mac) * [Cloner le repository](https://github.com/theoDELAS/Laravel_Game.git) * Créer une base de donnée avec le nom de base "laravel_game" * Créer une copie du fichier .env.example se situant dans le dossier laravel_game en retirant le ".example" * Aller dans le fichier .env que vous venez de créer * Modifier les lignes 9 à 14: ``` DB_CONNECTION="nom de votre sgbd(mariadb/mysql/...)" DB_HOST="adresse ip de votre serveur" DB_PORT="port d'écoute de votre serveur" DB_DATABASE="laravel_game" DB_USERNAME="username de votre bdd" DB_PASSWORD="<PASSWORD>" ``` * Ouvrer une console en étant dans le dossier "laravel_game" * Faire * `composer update` * `php artisan migrate` * `php artisan db:seed` * `php artisan key:generate` * `php artisan serv` <file_sep>/Laravel_Game/app/Personnage.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Notifications\Notifiable; class Personnage extends Model { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'pseudo', 'lvl_perso', 'hp_base', 'hp_current', 'hp_max', 'degats_base', 'degats_current', 'degats_max', 'defense_base', 'defense_current', 'defense_max', 'esquive_base', 'esquive_current', 'esquive_max', 'histoire_completed', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ ]; public function user() { return $this->belongsToMany('App\User'); } public function classe() { return $this->belongsToMany('App\Classe'); } public function inventaire() { return $this->belongsToMany('App\Inventaire'); } } <file_sep>/Laravel_Game/routes/web.php <?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Auth::routes(); Route::get('home', 'HomeController@index')->name('home'); Route::get('passer/{user}', 'TutoController@passerTuto')->name('passer'); Route::get('presentation', 'HomeController@presentation')->name('presentation'); Route::get('choixHistoire', 'HomeController@choixHistoire')->name('choixHistoire'); Route::get('tuto/introduction', 'TutoController@index')->name('introduction'); Route::get('tuto/debut', 'TutoController@debut')->name('tuto.debut'); Route::get('tuto/combatChevaux', 'TutoController@combatChevaux')->name('tuto.combatChevaux'); Route::get('tuto/combatSneaky', 'TutoController@combatSneaky')->name('tuto.combatSneaky'); Route::get('tuto/fin', 'TutoController@fin')->name('tuto.fin'); Route::post('tuto/getItem', 'PersonnageController@getItem')->name('personnage.getItem'); Route::post('tuto/lancerCombat', 'PersonnageController@lancerCombat')->name('personnage.lancerCombat'); Route::resource('personnage', 'PersonnageController'); Route::namespace('Admin')->prefix('admin')->name('admin.')->group(function (){ Route::resource('/users', 'UsersController', ['except' => ['create', 'store']]); Route::resource('/classe', 'ClasseController'); Route::resource('/monstres', 'MonstresController'); Route::resource('/items', 'ItemsController'); }); <file_sep>/Laravel_Game/app/Http/Controllers/TutoController.php <?php namespace App\Http\Controllers; use App\Classe; use App\Item; use App\Monstre; use App\Personnage; use App\Role; use App\User; use Faker\Provider\Person; use Gate; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class TutoController extends Controller { public function index() { $this->isFirstRedirect(); $users = User::all(); $classes = Classe::all(); return view('tuto.introduction')->with([ 'users'=> $users, 'classes' => $classes, ]); } public function debut() { $this->isFirstRedirect(); $personnage = Personnage::get()->last(); $items = Item::all(); $persoInventaire = $personnage->inventaire()->get()->first(); $itemsInventaire = $persoInventaire->items()->get()->all(); return view('tuto.debut')->with([ 'personnage'=> $personnage, 'items' => $items, 'itemsInventaire' => $itemsInventaire, ]); } public function combatChevaux() { $this->isFirstRedirect(); $personnage = Personnage::get()->last(); $items = Item::all(); $monstres = Monstre::all(); $persoInventaire = $personnage->inventaire()->get()->first(); $itemsInventaire = $persoInventaire->items()->get()->all(); return view('tuto.combatChevaux')->with([ 'personnage'=> $personnage, 'items' => $items, 'itemsInventaire' => $itemsInventaire, 'monstres' => $monstres, ]); } public function combatSneaky() { $this->isFirstRedirect(); $personnage = Personnage::get()->last(); $items = Item::all(); $monstres = Monstre::all(); $persoInventaire = $personnage->inventaire()->get()->first(); $itemsInventaire = $persoInventaire->items()->get()->all(); return view('tuto.combatSneaky')->with([ 'personnage'=> $personnage, 'items' => $items, 'itemsInventaire' => $itemsInventaire, 'monstres' => $monstres, ]); } public function fin() { $this->isFirstRedirect(); $personnage = Personnage::get()->last(); $items = Item::all(); $monstres = Monstre::all(); $persoInventaire = $personnage->inventaire()->get()->first(); $itemsInventaire = $persoInventaire->items()->get()->all(); $classesPerso = (Auth::user()->personnages()->get()->first()->classe); if ($classesPerso[0]->name == "Mage") { $arme = "Baton"; } elseif ($classesPerso[0]->name == "Guerrier") { $arme = "Epée"; } else { $arme = "Arc"; } return view('tuto.fin')->with([ 'personnage'=> $personnage, 'items' => $items, 'itemsInventaire' => $itemsInventaire, 'monstres' => $monstres, 'classesPerso' => $classesPerso, 'arme' => $arme ]); } public function passerTuto(User $user) { $userRole = Role::where('name', 'user')->first(); // enleve le role de l'user $user->roles()->detach(); // lui met son nouveau role 'user' $user->roles()->attach($userRole); //redirige vers la page 'home' return redirect(route('home')); } public function create() { // } public function store() { // } public function isFirstRedirect() { // Si le joueur à le status admin il est redirigé vers la page admin, si c'est un user normal il est dirigé vers sa page home if (Gate::denies('first-users')) { if (Gate::denies('admin-users')) { return redirect(route('home')); } return redirect(route('admin.users.index')); } } } <file_sep>/Laravel_Game/app/Http/Controllers/Admin/ClasseController.php <?php namespace App\Http\Controllers\Admin; use App\Classe; use App\Http\Controllers\Controller; use App\Personnage; use Exception; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Routing\Redirector; use Illuminate\View\View; class ClasseController extends Controller { /** * Display a listing of the resource. * * @return void */ public function index() { // } /** * Show the form for creating a new resource. * * @return Factory|View */ public function create() { // retourne ma vue de création de classes return view ('admin.classe.create'); } /** * Store a newly created resource in storage. * * @return RedirectResponse|Redirector */ public function store() { // ma requete a besoin de ces valeurs pour etre valide request()->validate([ 'name' => 'required', 'hp' => 'required', 'degats' => 'required', 'defense' => 'required', 'esquive' => 'required', 'histoire' => 'required', ]); $classe = Classe::create([ 'name' => request('name'), 'hp' => request('hp'), 'degats' => request('degats'), 'defense' => request('defense'), 'esquive' => request('esquive'), 'histoire' => request('histoire'), ]); $classe->save(); return redirect(route('admin.users.index')); } /** * Display the specified resource. * * @param Classe $classe * @return Factory|View */ public function show(Classe $classe) { return view('admin.classe.show')->with([ 'classe' => $classe, ]); } /** * Show the form for editing the specified resource. * * @param Classe $classe * @return Factory|View */ public function edit(Classe $classe) { return view('admin.classe.edit')->with([ 'classe' => $classe, ]); } /** * Update the specified resource in storage. * * @param Request $request * @param Classe $classe * @return Response */ public function update(Request $request, Classe $classe) { $classe->name = $request->name; $classe->hp = $request->hp; $classe->degats = $request->degats; $classe->defense = $request->defense; $classe->esquive = $request->esquive; $classe->histoire = $request->histoire; $classe->save(); return redirect()->route('admin.users.index'); } /** * Remove the specified resource from storage. * * @param Classe $classe * @return void * @throws Exception */ public function destroy(Classe $classe) { $classe->delete(); $classe->personnages()->detach(); $classe->personnages()->delete(); return redirect()->route('admin.users.index'); } } <file_sep>/Laravel_Game/app/Http/Controllers/HomeController.php <?php namespace App\Http\Controllers; use App\Role; use App\User; use Illuminate\Contracts\Support\Renderable; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Gate; use Illuminate\Routing\Redirector; use Illuminate\View\View; class HomeController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } public function presentation() { return view('presentation')->with([ ]); } /** * Show the application dashboard. * * @return Renderable */ public function index() { if (Gate::denies('basic-users')) { if (Gate::denies('admin-users')) { return redirect(route('presentation')); } return redirect(route('admin.users.index')); } $user = User::find(auth()->user()->id); return view('home', ['user' => $user]); } /** * @param User $user * @return Factory|View */ public function choixHistoire(User $user) { return view('home'); } } <file_sep>/Laravel_Game/database/seeds/ClassesTableSeeder.php <?php use App\Classe; use Illuminate\Database\Seeder; class ClassesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Classe::truncate(); Classe::create([ 'name' => 'Guerrier', 'hp' => 150, 'degats' => 10, 'defense' => 12, 'esquive' => 8, 'histoire' => 'Vous avez été élevé dans la caserne du fort Hekiparthos, creusé dans le mont Costpol, surplombant les terres de NakariK. Votre éducation vous a permis de perfectionner votre maniement des armes ainsi que d\'obtenir un physique à en faire pâlir les dieux. Pour votre 21ème anniversaire, votre maître d\'armes Sotark, vous a donné comme quête de parcourir le monde afin de perfectionner votre art.', ]); Classe::create([ 'name' => 'Archer', 'hp' => 100, 'degats' => 12, 'defense' => 10, 'esquive' => 10, 'histoire' => 'Vous avez grandi dans la magnifique forêt de Falyar, remplie d\'arbres géants habités par la tribu des Taëlyan. Votre mode de vie se basant sur la chasse, vous êtes rapidement devenu le meilleur archer de votre tribu. Votre chef, Ulore, vous a confié l\'étude de la désolation dans les terres de Gil\' Ead.', ]); Classe::create([ 'name' => 'Mage', 'hp' => 80, 'degats' => 15, 'defense' => 8, 'esquive' => 10, 'histoire' => 'Vous êtes né un soir d\'hiver sous les magnifiques aurores boréales de Nakarik, signe d\'une profonde aptitude pour la magie. Des érudits de l\'académie Doaxir sont donc venus vous chercher pour vous formez à ces arcanes et parfaire votre don. Vos années passées dans le royaume Ikaru, à flanc de falaise, n\'ont fait qu\'accroître vos envies de liberté et de voyage.', ]); } } <file_sep>/Laravel_Game/app/Http/Controllers/Admin/UsersController.php <?php namespace App\Http\Controllers\Admin; use App\Classe; use App\Http\Controllers\Controller; use App\Item; use App\Monstre; use App\Personnage; use App\User; use App\Role; use Exception; use Gate; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Routing\Redirector; use Illuminate\View\View; class UsersController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return RedirectResponse|Redirector */ public function index() { if (Gate::denies('admin-users')) { if (Gate::denies('basic-users')) { return redirect(route('presentation')); } return redirect(route('home')); } $users = User::all(); $classes = Classe::all(); $monstres = Monstre::all(); $items = Item::all(); return view('admin.users.index')->with([ 'users' => $users, 'classes' => $classes, 'monstres' => $monstres, 'items' => $items, ]); } public function show(User $user) { return view('admin.users.show')->with([ 'user' => $user, ]); } /** * Show the form for editing the specified resource. * * @param User $user * @return Factory|View */ public function edit(User $user) { if (Gate::denies('admin-users')) { return redirect(route('admin.users.index')); } $roles = Role::all(); return view('admin.users.edit')->with([ 'user' => $user, 'roles' => $roles ]); } /** * Update the specified resource in storage. * * @param Request $request * @param User $user * @return RedirectResponse */ public function update(Request $request, User $user) { $user->roles()->sync($request->roles); $user->name = $request->name; $user->email = $request->email; $user->save(); return redirect()->route('admin.users.index'); } /** * Remove the specified resource from storage. * * @param User $user * @return RedirectResponse|Redirector * @throws Exception */ public function destroy(User $user) { if (Gate::denies('admin-users')) { return redirect(route('admin.users.index')); } $user->roles()->detach(); $user->personnages()->detach(); $user->delete(); return redirect()->route('admin.users.index'); } } <file_sep>/Laravel_Game/app/Http/Controllers/Admin/MonstresController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Monstre; use Exception; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Routing\Redirector; use Illuminate\View\View; class MonstresController extends Controller { /** * Display a listing of the resource. * * @return Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return Factory|View */ public function create() { // retourne ma vue de création de monstres return view ('admin.monstres.create'); } /** * Store a newly created resource in storage. * * @return RedirectResponse|Redirector */ public function store() { // ma requete a besoin de ces valeurs pour etre valide request()->validate([ 'name' => 'required', 'hp' => 'required', 'degats' => 'required', 'defense' => 'required', 'esquive' => 'required', ]); $monstre = Monstre::create([ 'name' => request('name'), 'hp' => request('hp'), 'degats' => request('degats'), 'defense' => request('defense'), 'esquive' => request('esquive'), ]); $monstre->save(); return redirect(route('admin.users.index')); } /** * Display the specified resource. * * @param Monstre $monstre * @return Factory|View */ public function show(Monstre $monstre) { return view('admin.monstres.show')->with([ 'monstre' => $monstre, ]); } /** * Show the form for editing the specified resource. * * @param Monstre $monstre * @return Factory|View */ public function edit(Monstre $monstre) { return view('admin.monstres.edit')->with([ 'monstre' => $monstre, ]); } /** * Update the specified resource in storage. * * @param Request $request * @param Monstre $monstre * @return RedirectResponse */ public function update(Request $request, Monstre $monstre) { $monstre->name = $request->name; $monstre->hp = $request->hp; $monstre->degats = $request->degats; $monstre->defense = $request->defense; $monstre->esquive = $request->esquive; $monstre->save(); return redirect()->route('admin.users.index'); } /** * Remove the specified resource from storage. * * @param Monstre $monstre * @return RedirectResponse * @throws Exception */ public function destroy(Monstre $monstre) { $monstre->delete(); return redirect()->route('admin.users.index'); } } <file_sep>/Laravel_Game/database/seeds/ItemsTableSeeder.php <?php use App\Item; use Illuminate\Database\Seeder; class ItemsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Item::truncate(); Item::create([ 'name' => 'Epée', 'quantite' => 1, 'degats' => 15, 'defense' => 0, 'hp' => 0, 'esquive' => 0, ]); Item::create([ 'name' => 'Arc', 'quantite' => 1, 'degats' => 12, 'defense' => 0, 'hp' => 0, 'esquive' => 0, ]); Item::create([ 'name' => 'Baton', 'quantite' => 1, 'degats' => 16, 'defense' => 0, 'hp' => 0, 'esquive' => 0, ]); Item::create([ 'name' => 'Bouclier', 'quantite' => 1, 'degats' => 0, 'defense' => 10, 'hp' => 5, 'esquive' => 3, ]); Item::create([ 'name' => 'Casque', 'quantite' => 1, 'degats' => 0, 'defense' => 7, 'hp' => 5, 'esquive' => 1, ]); } }
30ab22b5424fbdbd30a84e7e4add592b1a0db1b4
[ "Markdown", "SQL", "PHP" ]
16
PHP
theoDELAS/Laravel_Game
b00f3ad99d9ad55a471d9752630a199a9c45c07c
2c672c6b4104edacb8ae5bf02351a22002dfbfa1
refs/heads/master
<repo_name>george-oakling/skaffold<file_sep>/pkg/skaffold/build/local/jib_test.go /* Copyright 2018 The Skaffold Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package local import ( "context" "testing" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" "github.com/GoogleContainerTools/skaffold/testutil" ) func TestGenerateMavenArgs(t *testing.T) { var testCases = []struct { in latest.JibMavenArtifact out []string }{ {latest.JibMavenArtifact{}, []string{"--non-recursive", "prepare-package", "jib:goal", "-Dimage=image"}}, {latest.JibMavenArtifact{Profile: "profile"}, []string{"--non-recursive", "prepare-package", "jib:goal", "-Dimage=image", "--activate-profiles", "profile"}}, {latest.JibMavenArtifact{Module: "module"}, []string{"--projects", "module", "--also-make", "package", "-Dimage=image"}}, {latest.JibMavenArtifact{Module: "module", Profile: "profile"}, []string{"--projects", "module", "--also-make", "package", "-Dimage=image", "--activate-profiles", "profile"}}, } for _, tt := range testCases { args := generateMavenArgs("goal", "image", &tt.in) testutil.CheckDeepEqual(t, tt.out, args) } } func TestMavenVerifyJibPackageGoal(t *testing.T) { var testCases = []struct { requiredGoal string mavenOutput string shouldError bool }{ {"xxx", "", true}, // no goals should fail {"xxx", "\n", true}, // no goals should fail; newline stripped {"dockerBuild", "dockerBuild", false}, {"dockerBuild", "dockerBuild\n", false}, // newline stripped {"dockerBuild", "build\n", true}, {"dockerBuild", "build\ndockerBuild\n", true}, } defer func(c util.Command) { util.DefaultExecCommand = c }(util.DefaultExecCommand) defer func(previous bool) { util.SkipWrapperCheck = previous }(util.SkipWrapperCheck) util.SkipWrapperCheck = true for _, tt := range testCases { util.DefaultExecCommand = testutil.NewFakeCmdOut("mvn --quiet --projects module jib:_skaffold-package-goals", tt.mavenOutput, nil) err := verifyJibPackageGoal(context.Background(), tt.requiredGoal, ".", &latest.JibMavenArtifact{Module: "module"}) if hasError := err != nil; tt.shouldError != hasError { t.Error("Unexpected return result") } } } func TestGenerateGradleArgs(t *testing.T) { var testCases = []struct { in latest.JibGradleArtifact out []string }{ {latest.JibGradleArtifact{}, []string{":task", "--image=image"}}, {latest.JibGradleArtifact{Project: "project"}, []string{":project:task", "--image=image"}}, } for _, tt := range testCases { command := generateGradleArgs("task", "image", &tt.in) testutil.CheckDeepEqual(t, tt.out, command) } } func TestGenerateJibImageRef(t *testing.T) { var testCases = []struct { workspace string project string out string }{ {"simple", "", "jibsimple"}, {"simple", "project", "jibsimple_project"}, {".", "project", "jib__d8c7cbe8892fe8442b7f6ef42026769ee6a01e67"}, {"complex/workspace", "project", "jib__965ec099f720d3ccc9c038c21ea4a598c9632883"}, } for _, tt := range testCases { computed := generateJibImageRef(tt.workspace, tt.project) testutil.CheckDeepEqual(t, tt.out, computed) } } <file_sep>/pkg/skaffold/util/process.go /* Copyright 2018 The Skaffold Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package util import ( "os/exec" "syscall" "github.com/pkg/errors" ) // IsTerminatedError returns true if the error is type exec.ExitError and the corresponding process was terminated by SIGTERM // This error is given when a exec.Command is ran and terminated with a SIGTERM. func IsTerminatedError(err error) bool { // unwrap to discover original cause err = errors.Cause(err) exitError, ok := err.(*exec.ExitError) if !ok { return false } ws := exitError.Sys().(syscall.WaitStatus) signal := ws.Signal() return signal == syscall.SIGTERM || signal == syscall.SIGKILL }
d6fcf8d348da5c8b060949cdd4f4a8fc7269d934
[ "Go" ]
2
Go
george-oakling/skaffold
b088cd88ee5bffc0e50736ac59ac7c00502fa4aa
18a25f4b2fe88ebfda6e6cc0a2c2353a5ddc7194
refs/heads/master
<file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { HomeComponent } from './component/home/home.component'; import { GeoFenceComponent } from './component/geo-fence/geo-fence.component'; import { ServicesComponent } from './component/services/services.component'; import { MarketingDataComponent } from './component/marketing-data/marketing-data.component'; import { ContactUsComponent } from './component/contact-us/contact-us.component'; import { TeamComponent } from './component/team/team.component'; const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'home', component: HomeComponent }, { path: 'geo-fence', component: GeoFenceComponent }, { path: 'services', component: ServicesComponent }, { path: 'marketing-data', component: MarketingDataComponent }, { path: 'contact-us', component: ContactUsComponent }, { path: 'team', component: TeamComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { MetaService } from '@ngx-meta/core'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { constructor(private readonly meta: MetaService) { console.warn("home"); this.meta.setTitle('Accurate and Affordable GEO Fencing Services'); this.meta.setTag('og:description', 'Monitize365 Residential and Business level GEO-fencing in the mobile display marketplace uses our new micro-targeting technology to pinpoint potential customers with unprecedented accuracy and efficiency.'); this.meta.setTag('twitter:description', 'Monitize365 Residential and Business level GEO-fencing in the mobile display marketplace uses our new micro-targeting technology to pinpoint potential customers with unprecedented accuracy and efficiency.'); this.meta.setTag('og:keyword', 'Monitize365, Residential Geofencing, Business Geofencing, Commercial Geofencing, Micro-targeting Technology, Monitize365 with Big Data'); this.meta.setTag('twitter:keyword', 'Monitize365, Residential Geofencing, Business Geofencing, Commercial Geofencing, Micro-targeting Technology, Monitize365 with Big Data'); this.meta.setTag('og:title', 'Accurate and Affordable GEO Fencing Services'); this.meta.setTag('twitter:title', 'Accurate and Affordable GEO Fencing Services'); this.meta.setTag('og:type', 'website'); this.meta.setTag('og:image', '../../assets/images/logo-fb.jpg'); this.meta.setTag('twitter:image', '../../assets/images/logo-twitter.jpg'); } ngOnInit() { window.scroll(0,0); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { MetaService } from '@ngx-meta/core'; @Component({ selector: 'app-geo-fence', templateUrl: './geo-fence.component.html', styleUrls: ['./geo-fence.component.css'] }) export class GeoFenceComponent implements OnInit { constructor(private readonly meta: MetaService) { this.meta.setTitle('Monitize365 - GeoFence'); this.meta.setTag('og:description', 'Monitize365 Residential and Business level GEO-fencing in the mobile display marketplace uses our new micro-targeting technology to pinpoint potential customers with unprecedented accuracy and efficiency.'); this.meta.setTag('twitter:description', 'Monitize365 Residential and Business level GEO-fencing in the mobile display marketplace uses our new micro-targeting technology to pinpoint potential customers with unprecedented accuracy and efficiency.'); this.meta.setTag('og:keyword', 'Monitize365, Residential Geofencing, Business Geofencing, Commercial Geofencing, Micro-targeting Technology, Monitize365 with Big Data'); this.meta.setTag('twitter:keyword', 'Monitize365, Residential Geofencing, Business Geofencing, Commercial Geofencing, Micro-targeting Technology, Monitize365 with Big Data'); this.meta.setTag('og:title', 'Monitize365 - GeoFence'); this.meta.setTag('twitter:title', 'Monitize365 - GeoFence'); this.meta.setTag('og:type', 'website'); this.meta.setTag('og:image', '../../assets/images/logo-fb.jpg'); this.meta.setTag('twitter:image', '../../assets/images/logo-twitter.jpg'); } ngOnInit() { window.scroll(0,0); } }
6f34f513508cc589e8516e38814f36ea73ca13f0
[ "TypeScript" ]
3
TypeScript
debasiskar-devel-007/monitize365-frontend-serverless
249243e1e30435a0fc2b23f902007ca3203e24c0
92427203a6f1ff812d3880f9d2cb4959ce9fc036
refs/heads/master
<file_sep>import React from "react"; const StepMoney = () => { return( <div className="step--container"> <h1> Informacja o pochodzeniu Twojego majątku i źródeł przychodów </h1> <h2> Musimy Cię o to zapytać z powodów formalnych, nie będziemy wykorzystywać tych informacji w innych celach </h2> <div className="select"> <select> <option> Wartość twojego majątku </option> <option>Poniżej 100 000 PLN</option> <option>Pomiędzy 100 000 - 500 000 PLN</option> <option> Powyżej 500 000 PLN </option> </select> </div> <div className="select"> <select> <option>Źródło majątku</option> <option> Wynagrodzenie </option> <option> przychody z udziaów w spółkach </option> <option> przychody inwestycyjne </option> <option> spadek/otrzymanie darowizny </option> <option> hazard </option> <option> kryptowaluty </option> <option> inne (tu miejsce do wpisania) ?? jak user to wybierze, to pokazujemy inputa czy jak?</option> </select> </div> <div className="select last-element"> <select> <option>Kraj pochodzenia majątku </option> <option>POlska</option> <option> Niemcy </option> <option> Chiny </option> <option> Francja </option> <option> Mongolia </option> <option> Luksemburg </option> <option> Finlandia </option> </select> </div> </div> ) } export default StepMoney;<file_sep>import React from "react"; const StepCode = () => { return( <div className="step--container"> <h1> Wprowadź kod weryfikacyjny </h1> <h2> kod został wprowadzony +48 123 456 789 </h2> <input className="input" type="text" inputMode="tel" /> <h3 className="last-element"> Jeśli nie dostałeś kodu możemy Ci go wysłać za 60 sek </h3> </div> ) } export default StepCode;<file_sep>import React from "react"; const StepAgreements = () => { return( <div className="step--container"> <h1 className="title"> Zaakceptuj oświadczenia </h1> <h2> których potrzebujemy, by otworzyć konto </h2> </div> ) } export default StepAgreements;<file_sep>import React from "react"; const StepEmail = () => { return( <div className="step--container"> <h1> Adres e-mail </h1> <h2> Będziemy go używać wyłącznie w celu prezazywania istotnych informacji. </h2> <h2> Będziesz mógł w dowolne chwili wyłączyć takie wiadomości </h2> <input className="input" inputmode="email" placeholder="email" /> <input className=" input last-element" inputmode="email" placeholder="powtorz email" /> </div> ) } export default StepEmail;<file_sep>import React from "react"; const StepNames = () => { return( <div className="step--container"> <h1> Imię i nazwisko </h1> <h2>formalne imię i nzwisko z dokumentu tożsamości</h2> <input className="input" type="text" placeholder="Imię lub imiona" /> <input className="input last-element" type="text" placeholder="Nazwisko" /> </div> ) } export default StepNames;<file_sep>import React, { useEffect } from "react"; const StepTest = () => { useEffect(() => { // Prefer camera resolution nearest to 1280x720. var constraints = { audio: false, video: { width: 1280, height: 720 } }; navigator.mediaDevices.getUserMedia(constraints) .then(function(mediaStream) { var video = document.querySelector('video'); video.srcObject = mediaStream; video.onloadedmetadata = function(e) { video.play(); }; }) .catch(function(err) { console.log(err.name + ": " + err.message); }); // always check for errors at the end. }, []) return( <div className="step--container"> <video /> </div> ) } export default StepTest;<file_sep>import React, { useState, useEffect } from "react" import "../styles/normalize.css" import "../styles/bulma.scss" import "../styles/layout.scss" import leftArrow from "../../static/left-arrow.svg" import hamburger from "../../static/hamburger.svg" import SwipeableViews from "react-swipeable-views" const Layout = ({ children }) => { const lastIndex = children.length - 1 const [modalIsOpen, setModalIsOpen] = useState() const [activeIndex, setActiveIndex] = useState(0) useEffect(() => { let html = document.getElementsByTagName( 'html' )[0]; if(modalIsOpen !== undefined) html.classList.toggle("overflow__hidden") }, [modalIsOpen]) return ( <> <div className="layout"> <div className="steps"> <ul> <li> number telefonu </li> <li> kod weryfikacyjny </li> <li> dane osobowe </li> <li> miejsce zamieszkania </li> <li> nazwisko mamy </li> <li> email </li> <li> źródła dochodu </li> </ul> </div> <div className="header"> <div className="header__buttons"> <img onClick={() => { if (activeIndex > 0) { setActiveIndex(i => i - 1) } }} className="header_back--arrow" src={leftArrow} /> <h1 className="title"> jakis title </h1> <img onClick={() => setModalIsOpen(true)} className="header_hamburger" src={hamburger} /> </div> <div> <progress class="progress is-primary" value={activeIndex} max={lastIndex + 1} > 15% </progress> </div> </div> <main> <form> <SwipeableViews index={activeIndex} onChangeIndex={i => setActiveIndex(i)} animateHeight={true} > {children} </SwipeableViews> </form> </main> <div class={`modal ${modalIsOpen && "is-active"}`}> <div class="modal-background"></div> <div class="modal-content"> <div className="box"> <h2> etataearfsdasrt test </h2> <h3> asdasdsadadfaf </h3> </div> </div> <button onClick={() => setModalIsOpen(false)} class="modal-close is-large" aria-label="close" ></button> </div> <div className="footer"> <button onClick={() => { if (activeIndex < lastIndex) { setActiveIndex(i => i + 1) }} } className="button is-primary footer_button--continue" > Continue </button> </div> </div> </> ) } export default Layout
804390553f0903af665459970b0cbd0da11bbfa7
[ "JavaScript" ]
7
JavaScript
PanLydka/test_onboarding
6e4294604a10b2766d6f498033db96f8c47ee2e0
76da6f2c4bbe5b3c770d9268e59c89a823202424
refs/heads/master
<file_sep>library(stringr) library(dplyr) connect_files = function(filenames){ df_tweets <- read_csv(filenames[1], col_names = TRUE) %>% dmap_at('text', conv_fun) print(dim(df_tweets)) for (filename in filenames[-c(1)]){ this_tweets <- read_csv(filename, col_names = TRUE) %>% dmap_at('text', conv_fun) df_tweets = rbind(df_tweets, this_tweets) print(dim(df_tweets)) } df_tweets } to_date <- function(x){ tryCatch({ as.Date(tolower(x), format='%a %b %d') }, error=function(cond) { return("___") }) } process_tweets = function(df_tweets){ df_tweets$created_at_date = lapply(df_tweets$created_at, to_date) df_tweets$text = lapply(df_tweets$text, tolower) df_tweets$created_at_date[is.na(df_tweets$created_at_date)] = "___" df_tweets = df_tweets[!c(df_tweets$created_at_date== "___"),] df_tweets = data.frame(df_tweets) df_tweets } produce_df = function(df_tweets, drivers_or_teams, FUN=mean){ dates = c() for (day in unique(df_tweets$created_at_date)){ dates = c(dates, day) } dates = sort(dates) cols = c() for (dd in unique(df_tweets$created_at_date)){ cols = c(cols, as.character(dd)) } print (cols) df = data.frame(matrix(nrow=length(drivers_or_teams), ncol=length(dates))) rownames(df) = drivers_or_teams colnames(df) = cols for (driver_or_team in drivers_or_teams){ driver_or_team = tolower(driver_or_team) this_df_tweets = df_tweets %>% filter(str_detect(text, driver_or_team)) driver_avgs = rep(NA, length(dates)) names(driver_avgs) = dates driver_avgs_init = tapply(this_df_tweets$sentiment, factor(unlist(this_df_tweets$created_at_date)), FUN) driver_avgs[names(driver_avgs_init)] = driver_avgs_init if (is.logical(driver_avgs)){ df[driver_or_team,] = rep(NA, length(dates)) } else { df[driver_or_team,] = driver_avgs } } return(df) } filenames = c("F1_tweets_W07_2017_sched.csv", "F1_tweets_W08_2017_sched.csv", "F1_tweets_W09_2017_sched.csv", "F1_tweets_W10_2017_sched.csv", "F1_tweets_W11_2017_sched.csv", "F1_tweets_W12_2017_sched.csv", "F1_tweets_W13_2017_sched.csv", "F1_tweets_W14_2017_sched.csv", "F1_tweets_W15_2017_sched.csv", "F1_tweets_W16_2017_sched.csv", "F1_tweets_W17_2017_sched.csv", "F1_tweets_W18_2017_sched.csv") df_tweets = connect_files(filenames) print(dim(df_tweets)) df_tweets = make_predictions(df_tweets) df_tweets = process_tweets(df_tweets) mode <- which.max(table(df_tweets$sentiment)) print (mode) df_tweets = df_tweets[df_tweets$sentiment<0.7021043 | df_tweets$sentiment>0.7021044,] drivers = c("@lewishamilton", "@valtteribottas", "@danielricciardo", "@max33verstappen", "@schecoperez", "@oconesteban", "@massafelipe19", "@lance_stroll", "@alo_oficial", "@svandoorne", "@dany_kvyat", "@Carlossainz55", "@Carlossainz", "@rgrosjean", "@kevinmagnussen", "@nicohulkenberg", "@jolyonpalmer", "@ericsson_marcus", "@pwehrlein") teams = c("@mercedesamgf1", "@redbullracing", "@scuderiaferrari", "@forceindiaf1", "@williamsracing", "@mclarenf1", "@tororossospy", "@haasf1team", "@renaultsportf1", "@sauberf1team") drivers_df = produce_df(df_tweets, tolower(drivers), mean) teams_df = produce_df(df_tweets, tolower(teams), mean) write.csv(drivers_df, "drivers_df.csv") write.csv(teams_df, "teams_df.csv") <file_sep> # This is the server logic for a Shiny web application. # You can find out more about building applications with Shiny here: # # http://shiny.rstudio.com # library(shiny) library(shinyjs) library(ggplot2) library(ggrepel) source("utils.R") drivers_data = loadData('driver') teams_data = loadData('team') my_min <- 1 my_max <- 3 # Define server logic for random distribution application shinyServer(function(input, output, session) { observe({ toggleState("driverCheckGroup", input$radio == "Drivers") toggleState("teamCheckGroup", input$radio == "Teams") }) #Allows only the selection of certain number of choices observe({ if(length(input$driverCheckGroup) > my_max) { showNotification(paste0("You can select up to ", my_max, " drivers"), duration = 5, type = "error") updateCheckboxGroupInput(session, "driverCheckGroup", selected= head(input$driverCheckGroup, my_max)) } if(length(input$driverCheckGroup) < my_min) { updateCheckboxGroupInput(session, "driverCheckGroup", selected= "@alo_oficial") } }) observe({ if(length(input$teamCheckGroup) > my_max) { showNotification(paste0("You can select up to ", my_max, " teams"), duration = 5, type = "error") updateCheckboxGroupInput(session, "teamCheckGroup", selected= head(input$teamCheckGroup, my_max)) } if(length(input$teamCheckGroup) < my_min) { updateCheckboxGroupInput(session, "teamCheckGroup", selected= "@scuderiaferrari") } }) #Check the file every 60 seconds pollRaces <- reactivePoll(10*1000, session, # This function returns the time that the file was last # modified checkFunc = function() { z = gs_ls() z[z$sheet_title=='races',]["updated"] }, # This function returns the content of the file valueFunc = function() { read_races() } ) # Reactive expression to generate the requested dataset. This is # called whenever the inputs change. data_d <- reactive({ if (input$radio == "Drivers"){ drivers_data[drivers_data[,2] %in% input$driverCheckGroup & drivers_data$Date>=input$date_range[1] & drivers_data$Date<=input$date_range[2],] } else { teams_data[teams_data[,2] %in% input$teamCheckGroup & teams_data$Date>=input$date_range[1] & teams_data$Date<=input$date_range[2],] } }) # Generate a plot of the data output$plot <- renderPlot({ d = data_d() races <- pollRaces() rr = merge(x = data.frame(Date = unique(d$Date)), y = races, by = "Date", all.x = TRUE) init_n_rows = nrow(rr) if (input$radio == "Drivers"){ rr = rr[rep(seq_len(nrow(rr)), length(input$driverCheckGroup)), ] rr[init_n_rows:dim(rr)[1],2] = NA plt <- ggplot(d, aes(x=Date, y=Sentiment, group=Driver)) + stat_smooth(aes(y = Sentiment, colour=Driver), se=F, span=input$smoother)+ geom_vline(data = races, aes(xintercept=as.numeric(races$Date)), linetype=4, colour="black") + theme(legend.position = "bottom") if (length(ggplot_build(plt)$data[[1]])==0){ plt <- ggplot(d, aes(x=Date, y=Sentiment, group=Driver)) + geom_line(aes(color=Driver),size=0.5)+ geom_point(aes(color=Driver))+ geom_vline(data = races, aes(xintercept=as.numeric(races$Date)), linetype=4, colour="black") + theme(legend.position = "bottom") } } else { rr = rr[rep(seq_len(nrow(rr)), length(input$teamCheckGroup)), ] rr[init_n_rows:dim(rr)[1],2] = NA plt <-ggplot(d, aes(x=Date, y=Sentiment, group=Team)) + stat_smooth(aes(y = Sentiment, colour=Team), se=F, span=input$smoother)+ geom_vline(data = races, aes(xintercept=as.numeric(races$Date)), linetype=4, colour="black") + theme(legend.position = "bottom") if (length(ggplot_build(plt)$data[[1]])==0){ plt <-ggplot(d, aes(x=Date, y=Sentiment, group=Team)) + geom_line(aes(color=Team),size=0.5)+ geom_point(aes(color=Team))+ geom_vline(data = races, aes(xintercept=as.numeric(races$Date)), linetype=4, colour="black") + theme(legend.position = "bottom") } } #Get the minimum of the y-axis min_y = ggplot_build(plt)$layout$panel_ranges[[1]]$y.range[1] plt <- plt + geom_label_repel(aes(x = rr$Date, y = rep(min_y, dim(rr)[1]), label = rr$GP), angle=0, size=4) plt }) output$dates <- renderUI({ d = data_d() sliderInput("date_range", "Date Range:", min = min(drivers_data$Date), max = max(drivers_data$Date), value = c(min(d$Date), max(d$Date)), width='100%') }) }) <file_sep># -*- coding: utf-8 -*- import pandas as pd import itertools import numpy as np import operator from sklearn.preprocessing import MinMaxScaler from keras.layers import (Input, Dense, Embedding, concatenate, Flatten, Subtract) from keras.layers.core import Dropout from keras.models import Model from keras import regularizers from keras.callbacks import EarlyStopping from keras.layers.normalization import BatchNormalization from keras.preprocessing.text import Tokenizer from keras.optimizers import SGD def transform_pairwise_all(X, y): X_new = [] y_new = [] comp_lst = [] races = [] y = np.asarray(y) if y.ndim == 1: y = np.c_[y, np.ones(y.shape[0])] comb = itertools.combinations(range(X.shape[0]), 2) for k, (i, j) in enumerate(comb): if y[i, 1] != y[j, 1]: # skip if same target or different group continue X_new.append(list((X.iloc[i] - X.iloc[j]).values)) y_new.append(-np.sign(y[i, 0] - y[j, 0])) comp_lst.append((y[i, 2], y[j, 2], y[i, 3], y[j, 3], y[i, 5], y[j, 5], y[i, 4], y[i, 1])) races.append(y[i, 1]) X_new.append(list((X.iloc[j] - X.iloc[i]).values)) y_new.append(-np.sign(y[j, 0] - y[i, 0])) comp_lst.append((y[j, 2], y[i, 2], y[j, 3], y[i, 3], y[j, 5], y[i, 5], y[j, 4], y[j, 1])) races.append(y[j, 1]) return np.asarray(X_new), np.asarray(y_new).ravel(), comp_lst, races if __name__ == '__main__': #################################### ########## Data reading ############ #################################### print ("Reading data...") df = pd.read_csv('data_sample.csv') #################################### ###### Data tranformations ######### #################################### print ("Transforming data...") df['gp'] = df['race'].apply(lambda x: x.split('_')[0]) df_d = df.iloc[np.random.permutation(len(df))] y = df_d[['result', 'race', 'driver', 'constructor', 'gp', 'constructor_year']] df_d = df_d.drop(['previous_race', 'result', 'race', 'driver', 'constructor', 'gp', 'constructor_year'], axis=1) X_trans, y_trans, comp_lst, races = transform_pairwise_all(df_d, y) y_trans[y_trans==-1] = 0 print ("Data has been transformed...") comp_lst_df = pd.DataFrame(comp_lst, columns = ['driver_1', 'driver_2', 'team_1', 'team_2', 'team_year_1', 'team_year_2', 'gp', 'race']) # Separate categorical data from the rest of the dataset driver_1 = np.array(comp_lst_df['driver_1']) driver_2 = np.array(comp_lst_df['driver_2']) team_1 = np.array(comp_lst_df['team_1']) team_2 = np.array(comp_lst_df['team_2']) team_year_1 = np.array(comp_lst_df['team_year_1']) team_year_2 = np.array(comp_lst_df['team_year_2']) gp = np.array(comp_lst_df['gp']) gp = np.array([i.replace(' ', '_') for i in gp]) # Scale numeric input mm = MinMaxScaler((-1,1)) X_train = mm.fit_transform(X_trans) y_train = y_trans.copy() ########################################### #### Tokenize the categorical inputs ##### ########################################### print ("Tokenizing data...") driver_tokenizer = Tokenizer(filters='!"#$%&()*+,-/:;<=>?@[\]^`{|}~ ') driver_tokenizer.fit_on_texts(driver_1) driver_1_encoded = driver_tokenizer.texts_to_sequences(driver_1) driver_2_encoded = driver_tokenizer.texts_to_sequences(driver_2) driver_1_encoded= np.array(driver_1_encoded) driver_2_encoded= np.array(driver_2_encoded) driver_vocab_size = len(driver_tokenizer.word_index) + 1 print('Driver vocabulary Size: %d' % driver_vocab_size) constructor_tokenizer = Tokenizer(filters='!"#$%&()*+,-/:;<=>?@[\]^`{|}~ ') constructor_tokenizer.fit_on_texts(team_1) constructor_1_encoded = constructor_tokenizer.texts_to_sequences(team_1) constructor_2_encoded = constructor_tokenizer.texts_to_sequences(team_2) constructor_1_encoded= np.array(constructor_1_encoded) constructor_2_encoded= np.array(constructor_2_encoded) constructor_vocab_size = len(constructor_tokenizer.word_index) + 1 print('Constructor vocabulary Size: %d' % constructor_vocab_size) constructor_year_tokenizer = Tokenizer(filters='!"#$%&()*+,-/:;<=>?@[\]^`{|}~ ') constructor_year_tokenizer.fit_on_texts(team_year_1) constructor_year_1_encoded = constructor_year_tokenizer.texts_to_sequences(team_year_1) constructor_year_2_encoded = constructor_year_tokenizer.texts_to_sequences(team_year_2) constructor_year_1_encoded= np.array(constructor_year_1_encoded) constructor_year_2_encoded= np.array(constructor_year_2_encoded) constructor_year_vocab_size = len(constructor_year_tokenizer.word_index) + 1 print('Constructor-year vocabulary Size: %d' % constructor_year_vocab_size) gp_tokenizer = Tokenizer(filters='!"#$%&()*+,-/ :;<=>?@[\]^`{|}~ ') gp_tokenizer.fit_on_texts(gp) gp_encoded = gp_tokenizer.texts_to_sequences(gp) gp_encoded = np.array(gp_encoded) gp_vocab_size = len(gp_tokenizer.word_index) + 1 print('GP vocabulary Size: %d' % gp_vocab_size) ########################################### ##### Model definition and training ###### ########################################## print ("Model training started...") inputs = Input(shape=(X_train.shape[1],)) x1 = Dropout(rate=0.1, seed=1)(inputs) x2 = Dense(50, activation='selu', kernel_initializer = 'lecun_normal')(x1) x2 = BatchNormalization()(x2) # Driver embedding driver_1_input = Input(shape=(1,), name='driver_1_input') driver_2_input = Input(shape=(1,), name='driver_2_input') driver_emb = Embedding(driver_vocab_size, 20, input_length=1, name='drivers_emb', embeddings_initializer = 'lecun_normal') driver_emb_1 = driver_emb(driver_1_input) driver_emb_1 = Flatten()(driver_emb_1) driver_emb_2 = driver_emb(driver_2_input) driver_emb_2 = Flatten()(driver_emb_2) driver_emb_diff = Subtract()([driver_emb_1, driver_emb_2]) # Constructor embedding team_1_input = Input(shape=(1,), name='team_1_input') team_2_input = Input(shape=(1,), name='team_2_input') team_emb = Embedding(constructor_vocab_size, 20, input_length=1, name='team_emb', embeddings_initializer = 'lecun_normal') team_emb_1 = team_emb(team_1_input) team_emb_1 = Flatten()(team_emb_1) team_emb_2 = team_emb(team_2_input) team_emb_2 = Flatten()(team_emb_2) team_emb_diff = Subtract()([team_emb_1, team_emb_2]) # GP embedding gp_input = Input(shape=(1,), name='gp_input') gp_emb = Embedding(gp_vocab_size, 10, input_length=1, name='gp_emb', embeddings_initializer = 'lecun_normal')(gp_input) gp_emb = Flatten()(gp_emb) # Constructor-year embedding team_year_1_input = Input(shape=(1,), name='team_year_1_input') team_year_2_input = Input(shape=(1,), name='team_year_2_input') team_year_emb = Embedding(constructor_year_vocab_size, 20, input_length=1, name='team_year_emb', embeddings_initializer = 'lecun_normal') team_year_emb_1 = team_year_emb(team_year_1_input) team_year_emb_1 = Flatten()(team_year_emb_1) team_year_emb_2 = team_year_emb(team_year_2_input) team_year_emb_2 = Flatten()(team_year_emb_2) team_year_emb_diff = Subtract()([team_year_emb_1, team_year_emb_2]) all_input = concatenate([x2, driver_emb_diff, team_emb_diff, gp_emb, team_year_emb_diff]) all_input = Dropout(rate=0.1, seed=1)(all_input) all_input = Dense(50, activation='selu', activity_regularizer=regularizers.l1(0.0001), kernel_initializer = 'lecun_normal')(all_input) predictions = Dense(1, activation='sigmoid', kernel_initializer = 'lecun_normal')(all_input) model = Model(inputs = [inputs, driver_1_input, driver_2_input, team_1_input, team_2_input, gp_input, team_year_1_input, team_year_2_input], outputs = predictions) model.compile(optimizer=SGD(lr=0.02, momentum=0.95, decay=0.0001, nesterov=True), loss='binary_crossentropy', metrics=['accuracy']) callbacks = [EarlyStopping(monitor='val_loss', patience=5, min_delta=0.0001, verbose=0)] model.fit([X_train, driver_1_encoded, driver_2_encoded, constructor_1_encoded, constructor_2_encoded, gp_encoded, constructor_year_1_encoded, constructor_year_2_encoded], y_train, batch_size=64, epochs=300, shuffle = True, verbose = 1, validation_split = 0.2, callbacks=callbacks) ########################################### ######## Save embedding weights ########## ########################################## print ("Saving embeddings and tokenizer values...") layer_names = ["drivers_emb", "team_emb", "team_year_emb", "gp_emb"] friendly_names = ["drivers_embeddings", "team_embeddings", "team_year_embeddings", "gp_embeddings"] for l, f in zip(layer_names, friendly_names): embeddings = model.get_layer(l).get_weights()[0] np.save(f + ".npy", embeddings) ########################################### ######## Save tokenizer values ########### ########################################## tokenizers = [driver_tokenizer, constructor_tokenizer, constructor_year_tokenizer, gp_tokenizer] friendly_names = ["drivers_names", "team_names", "team_year_names", "gp_names"] for t, f in zip(tokenizers, friendly_names): sorted_x = sorted(t.word_index.items(), key=operator.itemgetter(1)) names = ["----"] for i in sorted_x: names.append(i[0].title().replace('_', ' ').replace('Grand Prix', 'GP')) with open(f + ".txt", "w") as file: file.write(str(names)) <file_sep># FormulaOne2Vec Code for building the Neural Network and a small subset (both row-wise and column-wise) of the dataset used to calculate the embeddings of the blog post: http://www.f1-predictor.com/ 1. Run `keras_model.py` to build the model and save the resulting embeddings. 2. Execute `plot_embeddings.py` changing the filenames in rows 67 and 68 in order to plot the respective embeddings using UMAP. Otherwise, you can just download the learned embeddings and execute `plot_embeddings.py` to plot the respective embeddings using UMAP (you still need to change the filenames in rows 67 and 68). <file_sep>library(googlesheets) library(reshape2) library(Hmisc) loadData <- function(driver_or_team='driver') { # Grab the Google Sheet if (driver_or_team=='driver'){ sheet <- gs_key('key-to-drivers-data-file') } else { sheet <- gs_key('key-to-teams-data-file') } # Read the data data <- gs_read_csv(sheet, col_names=T) data <- data.frame(data) # Make data transformations n <- data$X1 data <- as.data.frame(t(data[,-1])) colnames(data) <- n data$Date = as.Date(sapply(row.names(data), removeFirst), format = '%m.%d.%Y') melted_data <- melt(data, id=c("Date")) names(melted_data) <- c("Date", capitalize(driver_or_team), "Sentiment") melted_data } removeFirst <- function(x) { substr(x,2,nchar(x)) } read_races <- function() { sheet <- gs_key('key-to-races-file') # Read the data data <- gs_read_csv(sheet, col_names=T) data <- data.frame(data) data$Date = as.Date(data$Date, format = '%d/%m/%Y') data }<file_sep># -*- coding: utf-8 -*- """ Created on Thu Jan 13 15:25:01 2017 @author: asterios """ from twitter.stream import TwitterStream, Timeout, HeartbeatTimeout, Hangup from twitter.oauth import OAuth from twitter.util import printNicely import time import pandas as pd import os import datetime from retrying import retry import ConfigParser import logging EXPORT_PATH = '/home/ec2-user/f1twitter/' def get_auth(): config_file_name = EXPORT_PATH + 'credentials - f1.ini' Config = ConfigParser.ConfigParser() Config.read(config_file_name) print Config.get("credentials", "consumer_key") auth = OAuth( consumer_key = Config.get("credentials", "consumer_key"), consumer_secret = Config.get("credentials", "consumer_secret"), token = Config.get("credentials", "token"), token_secret = Config.get("credentials", "token_secret") ) return auth def ConnectAndGetStream(stream_args, query_args, logger): print "Connecting to Twitter Streaming API..." logger.debug("Connecting to Twitter Streaming API...") auth = get_auth() twitter_stream = TwitterStream(auth=auth) try: tweet_iter = twitter_stream.statuses.filter(**query_args) print "Connected..." logger.debug("Connected...") except Exception as e: print "Error: " + str(e)[20:23] logger.debug("Error: " + str(e)[20:23]) return tweet_iter def saveTweets(tweet_lst, filename): #If file exists, open it, append new data and save again print "Saving tweets to " + filename + "..." logger.debug("Saving tweets to " + filename + "...") if os.path.exists(filename): print "File exists..." logger.debug("File exists...") try: existing = pd.read_csv(filename, encoding='utf-8') except: existing = pd.read_csv(filename, encoding='utf-8', engine='python') print existing.shape tweet_pd = pd.DataFrame.from_dict(tweet_lst) tweet_pd = pd.concat([existing, tweet_pd]) tweet_pd.to_csv(filename, index=False, encoding='utf-8') print tweet_pd.shape else: print "File does not exist..." logger.debug("File does not exist...") tweet_pd = pd.DataFrame.from_dict(tweet_lst) tweet_pd.to_csv(filename, index=False, encoding='utf-8') def StopIfLate(stop_at, case='', logger=''): now = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())) then = datetime.datetime.strptime(stop_at, "%Y-%m-%d %H:%M:%S") diff = now - then diff_minutes = (diff.days * 24 * 60) + (diff.seconds/60) if diff_minutes>=0: if case=='': print "Collection time has finished. Stopping collecting tweets." logger.debug("Collection time has finished. Stopping collecting tweets.") else: print "Time has ended. Stopping trying to collect tweets." logger.debug("Time has ended. Stopping trying to collect tweets.") return True else: return False def getStream(tweet_iter, filename, stop_at, logger): print "Will stop collecting data at " + stop_at logger.debug("Will stop collecting data at " + stop_at) count = 0 count_all = 0 tweet_lst = [] # Iterate over the stream for tweet in tweet_iter: tweet_dict={} if tweet is None: if count>0: saveTweets(tweet_lst, filename=filename) print "-- None --" logger.debug("-- None --") raise Exception("-- None --") elif tweet is Timeout: if count>0: saveTweets(tweet_lst, filename=filename) print "-- Timeout --" logger.debug("-- Timeout --") raise Exception("-- Timeout --") elif tweet is HeartbeatTimeout: if count>0: saveTweets(tweet_lst, filename=filename) print "-- Heartbeat Timeout --" logger.debug("-- Heartbeat Timeout --") raise Exception("-- Heartbeat Timeout --") elif tweet is Hangup: if count>0: saveTweets(tweet_lst, filename=filename) print "-- Hangup --" logger.debug("-- Hangup --") raise Exception("-- Hangup --") elif tweet.get('text'): count += 1 count_all += 1 tweet_dict['text'] = tweet['text'].encode('utf8') tweet_dict['time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(int(tweet['timestamp_ms'])/1000)) tweet_dict['created_at'] = tweet['created_at'] tweet_dict['lang'] = tweet['lang'] tweet_dict['followers_count'] = tweet['user']['followers_count'] tweet_dict['friends_count'] = tweet['user']['friends_count'] tweet_dict['location'] = tweet['user']['location'] tweet_dict['name'] = tweet['user']['name'] tweet_dict['retweeted'] = tweet['retweeted'] tweet_lst.append(tweet_dict) else: if count>0: saveTweets(tweet_lst, filename=filename) printNicely("-- Some data: " + str(tweet)) logger.debug("-- Some data: " + str(tweet)) raise Exception("-- Some data --") if count==20: print count_all logger.debug(count_all) saveTweets(tweet_lst, filename=filename) count = 0 tweet_lst = [] if StopIfLate(stop_at = stop_at): print count_all saveTweets(tweet_lst, filename=filename) return False @retry(wait_exponential_multiplier=1000, wait_exponential_max=600000) def runPipeline(tracked_hashtags, stop_at, logger): print "Started tracking: " + tracked_hashtags logger.debug("Started tracking: " + tracked_hashtags) stream_args = dict( timeout=90, heartbeat_timeout=90) query_args = dict() query_args['track'] = tracked_hashtags #Code to stop process when cannot connect to API and keeps trying forever if StopIfLate(stop_at = stop_at, case='error', logger=logger): return today = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())) weekNum = datetime.datetime.strftime(today,'%W') year = datetime.datetime.strftime(today,'%Y') filename = EXPORT_PATH + 'F1_tweets_W' + weekNum + '_' + year + '_sched.csv' tweet_iter = ConnectAndGetStream(stream_args, query_args, logger=logger) cond = getStream(tweet_iter, filename, stop_at = stop_at, logger=logger) if cond==False: return if __name__ == "__main__": #================================= #======Create Logger============== #================================= logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logger.propagate = False handler = logging.FileHandler(EXPORT_PATH + 'logfile.log') handler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') formatter.converter = time.gmtime handler.setFormatter(formatter) logger.addHandler(handler) tracked_hashtags = '#f1, #formula1, @lewishamilton, @valtteribottas, @danielricciardo, @max33verstappen, @schecoperez, @oconesteban, @massafelipe19, @lance_stroll, @alo_oficial, @svandoorne, @dany_kvyat, @Carlossainz55, @rgrosjean, @kevinmagnussen, @nicohulkenberg, @jolyonpalmer, @ericsson_marcus, @pwehrlein, @mercedesamgf1, @redbullracing, @scuderiaferrari, @forceindiaf1, @williamsracing, @mclarenf1, @tororossospy, @haasf1team, @renaultsportf1, @sauberf1team' logger.debug(tracked_hashtags) print str(datetime.datetime.fromtimestamp(time.mktime(time.gmtime()))) #Stop tomorrow at 04:00 AM GMT stop_at = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())) + datetime.timedelta(days=1) stop_at = stop_at.replace(hour=04, minute=00, second=0) stop_at = stop_at.strftime("%Y-%m-%d %H:%M:%S") runPipeline(tracked_hashtags = tracked_hashtags, stop_at = stop_at, logger=logger) #'#f1, f1' logger.debug("##########################") logger.removeHandler(handler) handler.close() logging.shutdown()<file_sep> # This is the user-interface definition of a Shiny web application. # You can find out more about building applications with Shiny here: # # http://shiny.rstudio.com # library(shiny) library(shinyjs) shinyUI(fluidPage( #This is only needed for hiding driver or team #check box group based on the radio button useShinyjs(), sidebarPanel( tags$head(tags$style(type="text/css", " #loadmessage { position: fixed; top: 0px; left: 0px; width: 100%; padding: 5px 0px 5px 0px; text-align: center; font-weight: bold; font-size: 100%; color: #FFFFFF; background-color: #009688; z-index: 105; } ")), conditionalPanel(condition="$('html').hasClass('shiny-busy')", tags$div("Loading...",id="loadmessage")), radioButtons("radio", label = h3("Drivers or team comparison"), choices = list("Drivers" = "Drivers", "Teams" = "Teams"), selected = "Drivers", inline=TRUE), fluidRow( column(6, checkboxGroupInput("driverCheckGroup", label = h3("Drivers"), choices = list("Hamilton" = "@lewishamilton", "Bottas" = "@valtteribottas", "Ricciardo" = "@danielricciardo", "Verstappen" = "@max33verstappen", "Perez" = "@schecoperez", "Ocon" = "@oconesteban", "Massa" = "@massafelipe19", "Stroll" = "@lance_stroll", "Alonso" = "@alo_oficial", "Vandoorne" = "@svandoorne", "Kvyat" = "@dany_kvyat", "Sainz" = "@carlossainz55", "Grosjean" = "@rgrosjean", "Magnussen" = "@kevinmagnussen", "Hulkenberg" = "@nicohulkenberg", "Palmer" = "@jolyonpalmer", "Ericsson" = "@ericsson_marcus", "Wehrlein" = "@pwehrlein"), selected = c("@lewishamilton", "@alo_oficial"))), column(6, checkboxGroupInput("teamCheckGroup", label = h3("Teams"), choices = list("Mercedes" = "@mercedesamgf1", "Ferrari" = "@scuderiaferrari", "Red Bull" = "@redbullracing", "Force India" = "@forceindiaf1", "Williams" = "@williamsracing", "McLaren" = "@mclarenf1", "<NAME>" = "@tororossospy", "Haas" = "@haasf1team", "Renault" = "@renaultsportf1", "Sauber" = "@sauberf1team"), selected = c("@mercedesamgf1", "@scuderiaferrari"))) ), sliderInput("smoother", label = h3("Smoothing"), min = 0, max = 1, value = 0.4, step=0.05), width = 4 ), mainPanel( tags$style(type="text/css", ".shiny-output-error { visibility: hidden; }", ".shiny-output-error:before { visibility: hidden; }" ), tabsetPanel( tabPanel("Sentiment Plot", plotOutput("plot"), uiOutput("dates")) ) ) ))<file_sep># MySQL to PostgreSQL Converter Adapted from https://github.com/lanyrd/mysql-postgresql-converter Works on Windows. Update the paths in rows 14 and 18. Change the filenames at the bottom of the script. <file_sep>make_predictions = function(df_tweets){ # preprocessing and tokenization it_tweets <- itoken(df_tweets$text, preprocessor = prep_fun, tokenizer = tok_fun, #ids = df_tweets$id, progressbar = TRUE) # creating vocabulary and document-term matrix dtm_tweets <- create_dtm(it_tweets, vectorizer) # transforming data with tf-idf dtm_tweets_tfidf <- fit_transform(dtm_tweets, tfidf) # loading classification model glmnet_classifier <- readRDS('glmnet_classifier.RDS') # predict probabilities of positiveness preds_tweets <- predict(glmnet_classifier, dtm_tweets_tfidf, type = 'response')[ ,1] # adding rates to initial dataset df_tweets$sentiment <- preds_tweets df_tweets }<file_sep># f1-predictor.com Code for anything posted on http://www.f1-predictor.com/ <file_sep># f1-predictor.com * Run train_model.R to train the model * Run make_predictions.R to load the function that outputs the predictions for a new dataset * Run per_driver.R that pre-processes the input data, makes the predictions and saves them as csv <file_sep># f1-predictor.com Code for the F1 sentiment analysis dashboard hosted here: http://www.f1-predictor.com/f1-sentiment-analysis-dashboard/ The blog post describing it is http://www.f1-predictor.com/f1-sentiment-analysis <file_sep># -*- coding: utf-8 -*- from matplotlib import pyplot import umap from adjustText import adjust_text import matplotlib.pyplot as plt import numpy as np import pandas as pd def plot_embeddings(names, embeddings, n_neighbors=10, min_dist=0.5, metric='euclidean', random_state=1, adjust_labels=False, d_names=None, highlighted_names=None): model = umap.UMAP(n_neighbors=min(len(names)-1, n_neighbors), min_dist=min_dist, metric=metric) vectors = model.fit_transform(embeddings) x, y = vectors[:, 0], vectors[:, 1] if d_names: s = pd.DataFrame([x, y, names]).T s.columns=['x','y','names'] s = s[s.names.isin(d_names)] s = s.sort_values('x') x = s['x'].tolist() y = s['y'].tolist() names = s['names'].tolist() plt.figure(figsize=(20, 15)) scatter = plt.scatter(x, y) annotations = [] for x_i, y_i, n_i in zip(x,y, names): if highlighted_names and n_i in highlighted_names: annotations.append(plt.text(x_i,y_i, n_i, color='red')) elif 'Verstappen' in n_i: annotations.append(plt.text(x_i,y_i, n_i, color='green')) elif 'Rosberg' in n_i: annotations.append(plt.text(x_i,y_i, n_i, color='blue')) elif 'Mf1' in n_i or 'Spyker' in n_i: annotations.append(plt.text(x_i,y_i, n_i, color='green')) elif 'Mclaren' in n_i and any([i in n_i for i in ['2015', '2016', '2017', '2018']]): annotations.append(plt.text(x_i,y_i, n_i, color='orange')) else: annotations.append(plt.text(x_i,y_i, n_i)) adjust_text(annotations, x=x, y=y) pyplot.show() return x, y def plot_stuff(names_txt, embs_file, exclude_names, highlighted_names): with open(names_txt, "r") as file: names = eval(file.readline()) embeddings = np.load(embs_file) d_names = [i for i in names if i not in exclude_names] x, y = plot_embeddings(names, embeddings, n_neighbors=10, min_dist=0.6, metric='euclidean', random_state=1, adjust_labels=True, d_names=d_names, highlighted_names=highlighted_names) return names if __name__ == '__main__': names_txt = "drivers_names.txt" embs_file = "drivers_embeddings.npy" # List of names you want to exclude from plotting exclude_names = ['----', 'Grassi', 'Jones'] # List of names you want to highlight with red color on the plot highlighted_names = ['Alonso', 'Hamilton', 'Vettel'] names = plot_stuff(names_txt, embs_file, exclude_names, highlighted_names)
bf68a765351b1ddbbb16e02fed2cb49bd8947452
[ "Markdown", "Python", "R" ]
13
R
asstergi/f1-predictor
c45b54bd8baf2ada8a444caae15b21e1d7de2b5a
272dd2179910c9849deb1c2d8db868594b23db99
refs/heads/main
<file_sep>package com.example.testapp.entity; public class RegisterResponseUser { private String server_message; private String status; public String getServer_message() { return server_message; } public void setServer_message(String server_message) { this.server_message = server_message; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public String toString() { return "RegisterResponseUser{" + "server_message='" + server_message + '\'' + ", status='" + status + '\'' + '}'; } }<file_sep>package com.example.testapp.constants; /** * Created by COBB on 11/15/2016. */ public class Constant { /** Preference kay***/ public static final String PREF_EMAIL="email"; public static final String PREF_PASSWORD="<PASSWORD>"; /** Preference msg***/ public static final String MSG_NOT_EMPTY="Please fil all data"; } <file_sep>package com.example.testapp.entity.response; import com.example.testapp.entity.LoginResponseUser; import com.example.testapp.entity.RegisterResponseUser; import com.example.testapp.entity.User; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.POST; public interface ApiClient { @POST("userService/login") Call<LoginResponseUser> login_inUser(@Body User User); @POST("userService/registration") Call<RegisterResponseUser>register_user(@Body User user ); } <file_sep>package com.example.testapp.entity.response; import com.google.gson.Gson; import java.io.IOException; import java.util.concurrent.TimeUnit; import okhttp3.Authenticator; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.Route; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class ServiceGenerator { private static final String API_BASE_URL="http://192.168.0.35:8080/Q-Mate/rest/"; private static OkHttpClient.Builder httpClient=new OkHttpClient.Builder(); private static Retrofit.Builder builder = new Retrofit.Builder() .baseUrl(API_BASE_URL) .addConverterFactory(GsonConverterFactory.create(new Gson())); private ServiceGenerator(){ } public static <S> S createService(Class<S> serviceClass){ httpClient.authenticator(new Authenticator() { @Override public Request authenticate(Route route, Response response) throws IOException { return response.request().newBuilder().build(); } }); HttpLoggingInterceptor httpLoggingInterceptor=new HttpLoggingInterceptor(); httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient.addInterceptor(httpLoggingInterceptor); Retrofit retrofit; OkHttpClient client=httpClient.build(); httpClient.connectTimeout(5, TimeUnit.MINUTES); httpClient.readTimeout(5,TimeUnit.MINUTES); httpClient.writeTimeout(5,TimeUnit.MINUTES); retrofit=builder.client(client).build(); return retrofit.create(serviceClass); } } <file_sep>package com.example.testapp.data; import com.example.testapp.entity.response.ApiClient; import com.example.testapp.entity.response.ServiceGenerator; import com.example.testapp.preferance.AppPreference; public class DataProcessController { private static volatile com.example.testapp.data.DataProcessController instance = null; private final AppPreference appPreference = new AppPreference(); private ApiClient apiClient = null; public DataProcessController() { apiClient = ServiceGenerator.createService(ApiClient.class); } public static com.example.testapp.data.DataProcessController getDataProcessController() { if (instance == null) { // double check synchronized (com.example.testapp.data.DataProcessController.class) { if (instance == null) { instance = new com.example.testapp.data.DataProcessController(); } } } return instance; } public AppPreference getPreference() { return appPreference; } public ApiClient getApiClient() { return apiClient; } } <file_sep>package com.example.testapp.constants; /** * Created by A0047 on 7/4/2017. */ public class Constants { public static final String API_STATUS_SUCCESS = "success"; public static final String API_STATUS_FAILED = "failed"; public static final String API_MESSAGE_NO_RESPONSE = "No Response From Server.Please Try Again Later"; public static final String REST_ERROR_API_ERROR ="Unable To Communicate With Server.Please Verify Your Connection" ; public static final String REST_ERROR_NETWORK = "Connection Problem Please Try Again Later"; } <file_sep>package com.example.testapp.entity; public class User { private String user_phone_no; private String password; private String user_email_id; private String user_firstname; private String user_lastname; private String user_address; private String user_village; private String user_district; public String getUser_phone_no () { return user_phone_no; } public void setUser_phone_no (String user_phone_no) { this.user_phone_no = user_phone_no; } public String getPassword () { return password; } public void setPassword (String password) { this.password = <PASSWORD>; } public String getUser_email_id () { return user_email_id; } public void setUser_email_id (String user_email_id) { this.user_email_id = user_email_id; } public String getUser_firstname () { return user_firstname; } public void setUser_firstname (String user_firstname) { this.user_firstname = user_firstname; } public String getUser_lastname () { return user_lastname; } public void setUser_lastname (String user_lastname) { this.user_lastname = user_lastname; } public String getUser_address () { return user_address; } public void setUser_address (String user_address) { this.user_address = user_address; } public String getUser_village () { return user_village; } public void setUser_village (String user_village) { this.user_village = user_village; } public String getUser_district () { return user_district; } public void setUser_district (String user_district) { this.user_district = user_district; } @Override public String toString() { return "User [user_phone_no = "+user_phone_no+", password = "+<PASSWORD>+", user_email_id = "+user_email_id+", user_firstname = "+user_firstname+", user_lastname = "+user_lastname+", user_address = "+user_address+", user_village = "+user_village+", user_district = "+user_district+"]"; } }
6445d69f34aa06ab49f79902b54972f897f39efb
[ "Java" ]
7
Java
pajva/WebServiceDemo
8fa30f1c6cc5727e4df20249d7e6746c5e2a799b
be50f14c4d7a9cdb3c87a83efccc0999c725116b
refs/heads/master
<file_sep>#pragma once #include "StackImplementation.h" #include "../LinkedList/LinkedList.h" template <typename ValueType> class ListStack: virtual public StackImplementation<ValueType>, public LinkedList<ValueType> { public: ListStack(); explicit ListStack(const ListStack& copyList); ListStack& operator=(const ListStack& copyVec); // Конструктор копирования присваиванием ListStack(ListStack&& moveVec) noexcept; ListStack& operator=(ListStack&& moveVec) noexcept; // добавление в конец void push(const ValueType& value) override; // удаление с хвоста void pop() override; // посмотреть элемент в хвосте const ValueType& top() const override; // проверка на пустоту bool isEmpty() const override; // размер size_t size() const override; // деструктор ~ListStack()override ; }; template <typename ValueType> ListStack<ValueType>::ListStack(): LinkedList<ValueType>(){} template <typename ValueType> ListStack<ValueType>::~ListStack() {} template <typename ValueType> ListStack<ValueType>::ListStack(const ListStack<ValueType> &copyList):LinkedList<ValueType>(copyList){} template <typename ValueType> ListStack<ValueType> &ListStack<ValueType>::operator=(const ListStack<ValueType> &copyList) { if(this == &copyList){ return *this; } LinkedList<ValueType>::operator=(copyList); return *this; } template <typename ValueType> ListStack<ValueType>::ListStack(ListStack<ValueType> &&moveList) noexcept:LinkedList<ValueType>(std::move(moveList)){} template <typename ValueType> ListStack<ValueType> &ListStack<ValueType>::operator=(ListStack<ValueType> &&moveList) noexcept { if(this == &moveList){ return *this; } LinkedList<ValueType>::operator=(std::move(moveList)); return *this; } template <typename ValueType> void ListStack<ValueType>::push(const ValueType &value) { (*this).pushBack(value); } template <typename ValueType> void ListStack<ValueType>::pop() { this->removeBack(); } template <typename ValueType> const ValueType &ListStack<ValueType>::top() const { return (*this)[this->size() - 1]; } template <typename ValueType> bool ListStack<ValueType>::isEmpty() const { return this->LinkedList<ValueType>::size() == 0; } template <typename ValueType> size_t ListStack<ValueType>::size() const { return LinkedList<ValueType>::size(); } <file_sep>#pragma once // потом поменяем на шаблоны #include <cstdlib> #include <stdexcept> //using ValueType = double; template <typename ValueType> class LinkedList{ class Node{ public: Node(const ValueType& value, Node* next = nullptr); ~Node(); ValueType value; Node* next; friend class LinkedList; private: void insertNext(const ValueType& value); void insertNext(Node* node); void removeNext(); }; public: //// LinkedList(); LinkedList(const LinkedList& copyList); LinkedList& operator=(const LinkedList& copyList); LinkedList(LinkedList&& moveList) noexcept; LinkedList& operator=(LinkedList&& moveList) noexcept; ~LinkedList(); //// // доступ к значению элемента по индексу ValueType& operator[](const size_t pos) const; // доступ к узлу по индексу LinkedList::Node* getNode(const size_t pos) const; // вставка элемента по индексу, сначала ищем, куда вставлять (О(n)), потом вставляем (O(1)) void insert(const size_t pos, const ValueType& value); // вставка элемента после узла, (O(1)) void insertAfterNode(Node* node, const ValueType& value); // вставка в конец (О(n)) void pushBack(const ValueType& value); // вставка в начало (О(1)) void pushFront(const ValueType& value); // удаление /*Отсюда пишу сам*/ void remove(const size_t pos);//+ void removeNextNode(Node* node);//+ void removeFront();//+ void removeBack();//+ // поиск, О(n) long long int findIndex(const ValueType& value) const;//+ Node* findNode(const ValueType& value) const;//+ // разворот списка void reverse(); // изменение текущего списка LinkedList reverse() const; // полчение нового списка (для константных объектов) LinkedList getReverseList() const; // чтобы неконстантный объект тоже мог возвращать новый развернутый список size_t size() const; /*Вспомогательные методы, НЕ МЕНЯЮТ _SIZE СПИСКА*/ protected: void pushBackNode(Node *node); void pushFrontNode(Node *node); void insert(const size_t pos, Node *node); private: Node* _head; size_t _size; void forceNodeDelete(Node* node); }; template<typename ValueType> LinkedList<ValueType>::Node::Node(const ValueType& value, Node* next) { this->value = value; this->next = next; } template<typename ValueType> LinkedList<ValueType>::Node::~Node(){} template<typename ValueType> void LinkedList<ValueType>::Node::insertNext(const ValueType& value) { Node* newNode = new Node(value, this->next); this->next = newNode; } template<typename ValueType> void LinkedList<ValueType>::Node::removeNext() { if(this->next){ Node* removeNode = this->next; Node* newNext = removeNode->next; this->next = newNext; removeNode->next = nullptr; delete removeNode; } } template<typename ValueType> void LinkedList<ValueType>::Node::insertNext(LinkedList::Node *node) { Node* tmp = this->next; this->next = node; node->next = tmp; } template<typename ValueType> LinkedList<ValueType>::LinkedList() : _head(nullptr), _size(0) { } template<typename ValueType> LinkedList<ValueType>::LinkedList(const LinkedList& copyList) { this->_size = copyList._size; if (this->_size == 0) { this->_head = nullptr; return; } this->_head = new Node(copyList._head->value); Node* currentNode = this->_head; Node* currentCopyNode = copyList._head; while (currentCopyNode->next) { currentNode->next = new Node(currentCopyNode->next->value);//fixed currentCopyNode = currentCopyNode->next; currentNode = currentNode->next; } currentNode->next = nullptr;//на всякий случай } template<typename ValueType> LinkedList<ValueType>& LinkedList<ValueType>::operator=(const LinkedList& copyList){ if (this == &copyList) { return *this; } forceNodeDelete(_head);//удалить весь текущий список this->_head = new Node(copyList._head->value);//копирование головы Node* currentNode = this->_head; Node* currentCopyNode = copyList._head; while (currentCopyNode->next) { currentNode->next = new Node(currentCopyNode->next->value); currentCopyNode = currentCopyNode->next; currentNode = currentNode->next; } currentNode->next = nullptr;//на всякий случай _size = copyList._size; return *this; } template<typename ValueType> LinkedList<ValueType>::LinkedList(LinkedList&& moveList) noexcept { this->_size = moveList._size; this->_head = moveList._head; moveList._size = 0; moveList._head = nullptr; } template<typename ValueType> LinkedList<ValueType>& LinkedList<ValueType>::operator=(LinkedList&& moveList) noexcept { if (this == &moveList) { return *this; } forceNodeDelete(_head); this->_size = moveList._size; this->_head = moveList._head; moveList._size = 0; moveList._head = nullptr; return *this; } template<typename ValueType> LinkedList<ValueType>::~LinkedList() { forceNodeDelete(_head); } template<typename ValueType> ValueType& LinkedList<ValueType>::operator[](const size_t pos) const { return getNode(pos)->value; } template<typename ValueType> typename LinkedList<ValueType>::Node* LinkedList<ValueType>::getNode(const size_t pos) const { if (pos < 0) { throw std::out_of_range("Index of required node is " "out of range\n"); } else if (pos >= this->_size) { throw std::out_of_range("Index of required node is" "out of range\n"); } Node* bufNode = this->_head; for (int i = 0; i < pos; ++i) { bufNode = bufNode->next; } return bufNode; } template<typename ValueType> void LinkedList<ValueType>::insert(const size_t pos, const ValueType& value) { if (pos < 0) { throw std::out_of_range("Index of required position is " "out of range\n"); } else if (pos > this->_size) { throw std::out_of_range("Index of required position is " "out of range\n"); } if (pos == 0) { pushFront(value); } else { Node* bufNode = this->_head; for (size_t i = 0; i < pos-1; ++i) { bufNode = bufNode->next; } bufNode->insertNext(value); ++_size; } } template<typename ValueType> void LinkedList<ValueType>::insertAfterNode(Node* node, const ValueType& value) { node->insertNext(value); this->_size += 1; } template<typename ValueType> void LinkedList<ValueType>::pushBack(const ValueType& value) { if (_size == 0) { pushFront(value); //return; } else{ insert(_size, value); } } template<typename ValueType> void LinkedList<ValueType>::pushFront(const ValueType& value) { _head = new Node(value, _head); ++_size; } template<typename ValueType> void LinkedList<ValueType>::remove(const size_t pos){ if (pos < 0) { throw std::out_of_range("Index of required position is " "out of range\n"); } else if (pos >= this->_size) { throw std::out_of_range("Index of required position is " "out of range\n"); } if (pos == 0) { removeFront(); } else { Node* bufNode = this->_head; for (size_t i = 0; i < pos - 1; ++i) { bufNode = bufNode->next; } bufNode->removeNext(); --_size; } } template<typename ValueType> void LinkedList<ValueType>::removeNextNode(Node* node){ node->removeNext(); --_size; } template<typename ValueType> void LinkedList<ValueType>::removeFront(){ if(_size){ Node* bufNode = _head->next; delete _head; _head = bufNode; --_size; } } template<typename ValueType> void LinkedList<ValueType>::removeBack() { if(_size > 1){ getNode(_size - 2)->removeNext(); --_size; } else{ removeFront(); } } template<typename ValueType> long long int LinkedList<ValueType>::findIndex(const ValueType& value) const { Node* bufNode = this->_head; for (size_t i = 0; i < _size; ++i) { if(bufNode->value == value) return i; bufNode = bufNode->next; } return -1; } template<typename ValueType> typename LinkedList<ValueType>::Node* LinkedList<ValueType>::findNode(const ValueType& value) const { Node* bufNode = this->_head; for (size_t i = 0; i < _size; ++i) { if(bufNode->value == value) return bufNode; bufNode = bufNode->next; } return nullptr; } template<typename ValueType> void LinkedList<ValueType>::reverse(){ if(_size > 1){ Node *tmp; for(int i = 0; i < _size; ++i){ tmp = getNode(_size - 1); this->insert(i, tmp); } //иначе петля в последнем элементе tmp->next = nullptr; } } template<typename ValueType> LinkedList<ValueType> LinkedList<ValueType>::reverse() const { LinkedList result = *this; result.reverse(); return result; } template<typename ValueType> LinkedList<ValueType> LinkedList<ValueType>::getReverseList() const{ LinkedList result = *this; result.reverse(); return result; } template<typename ValueType> size_t LinkedList<ValueType>::size() const { return _size; } template<typename ValueType> void LinkedList<ValueType>::forceNodeDelete(Node* node) { if (node == nullptr) { return; } Node* nextDeleteNode = node->next; delete node; forceNodeDelete(nextDeleteNode); } template<typename ValueType> void LinkedList<ValueType>::insert(const size_t pos, LinkedList::Node *node) { if (pos < 0) { throw std::out_of_range("Index of required position is " "out of range\n"); } else if (pos > this->_size) { throw std::out_of_range("Index of required position is " "out of range\n"); } if (pos == 0) { pushFrontNode(node); } else { Node* bufNode = this->_head; for (size_t i = 0; i < pos - 1; ++i) { bufNode = bufNode->next; } bufNode->insertNext(node); } } template<typename ValueType> void LinkedList<ValueType>::pushBackNode(LinkedList::Node *node) { if (_size == 0) { pushFrontNode(node); return; } insert(_size, node); } template<typename ValueType> void LinkedList<ValueType>::pushFrontNode(LinkedList::Node *node) { Node *tmp = _head; _head = node; _head->next = tmp; } <file_sep>#pragma once // потом поменяем на шаблоны #include <cstdlib> #include <iostream> template <typename ValueType> class TwoLinkedList{ class Node { public: Node(const ValueType& value, Node* next = nullptr, Node* prev = nullptr); ~Node(); ValueType value; Node* next; Node* previous; friend class TwoLinkedList; private: void insertNext(const ValueType& value); void insertNext(Node* node); void removeNext(); }; public: //// TwoLinkedList(); TwoLinkedList(const TwoLinkedList& copyList); TwoLinkedList& operator=(const TwoLinkedList& copyList); TwoLinkedList(TwoLinkedList&& moveList) noexcept; TwoLinkedList& operator=(TwoLinkedList&& moveList) noexcept; ~TwoLinkedList(); //// // доступ к значению элемента по индексу ValueType& operator[](const size_t pos) const; // доступ к узлу по индексу TwoLinkedList::Node* getNode(const size_t pos) const; // вставка элемента по индексу, сначала ищем, куда вставлять (О(n)), потом вставляем (O(1)) void insert(const size_t pos, const ValueType& value); // вставка элемента после узла, (O(1)) void insertAfterNode(Node* node, const ValueType& value); // вставка в конец (О(n)) void pushBack(const ValueType& value); // вставка в начало (О(1)) void pushFront(const ValueType& value); // удаление void remove(const size_t pos);//+ void removeNextNode(Node* node);//+ void removeFront();//+ void removeBack();//+ // поиск, О(n) long long int findIndex(const ValueType& value) const;//+ Node* findNode(const ValueType& value) const;//+ // разворот списка void reverse(); // изменение текущего списка TwoLinkedList reverse() const; // полчение нового списка (для константных объектов) TwoLinkedList getReverseList() const; // чтобы неконстантный объект тоже мог возвращать новый развернутый список size_t size() const; /*Вспомогательные методы, НЕ МЕНЯЮТ РАЗМЕР СПИСКА*/ protected: void pushBackNode(Node *node); void pushFrontNode(Node *node); void insert(const size_t pos, Node *node); private: Node* _head; Node* _tail; size_t _size; void forceNodeDelete(Node* node); }; template <typename ValueType> TwoLinkedList<ValueType>::Node::Node(const ValueType& value, Node* next, Node* prev){ this->value = value; this->previous = prev; this->next = next; } template <typename ValueType> TwoLinkedList<ValueType>::Node::~Node(){} template <typename ValueType> void TwoLinkedList<ValueType>::Node::insertNext(const ValueType& value){ Node* newNode = new Node(value, this->next, this); this->next = newNode; } template <typename ValueType> void TwoLinkedList<ValueType>::Node::removeNext(){ if(this->next){ Node* removeNode = this->next; Node* newNext = removeNode->next; this->next = newNext; this->next->previous = this; delete removeNode; } } template <typename ValueType> void TwoLinkedList<ValueType>::Node::insertNext(TwoLinkedList::Node *node) { Node* tmp = this->next; this->next = node; node->previous = this; node->next = tmp; tmp->previous = node; } template <typename ValueType> TwoLinkedList<ValueType>::TwoLinkedList() : _head(nullptr), _size(0), _tail(nullptr){} template <typename ValueType> TwoLinkedList<ValueType>::TwoLinkedList(const TwoLinkedList& copyList){ this->_size = copyList._size; if (this->_size == 0) { this->_head = nullptr; this->_tail = nullptr; return; } this->_head = new Node(copyList._head->value); Node* currentNode = this->_head; Node* currentCopyNode = copyList._head; while (currentCopyNode->next) { //копия текущей ноды currentNode->next = new Node(currentCopyNode->next->value); currentNode->next->previous = currentNode; //прокрутка currentCopyNode = currentCopyNode->next; currentNode = currentNode->next; } this->_tail = currentNode; } template <typename ValueType> TwoLinkedList<ValueType>& TwoLinkedList<ValueType>::operator=(const TwoLinkedList& copyList){ this->_size = copyList._size; if (this == &copyList) { return *this; } forceNodeDelete(_head);//удалить весь текущий список this->_head = new Node(copyList._head->value);//копирование головы Node* currentNode = this->_head; Node* currentCopyNode = copyList._head; while (currentCopyNode->next) { //копия текущей ноды currentNode->next = new Node(currentCopyNode->next->value); currentNode->next->previous = currentNode; //прокрутка currentCopyNode = currentCopyNode->next; currentNode = currentNode->next; } this->_tail = currentNode; return *this; } template <typename ValueType> TwoLinkedList<ValueType>::TwoLinkedList(TwoLinkedList&& moveList) noexcept{ this->_size = moveList._size; this->_head = moveList._head; this->_tail = moveList._tail; moveList._size = 0; moveList._head = nullptr; moveList._tail = nullptr; } template <typename ValueType> TwoLinkedList<ValueType>& TwoLinkedList<ValueType>::operator=(TwoLinkedList&& moveList) noexcept{ if (this == &moveList) { return *this; } forceNodeDelete(_head); this->_size = moveList._size; this->_head = moveList._head; this->_tail = moveList._tail; moveList._size = 0; moveList._head = nullptr; moveList._tail = nullptr; return *this; } template <typename ValueType> TwoLinkedList<ValueType>::~TwoLinkedList(){ forceNodeDelete(_head); } template <typename ValueType> ValueType& TwoLinkedList<ValueType>::operator[](const size_t pos) const{ return getNode(pos)->value; } template <typename ValueType> typename TwoLinkedList<ValueType>::Node* TwoLinkedList<ValueType>::getNode(const size_t pos) const{ if (pos < 0) { throw std::out_of_range("Index of required node is " "out of range\n"); } else if (pos >= this->_size) { throw std::out_of_range("Index of required node is" "out of range\n"); } else{ Node* bufNode; if(pos > _size / 2){ bufNode = this->_tail; for(size_t i = 0; i < _size - pos - 1; ++i){ bufNode = bufNode->previous; } } else{ bufNode = this->_head; for(size_t i = 0; i < pos; ++i){ bufNode = bufNode->next; } } return bufNode; } } template <typename ValueType> void TwoLinkedList<ValueType>::insert(const size_t pos, const ValueType& value){ if (pos < 0) { throw std::out_of_range("Index of required position is " "out of range\n"); } else if (pos > this->_size) { throw std::out_of_range("Index of required position is " "out of range\n"); } if (pos == 0) { pushFront(value); } else if(pos == _size){ pushBack(value); } else { getNode(pos - 1)->insertNext(value); ++_size; } } template <typename ValueType> void TwoLinkedList<ValueType>::insertAfterNode(Node* node, const ValueType& value){ node->insertNext(value); ++_size; } template <typename ValueType> void TwoLinkedList<ValueType>::pushBack(const ValueType& value){ if (_size == 0) { pushFront(value); } else{ _tail->next = new Node(value); _tail->next->previous = _tail; _tail = _tail->next; ++_size; } } template <typename ValueType> void TwoLinkedList<ValueType>::pushFront(const ValueType& value){ ++_size; if(_size == 1){ _head = new Node(value, _head); _tail = _head; } else{ Node* bufNode = _head; _head = new Node(value); _head->next = bufNode; _head->next->previous = _head; } } template <typename ValueType> void TwoLinkedList<ValueType>::remove(const size_t pos){ if (pos < 0) { throw std::out_of_range("Index of required position is " "out of range\n"); } else if (pos >= this->_size) { throw std::out_of_range("Index of required position is " "out of range\n"); } if (pos == 0) { removeFront(); } else if (pos == _size - 1){ removeBack(); } else { getNode(pos - 1)->removeNext(); --_size; } } template <typename ValueType> void TwoLinkedList<ValueType>::removeNextNode(Node* node){ node->removeNext(); } template <typename ValueType> void TwoLinkedList<ValueType>::removeFront(){ Node* bufNode = _head->next; delete _head; _head = bufNode; --_size; } template <typename ValueType> void TwoLinkedList<ValueType>::removeBack() { Node* bufNode = _tail; _tail = bufNode->previous; _tail->next = nullptr; delete bufNode; --_size; } template <typename ValueType> long long int TwoLinkedList<ValueType>::findIndex(const ValueType& value) const{ Node* bufNode = this->_head; for (size_t i = 0; i < _size; ++i) { if(bufNode->value == value) return i; bufNode = bufNode->next; } return -1; } template <typename ValueType> typename TwoLinkedList<ValueType>::Node* TwoLinkedList<ValueType>::findNode(const ValueType& value) const{ Node* bufNode = this->_head; for (size_t i = 0; i < _size; ++i) { if(bufNode->value == value) return bufNode; bufNode = bufNode->next; } return nullptr; } template <typename ValueType> void TwoLinkedList<ValueType>::reverse(){ if(_size > 1){ Node* bufNode = _tail; //Поменяем местами хвост и голову _tail->next = _tail->previous; _tail->previous = nullptr; _tail = _head; _head = bufNode; while(bufNode->next){ bufNode->next->next = bufNode->next->previous; bufNode->next->previous = bufNode; bufNode = bufNode->next; } } } template <typename ValueType> TwoLinkedList<ValueType> TwoLinkedList<ValueType>::reverse() const{ TwoLinkedList result = *this; result.reverse(); return result; } template <typename ValueType> TwoLinkedList<ValueType> TwoLinkedList<ValueType>::getReverseList() const{ TwoLinkedList result = *this; result.reverse(); return result; } template <typename ValueType> size_t TwoLinkedList<ValueType>::size() const{ return _size; } template <typename ValueType> void TwoLinkedList<ValueType>::forceNodeDelete(Node* node){ if (node == nullptr) { return; } Node* nextDeleteNode = node->next; delete node; forceNodeDelete(nextDeleteNode); } template <typename ValueType> void TwoLinkedList<ValueType>::insert(const size_t pos, TwoLinkedList::Node *node) { if (pos < 0) { throw std::out_of_range("Index of required position is " "out of range\n"); } else if (pos > this->_size) { throw std::out_of_range("Index of required position is " "out of range\n"); } if (pos == 0) { pushFrontNode(node); } else if(pos == _size){ pushBackNode(node); } else { getNode(pos - 1)->insertNext(node); } } template <typename ValueType> void TwoLinkedList<ValueType>::pushBackNode(TwoLinkedList::Node *node) { if (_size == 0) { pushFrontNode(node); } else{ _tail->next = node; node->previous = _tail; node->next = nullptr; _tail = node; } } template <typename ValueType> void TwoLinkedList<ValueType>::pushFrontNode(TwoLinkedList::Node *node) { Node *tmp = _head; _head = node; _head->next = tmp; _head->previous = nullptr; } <file_sep>#pragma once #include "StackImplementation.h" #include "../Vector/MyVector.h" #include <iostream> template <class ValueType> class VectorStack : public MyVector<ValueType>, virtual public StackImplementation<ValueType> { public: //конструктор VectorStack(); //конструктор копированием VectorStack(const VectorStack& copyVec); VectorStack& operator=(const VectorStack& copyVec); // Конструктор копирования присваиванием VectorStack(VectorStack&& moveVec) noexcept; VectorStack& operator=(VectorStack&& moveVec) noexcept; // добавление в конец void push(const ValueType& value) override; // удаление с хвоста void pop() override; // посмотреть элемент в хвосте const ValueType& top() const override; // проверка на пустоту bool isEmpty() const override; // размер size_t size() const override; // деструктор ~VectorStack(); }; template <typename ValueType> VectorStack<ValueType>::VectorStack() :MyVector<ValueType>(0, ResizeStrategy::Multiplicative, 2){} template <typename ValueType> VectorStack<ValueType>::~VectorStack() {} template <typename ValueType> VectorStack<ValueType>::VectorStack(const VectorStack &copyVec):MyVector<ValueType>(copyVec){} template <typename ValueType> VectorStack<ValueType>& VectorStack<ValueType>::operator=(const VectorStack &copyVec){ if(this == &copyVec){ return *this; } MyVector<ValueType>::operator=(copyVec); return *this; } template <typename ValueType> VectorStack<ValueType>::VectorStack(VectorStack &&moveVec) noexcept :MyVector<ValueType>(std::move(moveVec)){} template <typename ValueType> VectorStack<ValueType> &VectorStack<ValueType>::operator=(VectorStack &&moveVec) noexcept { if(this == &moveVec){ return *this; } MyVector<ValueType>::operator=(std::move(moveVec)); return *this; } template <typename ValueType> void VectorStack<ValueType>::push(const ValueType &value) { (*this).pushBack(value); } template <typename ValueType> void VectorStack<ValueType>::pop() { if(this->size()){ (*this).popBack(); } } template <typename ValueType> const ValueType &VectorStack<ValueType>::top() const { if(this->MyVector<ValueType>::size()){ return (*this)[this->MyVector<ValueType>::size() - 1]; } } template <typename ValueType> bool VectorStack<ValueType>::isEmpty() const { return this->MyVector<ValueType>::size() == 0; } template <typename ValueType> size_t VectorStack<ValueType>::size() const { return MyVector<ValueType>::size(); } <file_sep>#pragma once #include <cmath> #include <cstdlib> #include <cassert> #include <cmath> #include <cstring> #include <limits> #include <iterator> // стратегия изменения capacity enum class ResizeStrategy { Additive,// capacity = OldCapacity + delta Multiplicative // capacity = coef * OldCapacity }; //определение сортировки для sortedSquares() enum class SortedStrategy{ Increase, Decrease }; // тип значений в векторе // потом будет заменен на шаблон //using ValueType = double; template <typename ValueType> class MyVector { public: class VecIterator: public std::iterator<std::input_iterator_tag, ValueType> { friend class MyVector; private: VecIterator(ValueType* p); public: VecIterator(const VecIterator &it); bool operator!=(VecIterator const& other) const; bool operator==(VecIterator const& other) const; //need for BOOST_FOREACH typename VecIterator::reference operator*() const; VecIterator& operator++(); VecIterator& operator--(); private: ValueType* p; }; MyVector(size_t size = 0, ResizeStrategy = ResizeStrategy::Multiplicative, float coef = 1.5f); MyVector(size_t size, ValueType value, ResizeStrategy = ResizeStrategy::Multiplicative, float coef = 1.5f);//Заполнить иниц-ый вектор value MyVector(const MyVector& copy); MyVector& operator=(const MyVector& copy); //Конструктор перемещения MyVector(MyVector&& moveVec) noexcept; MyVector& operator=(MyVector&& moveVec) noexcept; ~MyVector(); size_t capacity() const; size_t size() const; float loadFactor(); // доступ к элементу, // должен работать за O(1) ValueType& operator[](const size_t i) const; // добавить в конец, // должен работать за amort(O(1)) void pushBack(const ValueType& value); // вставить, // должен работать за O(n) void insert(const size_t i, const ValueType& value); // версия для одного значения void insert(const size_t i, const MyVector& value); // версия для вектора // удалить с конца, // должен работать за amort(O(1)) void popBack(); // удалить // должен работать за O(n) void erase(const size_t i); void erase(const size_t i, const size_t len); // удалить len элементов начиная с i // найти элемент, // должен работать за O(n) // если isBegin == true, найти индекс первого элемента, равного value, иначе последнего // если искомого элемента нет, вернуть -1 long long int find(const ValueType& value, bool isBegin = true) const; // зарезервировать память (принудительно задать capacity) void reserve(const size_t capacity); // изменить размер // если новый размер больше текущего, то новые элементы забиваются дефолтными значениями // если меньше - обрезаем вектор void resize(const size_t size, const ValueType = 0.0); // очистка вектора, без изменения capacity void clear(); /*итераторы*/ typedef VecIterator iterator; typedef VecIterator const_iterator; iterator begin(); iterator end(); const_iterator begin() const; const_iterator end() const; /*Вспомогательные методы работы с памятью*/ protected: /*Считает новый _capacity с учётом политики выделения памяти и loadFactor-а*/ size_t capCalc(size_t cap, bool forced_increase = false); //процедура обрезки памяти void cropMem(); private: ValueType* _data; size_t _size; size_t _capacity; ResizeStrategy _strategy; float _coef; }; template <typename ValueType> MyVector<ValueType> sortedSquares(const MyVector<ValueType>& vec, SortedStrategy strategy); template <typename ValueType> size_t MyVector<ValueType>::capacity() const { return _capacity; } template <typename ValueType> size_t MyVector<ValueType>::size() const { return _size; } template <typename ValueType> MyVector<ValueType>::MyVector(size_t size, ResizeStrategy strategy, float coef) :_data(nullptr), _capacity(0) { if(strategy == ResizeStrategy::Multiplicative){ _capacity = size == 0? 1 : std::round(coef * size); } else if(strategy == ResizeStrategy::Additive){ _capacity = std::round(size + coef); } else{ //assert("Unidentified strategy"); throw std::invalid_argument("Unidentified strategy\n"); } _data = new ValueType[_capacity]; _size = size; _strategy = strategy; _coef = coef; } template <typename ValueType> MyVector<ValueType>::MyVector(size_t size, ValueType value, ResizeStrategy strategy, float coef) :_data(nullptr), _capacity(0) { if(strategy == ResizeStrategy::Multiplicative){ _capacity = size == 0? 1 : std::round(coef * size); } else if(strategy == ResizeStrategy::Additive){ _capacity = std::round(size + coef); } else{ //assert(strategy); throw std::invalid_argument("Unidentified strategy\n"); } _data = new ValueType[_capacity]; for(size_t i = 0; i < size; ++i){ *(_data + i) = value; } _size = size; _strategy = strategy; _coef = coef; } template <typename ValueType> MyVector<ValueType>::~MyVector() { delete []_data; } template <typename ValueType> MyVector<ValueType>::MyVector(const MyVector &copy) :_data(nullptr), _capacity(0) { _data = new ValueType[copy._capacity]; _size = copy._size; _capacity = copy._capacity; _strategy = copy._strategy; _coef = copy._coef; for(size_t i = 0; i < _size; ++i) *(_data + i) = *(copy._data + i); } template <typename ValueType> MyVector<ValueType>& MyVector<ValueType>::operator=(const MyVector &copy) { if(this == &copy) return *this; auto *tmp_data = new ValueType[copy._capacity]; delete []_data; _data = tmp_data; memcpy(_data, copy._data, sizeof(ValueType) * copy._size); _size = copy._size; _capacity = copy._capacity; _strategy = copy._strategy; _coef = copy._coef; return *this; } template <typename ValueType> MyVector<ValueType>::MyVector(MyVector &&moveVec) noexcept { _data = moveVec._data; _size = moveVec._size; _capacity = moveVec._capacity; _strategy = moveVec._strategy; _coef = moveVec._coef; moveVec._data = nullptr; moveVec._size = 0; moveVec._capacity = 0; moveVec._coef = 0; } template <typename ValueType> MyVector<ValueType>& MyVector<ValueType>::operator=(MyVector &&moveVec) noexcept { if(this == &moveVec) return *this; delete []_data; _size = moveVec._size; _capacity = moveVec._capacity; _data = moveVec._data; _strategy = moveVec._strategy; _coef = moveVec._coef; moveVec._data = nullptr; moveVec._size = 0; moveVec._capacity = 0; moveVec._coef = 0; return *this; } template <typename ValueType> ValueType &MyVector<ValueType>::operator[](const size_t i) const { if(i >= _size) throw std::out_of_range("Index of required position is out of range\n"); return _data[i]; } template <typename ValueType> float MyVector<ValueType>::loadFactor() { if(_capacity != 0) return (float)_size / (float)_capacity; return 0; } template <typename ValueType> void MyVector<ValueType>::pushBack(const ValueType &value) { if(_capacity < _size + 1){ reserve(capCalc(_capacity)); } _data[_size] = value; ++_size; } template <typename ValueType> size_t MyVector<ValueType>::capCalc(size_t cap, bool forced_increase) { size_t newCap = 0; if((std::fabs(loadFactor() - 1.f) < std::numeric_limits<float>::epsilon()) || forced_increase){ if(_strategy == ResizeStrategy::Multiplicative){ newCap = std::round(cap * _coef); } else if(_strategy == ResizeStrategy::Additive){ newCap = cap + _coef * 2; } } else{ if(_strategy == ResizeStrategy::Multiplicative){ newCap = std::round(cap / _coef); } else if(_strategy == ResizeStrategy::Additive){ newCap = cap - _coef; } } return newCap; } template <typename ValueType> void MyVector<ValueType>::insert(const size_t i, const ValueType &value) { if(i == _size) pushBack(value); else if(i > _size){ throw std::out_of_range("Index of required position is out of range\n"); } else{ if(_capacity < _size + 1){ _capacity = capCalc(_capacity); ValueType *tmp_data = new ValueType[_capacity]; tmp_data[i] = value; for(size_t j = 0; j < i; ++j) tmp_data[j] = _data[j]; for(size_t j = i + 1; j < _size + 1; ++j) tmp_data[j] = _data[j - 1]; delete []_data; _data = tmp_data; ++_size; } else{ //Здесь было красиво каставание for(long long j = _size; j > i; --j) _data[j] = _data[j - 1]; _data[i] = value; ++_size; } } } template <typename ValueType> void MyVector<ValueType>::insert(const size_t i, const MyVector &value){ size_t delta = value.size(); if(_size == 0){ *this = value; } else if(i == _size) for(size_t j = 0; j < delta; ++j) pushBack(value[j]); else if(i > _size){ throw std::out_of_range("Index of required position is out of range\n"); } else{ if(_capacity < _size + delta){ while(_capacity < _size + delta) _capacity = capCalc(_capacity,true); ValueType *tmp_data = new ValueType[_capacity]; for(size_t j = i; j < delta + i; j++){ tmp_data[j] = value[j - i]; } for(size_t j = 0; j < i; ++j) tmp_data[j] = _data[j]; for(size_t j = i + delta; j < _size + delta; ++j) tmp_data[j] = _data[j - delta]; delete []_data; _data = tmp_data; } else{ for(long long j = (long long)(_size + delta) - 1; j >= (const long long)i + delta; --j){ _data[j] = _data[j - delta]; } for(size_t j = i; j < i + delta; ++j) _data[j] = value[j - i]; } _size += delta; } } template <typename ValueType> void MyVector<ValueType>::popBack() { --_size; /*обрежем память, если необходимо*/ cropMem(); } template <typename ValueType> void MyVector<ValueType>::clear() { delete []_data; _data = new ValueType[_capacity]; _size = 0; } template <typename ValueType> void MyVector<ValueType>::reserve(const size_t capacity) { if(capacity < _size) _size = capacity; ValueType *tmp_data = new ValueType[capacity]; memcpy(tmp_data, _data, _size * sizeof(ValueType)); delete []_data; _data = tmp_data; _capacity = capacity; } template <typename ValueType> void MyVector<ValueType>::erase(const size_t i) { for(size_t j = i; j < _size - 1; ++j){ _data[j] = _data[j + 1]; } --_size; /*обрежем выделяемую память, если необходимо*/ cropMem(); } template <typename ValueType> void MyVector<ValueType>::erase(const size_t i, const size_t len) { if (i + len > _size) //assert(i + len >= _size); throw std::out_of_range("Index of required position is " "out of range\n"); else if (i + len == _size - 1) for (size_t j = i; j < len; ++j){ popBack(); } else{ /*сколько элементов от последнего удалённого до конца вектора*/ size_t delta = _size - (i + len /*+ 1*/); /*перенесём delta элементов с конца массива на освободившиеся позиции*/ for(size_t j = i; j < i + delta; ++j){ _data[j] = _data[j + len]; } _size -= len; } /*обрежем выделяемую память, если необходимо*/ cropMem(); } template <typename ValueType> void MyVector<ValueType>::resize(const size_t size, const ValueType default_value) { if(size > _size){ if(size > _capacity){ reserve(size); } for(size_t i = _size; i < size; ++i){ _data[i] = default_value; } } else if(size < _size){ _size = size; cropMem(); } _size = size; } template <typename ValueType> void MyVector<ValueType>::cropMem() { if(((std::fabs(loadFactor() - 1/pow(_coef, 2)) < std::numeric_limits<float>::epsilon()) || (loadFactor() < 1/pow(_coef, 2))) && (_size != 0)) { size_t bottom_border = _strategy == ResizeStrategy::Multiplicative? std::round((float)_size * _coef): std::round((float)_size + _coef); reserve(bottom_border); } else if (_size == 0) reserve(1); } template <typename ValueType> long long int MyVector<ValueType>::find(const ValueType &value, bool isBegin) const { if(isBegin){ for(size_t i = 0; i < _size; ++i){ if(_data[i] == value) return i; } } else{ for(long long i = _size; i > 0; --i){ if(_data[i - 1] == value) return i; } } return -1; } template <typename ValueType> typename MyVector<ValueType>::iterator MyVector<ValueType>::begin() { return iterator(_data); } template <typename ValueType> typename MyVector<ValueType>::iterator MyVector<ValueType>::end() { return iterator(_data + _size); } template <typename ValueType> typename MyVector<ValueType>::const_iterator MyVector<ValueType>::begin() const { return const_iterator(_data); } template <typename ValueType> typename MyVector<ValueType>::const_iterator MyVector<ValueType>::end() const { return const_iterator(_data + _size); } template <typename ValueType> MyVector<ValueType>::VecIterator::VecIterator(ValueType *p):p(p){} template <typename ValueType> MyVector<ValueType>::VecIterator::VecIterator(const VecIterator& it) : p(it.p) { } template <typename ValueType> bool MyVector<ValueType>::VecIterator::operator!=(VecIterator const& other) const { return p != other.p; } template <typename ValueType> bool MyVector<ValueType>::VecIterator::operator==(VecIterator const& other) const { return p == other.p; } template <typename ValueType> typename MyVector<ValueType>::VecIterator::reference MyVector<ValueType>::VecIterator::operator*() const{ return *p; } template <typename ValueType> typename MyVector<ValueType>::VecIterator &MyVector<ValueType>::VecIterator::operator++() { ++p; return *this; } template <typename ValueType> typename MyVector<ValueType>::VecIterator &MyVector<ValueType>::VecIterator::operator--() { --p; return *this; } template <typename ValueType> MyVector<ValueType> sortedSquares(const MyVector<ValueType>& vec, SortedStrategy strategy){ MyVector<ValueType> result(vec.size()); size_t top = vec.size() - 1, bottom = 0; size_t count = vec.size(); for(int i = 0; i < vec.size(); ++i){ if(pow(vec[top], 2) > pow(vec[bottom], 2)){ result[strategy == SortedStrategy::Decrease? i: count - i - 1] = pow(vec[top], 2); top -= 1; } else{ result[strategy == SortedStrategy::Decrease? i: count - i - 1] = pow(vec[bottom], 2); bottom += 1; } } return result; }
ba64b30e109e16e1eea6dec2cb0d63677a870f6f
[ "C++" ]
5
C++
Krage56/DataStructures
afe794ca719b90adf854ce728f5bf04474f02ab1
dae0e0d53fafafff632a6c6ffe41cd16013c2484
refs/heads/master
<file_sep>package me.zhennan.toolkit.android.design_pattern.command; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Created by zhangzhennan on 15/5/7. */ public abstract class MacroCommand implements Command { private List<Command> commands; final protected List<Command> getCommands(){ if(null == commands){ commands = new ArrayList<>(); } return commands; } final protected void addSubCommand(Command subCommand){ getCommands().add(subCommand); } @Override final public void execute() { onExecuteCommand(); Iterator<Command> iterator = getCommands().iterator(); while (iterator.hasNext()){ Command command = iterator.next(); command.execute(); } } protected abstract void onExecuteCommand(); }<file_sep>package me.zhennan.scp.android.view.scp_database; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import butterknife.ButterKnife; import butterknife.InjectView; import me.zhennan.scp.android.R; import me.zhennan.scp.android.base.BaseAppCompatActivity; import me.zhennan.scp.android.model.Entry; import me.zhennan.scp.android.model.EntryImpl; import me.zhennan.scp.android.service.CoreService; import me.zhennan.scp.android.view.scp_entry.EntryActivity; import me.zhennan.toolkit.android.multitypelistadapter.MultiTypeListAdapter; /** * Created by zhangzhennan on 15/5/7. */ public class DatabaseActivity extends BaseAppCompatActivity implements DatabaseMVP.DatabasePresenterView { private DatabaseMVP.DatabasePresenter presenter; @Override public DatabaseMVP.DatabasePresenter getPresenter() { if(null == presenter){ presenter = new DatabasePresenterImpl(); presenter.setView(this); } return presenter; } @Override public void setPresenter(DatabaseMVP.DatabasePresenter ref) { presenter = ref; } private ServiceConnection connection; @InjectView(R.id.list_view) protected ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_database); ButterKnife.inject(this); onSetupViewAdapter(); listView.setEmptyView(findViewById(R.id.empty_view)); listView.setAdapter(getPresenter().getListAdapter()); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Object object = getPresenter().getListAdapter().getItem(position); if(object instanceof Entry){ onEntryPressed((Entry)object); } } }); // service connection connection = getPresenter().getServiceConnection(); Intent intent = new Intent(this, CoreService.class); bindService(intent, connection, BIND_AUTO_CREATE); } @Override protected void onDestroy() { super.onDestroy(); if(null != connection){ unbindService(connection); } } protected void onSetupViewAdapter(){ MultiTypeListAdapter adapter = getPresenter().getListAdapter(); adapter.registerItemType(String.class, R.layout.li_header, new MultiTypeListAdapter.ItemRenderDelegate<String>() { @Override public void onItemRender(int position, String item, View view) { TextView textView = (TextView) view.findViewById(R.id.text_view); textView.setText(item); } }); adapter.registerItemType(EntryImpl.class, R.layout.li_entry, new MultiTypeListAdapter.ItemRenderDelegate<EntryImpl>() { @Override public void onItemRender(int position, EntryImpl item, View view) { TextView textView = (TextView) view.findViewById(R.id.text_view); textView.setText(item.getLabel()); } }); } protected void onEntryPressed(Entry entry){ Intent intent = new Intent(this, EntryActivity.class); intent.putExtra("entryId", entry.getUrl()); startActivity(intent); } } <file_sep>package me.zhennan.scp.android.service.components; import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import java.util.Locale; import me.zhennan.scp.android.usecase.config.AppConfiguration; /** * Created by zhangzhennan on 15/5/8. */ public class AppConfigurationManager implements AppConfiguration { static private AppConfiguration instance; final static private String SHARED_PREFERENCE_NAME = "appConfiguration"; static public AppConfiguration getInstance(Context context){ if(null == instance){ instance = new AppConfigurationManager(context.getApplicationContext()); } return instance; } private Context context; public AppConfigurationManager(Context context){ this.context = context; } protected SharedPreferences sharedPreferences; protected SharedPreferences getSharedPreferences(){ if(null == sharedPreferences){ sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); } return sharedPreferences; } public String getDefaultLanguage(){ return Locale.getDefault().getLanguage(); } @Override public String getLanguage() { return getSharedPreferences().getString("lang", getDefaultLanguage()); } @Override public void setLanguage(String lang) { if(!TextUtils.isEmpty(lang)) { getSharedPreferences().edit().putString("lang", lang).apply(); }else{ getSharedPreferences().edit().remove("lang").apply(); } } } <file_sep>include ':app' include ':modules:model', ':modules:usecase' include ':libraries:design_pattern', ':libraries:multitypelistadapter' <file_sep>package me.zhennan.toolkit.android.design_pattern.command; /** * Created by zhangzhennan on 15/5/7. */ public abstract class SimpleCommand implements Command { @Override final public void execute() { onExecuteCommand(); } /** * do business logic here * @return */ protected abstract void onExecuteCommand(); }<file_sep>package me.zhennan.scp.android.model; /** * Created by zhangzhennan on 15/5/8. */ public interface EntryWithDetail extends Entry { } <file_sep>package me.zhennan.scp.android; import android.app.Application; import com.facebook.stetho.Stetho; /** * Created by zhangzhennan on 15/5/7. */ public class APP extends Application { @Override public void onCreate() { super.onCreate(); Stetho.initialize(Stetho .newInitializerBuilder(this) .enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this)) .enableDumpapp(Stetho.defaultDumperPluginsProvider(this)) .build()); } } <file_sep>package me.zhennan.scp.android.usecase; /** * Created by zhangzhennan on 15/5/8. */ public interface UseCaseCallback { void onComplete(String html); void onFailed(int error, String message); } <file_sep>package me.zhennan.scp.android.view.home; import android.content.ServiceConnection; import android.widget.ListAdapter; import me.zhennan.toolkit.android.design_pattern.mvp.MVP; /** * Created by zhangzhennan on 15/5/7. */ public interface HomeMVP { interface HomePresenter extends MVP.Presenter<HomePresenterView>{ ServiceConnection getServiceConnection(); ListAdapter getListAdapter(); } interface HomePresenterView extends MVP.PresenterView<HomePresenter>{ void pressDrawer(); void showServiceConnectionFailedErrorMessage(); } } <file_sep>package me.zhennan.scp.android; /** * Created by zhangzhennan on 15/5/8. */ public class Consts { final static public boolean DEBUG = BuildConfig.DEBUG; public class Meta{ final static public String DEFAULT_ENDPOINT = "DefaultEndPoint"; } } <file_sep>package me.zhennan.scp.android.view.splash; import android.content.ComponentName; import android.content.ServiceConnection; import android.os.IBinder; import me.zhennan.scp.android.service.CoreServiceBinder; /** * Created by zhangzhennan on 15/5/7. */ public class SplashPresenterImpl implements SplashMVP.SplashPresenter { private SplashMVP.SplashPresenterView view; @Override public SplashMVP.SplashPresenterView getView() { return view; } @Override public void setView(SplashMVP.SplashPresenterView ref) { view = ref; } private ServiceConnection connection; @Override public ServiceConnection getServiceConnection() { if(null == connection){ connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { if(service instanceof CoreServiceBinder){ onServiceConnection((CoreServiceBinder) service); }else{ getView().navigateToHomeWithExtras(null); } } @Override public void onServiceDisconnected(ComponentName name) { } }; } return connection; } public void onServiceConnection(CoreServiceBinder binder){ getView().navigateToHomeWithExtras(null); } }
64cde4bade9b6b35a981f5f683c2e97c14ca701e
[ "Java", "Gradle" ]
11
Java
TinyRipper/scp
ae88f282c084e78396be15b785f3e7dc62a63e3c
7bd08528a4e57e5d0275149341302e20eff1619c
refs/heads/master
<repo_name>pgamamed/AliPhysics<file_sep>/PWGCF/FEMTOSCOPY/FemtoDream/AliAnalysisTaskDeuteronProtonEfficiency.h #ifndef ALIANALYSISTASKDEUTERONPROTONEFFICIENCY_H #define ALIANALYSISTASKDEUTERONPROTONEFFICIENCY_H #include "AliAnalysisTaskSE.h" class AliESDEvent; class AliESDInputHandler; class AliAnalysisTaskDeuteronProtonEfficiency : public AliAnalysisTaskSE { public: AliAnalysisTaskDeuteronProtonEfficiency(); AliAnalysisTaskDeuteronProtonEfficiency(const char *name); AliAnalysisTaskDeuteronProtonEfficiency& operator = (const AliAnalysisTaskDeuteronProtonEfficiency &task); AliAnalysisTaskDeuteronProtonEfficiency(const AliAnalysisTaskDeuteronProtonEfficiency &task); virtual ~AliAnalysisTaskDeuteronProtonEfficiency(); void UserCreateOutputObjects(); void UserExec(Option_t *); void Terminate(Option_t *); double CalculateRelativeMomentum(TLorentzVector &Pair, TLorentzVector &Part1, TLorentzVector &Part2); private: AliESDEvent *fESD; AliESDInputHandler *fESDHandler; AliVEvent *fEvent; AliMCEvent *mcEvent; bool fMCtrue; AliESDtrackCuts *fESDtrackCutsProton; AliESDtrackCuts *fESDtrackCutsDeuteron; TList *fHistList; // Histograms for generated particles TH1F *fHistPtProtonGen; TH1F *fHistEtaProtonGen; TH1F *fHistPtAntiProtonGen; TH1F *fHistEtaAntiProtonGen; TH1F *fHistPtDeuteronGen; TH1F *fHistEtaDeuteronGen; TH1F *fHistPtAntiDeuteronGen; TH1F *fHistEtaAntiDeuteronGen; TH1F *fHistPtHelium3Gen; TH1F *fHistEtaHelium3Gen; TH1F *fHistPtAntiHelium3Gen; TH1F *fHistEtaAntiHelium3Gen; TH1F *fHistSEDPairGen; TH1F *fHistSEDAntiPairGen; TH2F *fHistPtParticlesGen; TH2F *fHistPtAntiParticlesGen; // Histograms for reconstructed particles TH1F *fHistPtProtonRec; TH1F *fHistEtaProtonRec; TH1F *fHistPtAntiProtonRec; TH1F *fHistEtaAntiProtonRec; TH1F *fHistPtDeuteronRec; TH1F *fHistEtaDeuteronRec; TH1F *fHistPtAntiDeuteronRec; TH1F *fHistEtaAntiDeuteronRec; TH1F *fHistPtHelium3Rec; TH1F *fHistEtaHelium3Rec; TH1F *fHistPtAntiHelium3Rec; TH1F *fHistEtaAntiHelium3Rec; TH1F *fHistSEDPairRec; TH1F *fHistSEDAntiPairRec; TH2F *fHistPtParticlesRec; TH2F *fHistPtAntiParticlesRec; TH1F *fHistEventCounter; AliPIDResponse *fPIDResponse; ClassDef(AliAnalysisTaskDeuteronProtonEfficiency, 1); // analysisclass }; // end of "public AliAnalysisTaskSE" #endif <file_sep>/PWGCF/Correlations/macros/jcorran/AddTaskJHOCFAMaster10h.C AliAnalysisTask *AddTaskJHOCFAMaster10h (TString taskName = "JHOCFAMaster10h", double ptMin = 0.5, Bool_t removebadarea = kFALSE, Bool_t saveCatalystQA = kFALSE) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); // Configuration of the wagons. const int Nsets = 2; // Number of configurations. TString configNames[Nsets] = { "tpconly", // 0 = Default. "hybrid" }; // Loading of the correction map. TString MAPfilenames[Nsets]; TString MAPdirname = "alien:///alice/cern.ch/user/a/aonnerst/legotrain/NUAError/"; AliJCorrectionMapTask *cMapTask = new AliJCorrectionMapTask ("JCorrectionMapTask"); cMapTask->EnableEffCorrection ("alien:///alice/cern.ch/user/d/djkim/legotrain/efficieny/data/Eff--LHC10h-LHC11a10a_bis-0-Lists.root"); // Efficiency correction. for (Int_t i = 0; i < Nsets; i++) { MAPfilenames[i] = Form ("%sPhiWeights_LHC10h_Error_pt%02d_s_%s.root", MAPdirname.Data(), Int_t (ptMin * 10), configNames[i].Data()); // Azimuthal correction. cMapTask->EnablePhiCorrection (i, MAPfilenames[i]); // i is index for set file correction ->SetPhiCorrectionIndex(i); } mgr->AddTask((AliAnalysisTask *) cMapTask); // Loaded correction map added to the analysis manager. // Setting of the general parameters. UInt_t configTrigger = AliVEvent::kMB; // Minimum bias trigger for LHC10h. Int_t TPConlyFilter = 128; // Filterbit for TPConly tracks. Int_t hybridCut = 768; // Configuration of the catalyst tasks for the data selection. AliJCatalystTask *fJCatalyst[Nsets]; // One catalyst needed per configuration. for (Int_t i = 0; i < Nsets; i++) { fJCatalyst[i] = new AliJCatalystTask(Form("fJCatalystTask_%s", configNames[i].Data())); cout << "Setting the catalyst: " << fJCatalyst[i]->GetJCatalystTaskName() << endl; // TBI: Do we need the flag for outliers here? fJCatalyst[i]->SelectCollisionCandidates(configTrigger); fJCatalyst[i]->SetSaveAllQA(saveCatalystQA); fJCatalyst[i]->SetCentrality(0.,5.,10.,20.,30.,40.,50.,60.,70.,80.,-10.,-10.,-10.,-10.,-10.,-10.,-10.); fJCatalyst[i]->SetInitializeCentralityArray(); if (strcmp(configNames[i].Data(), "V0M") == 0) { fJCatalyst[i]->SetCentDetName("V0M"); // V0M for syst } else { fJCatalyst[i]->SetCentDetName("CL1"); // SPD clusters in the default analysis. } if (strcmp(configNames[i].Data(), "hybrid") == 0) { fJCatalyst[i]->SetTestFilterBit(hybridCut); } else { fJCatalyst[i]->SetTestFilterBit(TPConlyFilter); // default } fJCatalyst[i]->SetPtRange(ptMin, 5.0); fJCatalyst[i]->SetEtaRange(-0.8, 0.8); fJCatalyst[i]->SetPhiCorrectionIndex (i); mgr->AddTask((AliAnalysisTask *)fJCatalyst[i]); } // Configuration of the analysis task itself. AliJHOCFATask *myTask[Nsets]; for (Int_t i = 0; i < Nsets; i++){ myTask[i] = new AliJHOCFATask(Form("%s_s_%s", taskName.Data(), configNames[i].Data())); myTask[i]->SetJCatalystTaskName(fJCatalyst[i]->GetJCatalystTaskName()); myTask[i]->HOCFASetCentralityBinning(9); myTask[i]->HOCFASetCentralityArray("0. 5. 10. 20. 30. 40. 50. 60. 70. 80."); myTask[i]->HOCFASetMinMultiplicity(6); myTask[i]->HOCFASetParticleWeights(kTRUE); myTask[i]->HOCFASetNumberCombi(1); myTask[i]->HOCFASetHarmoArray("2 3 4"); mgr->AddTask((AliAnalysisTask *) myTask[i]); } // Connect the input and output. AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); AliAnalysisDataContainer *jHist[2*Nsets]; for (Int_t i = 0; i < Nsets; i++) { mgr->ConnectInput(fJCatalyst[i], 0, cinput); mgr->ConnectInput(myTask[i], 0, cinput); jHist[i] = new AliAnalysisDataContainer(); jHist[Nsets+i] = new AliAnalysisDataContainer(); jHist[i] = mgr->CreateContainer(Form ("%s", myTask[i]->GetName()), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s", AliAnalysisManager::GetCommonFileName())); mgr->ConnectOutput(myTask[i], 1, jHist[i]); jHist[Nsets+i] = mgr->CreateContainer(Form ("%s", fJCatalyst[i]->GetName()), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s", AliAnalysisManager::GetCommonFileName())); mgr->ConnectOutput(fJCatalyst[i], 1, jHist[Nsets+i]); } return myTask[0]; } <file_sep>/PWG/EMCAL/EMCALtrigger/AliEmcalTriggerMaskHandlerOCDB.cxx /************************************************************************************ * Copyright (C) 2021, Copyright Holders of the ALICE Collaboration * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * Neither the name of the <organization> nor the * * names of its contributors may be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * * DISCLAIMED. IN NO EVENT SHALL ALICE COLLABORATION 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. * ************************************************************************************/ #include <algorithm> #include <bitset> #include <functional> #include <iostream> #include <TH2.h> #include "AliCDBEntry.h" #include "AliCDBManager.h" #include "AliEMCALGeometry.h" #include "AliEMCALTriggerDCSConfig.h" #include "AliEMCALTriggerTRUDCSConfig.h" #include "AliEMCALTriggerSTUDCSConfig.h" #include "AliEmcalTriggerMaskHandlerOCDB.h" ClassImp(PWG::EMCAL::AliEmcalTriggerMaskHandlerOCDB) using namespace PWG::EMCAL; AliEmcalTriggerMaskHandlerOCDB *AliEmcalTriggerMaskHandlerOCDB::fgInstance = nullptr; AliEmcalTriggerMaskHandlerOCDB *AliEmcalTriggerMaskHandlerOCDB::Instance() { if(!fgInstance) fgInstance = new AliEmcalTriggerMaskHandlerOCDB; return fgInstance; } std::vector<int> AliEmcalTriggerMaskHandlerOCDB::GetMaskedFastorIndicesL0(int runnumber) { std::vector<int> maskedfastors; UpdateCache(runnumber); auto geo = GetGeometry(runnumber); std::function<int (int, int)> ChannelMaskHandler = geo->GetTriggerMappingVersion() == 2 ? GetChannelForMaskRun2 : GetChannelForMaskRun1; int itru = 0; for(auto truconfigobj : *fCurrentConfig->GetTRUArr()) { auto truconfig = dynamic_cast<AliEMCALTriggerTRUDCSConfig *>(truconfigobj); int localtru = itru % 32, detector = itru >= 32 ? 1 : 0, globaltru = geo->GetTriggerMapping()->GetTRUIndexFromSTUIndex(localtru, detector); for(int ipos = 0; ipos < 6; ipos++) { auto regmask = truconfig->GetMaskReg(ipos); std::bitset<16> bitsregmask(regmask); for(int ibit = 0; ibit < 16; ibit++) { if(bitsregmask.test(ibit)) { auto channel = ChannelMaskHandler(ipos, ibit); int absfastor; geo->GetTriggerMapping()->GetAbsFastORIndexFromTRU(globaltru, channel, absfastor); maskedfastors.push_back(absfastor); } } } itru++; } std::sort(maskedfastors.begin(), maskedfastors.end(), std::less<int>()); return maskedfastors; } std::vector<AliEmcalTriggerMaskHandlerOCDB::FastORPosition> AliEmcalTriggerMaskHandlerOCDB::GetMaskedFastorPositionsL0(int runnumber) { std::vector<FastORPosition> maskedfastors; auto geo = GetGeometry(runnumber); for(auto absfastor : GetMaskedFastorIndicesL0(runnumber)) { int row, col; geo->GetTriggerMapping()->GetPositionInEMCALFromAbsFastORIndex(absfastor, col, row); maskedfastors.push_back({col, row}); } std::sort(maskedfastors.begin(), maskedfastors.end(), std::less<FastORPosition>()); return maskedfastors; } std::vector<int> AliEmcalTriggerMaskHandlerOCDB::GetMaskedFastorIndicesL1(int runnumber) { std::vector<int> maskedfastors; // Find masked FastORs at L0 auto maskedL0 = GetMaskedFastorIndicesL0(runnumber); std::copy(maskedL0.begin(), maskedL0.end(), maskedfastors.begin()); // Look for TRUs which are masked in the L1 region // For each STU which is masked at L1 mask also the FastORs // if not yet masked at L0 AliEMCALGeometry *geo = nullptr; for(auto truID : GetGlobalMaskedTRUIndices()) { if(!geo) geo = GetGeometry(runnumber); for(int ichannel = 0; ichannel < 96; ichannel++) { int absfastor; geo->GetTriggerMapping()->GetAbsFastORIndexFromTRU(truID, ichannel, absfastor); if(std::find(maskedfastors.begin(), maskedfastors.end(), absfastor) != maskedfastors.end()) maskedfastors.push_back(absfastor); } } std::sort(maskedfastors.begin(), maskedfastors.end(), std::less<int>()); return maskedfastors; } std::vector<AliEmcalTriggerMaskHandlerOCDB::FastORPosition> AliEmcalTriggerMaskHandlerOCDB::GetMaskedFastorPositionsL1(int runnumber) { std::vector<FastORPosition> maskedfastors; auto geo = GetGeometry(runnumber); for(auto absfastor : GetMaskedFastorIndicesL1(runnumber)) { int row, col; geo->GetTriggerMapping()->GetPositionInEMCALFromAbsFastORIndex(absfastor, col, row); maskedfastors.push_back({col, row}); } std::sort(maskedfastors.begin(), maskedfastors.end(), std::less<FastORPosition>()); return maskedfastors; } std::vector<int> AliEmcalTriggerMaskHandlerOCDB::GetGlobalMaskedTRUIndices(int runnumber) { std::vector<int> truindices; UpdateCache(runnumber); auto geo = GetGeometry(runnumber); auto emcalstu = fCurrentConfig->GetSTUDCSConfig(false), dcalstu = fCurrentConfig->GetSTUDCSConfig(false); if(emcalstu) { std::bitset<32> mask(emcalstu->GetRegion()); for(int itru = 0; itru < 32; itru++) { if(!mask.test(itru)) { // TRU excluded from region, add to masked TRUs truindices.push_back(geo->GetTRUIndexFromSTUIndex(itru, 0)); } } } if(dcalstu) { std::bitset<32> mask(dcalstu->GetRegion()); for(int itru = 0; itru < 14; itru++) { if(!mask.test(itru)) { // TRU excluded from region, add to masked TRUs truindices.push_back(geo->GetTRUIndexFromSTUIndex(itru, 1)); } } } std::sort(truindices.begin(), truindices.end(), std::less<int>()); return truindices; } TH2 *AliEmcalTriggerMaskHandlerOCDB::MonitorMaskedFastORsL0(int runnumber) { std::string runstring = runnumber < 0 ? "Current" : Form("%d", runnumber); std::string histname = Form("maskedFastorsL0%s", runstring.data()), histtitle = Form("Masked fastors at L0 for run %s", runstring.data()); auto outputhist = PrepareHistogram(histname.data(), histtitle.data()); auto maskedfastors = GetMaskedFastorPositionsL0(runnumber); FillMaskedFastors(outputhist, maskedfastors); return outputhist; } TH2 *AliEmcalTriggerMaskHandlerOCDB::MonitorMaskedFastORsL1(int runnumber) { std::string runstring = runnumber < 0 ? "Current" : Form("%d", runnumber); std::string histname = Form("maskedFastorsL1%s", runstring.data()), histtitle = Form("Masked fastors at L1 for run %s", runstring.data()); auto outputhist = PrepareHistogram(histname.data(), histtitle.data()); auto maskedfastors = GetMaskedFastorPositionsL1(runnumber); FillMaskedFastors(outputhist, maskedfastors); return outputhist; } int AliEmcalTriggerMaskHandlerOCDB::GetChannelForMaskRun1(int mask, int bitnumber) { return mask * 16 + bitnumber; } int AliEmcalTriggerMaskHandlerOCDB::GetChannelForMaskRun2(int mask, int bitnumber) { const int kChannelMap[6][16] = {{ 8, 9,10,11,20,21,22,23,32,33,34,35,44,45,46,47}, // Channels in mask0 {56,57,58,59,68,69,70,71,80,81,82,83,92,93,94,95}, // Channels in mask1 { 4, 5, 6, 7,16,17,18,19,28,29,30,31,40,41,42,43}, // Channels in mask2 {52,53,54,55,64,65,66,67,76,77,78,79,88,89,90,91}, // Channels in mask3 { 0, 1, 2, 3,12,13,14,15,24,25,26,27,36,37,38,39}, // Channels in mask4 {48,49,50,51,60,61,62,63,72,73,74,75,84,85,86,87}}; // Channels in mask5 return kChannelMap[mask][bitnumber]; } AliEMCALGeometry *AliEmcalTriggerMaskHandlerOCDB::GetGeometry(int runnumber) { if(runnumber >= 0) return AliEMCALGeometry::GetInstanceFromRunNumber(runnumber); auto geo = AliEMCALGeometry::GetInstance(); if(!geo) throw GeometryNotSetException(); return geo; } void AliEmcalTriggerMaskHandlerOCDB::ClearCache() { if(fCurrentConfig) delete fCurrentConfig; fCurrentConfig = nullptr; fCurrentRunnumber = -1; } void AliEmcalTriggerMaskHandlerOCDB::UpdateCache(int runnumber) { if((runnumber == fCurrentRunnumber) && fCurrentConfig) return; ClearCache(); auto cdb = InitCDB(runnumber); auto trgobject = cdb->Get("EMCAL/CalibTrigger")->GetObject(); if(!trgobject) throw OCDBNotInitializedException(); fCurrentConfig = dynamic_cast<AliEMCALTriggerDCSConfig *>(trgobject); if(!fCurrentConfig) throw OCDBNotInitializedException(); if(runnumber != fCurrentRunnumber) fCurrentRunnumber = runnumber; } AliCDBManager *AliEmcalTriggerMaskHandlerOCDB::InitCDB(int runnumber) { AliCDBManager *cdb = AliCDBManager::Instance(); if(!cdb) throw OCDBNotInitializedException(); if(!cdb->IsDefaultStorageSet()) throw OCDBNotInitializedException(); if(runnumber >= 0) { // Run number handled by handler auto currentrun = cdb->GetRun(); if(currentrun != runnumber) { // Changing run numbre cdb->SetRun(runnumber); } } else { // Run number not specified - run number handled outside if(cdb->GetRun() <= 0) throw OCDBNotInitializedException(); } return cdb; } TH2 *AliEmcalTriggerMaskHandlerOCDB::PrepareHistogram(const char *name, const char *title) { TH2 *maskhist = new TH2I(name, title, 48, -0.5, 47.5, 104, -0.5, 103.5); maskhist->SetDirectory(nullptr); maskhist->GetXaxis()->SetTitle("#eta (col)"); maskhist->GetYaxis()->SetTitle("#phi (row)"); return maskhist; } void AliEmcalTriggerMaskHandlerOCDB::FillMaskedFastors(TH2 *outputhist, const std::vector<FastORPosition> &fastors) const { for(auto fastor : fastors) { outputhist->Fill(fastor.column, fastor.row); } }
0970325c2712cf6b63d9f373803906aeacdce268
[ "C", "C++" ]
3
C++
pgamamed/AliPhysics
87b17886e44c1e4f7c9484309036a81344728bc4
d0f40169cd8050fd4320b9c38cd8009c673a1461
refs/heads/main
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.doctor; import com.jfoenix.controls.JFXListView; import static immunehistory.ImmuneHistory.stage; import static immunehistory.labib_constants.Constants.previous_page; import immunehistory.labib_database.Database; import java.net.URL; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; /** * FXML Controller class * * @author labib */ public class Doctor_give_medicine_feedbackController implements Initializable { @FXML private TextField medicine_name; @FXML private TextField success_rate; @FXML private TextField age; @FXML private JFXListView<String> suggestions; @FXML private AnchorPane anchorpane; @FXML private Pane pane; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO medicine_name.textProperty().addListener((observable, oldValue, newValue) -> { ObservableList<String> medicine_generic_name = FXCollections.observableArrayList (); ResultSet result = Database.select_query( "SELECT * FROM medicine_generic_name WHERE medicine_generic_name LIKE '"+newValue+"%' " ); try { while( result.next() ){ medicine_generic_name.add( result.getString( "medicine_generic_name" ) ); } suggestions.setItems(medicine_generic_name); suggestions.visibleProperty().set(true); } catch (SQLException ex) { Logger.getLogger(Doctor_give_medicine_feedbackController.class.getName()).log(Level.SEVERE, null, ex); } }); } @FXML private void submit(MouseEvent event) { String mn = medicine_name.getText(); String sr = success_rate.getText(); String a = age.getText(); Database.insert_query( "INSERT INTO doc_med_feedback VALUES " + " ( '"+a+"', '"+mn+"', '"+sr+"' ) " ); } @FXML private void back(MouseEvent event) { stage.setScene( previous_page.pop() ); stage.show(); } @FXML private void suggestions_selected(MouseEvent event) { medicine_name.setText(""); medicine_name.setText( suggestions.getSelectionModel().getSelectedItem() ); suggestions.visibleProperty().set(false); } @FXML private void pane_clicked(MouseEvent event) { suggestions.visibleProperty().set(false); } @FXML private void anchorpane_clicked(MouseEvent event) { suggestions.visibleProperty().set(false); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.doctor; import static immunehistory.ImmuneHistory.stage; import static immunehistory.labib_constants.Constants.previous_page; import immunehistory.labib_database.Database; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.input.MouseEvent; /** * FXML Controller class * * @author labib */ public class Main_menuController implements Initializable { @FXML private Button medicine_feedback; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO } @FXML private void show_user_history(MouseEvent event) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("user_history_find.fxml")); Scene scene = new Scene(root); previous_page.push( stage.getScene() ); stage.setScene(scene); stage.show(); } @FXML private void back(MouseEvent event) { stage.setScene( previous_page.pop() ); stage.show(); } @FXML private void write_prescription(MouseEvent event) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("write_prescription.fxml")); Scene scene = new Scene(root); previous_page.push( stage.getScene() ); stage.setScene(scene); stage.show(); } @FXML private void edit_profile(MouseEvent event) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("doctor_edit_profile.fxml")); Scene scene = new Scene(root); previous_page.push( stage.getScene() ); stage.setScene(scene); stage.show(); } @FXML private void appointments(MouseEvent event) { } @FXML private void medicine_success_feedback(MouseEvent event) { } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.statics.statics_drug_panel; /** * * @author joyultimates */ public class statics_drug_panel { private String Drugid; private String MedGenericName; private String MedBrandName; private String Applyonpatient; private String Note; private String Action; public statics_drug_panel(String Drugid, String MedGenericName, String MedBrandName, String Note) { this.Drugid = Drugid; this.MedGenericName = MedGenericName; this.MedBrandName = MedBrandName; this.Note = Note; } /** * @return the Drugid */ public String getDrugid() { return Drugid; } /** * @param Drugid the Drugid to set */ public void setDrugid(String Drugid) { this.Drugid = Drugid; } /** * @return the MedGenericName */ public String getMedGenericName() { return MedGenericName; } /** * @param MedGenericName the MedGenericName to set */ public void setMedGenericName(String MedGenericName) { this.MedGenericName = MedGenericName; } /** * @return the MedBrandName */ public String getMedBrandName() { return MedBrandName; } /** * @param MedBrandName the MedBrandName to set */ public void setMedBrandName(String MedBrandName) { this.MedBrandName = MedBrandName; } /** /** * @return the Note */ public String getNote() { return Note; } /** * @param Note the Note to set */ public void setNote(String Note) { this.Note = Note; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.statics.login_registration; import com.jfoenix.controls.JFXPasswordField; import com.jfoenix.controls.JFXTextField; import static com.sun.javaws.ui.SplashScreen.hide; import static immunehistory.statics.login_registration.Statics_registrationController.statics_email; import static immunehistory.statics.login_registration.Statics_registrationController.statics_password; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Random; import java.util.Properties; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.Label; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javax.mail.Message.RecipientType; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.swing.JOptionPane; /** * FXML Controller class * * @author joyultimates */ public class Statics_otpController implements Initializable { private Connection con = null; private PreparedStatement pst = null; private ResultSet rs; public static int otpmatched=0; @FXML private Label lblOtpError; @FXML private JFXPasswordField statics_otp_field; @FXML private Button statics_otpSubmit_btn; @FXML private JFXTextField hide; @FXML private JFXTextField emailtest; @FXML private Label lblotpNotMatched; @FXML private AnchorPane statics_otp_id; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO con =dba.DBConnection.immunehistoryConnection(); Random(); sendotp(); } public void Random(){ Random rd=new Random(); hide.setText(""+rd.nextInt(10000+1)); emailtest.setText(statics_email); } public void sendotp(){ Properties props=new Properties(); props.put("mail.smtp.host","smtp.gmail.com"); props.put("mail.smtp.port",465); props.put("mail.smtp.user","<EMAIL>"); props.put("mail.smtp.auth",true); props.put("mail.smtp.starttls.enable",true); props.put("mail.smtp.debug",true); props.put("mail.smtp.socketFactory.port",465); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback",false); try { Session session = Session.getDefaultInstance(props, null); session.setDebug(true); MimeMessage message = new MimeMessage(session); message.setText("Your OTP is " + hide.getText()); message.setSubject("OTP For Immune History"); message.setFrom(new InternetAddress("")); message.addRecipient(RecipientType.TO, new InternetAddress(statics_email.trim())); message.saveChanges(); try { Transport transport = session.getTransport("smtp"); transport.connect("smtp.gmail.com","",""); transport.sendMessage(message, message.getAllRecipients()); transport.close(); // jTextField8.setEditable(true); // jPanel4.setVisible(false); // jPanel6.setVisible(true); // //JOptionPane.showMessageDialog(null,"OTP has send to your Email id"); }catch(Exception e) { JOptionPane.showMessageDialog(null,"Please check your internet connection"); } } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(null,e); } } @FXML private void statics_otp_home_id(MouseEvent event) throws IOException { Parent home = FXMLLoader.load(getClass().getResource("/immunehistory/home.fxml")); Scene scene = new Scene(home); statics_otp_id.getChildren().setAll(home); } @FXML private void statics_otp_submitOnAction(ActionEvent event) throws IOException { if(hide.getText().equals(statics_otp_field.getText())){ try { String insert ="INSERT INTO statics_user(statics_user_email,statics_user_password)Values(?,?)" ; pst = con.prepareStatement(insert); pst.setString(1,statics_email); pst.setString(2,statics_password); int i = pst.executeUpdate(); if(i==1){ Alert alert = new Alert(Alert.AlertType.INFORMATION.CONFIRMATION,"Registration successfully",ButtonType.OK); alert.show(); Parent home = FXMLLoader.load(getClass().getResource("statics_login.fxml")); Scene scene = new Scene(home); statics_otp_id.getChildren().setAll(home); } } catch (SQLException ex) { Logger.getLogger(Statics_registrationController.class.getName()).log(Level.SEVERE, null, ex); Alert alert = new Alert(Alert.AlertType.INFORMATION.WARNING,"Something Wrong",ButtonType.OK); alert.show(); } }else{ lblotpNotMatched.setText("OTP Not Matched"); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.statics.statics_drugstatics_panel; import immunehistory.statics.statics_drug_panel.statics_drug_panel; import immunehistory.statics.statics_drug_panel.statics_drug_panelController; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; /** * FXML Controller class * * @author joyultimates */ public class Statics_drugstaticsController implements Initializable { private Connection con = null; private PreparedStatement pst = null; private ResultSet rs = null; private ObservableList<Statics_drugstatics> data; private String menubox =""; @FXML private Button statics_medicine_feedback_menubtn; @FXML private TextField statics_diseases_panel_search_field; @FXML private TableView<Statics_drugstatics> medicinefeedbackTable; @FXML private TableColumn<?, ?> drugName; @FXML private TableColumn<?, ?> age1; @FXML private TableColumn<?, ?> age2; @FXML private TableColumn<?, ?> age3; @FXML private TableView<?> treatmentFeedbackDependentTable; @FXML private TableColumn<?, ?> DtreatmentFeedbackId; @FXML private TableColumn<?, ?> DconsultId; @FXML private TableColumn<?, ?> DsuccessRate; @FXML private TableColumn<?, ?> DcommulativeRate; @FXML private TextField inputage1; @FXML private TextField inputage2; @FXML private TextField inputage3; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO con =dba.DBConnection.immunehistoryConnection(); data = FXCollections.observableArrayList(); setDrugFeedbackTable(); } private void setDrugFeedbackTable(){ drugName.setCellValueFactory(new PropertyValueFactory<>("DrugName")); age1.setCellValueFactory(new PropertyValueFactory<>("age1")); age2.setCellValueFactory(new PropertyValueFactory<>("age2")); age3.setCellValueFactory(new PropertyValueFactory<>("age3")); } private void loadDataFromDatabase(){ data.clear(); try { pst = con.prepareStatement("Select [medicine_generic_name], ["+inputage1.getText()+"], ["+inputage2.getText()+"], ["+inputage3.getText()+"]\n" + "from \n" + "(\n" + " Select medicine_generic_name,age,med_success_rate from doc_med_feedback\n" + ") as SourceTable\n" + "Pivot\n" + "(\n" + " AVG(med_success_rate)\n" + " for age in ([20],[30],[40])\n" + ") as PivotTable"); rs = pst.executeQuery(); while(rs.next()){ data.add(new Statics_drugstatics(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4))); } } catch (SQLException ex) { Logger.getLogger(Statics_drugstaticsController.class.getName()).log(Level.SEVERE, null, ex); } medicinefeedbackTable.setItems(data); } @FXML private void statics_medicine_feedback_menubtnOnAction(ActionEvent event) { loadDataFromDatabase(); } @FXML private void statics_diseases_panel_search_fieldOnAction(ActionEvent event) { } @FXML private void btnSearchOnAction(ActionEvent event) { } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.introduction_doctor; import static immunehistory.ImmuneHistory.stage; import static immunehistory.labib_constants.Constants.previous_page; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.input.MouseEvent; /** * FXML Controller class * * @author labib */ public class Introduction_doctorController implements Initializable { /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO } @FXML public void doctor() throws Exception { Parent root = FXMLLoader.load(getClass().getResource("/immunehistory/doctor/doctor_login.fxml")); Scene scene = new Scene(root); previous_page.push( stage.getScene() ); stage.setScene(scene); stage.show(); } @FXML public void lab_assistant() throws Exception { Parent root = FXMLLoader.load(getClass().getResource("/lab_assistant/lab_assistant_login.fxml")); Scene scene = new Scene(root); previous_page.push( stage.getScene() ); stage.setScene(scene); stage.show(); } @FXML private void back(MouseEvent event) { stage.setScene( previous_page.pop() ); stage.show(); } } <file_sep># ImmuneHistory Patient affected by diseases. Patient Consults doctors. A patient can consult many doctors in many hospital. Doctors have assistants. Under a doctor Assistant treat the patient. Based on diseases doctor suggests tests. Certain Diagnostic center performs test. By the result of the test report doctor prescribe medicine. A medicine has a local name, a generic name and same medicines belongs to same group. Patients take medicine. Some medicine do not suit patients. Doctor change the medicine. Based on age sex, gender medicines work upon them. Every patient has an unique patient Id. A System should be designed based on this. ![195205890_1200779720348111_3919326691451456606_n](https://user-images.githubusercontent.com/42905945/121464190-3b988380-c9d5-11eb-8386-ad7e02398f0d.png) ![195742439_485824975839806_6231348816512142256_n](https://user-images.githubusercontent.com/42905945/121464760-4bfd2e00-c9d6-11eb-9ca5-b61f1a3be269.png) ![197682984_961670947980043_7963595285248499093_n](https://user-images.githubusercontent.com/42905945/121464765-4ef81e80-c9d6-11eb-9e3a-a524d498c050.png) <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package validation; import javafx.scene.control.Label; import javafx.scene.control.TextField; /** * * @author joyultimates */ public class TextFieldValidation { public static boolean isTextFieldNoEmpty(TextField tf){ boolean b = false; if(tf.getText().length() !=0 || tf.getText().isEmpty()) b= true; return b; } public static boolean isTextFieldNoEmpty(TextField tf,Label lb, String errorMessage){ boolean b = true; String msg = null; if(!isTextFieldNoEmpty(tf)){ b = false; msg = errorMessage; } lb.setText(msg); return b; } public static boolean istextFieldTypeNumber(TextField tf){ boolean b = false; if(tf.getText().matches("([0-9]+(\\.[0-9]+)?)+")) b = true; return b; } public static boolean istextFieldTypeNumber(TextField tf,Label lb, String errorMessage){ boolean b = true; String msg = null; if(!istextFieldTypeNumber(tf)){ b = false; msg = errorMessage; } lb.setText(msg); return b; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.lab_test; import static immunehistory.ImmuneHistory.stage; import immunehistory.labib_constants.Constants; import static immunehistory.labib_constants.Constants.previous_page; import immunehistory.labib_database.Database; import java.net.URL; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.DatePicker; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; /** * FXML Controller class * * @author labib */ public class Lab_test_edit_test_reportController implements Initializable { @FXML private TextField ref_id; @FXML private TextField consult_id; @FXML private TextField test_name; @FXML private TextField report; @FXML private DatePicker date_of_test; @FXML private DatePicker date_of_result; @FXML private TextField test_center; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO try { ResultSet result = Database.select_query( "SELECT * FROM lab_test WHERE assistant_id = '"+Constants.assistant_id_logged_in+"' " ); while( result.next() ){ ref_id.setText( result.getString("ref_id") ); consult_id.setText( String.valueOf( result.getInt("consult_id") ) ); test_name.setText( result.getString("test_name") ); report.setText( result.getString("report") ); test_center.setText( String.valueOf( result.getString("test_center")) ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); String date1 = result.getString("date_of_test").split(" ")[0]; String date2 = result.getString("date_of_result").split(" ")[0]; System.out.println(date1+" "+date2); LocalDate localDate = LocalDate.parse( date1, formatter ); LocalDate localDate2 = LocalDate.parse( date2, formatter ); date_of_test.setValue( localDate ); date_of_result.setValue( localDate2 ); } } catch (SQLException ex) { Logger.getLogger(Lab_test_edit_test_reportController.class.getName()).log(Level.SEVERE, null, ex); } } @FXML private void insert(MouseEvent event) { String r = ref_id.getText(); String cid = consult_id.getText(); String tn = test_name.getText(); String rep = report.getText(); String tc = test_center.getText(); String dot = date_of_test.getValue().toString(); String dor = date_of_result.getValue().toString(); Database.insert_query("UPDATE lab_test SET " + " ref_id = '"+r+"'," + " consult_id = '"+cid+"', " + " test_name = '"+tn+"', " + " report = '"+rep+"', " + " test_center = '"+tc+"', " + " date_of_test = '"+dot+"', " + " date_of_result = '"+dor+"' WHERE consult_id = '"+cid+"' AND ref_id = '"+r+"' "); } @FXML private void back(MouseEvent event) { stage.setScene( previous_page.pop() ); stage.show(); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.statics.login_registration; import com.jfoenix.controls.JFXPasswordField; import com.jfoenix.controls.JFXTextField; import static immunehistory.statics.login_registration.Statics_otpController.otpmatched; import static immunehistory.statics.login_registration.Statics_registrationController.statics_password; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import static javafx.scene.control.ButtonType.OK; import javafx.scene.control.Label; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; /** * FXML Controller class * * @author joyultimates */ public class Statics_registrationController implements Initializable { private Connection con = null; private PreparedStatement pst = null; public static String statics_email; public static String statics_password; @FXML private AnchorPane statics_registration_id; @FXML private Label lblEmailError; @FXML private Label lblPassError; @FXML private JFXTextField statics_email_id; @FXML private JFXPasswordField statics_password_id; @FXML private JFXPasswordField statics_confirmpass_id; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO con =dba.DBConnection.immunehistoryConnection(); } @FXML private void statics_registration_login_id(MouseEvent event) throws IOException { Parent home = FXMLLoader.load(getClass().getResource("statics_login.fxml")); Scene scene = new Scene(home); statics_registration_id.getChildren().setAll(home); } @FXML private void statics_registration_home_id(MouseEvent event) throws IOException { Parent home = FXMLLoader.load(getClass().getResource("/immunehistory/home.fxml")); Scene scene = new Scene(home); statics_registration_id.getChildren().setAll(home); } @FXML private void statics_registrationOnAction(ActionEvent event) throws IOException { boolean isValidEmail = validation.EmailValidation.isValidEmail(statics_email_id, lblEmailError,"Invalid Email!!"); boolean isPasswordMatched = validation.EmailValidation.isPasswordMatched(statics_password_id,statics_confirmpass_id,lblPassError,"Password not Matched !!"); if(isValidEmail && isPasswordMatched){ lblEmailError.setText(""); lblPassError.setText(""); statics_email= statics_email_id.getText(); statics_password = <PASSWORD>(); Parent home = FXMLLoader.load(getClass().getResource("statics_otp.fxml")); Scene scene = new Scene(home); statics_registration_id.getChildren().setAll(home); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.statics.statics_drug_panel; /** * * @author joyultimates */ public class Statics_add_new_trade_name { private String GenericId; private String GenericName; public Statics_add_new_trade_name(String GenericId, String GenericName) { this.GenericId = GenericId; this.GenericName = GenericName; } /** * @return the GenericId */ public String getGenericId() { return GenericId; } /** * @param GenericId the GenericId to set */ public void setGenericId(String GenericId) { this.GenericId = GenericId; } /** * @return the GenericName */ public String getGenericName() { return GenericName; } /** * @param GenericName the GenericName to set */ public void setGenericName(String GenericName) { this.GenericName = GenericName; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.statics.statics_drug_panel; import immunehistory.statics.statics_diseases_panel.*; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Optional; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.Label; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.util.Callback; import org.controlsfx.control.PrefixSelectionComboBox; public class statics_drug_panelController implements Initializable { private Connection con = null; private PreparedStatement pst = null; private ResultSet rs = null; private ObservableList<statics_drug_panel> data; private String menubox =""; @FXML private Button btnPrev; @FXML private Label lblTotalDiseases; @FXML private Label lblShowingDiseases; @FXML private Button btnNext; @FXML private TableView<statics_drug_panel> drugTable; @FXML private TableColumn<?, ?> clm_drug_id; @FXML private TableColumn<?, ?> clm_generic_name; @FXML private TableColumn<?, ?> clm_brand_name; @FXML private TableColumn<?, ?> clm_apply_onpatient; @FXML private TableColumn<?, ?> clm_note; @FXML private TableColumn<?, ?> clmAction; @FXML private PrefixSelectionComboBox<String> statics_drug_panel_menubox; @FXML private Button statics_drug_panel_menubtn; @FXML private TextField statics_drug_panel_search_field; /** * Initializes the controller class. * * @param url * @param rb */ @Override public void initialize(URL url, ResourceBundle rb) { con =dba.DBConnection.immunehistoryConnection(); data = FXCollections.observableArrayList(); setDrugTable(); loadDataFromDatabase_collective(); searchDrugPanel(); //ADD items to statics_diseases_panel_menubox statics_drug_panel_menubox.getItems().add("Indivudual Data"); statics_drug_panel_menubox.getItems().add("Collective Data"); } private void setDrugTable(){ clm_drug_id.setCellValueFactory(new PropertyValueFactory<>("Drugid")); clm_generic_name.setCellValueFactory(new PropertyValueFactory<>("MedGenericName")); clm_brand_name.setCellValueFactory(new PropertyValueFactory<>("MedBrandName")); clm_apply_onpatient.setCellValueFactory(new PropertyValueFactory<>("Applyonpatient")); clm_note.setCellValueFactory(new PropertyValueFactory<>("Note")); clmAction.setCellValueFactory(new PropertyValueFactory<>("Action")); } private void loadDataFromDatabase_collective(){ data.clear(); try { pst = con.prepareStatement("select \n" + " DISTINCT medicine_generic_name.medicine_generic_id,\n" + " \n" + " medicine_generic_name,\n" + " \n" + " STUFF((select DISTINCT ','+ medicine_local_name.medicine_local_name\n" + " from medicine_local_name\n" + " where medicine_local_name.medicine_generic_id = medicine_generic_name.medicine_generic_id\n" + " FOR XML PATH('')),1,1,'') AS med_local,\n" + " \n" + " medicine_generic_note\n" + "\n" + "from medicine_generic_name\n" + "left join medicine_local_name\n" + "on medicine_generic_name.medicine_generic_id = medicine_local_name.medicine_generic_id"); rs = pst.executeQuery(); while(rs.next()){ data.add(new statics_drug_panel(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4))); } } catch (SQLException ex) { Logger.getLogger(statics_drug_panelController.class.getName()).log(Level.SEVERE, null, ex); } drugTable.setItems(data); } private void loadDataFromDatabase_indivudual(){ data.clear(); try { pst = con.prepareStatement("select \n" + " medicine_generic_name.medicine_generic_id,\n" + " medicine_generic_name,\n" + " medicine_local_name.medicine_local_name,\n" + " medicine_generic_note\n" + "\n" + "from medicine_generic_name\n" + "left join medicine_local_name\n" + "on medicine_generic_name.medicine_generic_id = medicine_local_name.medicine_generic_id"); rs = pst.executeQuery(); while(rs.next()){ data.add(new statics_drug_panel(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4))); } } catch (SQLException ex) { Logger.getLogger(statics_drug_panelController.class.getName()).log(Level.SEVERE, null, ex); } drugTable.setItems(data); } @FXML private void btnSearchOnAction(ActionEvent event) { } @FXML private void handlePrevButton(ActionEvent event) { } @FXML private void handleNextButton(ActionEvent event) { } @FXML private void AddNewTradeNameOnAction(ActionEvent event) throws IOException { FXMLLoader fXMLLoader = new FXMLLoader(); fXMLLoader.setLocation(getClass().getResource("/immunehistory/statics/statics_drug_panel/statics_add_new_trade_name.fxml")); Stage stage = new Stage(); Scene scene = new Scene(fXMLLoader.load()); stage.setScene(scene); stage.setTitle("Add Drug"); stage.resizableProperty().setValue(false); stage.initModality(Modality.APPLICATION_MODAL); stage.show(); } @FXML private void AddNewDrugOnAction(ActionEvent event) throws IOException { FXMLLoader fXMLLoader = new FXMLLoader(); fXMLLoader.setLocation(getClass().getResource("/immunehistory/statics/statics_drug_panel/statics_add_new_drug.fxml")); Stage stage = new Stage(); Scene scene = new Scene(fXMLLoader.load()); stage.setScene(scene); stage.setTitle("Add Drug"); stage.resizableProperty().setValue(false); stage.initModality(Modality.APPLICATION_MODAL); stage.show(); } @FXML private void statics_drug_panel_menubtnOnAction(ActionEvent event) { menubox = statics_drug_panel_menubox.getSelectionModel().getSelectedItem(); System.out.println(menubox); if(menubox.equals("Indivudual Data")){ loadDataFromDatabase_indivudual(); } if(menubox.equals("Collective Data")){ loadDataFromDatabase_collective(); } } @FXML private void statics_drug_panel_search_fieldOnAction(ActionEvent event) { } private void searchDrugPanel(){ statics_drug_panel_search_field.setOnKeyReleased(e->{ if(menubox.equals("Collective Data") || menubox.equals("")) { if(statics_drug_panel_search_field.getText().equals("")){ loadDataFromDatabase_collective(); }else{ data.clear(); String sql = "with medicine_collective(med_generic_id,med_generic_name,med_local,med_generic_note)AS(\n" + "select \n" + " DISTINCT medicine_generic_name.medicine_generic_id as med_gemeric_id,\n" + " \n" + " medicine_generic_name as med_generic_name,\n" + " \n" + " STUFF((select DISTINCT ','+ medicine_local_name.medicine_local_name\n" + " from medicine_local_name\n" + " where medicine_local_name.medicine_generic_id = medicine_generic_name.medicine_generic_id\n" + " FOR XML PATH('')),1,1,'') AS med_local,\n" + " \n" + " medicine_generic_note as med_generic_note\n" + "\n" + "from medicine_generic_name\n" + "left join medicine_local_name\n" + "on medicine_generic_name.medicine_generic_id = medicine_local_name.medicine_generic_id\n" + ")\n" + "select * from medicine_collective\n" + "where med_generic_id LIKE '%"+statics_drug_panel_search_field.getText()+"%'\n" + " OR med_generic_name LIKE '%"+statics_drug_panel_search_field.getText()+"%'\n" + " OR med_local LIKE '%"+statics_drug_panel_search_field.getText()+"%'\n" + " OR med_generic_note LIKE '%"+statics_drug_panel_search_field.getText()+"%'"; try { pst = con.prepareStatement(sql); rs = pst.executeQuery(); while(rs.next()){ data.add(new statics_drug_panel(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4))); } drugTable.setItems(data); } catch (SQLException ex) { Logger.getLogger(Statics_drug_listController.class.getName()).log(Level.SEVERE, null, ex); } } }else if(menubox.equals("Indivudual Data")) { if(statics_drug_panel_search_field.getText().equals("")){ loadDataFromDatabase_indivudual(); }else{ data.clear(); String sql = "with medicine_individual (med_generic_id,med_generic_name,med_local_name,med_generic_note) AS(\n" + "select \n" + " medicine_generic_name.medicine_generic_id as med_generic_id,\n" + " medicine_generic_name as med_generic_name,\n" + " medicine_local_name.medicine_local_name as med_local_name,\n" + " medicine_generic_note as med_generic_note\n" + "\n" + "from medicine_generic_name\n" + "left join medicine_local_name\n" + "on medicine_generic_name.medicine_generic_id = medicine_local_name.medicine_generic_id\n" + ")\n" + "select * from medicine_individual\n" + "where med_generic_id LIKE '%"+statics_drug_panel_search_field.getText()+"%'\n" + " OR med_generic_name LIKE '%"+statics_drug_panel_search_field.getText()+"%'\n" + " OR med_local_name LIKE '%"+statics_drug_panel_search_field.getText()+"%'\n" + " OR med_generic_note LIKE '%"+statics_drug_panel_search_field.getText()+"%'"; try { pst = con.prepareStatement(sql); rs = pst.executeQuery(); while(rs.next()){ data.add(new statics_drug_panel(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4))); } drugTable.setItems(data); } catch (SQLException ex) { Logger.getLogger(Statics_drug_listController.class.getName()).log(Level.SEVERE, null, ex); } } } }); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.User; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.text.Text; import org.controlsfx.control.textfield.TextFields; /** * * @author Sadman */ public class TagBar extends HBox { private final ObservableList<String> tags; private final TextField inputTextField; static Set<String> doctorSuggestionOnDisease = new HashSet<>(); static String category; public ObservableList<String> getTags() { return tags; } public void clearText() { tags.removeAll(tags); } public String getText() { String text; text=this.inputTextField.getText(); return text; } public TagBar() { getStyleClass().setAll("tag-bar"); getStylesheets().add(getClass().getResource("style.css").toExternalForm()); tags = FXCollections.observableArrayList(); inputTextField = new TextField(); inputTextField.setOnAction(evt -> { String text = inputTextField.getText(); if (!text.isEmpty() && !tags.contains(text)) { tags.add(text); inputTextField.clear(); ConnectMSSQL cnObj=new ConnectMSSQL(); ArrayList<String> diseaseDoctors=new ArrayList(); diseaseDoctors=cnObj.fetchDoctorBasedOnDisease(text); doctorSuggestionOnDisease = new HashSet<>(); for(int i=0;i<diseaseDoctors.size()-1;i++) { doctorSuggestionOnDisease.add(diseaseDoctors.get(i)); } category=diseaseDoctors.get(diseaseDoctors.size()-1); System.out.println(category); } }); inputTextField.prefHeightProperty().bind(this.heightProperty()); HBox.setHgrow(inputTextField, Priority.ALWAYS); inputTextField.setBackground(null); tags.addListener((ListChangeListener.Change<? extends String> change) -> { while (change.next()) { if (change.wasPermutated()) { ArrayList<Node> newSublist = new ArrayList<>(change.getTo() - change.getFrom()); for (int i = change.getFrom(), end = change.getTo(); i < end; i++) { newSublist.add(null); } for (int i = change.getFrom(), end = change.getTo(); i < end; i++) { newSublist.set(change.getPermutation(i), getChildren().get(i)); } getChildren().subList(change.getFrom(), change.getTo()).clear(); getChildren().addAll(change.getFrom(), newSublist); } else { if (change.wasRemoved()) { getChildren().subList(change.getFrom(), change.getFrom() + change.getRemovedSize()).clear(); } if (change.wasAdded()) { getChildren().addAll(change.getFrom(), change.getAddedSubList().stream().map(Tag::new).collect(Collectors.toList())); } } } }); ConnectMSSQL cnObj=new ConnectMSSQL(); ArrayList<String> symptoms=new ArrayList(); symptoms=cnObj.fetchSymptomps(); TextFields.bindAutoCompletion(inputTextField, symptoms); getChildren().add(inputTextField); } private class Tag extends HBox { public Tag(String tag) { getStyleClass().setAll("tag"); Button removeButton = new Button("X"); removeButton.setOnAction((evt) -> tags.remove(tag)); Text text = new Text(tag); HBox.setMargin(text, new Insets(0, 0, 0, 5)); getChildren().addAll(text, removeButton); } } }<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package validation; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; /** * * @author joyultimates */ public class EmailValidation { public static boolean isValidEmail(TextField tf){ boolean b = false; String pattern = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*.\\w+([-.]\\w+)*"; if(tf.getText().matches(pattern)) b= true; return b; } public static boolean isValidEmail(TextField tf,Label lb, String errorMessage){ boolean b = true; String msg = null; if(!isValidEmail(tf)){ b = false; msg = errorMessage; } lb.setText(msg); return b; } public static boolean isPasswordMatched(PasswordField tf1, PasswordField tf2){ boolean b = false; if(tf1.getText().equals(tf2.getText())) b= true; return b; } public static boolean isPasswordMatched(PasswordField tf1,PasswordField tf2,Label lb, String errorMessage){ boolean b = true; String msg = null; if(!isPasswordMatched(tf1,tf2)){ b = false; msg = errorMessage; } lb.setText(msg); return b; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.statics.statics_diseases_panel; import immunehistory.statics.statics_drug_panel.Statics_drug_listController; import immunehistory.statics.statics_drug_panel.statics_drug_list; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Optional; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.Label; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.util.Callback; import org.controlsfx.control.PrefixSelectionComboBox; public class statics_diseases_panelController implements Initializable { private Connection con = null; private PreparedStatement pst = null; private ResultSet rs = null; private ObservableList<statics_diseases_panel> data; private String menubox =""; @FXML private Button btnPrev; @FXML private Label lblTotalDiseases; @FXML private Label lblShowingDiseases; @FXML private Button btnNext; @FXML private TableView<statics_diseases_panel> diseaseTable; @FXML private TableColumn<?, ?> clm_disease_id; @FXML private TableColumn<?, ?> clm_disease_name; @FXML private TableColumn<?, ?> clm_min_period; @FXML private TableColumn<?, ?> clm_max_period; @FXML private TableColumn<?, ?> clm_symptom; @FXML private TableColumn<?, ?> clm_medicine; @FXML private TableColumn<?, ?> clm_reactive_medicine; @FXML private TableColumn<?, ?> clmAction; @FXML private TableColumn<?, ?> clm_disease_type; @FXML private PrefixSelectionComboBox<String> statics_diseases_panel_menubox; @FXML private Button statics_diseases_panel_menubtn; @FXML private TextField statics_diseases_panel_search_field; /** * Initializes the controller class. * * @param url * @param rb */ @Override public void initialize(URL url, ResourceBundle rb) { con =dba.DBConnection.immunehistoryConnection(); data = FXCollections.observableArrayList(); setDiseaseListTable(); loadDataFromDatabase_collective(); searchDiseasesPanel(); //ADD items to statics_diseases_panel_menubox statics_diseases_panel_menubox.getItems().add("Indivudual Data"); statics_diseases_panel_menubox.getItems().add("Collective Data"); } private void setDiseaseListTable(){ clm_disease_id.setCellValueFactory(new PropertyValueFactory<>("Diseaseid")); clm_disease_name.setCellValueFactory(new PropertyValueFactory<>("DiseaseName")); clm_disease_type.setCellValueFactory(new PropertyValueFactory<>("DiseaseType")); clm_min_period.setCellValueFactory(new PropertyValueFactory<>("MinPeriod")); clm_max_period.setCellValueFactory(new PropertyValueFactory<>("MaxPeriod")); clm_symptom.setCellValueFactory(new PropertyValueFactory<>("Symptom")); clm_medicine.setCellValueFactory(new PropertyValueFactory<>("Medicine")); clm_reactive_medicine.setCellValueFactory(new PropertyValueFactory<>("ReactiveMedicine")); clmAction.setCellValueFactory(new PropertyValueFactory<>("Action")); } private void loadDataFromDatabase_collective(){ data.clear(); try { pst = con.prepareStatement("select \n" + " DISTINCT difo2.disease_id,\n" + " \n" + " (select disease_name from disease_name where disease_name.disease_id = difo2.disease_id) as diseaseName,\n" + "\n" + " STUFF((select DISTINCT ','+ (select disease_type from disease_type where disease_type.disease_type_id = difo1.disease_type_id)\n" + " from disease_info difo1\n" + " where difo1.disease_id = difo2.disease_id\n" + " FOR XML PATH('')),1,1,'') AS dis_type,\n" + "\n" + " STUFF((select DISTINCT ','+ CAST(AVG(min_period) AS NVARCHAR)\n" + " from disease_info difo1\n" + " where difo1.disease_id = difo2.disease_id\n" + " FOR XML PATH('')),1,1,'') AS dis_min_period,\n" + " \n" + " STUFF((select DISTINCT ','+ CAST(AVG(max_period) AS NVARCHAR)\n" + " from disease_info difo1\n" + " where difo1.disease_id = difo2.disease_id\n" + " FOR XML PATH('')),1,1,'') AS dis_max_period,\n" + "\n" + " STUFF((select DISTINCT ','+ (select symptom_name from symptom where symptom.symptom_id = difo1.symptom_id)\n" + " from disease_info difo1\n" + " where difo1.disease_id = difo2.disease_id\n" + " FOR XML PATH('')),1,1,'') AS symptom_list,\n" + "\n" + " STUFF((select DISTINCT ','+ (select medicine_generic_name from medicine_generic_name where medicine_generic_name.medicine_generic_id = difo1.medicine_generic_id)\n" + " from disease_info difo1\n" + " where difo1.disease_id = difo2.disease_id\n" + " FOR XML PATH('')),1,1,'') AS med_generic_name,\n" + " \n" + " STUFF((select DISTINCT ','+ (select medicine_generic_name from medicine_generic_name where medicine_generic_name.medicine_generic_id = difo1.anti_medicine_generic_name)\n" + " from disease_info difo1\n" + " where difo1.disease_id = difo2.disease_id\n" + " FOR XML PATH('')),1,1,'') AS antimed_generic_name\n" + " \n" + " \n" + "from disease_info difo2\n" + "group by disease_id,min_period,max_period"); rs = pst.executeQuery(); while(rs.next()){ data.add(new statics_diseases_panel(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8))); } } catch (SQLException ex) { Logger.getLogger(statics_diseases_panelController.class.getName()).log(Level.SEVERE, null, ex); } diseaseTable.setItems(data); } private void loadDataFromDatabase_indivudual(){ data.clear(); try { pst = con.prepareStatement("select \n" + " difo2.disease_id,\n" + " \n" + " (select disease_name from disease_name where disease_name.disease_id = difo2.disease_id) as diseaseName,\n" + "\n" + " (select disease_type from disease_type where disease_type.disease_type_id = difo2.disease_type_id) as dis_type,\n" + " \n" + " difo2.min_period,\n" + "\n" + " difo2.max_period,\n" + " \n" + " (select symptom_name from symptom where symptom.symptom_id = difo2.symptom_id) as symp,\n" + " \n" + " (select medicine_generic_name from medicine_generic_name where medicine_generic_name.medicine_generic_id = difo2.medicine_generic_id) as med_generic_name,\n" + " \n" + " (select medicine_generic_name from medicine_generic_name where medicine_generic_name.medicine_generic_id = difo2.anti_medicine_generic_name) as antimed_generic_name\n" + " \n" + " \n" + "from disease_info difo2"); rs = pst.executeQuery(); while(rs.next()){ data.add(new statics_diseases_panel(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8))); } } catch (SQLException ex) { Logger.getLogger(statics_diseases_panelController.class.getName()).log(Level.SEVERE, null, ex); } diseaseTable.setItems(data); } @FXML private void btnSearchOnAction(ActionEvent event) { } @FXML private void handlePrevButton(ActionEvent event) { } @FXML private void handleNextButton(ActionEvent event) { } @FXML private void AddNewDiseaseOnAction(ActionEvent event) throws IOException { FXMLLoader fXMLLoader = new FXMLLoader(); fXMLLoader.setLocation(getClass().getResource("/immunehistory/statics/statics_diseases_panel/statics_add_new_disease.fxml")); Stage stage = new Stage(); Scene scene = new Scene(fXMLLoader.load()); stage.setScene(scene); stage.setTitle("Add Disease"); stage.resizableProperty().setValue(false); stage.initModality(Modality.APPLICATION_MODAL); stage.show(); } @FXML private void statics_diseases_panel_menubtnOnAction(ActionEvent event) { menubox = statics_diseases_panel_menubox.getSelectionModel().getSelectedItem(); System.out.println(menubox); if(menubox.equals("Indivudual Data")){ loadDataFromDatabase_indivudual(); } if(menubox.equals("Collective Data")){ loadDataFromDatabase_collective(); } } @FXML private void statics_diseases_panel_search_fieldOnAction(ActionEvent event) { } private void searchDiseasesPanel(){ statics_diseases_panel_search_field.setOnKeyReleased(e->{ if(menubox.equals("Collective Data") || menubox.equals("")) { if(statics_diseases_panel_search_field.getText().equals("")){ loadDataFromDatabase_collective(); }else{ data.clear(); String sql = "WITH diseaseInfo_collective (disId,diseaseName,dis_type,dis_min_period,\n" + " dis_max_period,symptom_list,med_generic_name,antimed_generic_name) AS(\n" + "select \n" + " DISTINCT difo2.disease_id as disId,\n" + " \n" + " (select disease_name from disease_name where disease_name.disease_id = difo2.disease_id) as diseaseName,\n" + "\n" + " STUFF((select DISTINCT ','+ (select disease_type from disease_type where disease_type.disease_type_id = difo1.disease_type_id)\n" + " from disease_info difo1\n" + " where difo1.disease_id = difo2.disease_id\n" + " FOR XML PATH('')),1,1,'') AS dis_type,\n" + "\n" + " STUFF((select DISTINCT ','+ CAST(AVG(min_period) AS NVARCHAR)\n" + " from disease_info difo1\n" + " where difo1.disease_id = difo2.disease_id\n" + " FOR XML PATH('')),1,1,'') AS dis_min_period,\n" + " \n" + " STUFF((select DISTINCT ','+ CAST(AVG(max_period) AS NVARCHAR)\n" + " from disease_info difo1\n" + " where difo1.disease_id = difo2.disease_id\n" + " FOR XML PATH('')),1,1,'') AS dis_max_period,\n" + "\n" + " STUFF((select DISTINCT ','+ (select symptom_name from symptom where symptom.symptom_id = difo1.symptom_id)\n" + " from disease_info difo1\n" + " where difo1.disease_id = difo2.disease_id\n" + " FOR XML PATH('')),1,1,'') AS symptom_list,\n" + "\n" + " STUFF((select DISTINCT ','+ (select medicine_generic_name from medicine_generic_name where medicine_generic_name.medicine_generic_id = difo1.medicine_generic_id)\n" + " from disease_info difo1\n" + " where difo1.disease_id = difo2.disease_id\n" + " FOR XML PATH('')),1,1,'') AS med_generic_name,\n" + " \n" + " STUFF((select DISTINCT ','+ (select medicine_generic_name from medicine_generic_name where medicine_generic_name.medicine_generic_id = difo1.anti_medicine_generic_name)\n" + " from disease_info difo1\n" + " where difo1.disease_id = difo2.disease_id\n" + " FOR XML PATH('')),1,1,'') AS antimed_generic_name\n" + " \n" + " \n" + "from disease_info difo2\n" + "group by disease_id,min_period,max_period\n" + "\n" + ")\n" + "select disId,diseaseName,dis_type,dis_min_period,\n" + "dis_max_period,symptom_list,med_generic_name,antimed_generic_name \n" + "from diseaseInfo_collective \n" + "where disId LIKE '%"+statics_diseases_panel_search_field.getText()+"%' \n" + " OR diseaseName LIKE '%"+statics_diseases_panel_search_field.getText()+"%'\n" + " OR dis_type LIKE '%"+statics_diseases_panel_search_field.getText()+"%'\n" + " OR dis_min_period LIKE '%"+statics_diseases_panel_search_field.getText()+"%'\n" + " OR dis_max_period LIKE '%"+statics_diseases_panel_search_field.getText()+"%'\n" + " OR symptom_list LIKE '%"+statics_diseases_panel_search_field.getText()+"%'\n" + " OR med_generic_name LIKE '%"+statics_diseases_panel_search_field.getText()+"%'\n" + " OR antimed_generic_name LIKE '%"+statics_diseases_panel_search_field.getText()+"%'"; try { pst = con.prepareStatement(sql); rs = pst.executeQuery(); while(rs.next()){ data.add(new statics_diseases_panel(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8))); } diseaseTable.setItems(data); } catch (SQLException ex) { Logger.getLogger(Statics_disease_listController.class.getName()).log(Level.SEVERE, null, ex); } } }else if(menubox.equals("Indivudual Data")) { if(statics_diseases_panel_search_field.getText().equals("")){ loadDataFromDatabase_indivudual(); }else{ data.clear(); String sql = "WITH diseaseInfo_individual (disId,diseaseName,dis_type,dis_min_period,\n" + " dis_max_period,symptom_list,med_generic_name,antimed_generic_name) AS(\n" + "select \n" + " difo2.disease_id as disId,\n" + " \n" + " (select disease_name from disease_name where disease_name.disease_id = difo2.disease_id) as diseaseName,\n" + "\n" + " (select disease_type from disease_type where disease_type.disease_type_id = difo2.disease_type_id) as dis_type,\n" + " \n" + " difo2.min_period as dis_min_period,\n" + "\n" + " difo2.max_period as dis_max_period,\n" + " \n" + " (select symptom_name from symptom where symptom.symptom_id = difo2.symptom_id) as symptom_list,\n" + " \n" + " (select medicine_generic_name from medicine_generic_name where medicine_generic_name.medicine_generic_id = difo2.medicine_generic_id) as med_generic_name,\n" + " \n" + " (select medicine_generic_name from medicine_generic_name where medicine_generic_name.medicine_generic_id = difo2.anti_medicine_generic_name) as antimed_generic_name\n" + " \n" + " \n" + "from disease_info difo2\n" + " \n" + ")\n" + "select disId,diseaseName,dis_type,dis_min_period,\n" + "dis_max_period,symptom_list,med_generic_name,antimed_generic_name \n" + "from diseaseInfo_individual \n" + "where disId LIKE '%"+statics_diseases_panel_search_field.getText()+"%' \n" + " OR diseaseName LIKE '%"+statics_diseases_panel_search_field.getText()+"%'\n" + " OR dis_type LIKE '%"+statics_diseases_panel_search_field.getText()+"%'\n" + " OR dis_min_period LIKE '%"+statics_diseases_panel_search_field.getText()+"%'\n" + " OR dis_max_period LIKE '%"+statics_diseases_panel_search_field.getText()+"%'\n" + " OR symptom_list LIKE '%"+statics_diseases_panel_search_field.getText()+"%'\n" + " OR med_generic_name LIKE '%"+statics_diseases_panel_search_field.getText()+"%'\n" + " OR antimed_generic_name LIKE '%"+statics_diseases_panel_search_field.getText()+"%'"; try { pst = con.prepareStatement(sql); rs = pst.executeQuery(); while(rs.next()){ data.add(new statics_diseases_panel(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8))); } diseaseTable.setItems(data); } catch (SQLException ex) { Logger.getLogger(Statics_disease_listController.class.getName()).log(Level.SEVERE, null, ex); } } } }); } } <file_sep> package immunehistory.statics.statics_home_panel; import immunehistory.statics.statics_diseases_panel.Statics_disease_listController; import immunehistory.statics.statics_diseases_panel.statics_disease_list; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Scene; import javafx.scene.input.MouseEvent; import javafx.scene.text.Text; import javafx.stage.Modality; import javafx.stage.Stage; public class statics_home_panelController implements Initializable { private Connection con = null; private PreparedStatement pst = null; private ResultSet rs = null; private ObservableList<statics_disease_list> data; @FXML private Text lblTotalDiseases; @FXML private Text lblTotalDrug; @FXML private Text lblTotalTreatment; @FXML private Text lblTotalDrugStatics; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { con =dba.DBConnection.immunehistoryConnection(); lblTotalDiseases(); lblTotalDrug(); } private void lblTotalDrug(){ try { pst = con.prepareStatement("select COUNT(medicine_generic_id) from medicine_generic_name"); rs = pst.executeQuery(); if(rs.next()){ String drug_count = rs.getString(1); lblTotalDrug.setText(drug_count); } } catch (SQLException ex) { Logger.getLogger(Statics_disease_listController.class.getName()).log(Level.SEVERE, null, ex); } } private void lblTotalDiseases(){ try { pst = con.prepareStatement("select COUNT(disease_id) from disease_name"); rs = pst.executeQuery(); if(rs.next()){ String disease_count = rs.getString(1); lblTotalDiseases.setText(disease_count); } } catch (SQLException ex) { Logger.getLogger(Statics_disease_listController.class.getName()).log(Level.SEVERE, null, ex); } } @FXML private void addNewDiseases(ActionEvent event) throws IOException { FXMLLoader fXMLLoader = new FXMLLoader(); fXMLLoader.setLocation(getClass().getResource("/immunehistory/statics/statics_diseases_panel/statics_add_new_disease.fxml")); Stage stage = new Stage(); Scene scene = new Scene(fXMLLoader.load()); stage.setScene(scene); stage.setTitle("Add Disease"); stage.resizableProperty().setValue(false); stage.initModality(Modality.APPLICATION_MODAL); stage.show(); } @FXML private void addNewDrugs(ActionEvent event) throws IOException { FXMLLoader fXMLLoader = new FXMLLoader(); fXMLLoader.setLocation(getClass().getResource("/immunehistory/statics/statics_drug_panel/statics_add_new_drug.fxml")); Stage stage = new Stage(); Scene scene = new Scene(fXMLLoader.load()); stage.setScene(scene); stage.setTitle("Add Drug"); stage.resizableProperty().setValue(false); stage.initModality(Modality.APPLICATION_MODAL); stage.show(); } @FXML private void viewTreatment(ActionEvent event) { } @FXML private void viewDrugStatics(ActionEvent event) { } @FXML private void statics_disease_listOnAction(MouseEvent event) throws IOException { FXMLLoader fXMLLoader = new FXMLLoader(); fXMLLoader.setLocation(getClass().getResource("/immunehistory/statics/statics_diseases_panel/statics_disease_list.fxml")); Stage stage = new Stage(); Scene scene = new Scene(fXMLLoader.load()); stage.setScene(scene); stage.setTitle("Disease List"); stage.resizableProperty().setValue(false); stage.initModality(Modality.APPLICATION_MODAL); stage.show(); } @FXML private void statics_drug_listOnAction(MouseEvent event) throws IOException { FXMLLoader fXMLLoader = new FXMLLoader(); fXMLLoader.setLocation(getClass().getResource("/immunehistory/statics/statics_drug_panel/statics_drug_list.fxml")); Stage stage = new Stage(); Scene scene = new Scene(fXMLLoader.load()); stage.setScene(scene); stage.setTitle("Disease List"); stage.resizableProperty().setValue(false); stage.initModality(Modality.APPLICATION_MODAL); stage.show(); } }<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.User; import java.net.URL; import java.util.ResourceBundle; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Pane; import javafx.stage.Stage; import animatefx.animation.*; import static immunehistory.User.ItemController.name; import immunehistory.home; import java.io.IOException; import java.sql.SQLException; import java.time.format.DateTimeFormatter; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.DatePicker; import javafx.scene.control.PasswordField; import javafx.scene.image.Image; import javafx.scene.input.InputMethodEvent; import javafx.scene.input.KeyEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.paint.Color; import javafx.stage.StageStyle; /** * FXML Controller class * * @author Sadman */ public class LoginController implements Initializable { @FXML private TextField username; @FXML private TextField phone; @FXML private Button btn_SignIn; @FXML private Button btn_SignUp; @FXML private Label forget_label; @FXML private TextField username1; @FXML private TextField phone1; @FXML private Button btn_SignInFinal; @FXML private ImageView btn_close; @FXML private ImageView btn_minimize; @FXML private ImageView btn_info; @FXML private Pane pn_signup; @FXML private Pane pn_signin; @FXML private ImageView btn_back; @FXML private Label userlabel; @FXML private TextField email1; @FXML private Label phonelabel; @FXML private Label emaillabel; @FXML private ImageView icon1; @FXML private ImageView icon2; @FXML private ImageView icon3; @FXML private ImageView loginicon1; @FXML private ImageView loginicon2; @FXML private Label loginlabel1; @FXML private Label loginlabel2; @FXML private Pane pn_otp; @FXML private PasswordField passcode; @FXML private ImageView btn_otp; @FXML private AnchorPane rootpane; String finalName,finalPhone; @FXML private DatePicker dateBirth; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO } @FXML private void handleButtonAction(ActionEvent event) throws SQLException, ClassNotFoundException { if(event.getSource().equals(btn_SignUp)) { new ZoomIn(pn_signup).play(); pn_signup.toFront(); } if(event.getSource().equals(btn_SignInFinal)) { String dateofBirth = dateBirth.getValue().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); ConnectMSSQL cnObj = new ConnectMSSQL(); cnObj.insertData(username1.getText(), phone1.getText(), email1.getText(),dateofBirth); new ZoomIn(pn_signin).play(); pn_signin.toFront(); } if(event.getSource().equals(btn_SignIn)) { String name=username.getText(); String phoneno=phone.getText(); String userId; ConnectMSSQL cnObj = new ConnectMSSQL(); if(cnObj.loginValidation(name, phoneno)) { finalName=name; finalPhone=phoneno; FXMLLoader loader=new FXMLLoader(getClass().getResource("FXML.fxml"));; FXMLController control=loader.getController(); control.finalName=finalName; control.finalPhone=finalPhone; loginlabel1.setVisible(true); loginlabel1.setText("Username Matches"); loginlabel1.setTextFill(Color.web("#56ab2f")); Image image = new Image(getClass().getResourceAsStream("images/icons8_ok_96px_3.png")); loginicon1.setImage(image); loginicon1.setVisible(true); loginlabel2.setVisible(true); loginlabel2.setText("Phone Number Matches"); loginlabel2.setTextFill(Color.web("#56ab2f")); Image image2 = new Image(getClass().getResourceAsStream("images/icons8_ok_96px_3.png")); loginicon2.setImage(image2); loginicon2.setVisible(true); new SlideInRight(pn_otp).play(); pn_otp.toFront(); } else { //new animatefx.animation. new BounceIn(pn_signin).play(); pn_signin.toFront(); loginlabel1.setVisible(true); loginlabel1.setText("Username Does Not Match."); loginlabel1.setTextFill(Color.web("#ef473a")); Image image = new Image(getClass().getResourceAsStream("images/cancel_96px.png")); loginicon1.setImage(image); loginicon1.setVisible(true); loginlabel2.setVisible(true); loginlabel2.setText("Phone Does Not Match."); loginlabel2.setTextFill(Color.web("#ef473a")); Image image2 = new Image(getClass().getResourceAsStream("images/cancel_96px.png")); loginicon2.setImage(image2); loginicon2.setVisible(true); } } } @FXML private void handleMouseEvent(MouseEvent event) { if(event.getSource()==btn_close) { new animatefx.animation.FadeOut(btn_close.getParent().getParent().getParent().getParent()).play(); new java.util.Timer().schedule( new java.util.TimerTask() { @Override public void run() { cancel(); Platform.exit(); } }, 1500 ); } if(event.getSource()==btn_otp) { String password=passcode.getText(); if(password.equals("<PASSWORD>")) { new SlideInRight(rootpane).play(); rootpane.toBack(); loginSuccess(); } } if(event.getSource()==btn_minimize) { ((Stage)((ImageView)event.getSource()).getScene().getWindow()).setIconified(true); } if(event.getSource()==btn_back) { new ZoomIn(pn_signin).play(); pn_signin.toFront(); } } @FXML private void handleInput(KeyEvent event) { if(event.getSource()==username) { String name=username.getText(); if(name.equals("")) { loginlabel1.setVisible(true); loginlabel1.setText("Text Field Is Empty"); loginlabel1.setTextFill(Color.web("#ef473a")); Image image = new Image(getClass().getResourceAsStream("images/cancel_96px.png")); loginicon1.setImage(image); loginicon1.setVisible(true); } else { if(name.matches( "[A-Z][a-z]*") || name.contains(" ")) { loginlabel1.setVisible(true); loginlabel1.setText("Looks Good"); loginlabel1.setTextFill(Color.web("#56ab2f")); Image image = new Image(getClass().getResourceAsStream("images/icons8_ok_96px_3.png")); loginicon1.setImage(image); loginicon1.setVisible(true); } else {loginlabel1.setVisible(true); loginlabel1.setText("Username is invalid."); loginlabel1.setTextFill(Color.web("#ef473a")); Image image = new Image(getClass().getResourceAsStream("images/cancel_96px.png")); loginicon1.setImage(image); loginicon1.setVisible(true); } } } if(event.getSource()==phone) { String phn=phone.getText(); String MobilePattern = "[0-9]{10}"; if(phn.equals("")) { loginlabel2.setVisible(true); loginlabel2.setText("Phone Field Is Empty"); loginlabel2.setTextFill(Color.web("#ef473a")); Image image = new Image(getClass().getResourceAsStream("images/cancel_96px.png")); loginicon2.setImage(image); loginicon2.setVisible(true); } else { if(isValidMobile(phn)) { loginlabel2.setVisible(true); loginlabel2.setText("Looks Good"); loginlabel2.setTextFill(Color.web("#56ab2f")); Image image = new Image(getClass().getResourceAsStream("images/icons8_ok_96px_3.png")); loginicon2.setImage(image); loginicon2.setVisible(true); } else {loginlabel2.setVisible(true); loginlabel2.setText("Phone number is invalid."); loginlabel2.setTextFill(Color.web("#ef473a")); Image image = new Image(getClass().getResourceAsStream("images/cancel_96px.png")); loginicon2.setImage(image); loginicon2.setVisible(true); } } } if(event.getSource()==username1) { String name=username1.getText(); System.out.println(name); if(name.equals("")) { userlabel.setVisible(true); userlabel.setText("Text Field Is Empty"); userlabel.setTextFill(Color.web("#ef473a")); Image image = new Image(getClass().getResourceAsStream("images/cancel_96px.png")); icon1.setImage(image); icon1.setVisible(true); } else { if(name.matches( "[A-Z][a-z]*") || name.contains(" ")) { userlabel.setVisible(true); userlabel.setText("Looks Good"); userlabel.setTextFill(Color.web("#56ab2f")); Image image = new Image(getClass().getResourceAsStream("images/icons8_ok_96px_3.png")); icon1.setImage(image); icon1.setVisible(true); } else {userlabel.setVisible(true); userlabel.setText("Username is invalid."); userlabel.setTextFill(Color.web("#ef473a")); Image image = new Image(getClass().getResourceAsStream("images/cancel_96px.png")); icon1.setImage(image); icon1.setVisible(true); } } } if(event.getSource()==email1) { String mail=email1.getText(); System.out.println(name); String regex = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$"; if(mail.equals("")) { emaillabel.setVisible(true); emaillabel.setText("Email Field Is Empty"); emaillabel.setTextFill(Color.web("#ef473a")); Image image = new Image(getClass().getResourceAsStream("images/cancel_96px.png")); icon2.setImage(image); icon2.setVisible(true); } else { if(mail.matches(regex)) { emaillabel.setVisible(true); emaillabel.setText("Looks Good"); emaillabel.setTextFill(Color.web("#56ab2f")); Image image = new Image(getClass().getResourceAsStream("images/icons8_ok_96px_3.png")); icon2.setImage(image); icon2.setVisible(true); } else {emaillabel.setVisible(true); emaillabel.setText("Email is invalid."); emaillabel.setTextFill(Color.web("#ef473a")); Image image = new Image(getClass().getResourceAsStream("images/cancel_96px.png")); icon2.setImage(image); icon2.setVisible(true); } } } if(event.getSource()==phone1) { String phn=phone1.getText(); System.out.println(phn); String MobilePattern = "[0-9]{10}"; if(phn.equals("")) { phonelabel.setVisible(true); phonelabel.setText("Phone Field Is Empty"); phonelabel.setTextFill(Color.web("#ef473a")); Image image = new Image(getClass().getResourceAsStream("images/cancel_96px.png")); icon3.setImage(image); icon3.setVisible(true); } else { if(isValidMobile(phn)) { phonelabel.setVisible(true); phonelabel.setText("Looks Good"); phonelabel.setTextFill(Color.web("#56ab2f")); Image image = new Image(getClass().getResourceAsStream("images/icons8_ok_96px_3.png")); icon3.setImage(image); icon3.setVisible(true); } else {phonelabel.setVisible(true); phonelabel.setText("Phone number is invalid."); phonelabel.setTextFill(Color.web("#ef473a")); Image image = new Image(getClass().getResourceAsStream("images/cancel_96px.png")); icon3.setImage(image); icon3.setVisible(true); } } } } private double x, y; public void loginSuccess() { try { Parent root = FXMLLoader.load(getClass().getResource("FXML.fxml")); //control.passeddata("hello", "111"); Stage stage = (Stage) pn_otp.getScene().getWindow(); Scene scene=new Scene(root,1024,800); stage.setScene(scene); stage.show(); root.setOnMousePressed(event -> { x = event.getSceneX(); y = event.getSceneY(); }); root.setOnMouseDragged(event -> { stage.setX(event.getScreenX() - x); stage.setY(event.getScreenY() - y); }); } catch (IOException ex) { Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex); } } private boolean isValidMobile(String phone) { if(!Pattern.matches("[a-zA-Z]+", phone)) { return phone.length() > 6 && phone.length() <= 13; } return false; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.statics.statics_drug_panel; import immunehistory.ImmuneHistory; import immunehistory.statics.login_registration.Statics_login; import immunehistory.statics.login_registration.Statics_registrationController; import static immunehistory.statics.login_registration.Statics_registrationController.statics_email; import static immunehistory.statics.login_registration.Statics_registrationController.statics_password; import static java.awt.SystemColor.window; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.stage.Stage; /** * FXML Controller class * * @author joyultimates */ public class Statics_add_new_drugController implements Initializable { private Connection con = null; private PreparedStatement pst = null; private ResultSet rs; @FXML private TextField statics_add_new_generic_name_field; @FXML private TextArea statics_add_new_generic_note_field; @FXML private Label lblDataError; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO con =dba.DBConnection.immunehistoryConnection(); } @FXML private void saveOnAction(ActionEvent event) { if(statics_add_new_generic_name_field.getText().toUpperCase().equals(getData())){ lblDataError.setText("Already Added"); }else{ try { String insert ="insert into medicine_generic_name(medicine_generic_name,medicine_generic_note) values(UPPER(?),UPPER(?))" ; pst = con.prepareStatement(insert); pst.setString(1,statics_add_new_generic_name_field.getText()); pst.setString(2,statics_add_new_generic_note_field.getText()); int i = pst.executeUpdate(); if(i==1){ Alert alert = new Alert(Alert.AlertType.INFORMATION.CONFIRMATION,"Added successfully",ButtonType.OK); alert.show(); statics_add_new_generic_name_field.setText(""); statics_add_new_generic_note_field.setText(""); } } catch (SQLException ex) { Logger.getLogger(Statics_add_new_drugController.class.getName()).log(Level.SEVERE, null, ex); Alert alert = new Alert(Alert.AlertType.INFORMATION.WARNING,"Something Wrong",ButtonType.OK); alert.show(); } } } private String getData(){ String insertData = ""; try { pst= con.prepareStatement("select medicine_generic_name " + "from medicine_generic_name where medicine_generic_name=?"); pst.setString(1,statics_add_new_generic_name_field.getText().toUpperCase()); rs = pst.executeQuery(); if(rs.next()){ insertData = rs.getString(1); } rs.close(); } catch (SQLException ex) { Logger.getLogger(Statics_add_new_drugController.class.getName()).log(Level.SEVERE, null, ex); } return insertData; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.User; import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.Label; /** * FXML Controller class * * @author Sadman */ public class ItemController implements Initializable { static String serialno,name,consultid,cat,apdate,condate,stat; /** * Initializes the controller class. */ @FXML private Label serial_no; @FXML private Label consult_id; @FXML private Label doctorname; @FXML private Label appointing_date; @FXML private Label consulting_date; @FXML private Label category; @FXML private Button status; @Override public void initialize(URL url, ResourceBundle rb) { // TODO serial_no.setText(serialno); consult_id.setText(consultid); doctorname.setText(name); appointing_date.setText(apdate); consulting_date.setText(condate); category.setText(cat); String sDate1=condate; try { Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1); Date currentDate = new Date(); if(date1.compareTo(currentDate)<0) { status.setText("Expired"); status.setStyle("-fx-background-color: #FF6961"); } else { status.setText("Active"); status.setStyle("-fx-background-color: #90EE90"); } } catch (ParseException ex) { Logger.getLogger(ItemController.class.getName()).log(Level.SEVERE, null, ex); } } public void myFunction(String Text) { } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.labib_database; import immunehistory.doctor.Doctor; import immunehistory.lab_test.Lab_Test; import immunehistory.labib_constants.Constants; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import lab_assistant.Assistant; public class Database { public static Connection connection; public static void connectDB() { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); connection = DriverManager.getConnection( "jdbc:sqlserver://localhost:1433;databaseName=immune_history;selectMethod=cursor", "sa", "labib9130608"); System.out.println("DATABASE NAME IS:" + connection.getMetaData().getDatabaseProductName()); } catch (Exception e) { e.printStackTrace(); } } public static void insert_into_doctor( Doctor doctor ){ try { if( connection == null ){ connectDB(); } Statement statement = connection.createStatement(); statement .execute("INSERT INTO doctor " +"VALUES("+ "'"+doctor.getDoctor_name()+"',"+ "'"+doctor.getDegree()+"',"+ "'"+doctor.getHospital()+"',"+ "'"+doctor.getEmail()+"',"+ "'"+doctor.getAddress()+"',"+ "'"+doctor.getMobile()+"',"+ "'"+doctor.getZipcode()+"',"+ "'"+doctor.getCategory()+"',"+ "'"+doctor.getPassword()+"'" +")" ); } catch (SQLException ex) { Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); } } public static boolean authenticate_doctor( String email, String password ){ try { if( connection == null ){ connectDB(); } Statement statement = connection.createStatement(); ResultSet resultSet = statement .executeQuery( "SELECT * FROM doctor WHERE email = '"+email+"' AND password = '"+password+"'" ); if( resultSet.next() == true ){ Constants.doctor_id = resultSet.getInt("doctor_id"); return true; } else return false; } catch (SQLException ex) { Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); } return false; } public static int authenticate_assistant( String email, String password ){ try { if( connection == null ){ connectDB(); } Statement statement = connection.createStatement(); ResultSet resultSet = statement .executeQuery( "SELECT * FROM assistant WHERE email = '"+email+"' AND password = '"+password+"'" ); if( resultSet.next() == true ) return resultSet.getInt("assistant_id"); else return -1; } catch (SQLException ex) { Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); } return -1; } public static void insert_into_assistant( Assistant assistant ){ try { if( connection == null ){ connectDB(); } Statement statement = connection.createStatement(); statement .execute("INSERT INTO assistant " +"VALUES("+ "'"+assistant.getAssistant_name()+"',"+ "'"+assistant.getMobile()+"',"+ "'"+assistant.getDegree()+"',"+ "'"+assistant.getHospital()+"',"+ "'"+assistant.getEmail()+"',"+ "'"+assistant.getAddress()+"',"+ "'"+assistant.getZipcode()+"',"+ "'"+assistant.getPassword()+"'" +")" ); } catch (SQLException ex) { Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); } } public static void insert_into_lab_test( Lab_Test lab_test ){ try { if( connection == null ){ connectDB(); } Statement statement = connection.createStatement(); statement .execute("INSERT INTO lab_test " +"VALUES("+ "'"+lab_test.getRef_id()+"',"+ "'"+lab_test.getConsult_id()+"',"+ "'"+lab_test.getAssistant_id()+"',"+ "'"+lab_test.getTest_name()+"',"+ "'"+lab_test.getReport()+"',"+ "'"+lab_test.getTest_center()+"',"+ "'"+lab_test.getDate_of_test()+"',"+ "'"+lab_test.getDate_of_result()+"'" +")" ); } catch (SQLException ex) { Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); } } public static ResultSet select_from_lab_test( ){ try { if( connection == null ){ connectDB(); } Statement statement = connection.createStatement(); ResultSet result = statement .executeQuery("SELECT * FROM lab_test"); return result; } catch (SQLException ex) { Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); } return null; } public static ResultSet select_query( String query ){ try { if( connection == null ){ connectDB(); } Statement statement = connection.createStatement(); ResultSet result = statement .executeQuery(query); return result; } catch (SQLException ex) { Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); } return null; } public static void insert_query( String query ){ try { if( connection == null ){ connectDB(); } Statement statement = connection.createStatement(); statement .execute(query); } catch (SQLException ex) { Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); } } }<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.doctor; import static immunehistory.ImmuneHistory.stage; import immunehistory.lab_test.Lab_test_report_showController; import static immunehistory.labib_constants.Constants.previous_page; import immunehistory.labib_database.Database; import java.io.IOException; import java.net.URL; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; import javafx.stage.Stage; /** * FXML Controller class * * @author labib */ public class Write_prescriptionController implements Initializable { @FXML private Pane id_pane; @FXML private Pane data_pane; @FXML private AnchorPane main_anchor_pane; @FXML private ScrollPane main_parent_scroll; @FXML private Button add_more_button; @FXML private Label error_ap_sl_no; @FXML private Label error_consult_id; @FXML private ComboBox<String> symptoms; @FXML private ComboBox<String> test_name; @FXML private ComboBox<String> medicine_name; @FXML private ComboBox<String> test_center; @FXML private TextField dosage; @FXML private TextField dosage_duration; @FXML private TextField remarks; @FXML private Label error_symptoms; @FXML private Label error_medicine_name; @FXML private Label error_test_name; @FXML private Label error_test_center; @FXML private Label error_dosage; @FXML private Label error_dosage_duration; @FXML private Label error_remarks; /** * Initializes the controller class. */ Thread x; @FXML private TextField ap_sl_no; @FXML private TextField consult_id; ObservableList<String> symptoms_array = FXCollections.observableArrayList (); ObservableList<Integer> symptoms_id_array = FXCollections.observableArrayList (); ObservableList<String> test_name_array = FXCollections.observableArrayList (); ObservableList<String> medicine_name_array = FXCollections.observableArrayList (); ObservableList<Integer> test_id_array = FXCollections.observableArrayList (); ObservableList<Integer> medicine_id_array = FXCollections.observableArrayList (); ObservableList<String> test_center_array = FXCollections.observableArrayList (); ObservableList<Integer> test_center_id_array = FXCollections.observableArrayList (); @FXML private Button add_more_button1; @Override public void initialize(URL url, ResourceBundle rb) { // TODO test_name.setDisable(true); medicine_name.setDisable(true); test_center.setDisable(true); ResultSet result = Database.select_query( "SELECT * FROM symptom" ); ResultSet result4 = Database.select_query( "SELECT * FROM symptom" ); try { while( result.next() ){ symptoms_array.add( result.getString("symptom_name") ); symptoms_id_array.add( result.getInt("symptom_id") ); symptoms.setItems(symptoms_array ); } } catch (SQLException ex) { Logger.getLogger(Lab_test_report_showController.class.getName()).log(Level.SEVERE, null, ex); } } @FXML private void add_more(MouseEvent event) throws Exception { String ap = ap_sl_no.getText(); String cid = consult_id.getText(); String sym = symptoms.getSelectionModel().getSelectedItem(); String tn = test_name.getSelectionModel().getSelectedItem(); String mn = medicine_name.getSelectionModel().getSelectedItem(); int mid = medicine_id_array.get( medicine_name.getSelectionModel().getSelectedIndex() ); String tc = test_center.getSelectionModel().getSelectedItem(); String dos = dosage.getText(); String dosd = dosage_duration.getText(); String rm = remarks.getText(); System.out.println(ap+" "+sym+" "+tn+" "+mid+" "+mn+" "+dos+" "+rm); Database.insert_query( "INSERT INTO prescription VALUES " + " ( '"+ap+"', '"+sym+"', '"+tn+"', '"+mid+"', '"+dos+"', CURRENT_TIMESTAMP, DATEADD( DAY, "+dosd+", CURRENT_TIMESTAMP ), '"+rm+"')" ); } @FXML private void selected_symptoms(ActionEvent event) { ResultSet result2 = Database.select_query( "SELECT DISTINCT test_name FROM lab_test" ); ResultSet result3 = Database.select_query( "SELECT * FROM medicine_generic_name" ); try { while( result2.next() ){ test_name_array.add( result2.getString("test_name") ); // symptoms_id_array.add( result.getInt("symptom_id") ); test_name.setItems(test_name_array ); } } catch (SQLException ex) { Logger.getLogger(Lab_test_report_showController.class.getName()).log(Level.SEVERE, null, ex); } try { while( result3.next() ){ medicine_name_array.add( result3.getString("medicine_generic_name") ); medicine_id_array.add( result3.getInt( "medicine_generic_id" ) ); medicine_name.setItems(medicine_name_array ); } } catch (SQLException ex) { Logger.getLogger(Lab_test_report_showController.class.getName()).log(Level.SEVERE, null, ex); } test_name.setDisable(false); medicine_name.setDisable(false); } @FXML private void selected_test_name(ActionEvent event) { ResultSet result4 = Database.select_query( "SELECT DISTINCT test_center FROM lab_test" ); try { while( result4.next() ){ test_center_array.add( result4.getString("test_center") ); // symptoms_id_array.add( result.getInt("symptom_id") ); test_center.setItems(test_center_array ); } } catch (SQLException ex) { Logger.getLogger(Lab_test_report_showController.class.getName()).log(Level.SEVERE, null, ex); } test_center.setDisable(false); } @FXML private void back(MouseEvent event) { stage.setScene( previous_page.pop() ); stage.show(); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.doctor; import static immunehistory.ImmuneHistory.stage; import immunehistory.labib_constants.Constants; import static immunehistory.labib_constants.Constants.previous_page; import immunehistory.labib_database.Database; import java.net.URL; import java.sql.ResultSet; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; /** * FXML Controller class * * @author labib */ public class Doctor_edit_profileController implements Initializable { @FXML private TextField name; @FXML private Button done; @FXML private Label error_name; @FXML private TextField mobile; @FXML private Label error_mobile; @FXML private Label error_password; @FXML private PasswordField password; @FXML private Label error_re_enter_password; @FXML private PasswordField re_enter_password; @FXML private TextField hospital; @FXML private Label error_hospital; @FXML private TextField address; @FXML private Label error_address; @FXML private TextField zipcode; @FXML private Label error_zipcode; @FXML private ComboBox<String> degree; @FXML private ComboBox<String> category; @FXML private Button back; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO ObservableList<String> degree_options = FXCollections.observableArrayList( "MBBS", "MD", "DO", "Student" ); degree.setItems(degree_options); ObservableList<String> category_options = FXCollections.observableArrayList( "Diabetics and Hypertension", "Medicine", "Liver", "Food and Nutritionist", "Cancer", "Cardiologists", "Critical Care Medicine Specialists", "Endocrinologists", "Gastroenterologists" ); category.setItems(category_options); try { load_data(); } catch (Exception ex) { Logger.getLogger(Doctor_edit_profileController.class.getName()).log(Level.SEVERE, null, ex); } } @FXML private void done_button(MouseEvent event) { String n = name.getText(); String m = mobile.getText(); String p = password.getText(); String rp = re_enter_password.getText(); String hos = hospital.getText(); String add = address.getText(); String zip = zipcode.getText(); String deg = degree.getValue(); String cat = category.getValue(); Database.insert_query("UPDATE doctor SET " + " doctor_name = '"+n+"'," + " phone = '"+m+"', " + " password = '"+p+"', " + " hospital = '"+hos+"', " + " address = '"+add+"', " + " zipcode = '"+zip+"', " + " degree = '"+deg+"', " + " category = '"+cat+"' WHERE doctor_id = '"+Constants.doctor_id+"' " ); } public void load_data() throws Exception { ResultSet result = Database.select_query( "SELECT * FROM doctor WHERE doctor_id = '"+Constants.doctor_id+"' " ); while( result.next() ){ name.setText( result.getString("doctor_name") ); mobile.setText( String.valueOf( result.getInt("phone") ) ); password.setText( result.getString("password") ); re_enter_password.setText( result.getString("password") ); hospital.setText( result.getString("hospital") ); address.setText( result.getString("address") ); zipcode.setText( String.valueOf( result.getInt("zipcode")) ); degree.setValue(result.getString("degree") ); category.setValue( result.getString("category") ); } } @FXML private void back(MouseEvent event) { stage.setScene( previous_page.pop() ); stage.show(); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.statics.statics_diseases_panel; /** * * @author joyultimates */ public class statics_disease_list { private String id; private String DiseaseName; private String DiseaseType; private String Action; public statics_disease_list(String id, String DiseaseName, String DiseaseType) { this.id = id; this.DiseaseName = DiseaseName; this.DiseaseType = DiseaseType; } /** * @return the id */ public String getId() { return id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } /** * @return the DiseaseName */ public String getDiseaseName() { return DiseaseName; } /** * @param DiseaseName the DiseaseName to set */ public void setDiseaseName(String DiseaseName) { this.DiseaseName = DiseaseName; } /** * @return the DiseaseType */ public String getDiseaseType() { return DiseaseType; } /** * @param DiseaseType the DiseaseType to set */ public void setDiseaseType(String DiseaseType) { this.DiseaseType = DiseaseType; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.statics.statics_settings_panel; import com.jfoenix.controls.JFXPasswordField; import immunehistory.ImmuneHistory; import immunehistory.statics.login_registration.Statics_registrationController; import static immunehistory.statics.login_registration.Statics_registrationController.statics_email; import static immunehistory.statics.login_registration.Statics_registrationController.statics_password; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javafx.application.Platform; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; /** * FXML Controller class * * @author RIfat */ public class statics_changepasswordController implements Initializable { private Connection con = null; private PreparedStatement pst = null; @FXML private AnchorPane statics_changepassword_id; @FXML private JFXPasswordField statics_Newpassword_id; @FXML private JFXPasswordField statics_reNewpass_id; @FXML private Label lblchangePassError; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { con =dba.DBConnection.immunehistoryConnection(); } @FXML private void statics_changePasswordOnAction(ActionEvent event) throws IOException { if(statics_Newpassword_id.getText().equals(statics_reNewpass_id.getText())){ try { String update ="Update statics_user set statics_user_password =? where statics_user_email =?"; pst = con.prepareStatement(update); pst.setString(1,statics_Newpassword_id.getText()); pst.setString(2,statics_email); int i = pst.executeUpdate(); if(i==1){ Alert alert = new Alert(Alert.AlertType.INFORMATION.CONFIRMATION,"Password Update successfully",ButtonType.OK); alert.show(); // Parent home = FXMLLoader.load(getClass().getResource("statics_login.fxml")); // Scene scene = new Scene(home); // statics_otp_id.getChildren().setAll(home); // FXMLLoader fXMLLoader = new FXMLLoader(); // fXMLLoader.setLocation(getClass().getResource("/immunehistory/statics/statics_home/statics_home.fxml")); // // Stage stage = new Stage(); // Scene scene = new Scene(fXMLLoader.load()); // stage.setScene(scene); // stage.setTitle("Statics"); // ImmuneHistory.stage.close(); // stage.show(); } } catch (SQLException ex) { Logger.getLogger(Statics_registrationController.class.getName()).log(Level.SEVERE, null, ex); Alert alert = new Alert(Alert.AlertType.INFORMATION.WARNING,"Something Wrong",ButtonType.OK); alert.show(); } }else{ lblchangePassError.setText("Password not Matched"); } } }<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package immunehistory.statics.statics_treatment_panel; import immunehistory.statics.statics_drug_panel.Statics_drug_listController; import immunehistory.statics.statics_drug_panel.statics_drug_list; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; /** * FXML Controller class * * @author joyultimates */ public class Statics_treatment_feedbackController implements Initializable { private Connection con = null; private Connection con2 = null; private PreparedStatement pst = null; private PreparedStatement pst2 = null; private ResultSet rs = null; private ResultSet rs2 = null; private ObservableList<Statics_treatment_feedback> data; private ObservableList<Statics_treatment_feedback> data2; @FXML private TextField statics_treatment_feedback_field; @FXML private Button statics_treatment_feedback_menubtn; @FXML private TextField statics_diseases_panel_search_field; @FXML private TableView<Statics_treatment_feedback> treatmentFeedbackCommulativeTable; @FXML private TableColumn<?, ?> CtreatmentFeedbackId; @FXML private TableColumn<?, ?> CconsultId; @FXML private TableColumn<?, ?> CsuccessRate; @FXML private TableColumn<?, ?> CcommulativeRate; private TableView<Statics_treatment_feedbackDependent> treatmentFeedbackDependentTable; private TableColumn<?, ?> DtreatmentFeedbackId; private TableColumn<?, ?> DconsultId; private TableColumn<?, ?> DsuccessRate; private TableColumn<?, ?> DcommulativeRate; @FXML private TableView<Statics_treatment_feedback> treatmentFeedbackCommulativeTable1; @FXML private TableColumn<?, ?> CtreatmentFeedbackId1; @FXML private TableColumn<?, ?> CconsultId1; @FXML private TableColumn<?, ?> CsuccessRate1; @FXML private TableColumn<?, ?> CcommulativeRate1; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO con =dba.DBConnection.immunehistoryConnection(); con2 =dba.DBConnection.immunehistoryConnection(); data = FXCollections.observableArrayList(); data2 = FXCollections.observableArrayList(); settreatmentFeedbackCommulativeTable(); // settreatmentFeedbackDependentTable(); settreatmentFeedbackCommulativeTable1(); // searchDrugList(); } private void settreatmentFeedbackCommulativeTable(){ CtreatmentFeedbackId.setCellValueFactory(new PropertyValueFactory<>("TID")); CconsultId.setCellValueFactory(new PropertyValueFactory<>("CID")); CsuccessRate.setCellValueFactory(new PropertyValueFactory<>("SuccessRate")); CcommulativeRate.setCellValueFactory(new PropertyValueFactory<>("CDRate")); } // private void settreatmentFeedbackDependentTable(){ // // DtreatmentFeedbackId.setCellValueFactory(new PropertyValueFactory<>("dTID")); // DconsultId.setCellValueFactory(new PropertyValueFactory<>("dCID")); // DsuccessRate.setCellValueFactory(new PropertyValueFactory<>("dSuccessRate")); // DcommulativeRate.setCellValueFactory(new PropertyValueFactory<>("dCDRate")); // } private void settreatmentFeedbackCommulativeTable1(){ CtreatmentFeedbackId1.setCellValueFactory(new PropertyValueFactory<>("TID")); CconsultId1.setCellValueFactory(new PropertyValueFactory<>("CID")); CsuccessRate1.setCellValueFactory(new PropertyValueFactory<>("SuccessRate")); CcommulativeRate1.setCellValueFactory(new PropertyValueFactory<>("CDRate")); } private void loadDataFromtreatmentFeedbackCommulativeTable(){ data.clear(); try { pst = con.prepareStatement("select treatment_feedback_id,consult_id, success_rate,\n" + " ROUND( AVG(success_rate) OVER(ORDER BY success_rate),3) AS average_success_rate\n" + "from treatment_feedback\n" + "where consult_id ="+statics_treatment_feedback_field.getText()+""); rs = pst.executeQuery(); while(rs.next()){ data.add(new Statics_treatment_feedback(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4))); } } catch (SQLException ex) { Logger.getLogger(Statics_treatment_feedbackController.class.getName()).log(Level.SEVERE, null, ex); } treatmentFeedbackCommulativeTable.setItems(data); // loadDataFromtreatmentFeedbackDependentTable(); } private void loadDataFromtreatmentFeedbackDependentTable(){ data2.clear(); try { pst = con.prepareStatement("select treatment_feedback_id,consult_id, success_rate,\n" + " ROUND(AVG(success_rate) OVER(ORDER BY treatment_feedback_id\n" + " ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING),3) AS average_success_rate\n" + "from treatment_feedback\n" + "where consult_id ="+statics_treatment_feedback_field.getText()+""); rs = pst.executeQuery(); while(rs.next()){ data2.add(new Statics_treatment_feedback(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4))); } } catch (SQLException ex) { Logger.getLogger(Statics_treatment_feedbackController.class.getName()).log(Level.SEVERE, null, ex); } //treatmentFeedbackDependentTable.setItems(data2); treatmentFeedbackCommulativeTable1.setItems(data2); } @FXML private void statics_treatment_feedback_menubtnOnAction(ActionEvent event) { loadDataFromtreatmentFeedbackCommulativeTable(); loadDataFromtreatmentFeedbackDependentTable(); } @FXML private void statics_diseases_panel_search_fieldOnAction(ActionEvent event) { } @FXML private void btnSearchOnAction(ActionEvent event) { } }
077aee9e809bd85340ca17e1c9b7f3514bdd1d38
[ "Markdown", "Java" ]
25
Java
astro05/ImmuneHistory
20dc98721744bffc8a8fb2e98929dfab99c6991e
f357186ad0c590dad1335b11af154d04f881d389
refs/heads/master
<file_sep>#!/bin/sh ## t2si.sh: generate image for Slack icon from text ## Copyright (C) 2017 <NAME> <https://GitHub.com/tamanobi> ## License: Apache2 ## Depends on: ImageMagick ## if [ $# -ne 2 ]; then echo "usage: $0 <text> <output_image_path>" exit 1 fi INPUT_TEXT=$1 OUTPUT_PATH=$2 convert -font /System/Library/Fonts/Hiragino\ Sans\ GB\ W6.ttc \ -pointsize 128 \ caption:"${INPUT_TEXT}"\ -trim -transparent white \ -resize "128x128" ${OUTPUT_PATH} <file_sep>#!/bin/bash set -euxo pipefail git grep -l -F "$1" -- "$3" | php -r 'while (false !== $s = fgets(STDIN)) { $p = rtrim($s, "\n"); $c = file_get_contents($p); $c = str_replace($argv[1], $argv[2], $c); file_put_contents($p, $c); }' "$1" "$2"
fe9031ae3c9927f314a5b7d725ccbc178738f380
[ "Shell" ]
2
Shell
tamanobi/utils
ea9aeab032f818c33c6a39643405f24e0f8ae4a7
ba16d2efdb1bd25f9c8149063ff01c18fd6137ee
refs/heads/master
<repo_name>hemal08ce094/MovieListing<file_sep>/MoviesApp/NetworkAdapter/NetworkAccess.swift // // NetworkAccess.swift // MoviesApp // // Created by Hemal on 02/05/20. // Copyright © 2020 Hemal. All rights reserved. // import Foundation enum NetworkResult<T> { case success(T) case cancel(Error?) case failure(Error?) } public class NetworkAccess { public enum Method: String { case get = "GET" case post = "POST" case put = "PUT" case delete = "DELETE" } public enum QueryType { case json, path } static func fetchData<T: Requestable>(req: T,completionHandler: @escaping (NetworkResult<T.ResponseType>) -> Void) { let url = req.baseUrl.appendingPathComponent(req.endpoint) let request = prepareRequest(for: url, req: req) let task = URLSession.shared.dataTask(with: request) { (data, response, error) in if let err = error { if let urlError = error as? URLError, urlError.code == URLError.cancelled { // cancelled completionHandler(NetworkResult.cancel(urlError)) } else { // other failures completionHandler(NetworkResult.failure(err)) } return } if let data = data { let decoder = JSONDecoder() DispatchQueue.main.async { do { let object = try decoder.decode(T.ResponseType.self, from: data) completionHandler(NetworkResult.success(object)) } catch let error { completionHandler(NetworkResult.failure(error)) } } } } task.resume() } private static func prepareRequest<T: Requestable>(for url: URL, req: T) -> URLRequest { var request : URLRequest? = nil switch req.query { case .json: request = URLRequest(url: url, cachePolicy: req.cachePolicy, timeoutInterval: req.timeout) if let params = req.parameters { do { let body = try JSONSerialization.data(withJSONObject: params, options: []) request!.httpBody = body } catch { assertionFailure("Error : while attemping to serialize the data for preparing httpBody \(error)") } } case .path: var query = "" req.parameters?.forEach { key, value in query = query + "\(key)=\(value)&" } var components = URLComponents(url: url, resolvingAgainstBaseURL: true)! components.query = query request = URLRequest(url: components.url!, cachePolicy: req.cachePolicy, timeoutInterval: req.timeout) } request!.allHTTPHeaderFields = req.headers request!.httpMethod = req.method.rawValue return request! } } <file_sep>/MoviesApp/MovieListViewModel.swift // // MovieListViewModel.swift // MoviesApp // // Created by Hemal on 02/05/20. // Copyright © 2020 Hemal. All rights reserved. // import Foundation <file_sep>/README.md # MovieListing Lists the most popular movies using TMDB API, by creating NetworkAccess module. Sample project for themoviedb iOS api usage Here is how it looks. ![Simulator Screen Shot - iPhone 11 Pro Max - 2020-05-02 at 22 08 49](https://user-images.githubusercontent.com/21290914/80872374-8b7d2500-8cc2-11ea-886b-7d8c9e857da1.png) ![Simulator Screen Shot - iPhone 11 Pro Max - 2020-05-02 at 22 08 45](https://user-images.githubusercontent.com/21290914/80872376-9041d900-8cc2-11ea-864c-d400265af616.png) <file_sep>/MoviesApp/MovieDetailViewController.swift // // MovieDetailViewController.swift // MoviesApp // // Created by Hemal on 02/05/20. // Copyright © 2020 Hemal. All rights reserved. // import UIKit class MovieDetailViewController: UIViewController { var moviesData :MovieResult? @IBOutlet weak var moviePoster: UIImageView! @IBOutlet weak var movieOverView: UITextView! override func viewDidLoad() { super.viewDidLoad() loadMovieDetails() } //MARK: - load data private func loadMovieDetails() { movieOverView.text = moviesData?.overview if let imageEndPath = moviesData?.posterPath { let url = URL(string: "https://image.tmdb.org/t/p/original/\(imageEndPath)") self.moviePoster.kf.setImage(with: url) } if let movieID = moviesData?.id { _ = NetworkAccess.fetchData(req: MovieDetailRequest(movieID: "\(movieID)"),completionHandler: { [weak self] (result) in guard let self = self else {return} switch result { case .success(let movieDetail): print(movieDetail) case .cancel(let cancelError): print(cancelError!) case .failure(let error): print(error!) } }) } } } <file_sep>/MoviesApp/MovieListViewController.swift.swift // // ViewController.swift // MoviesApp // // Created by Hemal on 02/05/20. // Copyright © 2020 Hemal. All rights reserved. // import UIKit class MovieListViewController: UIViewController { @IBOutlet weak var movieListTableView: UITableView! var moviesData :[MovieResult] = [] override func viewDidLoad() { super.viewDidLoad() movieListTableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier") loadMovies(forPage: 1) // Do any additional setup after loading the view. } //MARK: - load data private func loadMovies(forPage page : Int) { _ = NetworkAccess.fetchData(req: MovieListingRequest(pageNumber: "1"),completionHandler: { [weak self] (result) in guard let self = self else {return} switch result { case .success(let movieListing): self.moviesData = movieListing.results self.movieListTableView.reloadData() case .cancel(let cancelError): print(cancelError!) case .failure(let error): print(error!) } }) } } extension MovieListViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { moviesData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) let movie = moviesData[indexPath.row] cell.textLabel?.text = movie.title cell.detailTextLabel?.text = movie.overview return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let movie = moviesData[indexPath.row] if let aViewController = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "MovieDetailViewController") as? MovieDetailViewController { aViewController.moviesData = movie self.navigationController?.pushViewController(aViewController, animated: true) } } }
414345a76a49586c1bc0b212d9dd35c80402baff
[ "Swift", "Markdown" ]
5
Swift
hemal08ce094/MovieListing
c5053cc9d2c37fc3d2181eb909ea591d3ec99ced
9132551bf4c8b5c5409a631c85ebf93938e05afa
refs/heads/master
<repo_name>tharinda221/Testing_lab<file_sep>/implementation/src/Task2Part1/UserValidation.java package Task2Part1; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; /** * Created by Ehelepola on 14/09/2015. */ public class UserValidation { @DataProvider public Object[][] UsersProvider() { return new Object[][] { { new String[] {"user1","sdfsdf@sa","sasd^*&sdfsd)()_)(","SFDSFSDcvxcv","54654654lkjlkj"} } }; } @Test(dataProvider = "UsersProvider") public void ValidUsersTest(String[] Users) { WebDriver driver; WebDriverWait wait; driver = new FirefoxDriver(); wait = new WebDriverWait(driver, 10); driver.manage().window().maximize(); driver.get("http://localhost:8080/hello"); for (String temp : Users) { driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); driver.findElement(By.id("inputName")).clear(); driver.findElement(By.id("inputName")).sendKeys(temp); driver.findElement(By.id("searchButton")).click(); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); String element = driver.findElement(By.id("userFrom")).getText(); System.out.println(element); if(element.equals(temp)){ System.out.println("Test OK"); }else{ System.out.println("Test Fail"); } Assert.assertEquals(temp,element ); driver.findElement(By.id("submitAnother")).click(); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); } driver.quit(); } } <file_sep>/README.md # Testing_lab For Email validation http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/ <file_sep>/implementation/src/MailCheck/YahooTest.java package MailCheck; import java.util.concurrent.TimeUnit; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.WebDriverWait; public class YahooTest { @Test public void test()throws Exception { WebDriver driver; //WebDriver driver = new ChromeDriver(); WebDriverWait wait; //driver = new ChromeDriver(); driver = new FirefoxDriver(); wait = new WebDriverWait(driver, 10); driver.manage().window().maximize(); driver.get("https://login.yahoo.com/"); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); driver.findElement(By.id("login-username")).sendKeys("Dishan000001"); driver.findElement(By.name("passwd")).sendKeys("<PASSWORD>"); driver.findElement(By.id("login-signin")).sendKeys("LOGIN BUTTON"); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); driver.quit(); } }
98f5fe00e6ba4f63e62d679f1969f41076aafa32
[ "Markdown", "Java" ]
3
Java
tharinda221/Testing_lab
a45a8a9b13e65faa8149839413aaaeafb1867a1a
0d7a06acbdbcfc00d959a297830217cefa5898ab
refs/heads/master
<repo_name>wpzero/notes<file_sep>/useful_js.js var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == XMLHttpRequest.DONE ) { if (xmlhttp.status == 200) { alert("ok"); } else if (xmlhttp.status == 400) { alert('There was an error 400'); } else { alert('something else other than 200 was returned'); } } }; xmlhttp.open("GET", "https://loyalty-cdn-cn-production.oss-cn-shanghai.aliyuncs.com/client_assets/badges/de706011.png", true); xmlhttp.send(); <file_sep>/cb.sql CREATE USER 'cbuser'@'localhost' IDENTIFIED BY 'cbpass'; GRANT ALL ON cookbook.* TO 'cbuser'@'localhost'; CREATE DATABASE cookbook; USE cookbook; CREATE TABLE limbs (thing VARCHAR(20), legs INT, arms INT); select count(1) from limbs; INSERT INTO limbs (thing, legs, arms) VALUES('human', 2, 2); insert into limbs (thing, legs, arms) values('dog', 4, 0); select * from limbs; -- ; and \g are terminators select NOW()\g SHOW FULL COLUMNS FROM limbs; -- vertical infos SHOW FULL COLUMNS FROM limbs LIKE 'thing'\G -- horizontal info SHOW FULL COLUMNS FROM limbs LIKE 'thing'\g select * from limbs limit 2\G -- import source file and execute oneline by oneline source /Users/wpzero/workspace/mysql_workspace/recipes/tables/limbs.sql select @max_legs := MAX(legs) from limbs; select @max_legs; status; select id from accounts where uuid='KaHXF9ypjEC7N6J'; DROP TABLE IF EXISTS mail; #@ _CREATE_TABLE_ CREATE TABLE mail ( t DATETIME, # when message was sent srcuser VARCHAR(8), # sender (source user and host) srchost VARCHAR(20), dstuser VARCHAR(8), # recipient (destination user and host) dsthost VARCHAR(20), size BIGINT, # message size in bytes INDEX (t) ); select database(); SHOW TABLES; DESCRIBE MAIL; show index from cookbook.mail; select srcuser, srchost, t, size from mail; select t, srcuser, srchost from mail where srchost = 'venus'; select t, srcuser, srchost from mail where srchost like '%s'; select t, CONCAT(srcuser, '@', srchost), size from mail; select t, CONCAT(srcuser, '@', srchost) as mail, size from mail; select DATE_FORMAT(t, "%a") from mail; select DATE_FORMAT(t, "%y-%m-%d") as date from mail; select DATE_FORMAT(t, "%Y-%m-%d") as date from mail; -- The select alias can not be used in where clause -- select DATE_FORMAT(t, "%Y-%m-%d") as date, CONCAT(srcuser, '@', srchost) as sender from mail where sender = 'barb@saturn'; -- single quote is so usefull select DATE_FORMAT(t, "%Y-%m-%d") as 'send date', CONCAT(srcuser, '@', srchost) as 'the sender' from mail; -- The error occurs because an alias names an output column, whereas a where clause operates on input columns -- select t, srcuser, dstuser, size/1024 as kilobytes from mail where kilobytes > 500; -- so change it to select t, srcuser, dstuser, size/1024 as kilobytes from mail where size/1024 > 500; -- when you select rows, the mysql server is free to return them in any order unless you instruct them select * from mail where dstuser = 'tricia' order by srchost, srcuser; select * from mail order by t; select * from mail where size > 50000 order by size DESC; -- use DISTINCT to remove duplicate rows select srcuser from mail; select DISTINCT srcuser from mail; -- to count distinct use COUNT(distinct column_name) select COUNT(DISTINCT srcuser) from mail; select DISTINCT YEAR(t), MONTH(t), DAYOFMONTH(t) from mail; describe expt; select count(1) from expt; -- NULL check use IS NULL or IS NOT NULL select * from expt where score IS null; INSERT INTO expt (subject, test, score) values('chinese', 'a', 10); -- This will not work as expected select * from expt where score = null; select * from expt where score is not null; -- <=> this symbol can be used to check if the value is null select null = null, null <=> null; select subject, test, IF(score IS NULL, 'unkown', score) as score from expt; select subject, test, IFNULL(score, 'unkown') as 'score' from expt; -- Use view to simplify sql CREATE VIEW mail_views AS select DATE_FORMAT(t, "%y-%m-%d") as date, CONCAT(srcuser, '@', srchost) as sender, CONCAT(dstuser, '@', dsthost) as recipient, size from mail; -- Now you can view view's content like table select date, sender, size from mail_views where date = '14-05-11'; select * from profile_contact ORDER BY profile_id, service; describe profile_contact; describe profile; select name, service, contact_name from profile INNER JOIN profile_contact ON profile.id = profile_contact.profile_id; select name, service, contact_name from profile INNER JOIN profile_contact ON profile.id = profile_contact.profile_id where name = 'Nancy'; -- limit select name, DATE_FORMAT(birth, "%m-%d") as birthday from profile order by birthday limit 1; select name, DATE_FORMAT(birth, "%m-%d") as birthday from profile order by birthday limit 1, 2; select SQL_CALC_FOUND_ROWS name, DATE_FORMAT(birth, "%m-%d") as birthday from profile order by birthday limit 4; select FOUND_ROWS(); -- two order, so cool yeah? select * from (select * from profile order by birth DESC limit 4) as t order by birth; -- limit params can not be expression -- select name, DATE_FORMAT(birth, "%m-%d") as birthday from profile order by birthday limit 2 * 2; set @va1 = 1; -- limit params can not be variable, must be iteger -- select name, DATE_FORMAT(birth, "%m-%d") as birthday from profile order by birthday limit @va1; -- create a table like one table structure create table new_profile like profile; describe new_profile; insert into new_profile select * from profile; select count(1) from new_profile; create table new_mail like mail; select * from mail; insert into new_mail select * from mail where srcuser = 'tricia'; select count(1) from new_mail; describe profile; describe mail; create table srcuser select distinct srcuser as name from mail; describe srcuser; select * from srcuser; drop table srcuser; CREATE TABLE srcuser ( id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (id) ) SELECT DISTINCT srcuser as name from mail; describe srcuser; select * from srcuser; create table dstuser like srcuser; INSERT INTO dstuser (name) select DISTINCT dstuser as name from mail; select * from dstuser; select DISTINCT dstuser as name from mail; drop table IF exists srcuser; describe srcuser; drop table IF exists new_mail; create table new_mail select * from mail; describe new_mail; select count(1) from new_mail; select count(1) from mail; create temporary table temporary_new_mail like mail; describe mail; select ENGINE FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'cookbook' and TABLE_NAME = 'mail'; show table status like 'mail'\G show create table mail\G ALTER TABLE mail ENGINE = MyISAM; show table status like 'mail'\G ALTER TABLE mail ENGINE = InnoDB; show table status like 'new_mail'\G RENAME TABLE new_mail TO mail2; show table status like 'mail2'\G status; show character set; set @s = CONVERT('abc' USING utf8); select @s; -- byte size, char size select LENGTH(@s), CHAR_LENGTH(@s); set @s = CONVERT('abc' USING ucs2); show table status like 'mail'\G show create table mail\G show COLLATION like 'utf8%'; show COLLATION like 'latin1%'; show table status; create TABLE t( c CHAR(3) character set latin1 ); insert into t (c) values('AAA'), ('bbb'), ('aaa'), ('BBB'); select c from t; -- _ci case insensitive, _cs case sensitive, _bin binary select c from t order by c COLLATE latin1_swedish_ci; select c from t order by c COLLATE latin1_general_cs; drop table t; create TABLE t (c char(2) character set utf8); insert into t(c) values('cg'), ('ch'), ('ci'), ('lk'), ('ll'), ('lm'); select c from t; drop table t; -- Binary and char mysql stores column values using fixed witdh -- varbinary varchar blob text mysql stores values using only as much storage as required, upto maximum, no padding is added or stripped when values are stored or retrieved -- If you store a string that contains trailing space into a char column, -- they are removed when you retrieve the value. -- so, if you store character strings that might end with spaces, and want to preserve them use varchar or one of the text data types create table t (c1 char(10), c2 varchar(10)); insert into t(c1, c2) values('abc ', 'abc '); select * from t; select c1, c2, char_length(c1), char_length(c2) from t; -- after connect mysql, set client default character set set names 'utf8' collate 'utf8_general_ci'; <file_sep>/useful_ruby.rb exceptions = [] bad_items = [] bad_cids = [] Resque::Failure.each do |i, item| begin if item["payload"]["class"] == "CustomerJobs" bad_cids << item["payload"]["args"][0] bad_items << item end rescue exceptions << $! end end;1 Resque::Failure.each do |i, item| begin if item["payload"]["class"] == "CustomerJobs" cid = item["payload"]["args"][0] end rescue exceptions << $! bad_items << item end end;1 new_items = bad_items.reject{|x| x["error"].include?("Duplicate entry") || x["error"].include?("total_revenue_sofar")} new_items.map{|x| x["error"].first(20)} new_items.select{|x| x["args"][0] == 642302} this_customer = [] Resque::Failure.each do |i, item| this_customer << item if item["payload"]["args"][0] == 650106 end;1 Resque::Failure.each(0, Resque::Failure.count, nil, "SPECIFIC_JOB_TYPE") do |id, item| Resque::Failure.requeue(id) Resque::Failure.remove(id) end;1 ActiveRecord::Base.on_db(:slave) do res = ActiveRecord::Base.connection.execute(sql) res.each do |row| evt_ids << row[0] cust_ids << row[1] end end # A size bench arr = (0...1000000).to_a.map do |_| [rand(1000000), rand(200), rand(1000000)] end;1 str = Marshal.dump(arr);1 str.bytesize / (1024 * 1024) #=> 13 # 1. 10000 should be the max entities count # 2. split the result by multiple cache key p_c = PrismCache.new('leaderboard/results', ttl: 1.day, persist_long: true, type: :redis) # badge bug find badge = Badge.find(6) rules = badge.rules customer = Customer.find(145834) badge.actions_required(customer) time_period = rule.calculate_timeframe(customer, Time.now) rule.value_required(customer, time_period) account_member_attribute = AccountMemberAttribute.find(22) # some safe convert def to_integer_or_myself(value) safe_convert_to(:to_i, value) end def to_string_or_myself(value) safe_convert_to(:to_s, value) end def safe_convert_to(sym, value) (value.respond_to?(sym) && value.send(sym)) || value end # temporary beta notify code, after in beta, will be deleted def auto_beta_notify(event) if event.event_type == "login_app" sms_template = VendorService['alidayu.sms.template']['app_notification'] svc = VendorSvc::Alidayu.new(sms_template: sms_template, sms_sign: 'NBA中国') svc.send_sms(external_customer_id) end end @cache = ThreadSafe::Cache.new THREADS = 10 (0...THREADS).map do |i| Thread.new do 1000.times do |j| key = i * 1000 + j @cache[key] = i @cache[key] end end end.map(&:join) @cache2 = {} THREADS = 10 (0...THREADS).map do |i| Thread.new do 1000.times do |j| key = i * 1000 + j @cache2[key] = i @cache2[key] end end end.map(&:join) # Ruby hash mock class Node attr_reader :object, :next def initialize(o, n) @object, @next = o, n end end class TurboHash STARTING_BINS = 16 MAX_DENSITY = 5 attr_reader :table # This is bins def initialize @entry_count = 0 @bin_count = STARTING_BINS @table = produce_table end def grow @bin_count = @bin_count << 1 @table = produce_table(@table) end def produce_table(old_table = []) new_table = Array.new(@bin_count) old_table.each do |node| while node new_index = index_of(node.object[0]) new_table[new_index] = Node.new(node.object, new_table[new_index]) node = node.next end end new_table end def full? @entry_count > @bin_count * MAX_DENSITY end # Get bin alth def index_of(key) key.hash % @bin_count end def node_for(key) @table[index_of(key)] end def []=(key, value) grow if full? @table[index_of(key)] = Node.new([key, value], node_for(key)) end def [](key) node = node_for(key) while node return node.object[1] if node.object[0] == key node = node.next end end end require "benchmark" legacy = Hash.new turbo = TurboHash.new def set_and_find(target) keys = Array.new(30000) {rand} keys.each do |key| target[key] = rand end.shuffle.each do |key| target[key] end end Benchmark.bm do |x| x.report("Hash: ") { set_and_find(legacy) } x.report("TurboHash: ") { set_and_find(turbo) } end <file_sep>/useful_sql.sql select local_date(inv.updated_at) as sent_date, case when invcode.status = 1 then 'not' when invcode.status = 2 and (local_date(invcode.updated_at) = local_date(inv.updated_at) ) then 'inbeta' when invcode.status = 2 and (local_date(invcode.updated_at) > local_date(inv.updated_at) ) then 'later' end as inbeta_status, count(1) from invitations inv, invitation_codes invcode where inv.code = invcode.value and batch_number > 9 group by sent_date, inbeta_status; CREATE DEFINER=`ffuser`@`%` FUNCTION `local_date`(time_value DATETIME) RETURNS date DETERMINISTIC BEGIN RETURN DATE(CONVERT_TZ(time_value, '+00:00', CONCAT('+', SUBSTRING_INDEX(TIMEDIFF(NOW(), UTC_TIMESTAMP), ':', 2)))); END select count(1) from customers; status; -- Check if table index exists, if exists drop it DELIMITER $$ DROP PROCEDURE IF EXISTS drop_index_if_exists $$ CREATE PROCEDURE drop_index_if_exists(in theTable varchar(128), in theIndexName varchar(128) ) BEGIN IF((SELECT COUNT(*) AS index_exists FROM information_schema.statistics WHERE TABLE_SCHEMA = DATABASE() and table_name = theTable AND index_name = theIndexName) > 0) THEN SET @s = CONCAT('DROP INDEX ' , theIndexName , ' ON ' , theTable); PREPARE stmt FROM @s; EXECUTE stmt; END IF; END $$ DELIMITER ; SET @prev_value = NULL; SET @rank_count = 0; SELECT id, rank_column, CASE WHEN @prev_value = rank_column THEN @rank_count WHEN @prev_value := rank_column THEN @rank_count := @rank_count + 1 END AS rank FROM rank_table ORDER BY rank_column; -- timezone convert select CONVERT_TZ(birthdate, "Etc/UTC", "Asia/Shanghai") from customer_details where customer_id = 11949; <file_sep>/useful_shell.sh mysql --auto-vertical-output mysql -u cbuser -p mysql -u cbuser -p -e "select COUNT(*) FROM limbs" cookbook mysql -u cbuser -p cookbook < file_name # Replace output to screen, put this message to outfile mysql -u cbuser -p > outfile mysql -u cbuser -p < inputfile > outfile mysql -u cbuser -p < inputfile | mail paul # Mysql output html format mysql -H -u cbuser -p -e "select * from limbs;" cookbook # Mysql output xml format mysql -X -u cbuser -p -e "select * from limbs;" cookbook mysql --skip-column-names -u cbuser -p -e "select arms from limbs" cookbook # Use the gnu's util, mac's default is not friendly to tab and so on mysql -u cbuser -p cookbook -e "select * from limbs" | gsed -e "s/\t/:/g" > outputfile mysql -u cbuser -p cookbook -e "select * from limbs" | gtr "\t" ":" > outputfile # Verbose echo "select NOW()" | mysql -u cbuser -p -vvv # Slient echo "select NOW()" | mysql u cbuser -p -s mysqldump -u cbuser -p cookbook mail > mail.sql mysqldump -u cbuser -p cookbook > all_database.sql
2ba1a27b2dfdce51742172e4db5b25edaba8e106
[ "JavaScript", "SQL", "Ruby", "Shell" ]
5
JavaScript
wpzero/notes
4fd4ebe8eb30bae81297f7d35fcd3b6a6fb7465c
ead5b332a467994cd2c0a98896884cee4922e42a
refs/heads/main
<repo_name>ADCeres/my-portfolio-project<file_sep>/projects/weather/src/script_api.js //this section updates the Current Temperature & City through API function getCLInfo(response) { let newCity = response.data.name; let oldCity = document.querySelector("#selected-city"); document.querySelector("#entry-line").value = ""; oldCity.innerHTML = newCity; getStats(response); } //this function sends Geo-Location LAT and LON data to API Weather function determinePosition(position) { console.log(position); let apiKey = `<KEY>`; let lat = position.coords.latitude; let lon = position.coords.longitude; console.log(lat); console.log(lon); let url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&units=imperial&appid=${apiKey}`; axios.get(url).then(getCLInfo); } //this function intiates the Geo-Location grab function getPosition(event) { event.preventDefault(); navigator.geolocation.getCurrentPosition(determinePosition); } function calculateForecastMaxFahrenheit() { let maxTempArray = document.querySelectorAll("#forecast-temp-max"); arrayNumber = -1; maxTempArray.forEach(function () { arrayNumber = arrayNumber + 1; let oldMax = maxTempArray[arrayNumber].innerHTML; let tempLenOne = oldMax.length - 2; oldMax = oldMax.substring(0, tempLenOne); let newMax = oldMax * (9 / 5) + 32; newMax = newMax.toFixed(0); maxTempArray[arrayNumber].innerHTML = `${newMax}°C`; }); } function calculateForecastMinFahrenheit() { let minTempArray = document.querySelectorAll("#forecast-temp-min"); arrayNumber = -1; minTempArray.forEach(function () { arrayNumber = arrayNumber + 1; let oldMin = minTempArray[arrayNumber].innerHTML; let tempLenOne = oldMin.length - 2; oldMin = oldMin.substring(0, tempLenOne); let newMin = oldMin * (9 / 5) + 32; newMin = newMin.toFixed(0); minTempArray[arrayNumber].innerHTML = `${newMin}°C`; }); } function calculateFeelFahrenheit() { let currentFeel = document.querySelector("#cur-temp-feel").innerHTML; let feelLen = currentFeel.length - 2; currentFeel = currentFeel.substring(0, feelLen); let newFeel = currentFeel * (9 / 5) + 32; newFeel = newFeel.toFixed(0); newFeel = `${newFeel}°F`; document.querySelector("#cur-temp-feel").innerHTML = newFeel; } //the function converts the Current Temperature into Fahrenheit (if it is in Celsius) function calculateFahrenheit() { let currentTempUnit = document.querySelector("#cur-temp").innerHTML; let tempLen = currentTempUnit.length - 2; let currentTemp = currentTempUnit.substring(0, tempLen); let newTemp = currentTemp * (9 / 5) + 32; newTemp = newTemp.toFixed(0); let newTempUnit = `${newTemp}°F`; document.querySelector("#cur-temp").innerHTML = `${newTempUnit}`; calculateFeelFahrenheit(); calculateForecastMaxFahrenheit(); calculateForecastMinFahrenheit(); } function calculateForecastMaxCelsius() { let maxTempArray = document.querySelectorAll("#forecast-temp-max"); arrayNumber = -1; maxTempArray.forEach(function () { arrayNumber = arrayNumber + 1; let oldMax = maxTempArray[arrayNumber].innerHTML; let tempLenOne = oldMax.length - 2; oldMax = oldMax.substring(0, tempLenOne); let newMax = (oldMax - 32) * (5 / 9); newMax = newMax.toFixed(0); maxTempArray[arrayNumber].innerHTML = `${newMax}°C`; }); } function calculateForecastMinCelsius() { let minTempArray = document.querySelectorAll("#forecast-temp-min"); arrayNumber = -1; minTempArray.forEach(function () { arrayNumber = arrayNumber + 1; let oldMin = minTempArray[arrayNumber].innerHTML; let tempLenOne = oldMin.length - 2; oldMin = oldMin.substring(0, tempLenOne); let newMin = (oldMin - 32) * (5 / 9); newMin = newMin.toFixed(0); minTempArray[arrayNumber].innerHTML = `${newMin}°C`; }); } function calculateFeelCelsius() { let currentFeel = document.querySelector("#cur-temp-feel").innerHTML; let feelLen = currentFeel.length - 2; currentFeel = currentFeel.substring(0, feelLen); let newFeel = (currentFeel - 32) * (5 / 9); newFeel = newFeel.toFixed(0); newFeel = `${newFeel}°C`; document.querySelector("#cur-temp-feel").innerHTML = newFeel; } //the function converts the Current Temperature into Celsius (if it is in Fahrenheit) function calculateCelsius() { let currentTempUnit = document.querySelector("#cur-temp").innerHTML; let tempLen = currentTempUnit.length - 2; let currentTemp = currentTempUnit.substring(0, tempLen); let newTemp = (currentTemp - 32) * (5 / 9); newTemp = newTemp.toFixed(0); let newTempUnit = `${newTemp}°C`; document.querySelector("#cur-temp").innerHTML = `${newTempUnit}`; calculateFeelCelsius(); calculateForecastMaxCelsius(); calculateForecastMinCelsius(); } //the function looks to confirm if the Current Temperature is in Fahrenheit function confirmUnitF(event) { let currentTempUnit = document.querySelector("#cur-temp").innerHTML; let currentUnit = currentTempUnit.slice(-1); if (currentUnit === "F") { calculateCelsius(); } else { } } //the function looks to confirm if the Current Temperature is in Celsius function confirmUnitC(event) { let currentTempUnit = document.querySelector("#cur-temp").innerHTML; let currentUnit = currentTempUnit.slice(-1); if (currentUnit === "C") { calculateFahrenheit(); } else { } } //This section of code updates all the weather stats for a user-entered city function updateTemp(newTemp) { let oldTemp = document.querySelector("#cur-temp"); newTemp = newTemp.toFixed(0); newTemp = `${newTemp}°F`; oldTemp.innerHTML = newTemp; } function updateFeel(newFeel) { let oldFeel = document.querySelector("#cur-temp-feel"); newFeel = newFeel.toFixed(0); newFeel = `${newFeel}°F`; oldFeel.innerHTML = newFeel; } function updateWeather(newWeather) { let oldWeather = document.querySelector("#cur-emoji-desc"); oldWeather.innerHTML = newWeather; } function updateEmoji(newWeather) { let newEmoji = document.querySelector("#cur-emoji"); switch (newWeather) { case "Clouds": return "☁️"; break; case "Rain": return "🌧"; break; case "Sunny": return "☀️"; break; case "Snow": return "❄️"; break; case "Storm": return "⛈"; break; case "Tornado": return "🌪"; break; case "Hail": return "🌨"; break; case "Fog": return "🌫"; break; case "Extreme": return "❗"; break; case "Windy": return "💨"; break; case "Clear": return "☀️"; break; default: return "❗❗"; break; } } function updateWind(newWind) { let oldWind = document.querySelector("#wind"); newWind = newWind.toFixed(0); oldWind.innerHTML = `${newWind}mph`; } function updateHumidity(newHumidity) { let oldHumidity = document.querySelector("#humidity"); oldHumidity.innerHTML = `${newHumidity}%`; } function convertHour(hour) { let hours = [ 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ]; return hours[hour]; } function convertMinutes(minute) { if (minute < 10) { return `0${minute}`; } else { return `${minute}`; } } function defineAM_PM(hour) { if (hour <= 11) { return "AM"; } else { return "PM"; } } function updateSunrise(newSunrise) { let oldSunrise = document.querySelector("#sunrise"); newSunrise = newSunrise * 1000; let dateSunrise = new Date(newSunrise); let hoursSunrise = dateSunrise.getHours(); let convertedHour = convertHour(hoursSunrise); let minutesSunrise = dateSunrise.getMinutes(); let convertedMinute = convertMinutes(minutesSunrise); let morningOrAfternoon = defineAM_PM(hoursSunrise); let fullSunrise = `${convertedHour}:${convertedMinute}${morningOrAfternoon}`; oldSunrise.innerHTML = fullSunrise; } function updateSunset(newSunset) { let oldSunset = document.querySelector("#sunset"); newSunset = newSunset * 1000; let dateSunset = new Date(newSunset); let hoursSunset = dateSunset.getHours(); let convertedHour = convertHour(hoursSunset); let minutesSunset = dateSunset.getMinutes(); let convertedMinute = convertMinutes(minutesSunset); let morningOrAfternoon = defineAM_PM(hoursSunset); let fullSunset = `${convertedHour}:${convertedMinute}${morningOrAfternoon}`; oldSunset.innerHTML = fullSunset; } function determineForecastArray() { let date = new Date(); let currentDay = date.getDay(); switch (currentDay) { case 0: return ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; break; case 1: return ["Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; break; case 2: return ["Wed", "Thu", "Fri", "Sat", "Sun", "Mon"]; break; case 3: return ["Thu", "Fri", "Sat", "Sun", "Mon", "Tue"]; break; case 4: return ["Fri", "Sat", "Sun", "Mon", "Tue", "Wed"]; break; case 5: return ["Sat", "Sun", "Mon", "Tue", "Wed", "Thu"]; break; case 6: return ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri"]; break; default: return ["Error", "Error", "Error", "Error", "Error", "Error"]; break; } } function displayForecast(response) { let forecastElement = document.querySelector("#forecast"); let days = determineForecastArray(); let forecastHTML = `<div class="row"> `; let arrayNumber = -1; days.forEach(function (day) { arrayNumber = arrayNumber + 1; let minTemp = response.data.daily[arrayNumber].temp.min; minTemp = minTemp.toFixed(0); let maxTemp = response.data.daily[arrayNumber].temp.max; maxTemp = maxTemp.toFixed(0); let emojiDesc = response.data.daily[arrayNumber].weather[0].main; let emoji = updateEmoji(emojiDesc); forecastHTML = forecastHTML + ` <div class="col-2"> <span class="forecast-day">${day}</span> <div class="row"> <div class="card-body"> <p class="card-text subtext"> <span id="forecast-emoji">${emoji}</span> <br /> <span id="forecast-desc">${emojiDesc}</span> <br /> <span id="forecast-temp-max">${maxTemp}°F</span> | <span id="forecast-temp-min">${minTemp}°F</span> </p> </div> </div> </div> `; }); forecastHTML = forecastHTML + `</div>`; forecastElement.innerHTML = forecastHTML; } function updateForecast(newForecast) { let lat = newForecast.lat; let lon = newForecast.lon; let apiKey = `<KEY>`; let url = `https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&exclude=hourly,alerts&units=imperial&appid=${apiKey}`; axios.get(url).then(displayForecast); } function getStats(response) { let newTemp = response.data.main.temp; let newFeel = response.data.main.feels_like; let newWeather = response.data.weather[0].main; let newWind = response.data.wind.speed; let newHumidity = response.data.main.humidity; let newSunrise = response.data.sys.sunrise; let newSunset = response.data.sys.sunset; let newForecast = response.data.coord; updateTemp(newTemp); updateFeel(newFeel); updateWeather(newWeather); updateWind(newWind); updateHumidity(newHumidity); updateSunrise(newSunrise); updateSunset(newSunset); updateForecast(newForecast); let newEmoji = updateEmoji(newWeather); let oldEmoji = document.querySelector("#cur-emoji"); oldEmoji.innerHTML = newEmoji; } function updateCity(newCity) { newCity = newCity.trim(); newCity = newCity.charAt(0).toUpperCase() + newCity.slice(1); let oldCity = document.querySelector("#selected-city"); document.querySelector("#entry-line").value = ""; oldCity.innerHTML = newCity; } function triggerApi(event) { event.preventDefault(); //this piece stores the enter city and sends it to the updateCity function let newCity = document.querySelector("#entry-line").value; updateCity(newCity); //this piece triggers pulling the API data to initiate other functions let apiKey = `<KEY>`; let url = `https://api.openweathermap.org/data/2.5/weather?q=${newCity}&units=imperial&appid=${apiKey}`; axios.get(url).then(getStats); //this piece retriggers the updating of the current date let dateDisplay = document.querySelector("#cur-day-time"); dateDisplay.innerHTML = showDayTime(new Date()); } function initialCity() { let newCity = "New York"; updateCity(newCity); let apiKey = `<KEY>`; let url = `https://api.openweathermap.org/data/2.5/weather?q=${newCity}&units=imperial&appid=${apiKey}`; axios.get(url).then(getStats); } function determineDay(day) { let days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; return days[day]; } function determineMonth(month) { let months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ]; return months[month]; } function showDayTime(date) { let convertedDay = determineDay(date.getDay()); let convertedMonth = determineMonth(date.getMonth()); let convertedMinute = convertMinutes(date.getMinutes()); let convertedHour = convertHour(date.getHours()); let am_or_pm = defineAM_PM(date.getHours()); let currentDate = date.getDate(); let formattedDate = `<strong>Last Data Request:</strong> ${convertedDay}, ${convertedMonth} ${currentDate}, ${convertedHour}:${convertedMinute}${am_or_pm}`; return formattedDate; } //this is the Event Listener button for the Change City Button let changeCity = document.querySelector("#submit-button"); changeCity.addEventListener("click", triggerApi); //this is the Event Listener button for the Fahrenheit to Celcius Conversion process let buttonConverterC = document.querySelector("#celsius"); buttonConverterC.addEventListener("click", confirmUnitF); //this is the Event Listener button for the Celsius to Fahrenheit Conversion process let buttonConverterF = document.querySelector("#fahrenheit"); buttonConverterF.addEventListener("click", confirmUnitC); //this sequence queues the updating of the "Last Data Request" timestamp let dateDisplay = document.querySelector("#cur-day-time"); dateDisplay.innerHTML = showDayTime(new Date()); //this is the Event Listener button for the Current Location Button let currentLocation = document.querySelector("#current-location-button"); currentLocation.addEventListener("click", getPosition); initialCity();
f7359aab6951ddf5aa94817dd333b361b082dcbc
[ "JavaScript" ]
1
JavaScript
ADCeres/my-portfolio-project
ee1f1b3d3ea9667b2254f198460e8dc100e5f0d7
83e1fd67b3b8c23fb8a27ccbead030866a46c3c4
refs/heads/main
<file_sep>/*document.createElement(element) Create an HTML element document.removeChild(element) Remove an HTML element document.appendChild(element) Add an HTML element document.replaceChild(new, old) Replace an HTML element document.write(text) Write into the HTML output stream */ /* window.addEventListener("load",function(){ }) */ function girar(){ var ponteiro = document.getElementById("ponteiro"); var circulo = document.getElementById("circulo"); var tempo=Math.floor(Math.random()*10)+1; switch(tempo){ case 0: alert("parabéns"); break; case 1: alert("Girou com força"); circulo.style.animation="girar5 2s linear"; ponteiro.style.animation="virar 1s infinite"; break; case 2 : alert("caso 2"); circulo.style.animation="girar2 2s linear"; ponteiro.style.animation="virar 1s infinite"; break; case 3: alert("caso 3"); circulo.style.animation="girar3 5s linear"; ponteiro.style.animation="virar 1s infinite"; break; case 4: alert("caso 4"); circulo.style.animation="girar4 2s linear"; ponteiro.style.animation="virar 1s infinite"; break; case 5: alert("caso 5"); circulo.style.animation="girar2 2s linear"; ponteiro.style.animation="virar 1s infinite"; break; case 6: alert("caso 6"); circulo.style.animation="girar3 2s linear"; ponteiro.style.animation="virar 1s infinite"; break; case 7: alert("caso 7"); circulo.style.animation="girar4 3s linear"; ponteiro.style.animation="virar 1s infinite"; break; case 8: alert("caso 8"); circulo.style.animation="girar4 2s linear"; ponteiro.style.animation="virar 1s infinite"; break; case 9: alert("caso 9"); circulo.style.animation="girar2 2s linear"; ponteiro.style.animation="virar 1s infinite"; break; case 10: alert("caso 10"); circulo.style.animation="girar4 2s linear"; ponteiro.style.animation="virar 2s linear"; default: break; } ponteiro.style.animation="virar 2s linear"; } /* window.open('index.html','_self');*/ var i=0; function inicia(){ /* Adicionar imagem document.getElementById("btnAdd").addEventListener("click",function(){ for(i=0 ;i<4;i++){ var imagem = document.createElement("img"); imagem.src = "romance.webp"; imagem.style.width="20%"; imagem.style.height="auto"; imagem.style.float="left"; imagem.style.margin="10px"; document.body.appendChild(imagem); } }); */ document.getElementById("liAdd").addEventListener("click",function(){ var lista = document.createElement("li"); lista.style.textAlign="center"; var li = document.getElementById("input").value; var random =Math.floor(Math.random() * li) + 1; lista.innerHTML=random; switch(random){ case 1: lista.style.color="red"; break; case 2 : lista.style.color="blue"; break; case 3: lista.style.color="gray"; break; case 4: lista.style.color="green"; break; default: break; } document.body.appendChild(lista); }); } window.addEventListener("load",inicia); <file_sep># trainning_javascript explorando o maximo da linguagem de programaçâo para web
98255d8ed51fb04d3cb5438219188096513c1f5d
[ "JavaScript", "Markdown" ]
2
JavaScript
leandroluizpereira/trainning_javascript
7e7b6803810f37ab0b783b37729e6926522892f2
e73bb9e8dcf7f951a6fd020dbff4b51088483bf9
refs/heads/master
<file_sep>#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QNetworkAccessManager> #include <QStringList> #include "wltickerlistform.h" #include "ui_mainwindow.h" #define DEND "112341201205107" // "dd---mm--yy-y-y" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void on_pushButton_clicked(); void on_pbDataBaseClear_clicked(); void on_pbReorganiseTickers_clicked(); void on_pbClearUser_clicked(); void replyFinished(QNetworkReply*reply); void usedTickersEditingEnded(QStringList tickers); // Слоты от сетки на всякие случаи чтобы видеть что произошло void authenticationRequired(QNetworkReply * reply, QAuthenticator * authenticator); void encrypted(QNetworkReply * reply); void networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility accessible); // void proxyAuthenticationRequired(const QNetworkProxy & proxy, QAuthenticator * authenticator); void sslErrors(QNetworkReply * reply, const QList<QSslError> & errors); private: Ui::MainWindow *ui; WLTickerListForm *m_tlists; QNetworkAccessManager * m_netManager; QStringList m_allTickers; QStringList m_usedTickers; bool getAllTickersFile(); void getWLASTickers(); void clearDataBase(bool needSilent = false); void clearUserInfo(); }; #endif // MAINWINDOW_H <file_sep>#include "wltickerlistmodel.h" #include <QApplication> #include <QDebug> WlTickerListModel::WlTickerListModel(int modelType, QObject *parent) : QAbstractTableModel(parent) { m_modelType = modelType; m_rows = 0; } QVariant WlTickerListModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole) { if( section == 0 ) { return QString("Ticker (%1)").arg(m_tickers.size()); } else if( section == 1 ) { return QString("isOn"); } } else if(role == Qt::SizeHintRole) { QFont font = QApplication::font(); font.setPointSize(5); QFontMetrics fontMetrics(font); if( section == 0 ) { return QSize(30, fontMetrics.height()+15); } else if( section == 1 ) { return QSize(30, fontMetrics.height()+15); } } else if(role == Qt::TextAlignmentRole) { if(section == 0){ return (int)Qt::AlignLeft; } else if( section == 1 ) { return (int)Qt::AlignRight; } } } return QAbstractItemModel::headerData(section, orientation, role); } bool WlTickerListModel::setData ( const QModelIndex & index, const QVariant & value, int role ) { //qDebug() << index.row() << index.column() << value.toString() << role; return QAbstractTableModel::setData(index,value,role); } QVariant WlTickerListModel::data(const QModelIndex & index, int role) const { //qDebug() << "data***" << index.row() << index.column() << role; if(index.isValid() ) { if ( role==Qt::DisplayRole ) { if ( index.column()==0 ) { return QVariant(m_tickers[index.row()]); } else if ( index.column()==1 ) { return QVariant(0); } //} else if( role==Qt::BackgroundColorRole ) { //if ( index.row()%2==0 ) { // return QVariant(QColor(230,230,230)); // Qt::lightGray //} else { // return QVariant(QColor(Qt::white)); //} } else if ( role==Qt::EditRole ) { if ( index.column()==1 ) { return QVariant(QString("0")); } } } return QVariant(); } Qt::ItemFlags WlTickerListModel::flags(const QModelIndex &index) const { if ( index.column()==1 ) { return (QAbstractTableModel::flags(index) | Qt::ItemIsEditable); } return QAbstractTableModel::flags(index); } void WlTickerListModel::clear(){ if ( m_rows > 0 ){ beginRemoveRows(QModelIndex(), 0, m_rows-1); m_tickers.clear(); m_rows = 0; endRemoveRows(); } } void WlTickerListModel::setTickers(const QStringList & tickers) { clear(); beginInsertRows(QModelIndex(),0,tickers.size()-1); m_rows = tickers.size(); m_tickers = tickers; endInsertRows(); } QStringList WlTickerListModel::getTickers() { return m_tickers; } const QString WlTickerListModel::ticker(int row) { return m_tickers.at(row); } int WlTickerListModel::getRow(const QString & ticker ) { return m_tickers.indexOf(ticker); } void WlTickerListModel::tickerAdded(const QString & ticker) { if ( ticker.isEmpty() || m_tickers.contains(ticker) ) return; beginInsertRows(QModelIndex(),m_rows,m_rows); ++m_rows; m_tickers.append(ticker); m_tickers.sort(); endInsertRows(); } void WlTickerListModel::tickerListAdded(const QStringList & tickers) { foreach (QString ticker, tickers){ tickerAdded(ticker); } } void WlTickerListModel::tickerDeleted(const QString & ticker) { int row = getRow(ticker); if( row >= 0 ) { beginRemoveRows(QModelIndex(), row, row); m_rows--; m_tickers.removeAt(row); endRemoveRows(); } } void WlTickerListModel::tickerListDeleted(const QStringList & tickers) { foreach (QString ticker, tickers){ tickerDeleted(ticker); } } <file_sep>#include "wltickerlistform.h" #include "ui_wltickerlistform.h" #include <QTableView> #include <QtGui> #include <QDebug> #include <QNetworkRequest> #include <QNetworkReply> #include <QByteArray> WLTickerListForm::WLTickerListForm(QWidget *parent) : QWidget(parent), ui(new Ui::WLTickerListForm) { ui->setupUi(this); tl_model_1 = new WlTickerListModel(); m_pmodel_1 = new QSortFilterProxyModel(); m_pmodel_1->setSourceModel(tl_model_1); ui->tableView_1->setModel(m_pmodel_1); tl_model_2 = new WlTickerListModel(); m_pmodel_2 = new QSortFilterProxyModel(); m_pmodel_2->setSourceModel(tl_model_2); ui->tableView_2->setModel(m_pmodel_2); m_netManager = 0; finvizStakN = 0; } WLTickerListForm::~WLTickerListForm() { if ( m_netManager ) m_netManager->deleteLater(); delete ui; } void WLTickerListForm::closeEvent(QCloseEvent *event) { emit tickersEditingEnded(tl_model_2->getTickers()); event->accept(); // event->ignore(); } void WLTickerListForm::setAllTickers(QStringList & tickers) { tl_model_1->setTickers(tickers); ui->tableView_1->resizeRowsToContents(); } void WLTickerListForm::setUsedTickers(QStringList & tickers) { tl_model_2->setTickers(tickers); ui->tableView_2->resizeRowsToContents(); } void WLTickerListForm::on_tbAdd_clicked() { QModelIndexList selIndexes = ui->tableView_1->selectionModel()->selectedRows(); QStringList selTickers; foreach( QModelIndex index, selIndexes ) { selTickers << m_pmodel_1->data(index).toString(); } qDebug() << "Add:" << selTickers; tl_model_2->tickerListAdded(selTickers); ui->tableView_2->resizeRowsToContents(); m_pmodel_1->setFilterRegExp(ui->lineEdit->text()); m_pmodel_2->setFilterRegExp(ui->lineEdit->text()); //m_pmodel_2->sort(0); } void WLTickerListForm::on_tbDel_clicked() { QModelIndexList selIndexes = ui->tableView_2->selectionModel()->selectedRows(); QStringList selTickers; foreach( QModelIndex index, selIndexes ) { selTickers << m_pmodel_2->data(index).toString(); //qDebug() << index.row() << tl_model_2->ticker(index.row()); } qDebug() << "Del:" << selTickers; tl_model_2->tickerListDeleted(selTickers); m_pmodel_1->setFilterRegExp(ui->lineEdit->text()); m_pmodel_2->setFilterRegExp(ui->lineEdit->text()); } void WLTickerListForm::on_lineEdit_textChanged(const QString &arg1) { //m_pmodel_2->setFilterRegExp(QRegExp(arg1,Qt::CaseSensitive,QRegExp::Wildcard)); //m_pmodel_2->setFilterFixedString(arg1); QString filter = QString("^") + arg1; m_pmodel_1->setFilterRegExp(QRegExp(filter,Qt::CaseInsensitive)); m_pmodel_2->setFilterRegExp(QRegExp(filter,Qt::CaseInsensitive)); //qDebug() << "on_lineEdit_textChanged:" << arg1; } void WLTickerListForm::on_pbImport_clicked() { QString text = ui->plainTextEdit->toPlainText(); if ( text.isEmpty() ) return; ui->pbImport->setEnabled(false); if ( ui->cbReplace->isChecked() ) { tl_model_2->clear(); } QStringList t = text.split(QRegExp("\\s+")); QStringList lookupedList; if( t.size() > 0 ) { foreach (QString ticker, t) { if( tl_model_1->getRow(ticker)!=-1 ) { lookupedList.append(ticker); } } if( lookupedList.size() > 0 ) { tl_model_2->tickerListAdded(lookupedList); ui->tableView_2->resizeRowsToContents(); } } ui->plainTextEdit->clear(); ui->pbImport->setEnabled(true); } void WLTickerListForm::on_pbFinViz_clicked() { bool ok; QString sLink = QInputDialog::getText(this, tr("Enter link to finviz screener"), tr("Link (you may copy it from your browser address line):"), QLineEdit::Normal, "", &ok); if ( ok && !sLink.isEmpty() ) { qDebug() << sLink; if ( !sLink.startsWith("https://finviz.com/screener.ashx?v=111") || sLink.count("http")>1 || sLink.count("finviz.com")>1 ) { QMessageBox::critical(this,tr("Error!"),tr("Bad link.")); return; } if ( sLink.contains("&r=") ) { QMessageBox::critical(this,tr("Error!"),tr("Link must be to the first page!")); return; } ui->pbFinViz->setEnabled(false); if ( !m_netManager ) { m_netManager = new QNetworkAccessManager(this); if ( !m_netManager ) { qDebug() << "Error! Can not make network manager."; QMessageBox::critical(this,tr("Error"),tr("Network error!")); return; } connect(m_netManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*))); connect(m_netManager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), this, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); connect(m_netManager, SIGNAL(encrypted(QNetworkReply*)), this, SLOT(encrypted(QNetworkReply*))); connect(m_netManager, SIGNAL(networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility)), this, SLOT(networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility))); connect(m_netManager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), this, SLOT(sslErrors(QNetworkReply*,QList<QSslError>))); } finvizLink = sLink; finvizStakN = 0; finvizTickers.clear(); QUrl url = QUrl(finvizLink); QNetworkRequest request(url); qDebug() << request.url().toString() << request.url().port() << request.url().scheme(); QNetworkReply * reply = m_netManager->get(request); if ( !reply ) { qDebug() << "Network error! Get reply error."; QMessageBox::critical(this,tr("Error"),tr("Network error!")); return; } qDebug() << "get finviz first page..."; } } void WLTickerListForm::authenticationRequired(QNetworkReply * reply, QAuthenticator * authenticator) { Q_UNUSED(reply) Q_UNUSED(authenticator) qDebug() << "authenticationRequired"; QMessageBox::critical(this,tr("Error"),tr("Network error!")); } void WLTickerListForm::encrypted(QNetworkReply * reply) { Q_UNUSED(reply) qDebug() << "encrypted"; QMessageBox::critical(this,tr("Error"),tr("Network error!")); } void WLTickerListForm::networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility accessible) { Q_UNUSED(accessible) qDebug() << "networkAccessibleChanged"; QMessageBox::critical(this,tr("Error"),tr("Network error!")); } void WLTickerListForm::sslErrors(QNetworkReply * reply, const QList<QSslError> & errors) { Q_UNUSED(reply) Q_UNUSED(errors) qDebug() << "sslErrors"; QMessageBox::critical(this,tr("Error"),tr("Network error!")); } void WLTickerListForm::replyFinished(QNetworkReply* reply) { qDebug() << "Finviz replyFinished"; if ( reply->error()!=QNetworkReply::NoError ) { qDebug() << "Network error! Reply error:" << reply->error(); reply->deleteLater(); QMessageBox::critical(this,tr("Error"),tr("Network error!")); return; } if ( reply->bytesAvailable()<100 ) { qDebug() << "Network error! Reply too small:" << reply->bytesAvailable(); reply->deleteLater(); QMessageBox::critical(this,tr("Error"),tr("Network error!")); return; } QByteArray ba = reply->readAll(); reply->deleteLater(); ba.replace("\r", ""); QString html = ba; int beg=0, end=0, total=0, from=0; QString tmp = "<td width=\"140\" align=\"left\" valign=\"bottom\" class=\"count-text\"><b>Total: </b>"; if ( html.contains(tmp) ) { beg = html.indexOf(tmp); if ( beg>0 ) { beg += tmp.length(); end = html.indexOf(" ",beg); if ( end>0 && end>beg ) { total = html.mid(beg,end-beg).toInt(); beg = html.indexOf(" #",end); if ( beg>0 ) { end = html.indexOf("</td>",beg); beg += 2; if ( end>0 && end>beg ) { from = html.mid(beg,end-beg).toInt(); } } } } } qDebug() << "Total:" << total << " from:" << from; if ( total==0 || from==0) { QMessageBox::critical(this,tr("Error"),tr("Tickers get error!")); return; } tmp = "\n<td height=\"10\" align=\"right\" class=\"screener-body-table-nw\"><a href=\"quote.ashx?t="; if ( html.contains(tmp) ) { beg = 0; end = 0; while ( 1 ) { beg = html.indexOf(tmp,end); if ( beg>0 ) { beg += tmp.length(); end = html.indexOf("&",beg); if ( end>0 && end>beg ) { QString stak = html.mid(beg,end-beg); //qDebug() << "Stak: " << stak; if ( !finvizTickers.contains(stak) ) { finvizTickers.append(stak); ++finvizStakN; } } else { break; } } else { break; } } } if ( total >= (from+20) ) { QUrl url = QUrl(finvizLink+QString("&r=%1").arg(from+20)); QNetworkRequest request(url); //qDebug() << request.url().toString() << request.url().port() << request.url().scheme(); QNetworkReply * reply = m_netManager->get(request); if ( !reply ) { qDebug() << "Network error! Get reply error."; QMessageBox::critical(this,tr("Error"),tr("Network error!")); return; } qDebug() << "get finviz next page " << (from+19)/20+1; } else { qDebug() << "get all staks from finviz."; ui->plainTextEdit->clear(); ui->plainTextEdit->setPlainText(finvizTickers.join(" ")); if ( QMessageBox::question(this,tr("Success"),tr("Got %1 tickers. Import now?").arg(finvizStakN),QMessageBox::Yes | QMessageBox::No)==QMessageBox::Yes ) { on_pbImport_clicked(); } finvizStakN=0; finvizTickers.clear(); finvizLink=""; ui->pbFinViz->setEnabled(true); } } <file_sep>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QSharedMemory> #include <QDebug> #include <QNetworkRequest> #include <QNetworkReply> #include <QUrl> #include <QString> #include <QStringList> #include <QByteArray> #include <QFile> #include <QMessageBox> #include <QDate> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); m_tlists = new WLTickerListForm(); connect(m_tlists,SIGNAL(tickersEditingEnded(QStringList)),this,SLOT(usedTickersEditingEnded(QStringList))); m_netManager = new QNetworkAccessManager(this); if ( !m_netManager ) { qDebug() << "Error! Can not make network manager."; QMessageBox::critical(this,tr("Error"),tr("Network error!")); } else { connect(m_netManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*))); connect(m_netManager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), this, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); connect(m_netManager, SIGNAL(encrypted(QNetworkReply*)), this, SLOT(encrypted(QNetworkReply*))); connect(m_netManager, SIGNAL(networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility)), this, SLOT(networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility))); // connect(m_netManager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), // this, SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); connect(m_netManager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), this, SLOT(sslErrors(QNetworkReply*,QList<QSslError>))); } QSharedMemory sharedMemory; sharedMemory.setKey("<KEY>"); if ( sharedMemory.attach() ) { qDebug() << "WLAS Running = true"; QMessageBox::critical(this,tr("Error"),tr("WLAS is running!")); } else { qDebug() << "WLAS Running = false"; ui->pbDataBaseClear->setEnabled(true); ui->pbClearUser->setEnabled(true); getAllTickersFile(); } /// ftp://ftp.nasdaqtrader.com/SymbolDirectory/nasdaqtraded.txt /// Разбор ниже: // QFile file; // file.setFileName(QString(applicationHomeDir()+"nasdaqtraded.txt")); // if (!file.open(QIODevice::ReadOnly) ) { // file.setFileName(QString(applicationHomeDir()+"nasdaqtraded.bak")); // if (!file.open(QIODevice::ReadOnly) ) { // qlDebug() << "WARNING! Can't open available ticker list - nasdaqtraded.txt!!!"; // qApp->quit(); // return; // } // } // QByteArray ba = file.readAll(); // QStringList tickerList; // QString create_date; // ba.replace("\r", ""); // QList<QByteArray> res_list = ba.split('\n'); // qlDebug() << "res_list=" << res_list.size(); // foreach ( QByteArray str, res_list ) { // if( !str.isEmpty() ) { // QList<QByteArray> str_part = str.split('|'); // if( str_part.size() > 1 && !str_part[1].isEmpty() && str_part[1] != "Symbol") { // tickerList << str_part[1]; // } // if( str.startsWith("File Creation Time") ) { // create_date += QString(str.split(':')[1]).trimmed(); // //qlDebug() << QDateTime::fromString(dt, "MMddyyyyHH").toString(Qt::ISODate); // } // } // } // m_availableTickerList = tickerList; // qlDebug() << "m_availableTickerList.size()=" << m_availableTickerList.size(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { this->close(); } void MainWindow::replyFinished(QNetworkReply* reply) { qDebug() << "replyFinished"; if ( reply->error()!=QNetworkReply::NoError ) { qDebug() << "Network error! Reply error:" << reply->error(); reply->deleteLater(); return; } if ( reply->bytesAvailable()<100 ) { qDebug() << "Network error! Reply too small:" << reply->bytesAvailable(); reply->deleteLater(); return; } QByteArray ba = reply->readAll(); reply->deleteLater(); QString tmpds = DEND; tmpds.remove(13,1); tmpds.remove(11,1); tmpds.remove(3,1); tmpds.replace(2,2,"=="); tmpds.replace(6,2,"--"); QStringList tickerList; QString create_date; ba.replace("\r", ""); QList<QByteArray> res_list = ba.split('\n'); qDebug() << "res_list=" << res_list.size(); foreach ( QByteArray str, res_list ) { if( !str.isEmpty() ) { QList<QByteArray> str_part = str.split('|'); if( str_part.size() > 1 && !str_part[1].isEmpty() && str_part[1] != "Symbol") { if ( !str_part[1].contains('$') && !str_part[1].contains('.') ) { tickerList << str_part[1]; } } if( str.startsWith("File Creation Time") ) { create_date += QString(str.split(':')[1]).trimmed(); } } } QDate tmpd = QDate::fromString(create_date.left(8),"MMddyyyy"); QDate tmpd1 = QDate::fromString(tmpds,"dd==MM--yyyy"); qDebug() << "tickerList.size()=" << tickerList.size() << "Created:" << create_date; m_allTickers = tickerList; m_tlists->setAllTickers(m_allTickers); // QFile file; // file.setFileName("nasdaqtraded.lst"); // if ( file.open(QIODevice::WriteOnly) ) { // foreach ( QString tmp, tickerList ) { // file.write(tmp.toLatin1()+','); // } // file.close(); // } if ( !tmpd.isValid() || !tmpd1.isValid() || tmpd > tmpd1 ) { m_tlists = 0; return; } if ( m_allTickers.size()<1000 ) { return; } getWLASTickers(); } bool MainWindow::getAllTickersFile() { //QUrl url = QUrl("ftp://ftp.nasdaqtrader.com/SymbolDirectory/nasdaqtraded.txt"); QUrl url = QUrl("http://watchlister.ru/wp-content/uploads/2017/08/nasdaqtraded.txt"); QNetworkRequest request(url); qDebug() << request.url().toString() << request.url().port() << request.url().scheme(); QNetworkReply * reply = m_netManager->get(request); if ( !reply ) { qDebug() << "Network error! Get reply error."; return false; } qDebug() << "getAllTickersFile"; return true; } void MainWindow::getWLASTickers() { QFile file; file.setFileName("wlas_all.wtl"); if ( !file.open(QIODevice::ReadOnly) ) { QMessageBox::warning(this,tr("Warning!"),tr("Can not open file wlas_all.wtl.")); } else { QByteArray ba = file.readAll(); file.close(); ba.replace("\r", ""); if ( ba.size()>0 ) { m_usedTickers = QString(ba).split("\n"); m_tlists->setUsedTickers(m_usedTickers); } } ui->pbReorganiseTickers->setEnabled(true); } void MainWindow::usedTickersEditingEnded(QStringList tickers) { if ( tickers==m_usedTickers ) { qDebug("Tickers not changed."); return; } qDebug("Tickers changed!"); if ( QMessageBox::question(this,tr("Tickers changed."),tr("Save changes?"),QMessageBox::Yes | QMessageBox::No)==QMessageBox::Yes ) { QSharedMemory sharedMemory; sharedMemory.setKey("<KEY>"); if ( sharedMemory.attach() ) { qDebug() << "WLAS Running = true"; QMessageBox::critical(this,tr("Error"),tr("WLAS is running!")); } else { QFile file("wlas_all.wtl"); if ( !file.open(QIODevice::WriteOnly) ) { QMessageBox::warning(this,tr("Warning!"),tr("Can not open file wlas_all.wtl.")); } else { QString res; res = tickers.join("\r\n"); if ( file.write(res.toLatin1())==-1 ) { QMessageBox::critical(this,tr("Error!"),tr("Write error.")); } file.close(); m_usedTickers = tickers; clearDataBase(true); } } } } void MainWindow::clearDataBase(bool needSilent) { bool isOk=true, isExists=false; QSharedMemory sharedMemory; sharedMemory.setKey("<KEY>"); if ( sharedMemory.attach() ) { qDebug() << "WLAS Running = true"; QMessageBox::critical(this,tr("Error"),tr("WLAS is running!")); return; } QStringList fnames; fnames << "wl_data_1d.db" << "wl_data_15m.db" << "wl_data_1m.db" << "bdb_1d.db" << "bdb_15m.db" << "bdb_1m.db" << "bdb_indx_1d.db" << "bdb_indx_15m.db" << "bdb_indx_1m.db"; foreach ( QString fname, fnames ) { if ( QFile::exists(fname) ) { isExists = true; if ( !QFile::remove(fname) ) { qDebug() << "Error! Can not remove '" << fname << "'."; isOk = false; } } } if ( !isExists ) { if (!needSilent) QMessageBox::warning(this,tr("Warning!"),tr("No Database found.")); return; } if ( !isOk ) { QMessageBox::critical(this,tr("Error!"),tr("Can not remove database.")); return; } if (!needSilent) QMessageBox::information(this,tr("Success!"),tr("Database cleaned.")); } void MainWindow::clearUserInfo() { QSharedMemory sharedMemory; sharedMemory.setKey("<KEY>"); if ( sharedMemory.attach() ) { qDebug() << "WLAS Running = true"; QMessageBox::critical(this,tr("Error"),tr("WLAS is running!")); return; } if ( QFile::exists("WLAS.ini") ) { QFile file("WLAS.ini"); if ( !file.open(QIODevice::ReadOnly) ) { QMessageBox::critical(this,tr("Error!"),tr("Can not open file WLAS.ini.")); } else { QByteArray ba = file.readAll(); file.close(); if ( ba.size()==0 ) { QMessageBox::critical(this,tr("Error!"),tr("Can not read file WLAS.ini.")); return; } ba.replace('\r',QByteArray()); QStringList sl = QString(ba).split("\n"); file.setFileName("WLAS.ini"); if ( !file.open(QIODevice::WriteOnly) ) { QMessageBox::critical(this,tr("Error!"),tr("Can not open file WLAS.ini for writting.")); return; } foreach ( QString s, sl ) { if ( !s.startsWith("wlas.auth.code=") && !s.startsWith("wlas.auth.pvtkey=") && !s.startsWith("wlas.autologin.on=") ) { s.append('\n'); file.write(s.toLatin1()); } } file.close(); QMessageBox::information(this,tr("Success!"),tr("User info cleaned.")); } } else { QMessageBox::warning(this,tr("Warning!"),tr("No ini file found.")); } } void MainWindow::authenticationRequired(QNetworkReply * reply, QAuthenticator * authenticator) { Q_UNUSED(reply) Q_UNUSED(authenticator) qDebug() << "authenticationRequired"; } void MainWindow::encrypted(QNetworkReply * reply) { Q_UNUSED(reply) qDebug() << "encrypted"; } void MainWindow::networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility accessible) { Q_UNUSED(accessible) qDebug() << "networkAccessibleChanged"; } //void MainWindow::proxyAuthenticationRequired(const QNetworkProxy & proxy, QAuthenticator * authenticator) { // Q_UNUSED(proxy) // Q_UNUSED(authenticator) // qDebug() << "proxyAuthenticationRequired"; //} void MainWindow::sslErrors(QNetworkReply * reply, const QList<QSslError> & errors) { Q_UNUSED(reply) Q_UNUSED(errors) qDebug() << "sslErrors"; } void MainWindow::on_pbDataBaseClear_clicked() { clearDataBase(); } void MainWindow::on_pbReorganiseTickers_clicked() { m_tlists->show(); } void MainWindow::on_pbClearUser_clicked() { clearUserInfo(); } <file_sep>1) Пометить листы (все, wlas) 2) номер версии 3) О программе 4) Вычищать код и ключ <file_sep>#ifndef WLTICKERLISTMODEL_H #define WLTICKERLISTMODEL_H #include <QAbstractTableModel> #include <QObject> #include <QFont> #include <QFontMetrics> #include <QColor> #include <QMap> class WlTickerListModel : public QAbstractTableModel { Q_OBJECT public: WlTickerListModel(int modelType = 0, QObject * parent = 0); int columnCount(const QModelIndex & parent = QModelIndex()) const { Q_UNUSED(parent); if ( m_modelType==1 ) return 2; return 1; } int rowCount(const QModelIndex & parent = QModelIndex()) const { Q_UNUSED(parent); return m_rows; } bool setData ( const QModelIndex & index, const QVariant & value, int role = Qt::EditRole ); QVariant headerData(int section, Qt::Orientation orientation = Qt::Horizontal, int role = Qt::DisplayRole) const; QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const; void clear(); void setTickers(const QStringList & tickers); QStringList getTickers(); const QString ticker(int row); int getRow(const QString & ticker ); QModelIndex getIndex(const QString & UID ); Qt::ItemFlags flags(const QModelIndex &index) const; public slots: void tickerAdded(const QString & ticker); void tickerListAdded(const QStringList & tickers); void tickerDeleted(const QString & ticker); void tickerListDeleted(const QStringList &tickers); signals: void alertAppendedInTable(int row); void alertsAppendedInTable(); void alertDeletedFromTable(int row); void alertsDeletedFromTable(); private: int m_modelType; // 0 - 1 colum list, 1 - 2 column list int m_rows; QStringList m_tickers; }; #endif // WLTICKERLISTMODEL_H <file_sep>#ifndef WLTICKERLISTFORM_H #define WLTICKERLISTFORM_H #include <QWidget> #include "wltickerlistmodel.h" #include <QSortFilterProxyModel> #include <QNetworkAccessManager> namespace Ui { class WLTickerListForm; } class WLTickerListForm : public QWidget { Q_OBJECT public: explicit WLTickerListForm(QWidget *parent = 0); ~WLTickerListForm(); public slots: void setAllTickers(QStringList & tickers); void setUsedTickers(QStringList & tickers); private slots: void on_tbAdd_clicked(); void on_tbDel_clicked(); void on_lineEdit_textChanged(const QString &arg1); void on_pbImport_clicked(); void on_pbFinViz_clicked(); // Слоты от сетки void replyFinished(QNetworkReply*reply); void authenticationRequired(QNetworkReply * reply, QAuthenticator * authenticator); void encrypted(QNetworkReply * reply); void networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility accessible); void sslErrors(QNetworkReply * reply, const QList<QSslError> & errors); signals: void tickersEditingEnded(QStringList tickers); private: Ui::WLTickerListForm *ui; WlTickerListModel *tl_model_1; WlTickerListModel *tl_model_2; QSortFilterProxyModel *m_pmodel_1; QSortFilterProxyModel *m_pmodel_2; QNetworkAccessManager *m_netManager; int finvizStakN; QString finvizLink; QStringList finvizTickers; protected: void closeEvent(QCloseEvent *event); }; #endif // WLTICKERLISTFORM_H
7496220b42c216ae48eb44febc0e1090d5c40da1
[ "Text", "C++" ]
7
C++
posproger/WL_Setup
4f9dc868bdf908e7ace64fc9ce2843489766168d
73f340e75e7001b718c91e460a96a67c4124d120