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># -*- coding: utf-8 -*-
"""
Created on Wed Jul 19 20:33:28 2017
@author: <NAME>
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
import os
from math import *
from PIL import Image,ImageFont,ImageDraw
import random
# create black background
def createBlackBG(bg):
blackBG = np.zeros((bg.shape[0], bg.shape[1], bg.shape[2]),dtype=bg.dtype )
return blackBG
# create the label
def createLable(img, line_width):
# height width passway
height = img.shape[0]
width = img.shape[1]
passway = img.shape[2]
label_img = np.zeros((img.shape[0], img.shape[1], img.shape[2]),dtype=img.dtype )
for i in range(width):
for j in range(line_width):
label_img[j,i,0] = 255
label_img[j,i,1] = 255
label_img[j,i,2] = 255
for i in range(width):
for j in range(height-line_width,height):
label_img[j,i,0] = 255
label_img[j,i,1] = 255
label_img[j,i,2] = 255
for i in range(line_width):
for j in range(height):
label_img[j,i,0] = 255
label_img[j,i,1] = 255
label_img[j,i,2] = 255
for i in range(width-line_width,width):
for j in range(height):
label_img[j,i,0] = 255
label_img[j,i,1] = 255
label_img[j,i,2] = 255
return label_img
# rotate the img (antialockwise)
def rotate(img, degree):
height,width=img.shape[:2]
#旋转后的尺寸
heightNew=int(width*fabs(sin(radians(degree)))+height*fabs(cos(radians(degree))))
widthNew=int(height*fabs(sin(radians(degree)))+width*fabs(cos(radians(degree))))
matRotation=cv2.getRotationMatrix2D((width/2,height/2),degree,1)
matRotation[0,2] +=(widthNew-width)/2
matRotation[1,2] +=(heightNew-height)/2
imgRotation = cv2.warpAffine(img, matRotation, (widthNew,heightNew), borderValue=(0,0,0))
#print imgRotation.shape
#np.savetxt("rotate.txt", imgRotation)
'''
cv2.imshow("img",img)
cv2.imshow("imgRotation",imgRotation)
cv2.waitKey(0)
'''
return imgRotation
# affine the img
def Affine(img, point1, point2, point3):
height = img.shape[0]
width = img.shape[1]
SrcPointsA = np.float32([[0,0], [0,height], [width,0]])
CanvasPointsA = np.float32([point1, point2, point3])
AffineMatrix = cv2.getAffineTransform(SrcPointsA, CanvasPointsA)
AffineImg = cv2.warpAffine(img, AffineMatrix, (int(7*width/6), int(7*height/6)), borderValue=(0,0,0))
return AffineImg
# resize the image
def resize(image, new_width=None, new_height=None, inter=cv2.INTER_AREA):
dim = None
(h, w) = image.shape[:2]
if new_width is None and new_height is None:
return image
if new_width is None:
# 则根据高度计算缩放比例
r = new_height / float(h)
dim = (int(w * r), new_height)
else:
# 根据宽度计算缩放比例
r = new_width / float(w)
dim = (new_width, int(h * r))
resized = cv2.resize(image, dim, interpolation=inter)
return resized
# paste image on the background
def paste(background, upimg, black_bg, label):
copy_background = background.copy()
copy_black_bg = black_bg.copy()
bg_height, bg_width = background.shape[:2]
upimg_height, upimg_width = upimg.shape[:2]
alpa = 0.95
temp = 1
while temp*upimg_height > 0.8*bg_height or temp*upimg_width > 0.8*bg_width:
temp = temp*alpa
upimg = resize(upimg, new_width=int(upimg_width*temp))
label = resize(label, new_width=int(upimg_width*temp))
upimg_height, upimg_width = upimg.shape[:2]
#cv2.imwrite("la_.png", label)
m = random.randint(1, bg_width-upimg_width)
n = random.randint(1, bg_height-upimg_height)
upimg = rmblack(upimg)
for i in range(upimg_width):
for j in range(upimg_height):
if upimg[j, i, 0] == 0 and upimg[j, i, 1] == 0 and upimg[j, i, 2] == 0:
continue
else:
copy_background[j+n, i+m, 0] = upimg[j, i, 0]
copy_background[j+n, i+m, 1] = upimg[j, i, 1]
copy_background[j+n, i+m, 2] = upimg[j, i, 2]
for i in range(upimg_width):
for j in range(upimg_height):
copy_black_bg[j+n, i+m, 0] = label[j, i, 0]
copy_black_bg[j+n, i+m, 1] = label[j, i, 1]
copy_black_bg[j+n, i+m, 2] = label[j, i, 2]
return (copy_background, copy_black_bg)
def GetFileNameAndExt(filename):
(filepath,tempfilename) = os.path.split(filename)
(shotname,extension) = os.path.splitext(tempfilename)
return (shotname,extension)
def mkdir(path):
# 去除首位空格
path = path.strip()
# 去除尾部 \ 符号
path = path.rstrip("//")
isExists = os.path.exists(path)
if not isExists:
os.makedirs(path)
print path+' 创建成功'
return True
else:
print path+' 目录已存在'
return False
# create square black background
def createSquareBG(background):
height, width = background.shape[:2]
if height > width :
return background[0:width-1, 0:width-1]
else:
return background[0:height-1, 0:height-1]
# do not rotate, affine and perspective the image
def pasteNormal(background, upimg, black_bg, label):
copy_background = background.copy()
copy_black_bg = black_bg.copy()
bg_height, bg_width = background.shape[:2]
upimg_height, upimg_width = upimg.shape[:2]
while bg_height*0.7 < upimg_height or bg_width*0.7 < upimg_width :
upimg = resize(upimg, new_width=int(upimg_width*0.95))
label = resize(label, new_width=int(upimg_width*0.95))
upimg_height, upimg_width = upimg.shape[:2]
m = random.randint(1, bg_width-upimg_width)
n = random.randint(1, bg_height-upimg_height)
for i in range(upimg_width):
for j in range(upimg_height):
copy_background[j+n, i+m, 0] = upimg[j, i, 0]
copy_background[j+n, i+m, 1] = upimg[j, i, 1]
copy_background[j+n, i+m, 2] = upimg[j, i, 2]
copy_black_bg[j+n, i+m, 0] = label[j, i, 0]
copy_black_bg[j+n, i+m, 1] = label[j, i, 1]
copy_black_bg[j+n, i+m, 2] = label[j, i, 2]
return (copy_background, copy_black_bg)
#smooth the image
def smooth(img):
img1 = np.float32(img)
kernel = np.ones((5,5),np.float32)/25
dst = cv2.filter2D(img1,-1,kernel)
return dst
# perspective the image
def perspective(img):
height = img.shape[0]
width = img.shape[1]
pts1 = np.float32([[0, 0],[width, 0],[0, height],[width, height]])
pts2 = np.float32([[0, 0],[random.randint(5*width/6, width), random.randint(0, height/6)], \
[random.randint(0, width/6), random.randint(5*height/6, height)], \
[random.randint(5*width/6, width), random.randint(5*height/6, height)]])
M = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(img,M,(img.shape[1], img.shape[0]))
return dst
# remove the black border
def rmblack(im):
height, width = im.shape[:2]
num = 7
for j in range(0, height):
for i in range(width-1, -1, -1):
if im[j][i][0] == 0 and im[j][i][1] == 0 and im[j][i][2] == 0:
continue
else:
for num in range(0, 4):
im[j][i][0] = 0
im[j][i][1] = 0
im[j][i][2] = 0
i = i -1
break;
for i in range(0, width):
if im[j][i][0] == 0 and im[j][i][1] == 0 and im[j][i][2] == 0:
continue
else:
for num in range(0, 4):
im[j][i][0] = 0
im[j][i][1] = 0
im[j][i][2] = 0
i = i + 1
break;
#print 'remove black border!'
return im
if __name__ == "__main__":
image = []
background = []
image_path = 'image'
bg_path = 'background'
Loutdir = './/merge//label//'
Ioutdir = './/merge//image//'
mkdir(Loutdir)
mkdir(Ioutdir)
for root, sub_dirs, files in os.walk(image_path):
for afile in files:
image.append(os.path.join(root,afile))
for root, sub_dirs, files in os.walk(bg_path):
for afile in files:
background.append(os.path.join(root,afile))
i = 0
for forward in image:
for back in background:
(shotname_f,extension) = GetFileNameAndExt(forward)
(shotname_b,extension) = GetFileNameAndExt(back)
im = cv2.imread(forward)
bg = cv2.imread(back)
bg = createSquareBG(bg)
if bg.shape[1] > 1000 :
bg = resize(bg, new_width= 1000)
blackBG = createBlackBG(bg)
label = createLable(im, 5)
(height, width) = im.shape[:2]
(normal_img, normal_label) = pasteNormal(bg, im, blackBG, label)
cv2.imwrite(Ioutdir+str(i)+".jpg" , normal_img)
cv2.imwrite(Loutdir+str(i)+".png", normal_label)
print "generate new image and label:\n" + Ioutdir+str(i)+".jpg\n" \
+ Loutdir+str(i)+".png"
# affine
#point1 = [random.randint(0, int(width/6)), random.randint(0, int(width/6))]
point1 = [0, 0]
point2 = [random.randint(0, int(width/6)), random.randint(int(5*height/6), height)]
point3 = [random.randint(int(5*width/6), width),random.randint(0, int(height/6))]
af_img = Affine(im, point1, point2, point3)
af_lable = Affine(label, point1, point2, point3)
(paste_img, paste_label) = paste(bg, af_img, blackBG, af_lable)
paste_img = resize(paste_img, new_width = 800)
paste_label = resize(paste_label, new_width = 800)
cv2.imwrite(Ioutdir+"affine_"+str(i)+".jpg" , paste_img)
cv2.imwrite(Loutdir+"affine_"+str(i)+".png", paste_label)
print "generate affine image and label:\n" + Ioutdir+"affine_"+str(i)+".jpg\n" \
+ Loutdir+"affine_"+str(i)+".png"
# rotate
degree = random.randint(0,360)
Rimg = rotate(im, degree)
Rlable = rotate(label, degree)
(final_img, final_label) = paste(bg, Rimg, blackBG, Rlable)
final_img = resize(final_img, new_width= 800)
final_label = resize(final_label, new_width= 800)
cv2.imwrite(Ioutdir+"rotate_"+str(i)+".jpg", final_img)
cv2.imwrite(Loutdir+"rotate_"+str(i)+".png", final_label)
print "generate rotate image and label:\n" + Ioutdir+"rotate_"+str(i)+".jpg\n" \
+ Loutdir+"rotate_"+str(i)+".png"
#makeB = cv2.copyMakeBorder(final_img,10, 10, 10, 10, borderType=1)
#cv2.imwrite(Ioutdir+"makeB_"+str(i)+".jpg", makeB)
#perspective
per_im = perspective(im)
per_lable = perspective(label)
(per_final_img, per_final_label) = paste(bg, per_im, blackBG, per_lable)
cv2.imwrite(Loutdir+"per_"+str(i)+".png", per_final_label)
cv2.imwrite(Ioutdir+"per_"+str(i)+".jpg", per_final_img)
print "generate perspective image and label:\n" + Ioutdir+"per_"+str(i)+".jpg\n" \
+ Loutdir+"per_"+str(i)+".png"
i = i + 1
<file_sep># A tool to merge the image
by <NAME>
## four operation: normal, rotate, affine and perspective
## folder
merge folder is the output-folder
merge/image contains the merged image
merge/label contains the merged label(ground truth)
## command
```eg: $ python mergeImage.py ```
<file_sep># -*- coding: utf-8 -*-
"""
Created on Wed Aug 09 17:31:16 2017
@author: guan
"""
from skimage import data, exposure, img_as_float, io
#from skimage import io
import matplotlib.pyplot as plt
import cv2
import os
import numpy as np
import argparse
import sys
# change the lightness of the image
# alpa = [0:1] -> 变亮
# alpa = [1:~] -> 变暗
def changeLight(imageName, outdir, alpa):
mkdir(outdir)
(name, extension) = parseName(imageName)
image = img_as_float(io.imread(imageName))
change_img= exposure.adjust_gamma(image, alpa)
outPatn = os.path.join(outdir, 'L_'+name+extension)
plt.imsave(outPatn, change_img)
# move the pixel
def movePixel(img, dist):
mv_img = np.copy(img)
#print mv_img
for j in range(img.shape[0]-dist):
for i in range(img.shape[1]-dist):
mv_img[j+dist, i+dist, 0] = img[j, i, 0]
mv_img[j+dist, i+dist, 1] = img[j, i, 1]
mv_img[j+dist, i+dist, 2] = img[j, i, 2]
#cv2.imwrite('g_test.jpg', mv_img)
return mv_img
# generate the ghost image
def ghost(img):
mv_img = movePixel(img, 8)
#print type(mv_img), type(img)
#dest = img
dest = cv2.addWeighted(img, 0.7, mv_img, 0.3, 0)
return dest
def addWater(img):
water = cv2.imread('resource//water.jpg')
#im = cv2.imread('test2.jpeg')
height,width = img.shape[:2]
water_re = cv2.resize(water, ( width, height), interpolation=cv2.INTER_AREA)
#print water_re.shape
dest = cv2.addWeighted(img, 0.6, water_re, 0.4, 0)
return dest
# 创建目录
def mkdir(path):
# 去除首位空格
path = path.strip()
# 去除尾部符号
path = path.rstrip("//")
isExists = os.path.exists(path)
if not isExists:
os.makedirs(path)
print path+' 创建成功'
return True
else:
print path+' 目录已存在'
return False
def parseName(path):
(dirpath, file_name) = os.path.split(path)
(name, extension) = os.path.splitext(file_name)
return (name, extension)
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Blur the image')
parser.add_argument('--a', dest='alpa',
help='light degree: alpa = 1 not change || alpa->0 lighter || alpa -> ∞ darker ',
default=1, type=float)
parser.add_argument('--out', dest='outdir',
help='output dir (default ''output/'' )',
default='output/', type=str)
parser.add_argument('--imagePath', dest='image_path',
help='The path of image',
default=None, type=str)
if len(sys.argv) < 3:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
return args
if __name__ == "__main__":
args = parse_args()
(name, extension) = parseName(args.image_path)
changeLight(args.image_path, args.outdir, args.alpa)
im = cv2.imread(args.image_path)
ghost_im = ghost(im)
outpath = os.path.join(args.outdir,'G_'+name+extension)
cv2.imwrite(outpath, ghost_im)
addW_im = addWater(im)
outpath = os.path.join(args.outdir,'W_'+name+extension)
cv2.imwrite(outpath, addW_im)
<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Jul 28 16:33:37 2017
@author: guan
"""
import cv2
import os
import sys
import argparse
import numpy as np
def blur(img, (minx, miny), (maxx, maxy), beta, flag):
height = img.shape[0]
width = img.shape[1]
if minx == -1 or miny ==-1 or maxx == -1 or maxy == -1:
minx = 0
miny = 0
maxx = width
maxy = height
if maxy > height or maxx > width or \
minx >= maxx or miny >= maxy:
print 'The region is unlegal!'
return 0
kernel_size = (int(20*beta)*2+1, int(20*beta)*2+1)
sigma = 10*beta
if flag == 0:
part_of_img = img[miny:maxy, minx:maxx]
#cv2.imwrite('part.jpg', part_of_img)
img_blur = cv2.GaussianBlur(part_of_img, kernel_size, sigma)
for i in range(minx, maxx):
for j in range(miny, maxy):
img[j][i][0] = img_blur[j-miny][i-minx][0]
img[j][i][1] = img_blur[j-miny][i-minx][1]
img[j][i][2] = img_blur[j-miny][i-minx][2]
return img
else:
copy_im = img.copy()
blur_copy_im = cv2.GaussianBlur(copy_im, kernel_size, sigma)
for i in range(minx, maxx):
for j in range(miny, maxy):
blur_copy_im[j][i][0] = img[j-miny][i-minx][0]
blur_copy_im[j][i][1] = img[j-miny][i-minx][1]
blur_copy_im[j][i][2] = img[j-miny][i-minx][2]
return blur_copy_im
def createBlack(img):
black_im = np.zeros(img.shape)
return black_im
def black(img, (minx, miny), (maxx, maxy), beta, flag):
height = img.shape[0]
width = img.shape[1]
if minx == -1 or miny ==-1 or maxx == -1 or maxy == -1:
minx = 0
miny = 0
maxx = width
maxy = height
if maxy > height or maxx > width or \
minx >= maxx or miny >= maxy:
print 'The region is unlegal!'
return 0
if flag == 0:
part_of_img = img[miny:maxy, minx:maxx]
#cv2.imwrite('part.jpg', part_of_img)
img_black = createBlack(part_of_img)
for i in range(minx, maxx):
for j in range(miny, maxy):
img[j][i][0] = img_black[j-miny][i-minx][0]
img[j][i][1] = img_black[j-miny][i-minx][1]
img[j][i][2] = img_black[j-miny][i-minx][2]
return img
else:
copy_im = img.copy()
blur_copy_im = createBlack(copy_im)
for i in range(minx, maxx):
for j in range(miny, maxy):
blur_copy_im[j][i][0] = img[j-miny][i-minx][0]
blur_copy_im[j][i][1] = img[j-miny][i-minx][1]
blur_copy_im[j][i][2] = img[j-miny][i-minx][2]
return blur_copy_im
def mkdir(path):
# 去除首位空格
path = path.strip()
# 去除尾部符号
path = path.rstrip("//")
isExists = os.path.exists(path)
if not isExists:
os.makedirs(path)
print path+' 创建成功'
return True
else:
print path+' 目录已存在'
return False
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Blur the image')
parser.add_argument('--b', dest='beta',
help='blur degree (default 0.5)',
default=0.5, type=float)
parser.add_argument('--out', dest='outdir',
help='output dir (default ''output/'' )',
default='output/', type=str)
parser.add_argument('--imagePath', dest='image_path',
help='The path of image',
default=None, type=str)
parser.add_argument('--Xpoint1', dest='minx',
help='The X of point1, (if equal -1 then blur the entire image!)',
default=None, type=int)
parser.add_argument('--Ypoint1', dest='miny',
help='The Y of point1, (if equal -1 then blur the entire image!)',
default=None, type=int)
parser.add_argument('--Xpoint2', dest='maxx',
help='The X of point2, (if equal -1 then blur the entire image!)',
default=None, type=int)
parser.add_argument('--Ypoint2', dest='maxy',
help='The Y of point2, (if equal -1 then blur the entire image!)',
default=None, type=int)
parser.add_argument('--isturn', dest='flag',
help='If isturn equal 1, the image is blured except the \
designated areas (default 0)',
default=0, type=int)
if len(sys.argv) < 5:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
return args
if __name__ == "__main__":
args = parse_args()
print args
mkdir(args.outdir)
leftup_point = (args.minx, args.miny)
rightdown_point = (args.maxx, args.maxy)
im = cv2.imread(args.image_path)
im = black(im, leftup_point, rightdown_point, args.beta, args.flag)
name = os.path.splitext(os.path.split(args.image_path)[1])[0]
cv2.imwrite(args.outdir + name + '_black.jpg', im)
print 'black the image: '+ name +'.jpg successfully!'<file_sep># A tool about blurring/blackening the image in designated areas
by <NAME>
## optional arguments:
- -h, --help show this help message and exit
- --b BETA blur degree (default 0.5)
- --out OUTDIR output dir (default 'output/' )
- --imagePath IMAGE_PATH The path of image
- --Xpoint1 MINX The X of point1, (if equal -1 then blur/blacken the entire image!)
- --Ypoint1 MINY The Y of point1, (if equal -1 then blur/blacken the entire image!)
- --Xpoint2 MAXX The X of point2, (if equal -1 then blur/blacken the entire image!)
- --Ypoint2 MAXY The Y of point2, (if equal -1 then blur/blacken the entire image!)
- --isturn FLAG If isturn equal 1, the image is blured except the designated area (default 0)
- Xpoint1, Ypoint1, Xpoint2, Ypoint2 and imagePath is required necessarily
- isturn, out and b is not necessarily
## Example
eg:$ python blur.py --imagePath image --Xpoint1 40 --Ypoint1 40 --Xpoint2 400 --Ypoint2 400
eg:$ python black.py --imagePath image --Xpoint1 40 --Ypoint1 40 --Xpoint2 400 --Ypoint2 400 --isturn 1
## result
- **orginial image**

- **after blur**

- **after black**

<file_sep>python imageChange.py --imagePath test2.jpeg --a 0.3<file_sep># Some tools on image
by <NAME><file_sep>python blur.py --imagePath ./image/test.jpg --Xpoint1 40 --Ypoint1 40 --Xpoint2 400 --Ypoint2 400
<file_sep># A Tool making the image looks like fake
by <NAME>
## options:
- -h, --help show this help message and exit
- --a ALPA light degree:
alpa = 1 not change || alpa->0 lighter || alpa -> ∞ darker
- --out OUTDIR output dir (default output/ )
- --imagePath IMAGE_PATH The path of image
## run
$ sh run.sh
## three operations
### original image

**1. change the light**

**2. add the water**

**3. create the ghost**
 | c9b4b4485180100b2882bf00ea37639e2018b841 | [
"Markdown",
"Python",
"Shell"
] | 9 | Python | coderguanmingyang/imageTool | 2dbf471258c8902322b4ac9d5f987204e85eb267 | 1f0ffba30f3406ec1dda006f56ef64cc9f6c274a |
refs/heads/master | <repo_name>sriramrajendiran/Multi-label-Inception-net<file_sep>/combined_label_image.py
import tensorflow as tf
import sys
import os
from tensorflow.contrib import learn
import numpy as np
import re
import urllib
# change this as you see fit
image_path = "http://dtpmhvbsmffsz.cloudfront.net/posts/2014/09/17/541a5558b539e42fdf0bcfc4/m_541a555eb539e42fdf0bcfce.jpg"
req = urllib.request.Request(image_path)
response = urllib.request.urlopen(req)
image_data = response.read()
test_description = " Peacock inspired Necklace NWOT Beautiful Peacock color inspired necklace. Never worn! Price negotiable use the the offer button"
# Read in the image_data
#image_data = tf.gfile.FastGFile(image_path, 'rb').read()
# Loads label file, strips off carriage return
label_lines = [line.rstrip() for line
in tf.gfile.GFile("labels.txt")]
def clean_str(s):
"""Clean sentence"""
s = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", s)
s = re.sub(r"\'s", " \'s", s)
s = re.sub(r"\'ve", " \'ve", s)
s = re.sub(r"n\'t", " n\'t", s)
s = re.sub(r"\'re", " \'re", s)
s = re.sub(r"\'d", " \'d", s)
s = re.sub(r"\'ll", " \'ll", s)
s = re.sub(r",", " , ", s)
s = re.sub(r"!", " ! ", s)
s = re.sub(r"\(", " \( ", s)
s = re.sub(r"\)", " \) ", s)
s = re.sub(r"\?", " \? ", s)
s = re.sub(r"\s{2,}", " ", s)
s = re.sub(r'\S*(x{2,}|X{2,})\S*', "xxx", s)
s = re.sub(r'[^\x00-\x7F]+', "", s)
return s.strip().lower()
# Unpersists graph from file
with tf.gfile.FastGFile("/goshposh/Multi-label-Inception-net/models/combined/combined_output_graph.pb", 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='')
with tf.Session() as sess:
vocab_path = os.path.join('/goshposh/Multi-label-Inception-net/models/combined/', "vocab.pickle")
vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path)
description = np.array(list(vocab_processor.transform(clean_str(test_description))))
description_tensor = sess.graph.get_operation_by_name("input/DescriptionsInput").outputs[0]
# Feed the image_data as input to the graph and get first prediction
sigmoid_tensor = sess.graph.get_tensor_by_name('final_result:0')
predictions = sess.run(sigmoid_tensor, \
{'DecodeJpeg/contents:0': image_data,
description_tensor: description})
# Sort to show labels of first prediction in order of confidence
top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]
for node_id in top_k:
human_string = label_lines[node_id]
score = predictions[0][node_id]
print('%s (score = %.5f)' % (human_string, score))
filename = "results.txt"
with open(filename, 'a+') as f:
f.write('\n**%s**\n' % (image_path))
for node_id in top_k:
human_string = label_lines[node_id]
score = predictions[0][node_id]
f.write('%s (score = %.5f)\n' % (human_string, score))
<file_sep>/freeze_checkpoint.py
import tensorflow as tf
from tensorflow.contrib.slim.python.slim.nets import inception
from tensorflow.python.training import saver as tf_saver
from tensorflow.python.framework import graph_util
slim = tf.contrib.slim
input_checkpoint = "/goshposh/Multi-label-Inception-net/openimages_2016_08/model.ckpt"
output_file = 'inference_graph.pb'
def PreprocessImage(image, central_fraction=0.875):
"""Load and preprocess an image.
Args:
image: a tf.string tensor with an JPEG-encoded image.
central_fraction: do a central crop with the specified
fraction of image covered.
Returns:
An ops.Tensor that produces the preprocessed image.
"""
# Decode Jpeg data and convert to float.
image = tf.cast(tf.image.decode_jpeg(image, channels=3), tf.float32)
image = tf.image.central_crop(image, central_fraction=central_fraction)
# Make into a 4D tensor by setting a 'batch size' of 1.
image = tf.expand_dims(image, [0])
image = tf.image.resize_bilinear(image,
[299, 299],
align_corners=False)
# Center the image about 128.0 (which is done during training) and normalize.
image = tf.multiply(image, 1.0 / 127.5)
return tf.subtract(image, 1.0)
g = tf.Graph()
with g.as_default():
input_image = tf.placeholder(tf.string, name='input')
processed_image = PreprocessImage(input_image)
with slim.arg_scope(inception.inception_v3_arg_scope()):
logits, end_points = inception.inception_v3(processed_image, num_classes=6012, is_training=False)
predictions = tf.nn.sigmoid(logits, name='multi_predictions')
saver = tf_saver.Saver()
input_graph_def = g.as_graph_def()
sess = tf.Session()
saver.restore(sess, input_checkpoint)
output_node_names = "multi_predictions"
output_graph_def = graph_util.convert_variables_to_constants(
sess, # The session is used to retrieve the weights
input_graph_def, # The graph_def is used to retrieve the nodes
output_node_names.split(",") # The output node names are used to select the usefull nodes
)
# Finally we serialize and dump the output graph to the filesystem
with tf.gfile.GFile(output_file, "wb") as f:
f.write(output_graph_def.SerializeToString()) | 71ec22c343d2b452795c4025c850aee5e2395e7f | [
"Python"
] | 2 | Python | sriramrajendiran/Multi-label-Inception-net | 7db952a84d0eabf8769a82132893cf403c4d8fbe | bb29c973a4b275db746737ce2fc75202c5a50998 |
refs/heads/master | <repo_name>alexherlanda/cerros-api<file_sep>/routes/volunteers.js
const express = require("express");
const { VolunteersService } = require("../services/VolunteersService");
function volunteersRouter(expressApp) {
const router = new express.Router();
expressApp.use("/api/volunteers", router);
const volunteersService = new VolunteersService();
router.get("/", async (req, res, next) => {
try {
const volunteersList = await volunteersService.findVolunteers({});
res.status(200);
res.send({
data: volunteersList,
message: "Consult of volunteers was successful",
});
} catch (error) {
next(error);
}
});
}
module.exports = volunteersRouter;
<file_sep>/services/VolunteersService.js
const MongoLib = require("../lib/MongoLib");
class VolunteersService {
constructor() {
this.collection = "volunteers";
this.mongoDB = new MongoLib();
}
async addOneVolunteer() {}
async updateOneVolunteer() {}
async deleteOneVolunteer() {}
async findVolunteers(query = {}) {
const results = await this.mongoDB.findByQuery(this.collection, query);
return results;
}
}
module.exports = { VolunteersService };
<file_sep>/.env.example
PORT=
DB_USER=
DB_PASSWORD=
DB_NAME=
DB_HOST=<file_sep>/scripts/teamSeeds.js
// DEBUG=app:* node scripts/teamSeeds.js
const chalk = require("chalk");
const debug = require("debug")("app:scripts:teamSeeds");
const MongoLib = require("../lib/MongoLib");
const volunteers = [
{
name: "<NAME>",
roleDescription: "Lider Técnico",
background: "Code",
axis: 1,
birthDate: "08/06/1973",
nationality: "MX",
locationCity: "CDMX",
locationCountry: "mx",
occupation: "Empleado",
email: "<EMAIL>",
admissionDate: "22/05/2020",
exitDate: null,
imageURL: "https://live.some.com/65535/50800739818_baae417d1e.jpg",
},
];
async function seedEvents() {
try {
const mongoDB = new MongoLib();
const promises = volunteers.map(async (member) => {
await mongoDB.createOne("volunteers", member);
});
await Promise.all(promises);
debug(chalk.green(`${promises.length} team members have been created succesfully`)); // prettier-ignore
} catch (error) {
debug(chalk.red(error));
process.exit(1);
}
return process.exit(0);
}
seedEvents();
<file_sep>/lib/MongoLib.js
const config = require("../config");
const { MongoClient, ObjectID } = require("mongodb");
const USER = encodeURIComponent(config.dbUser);
const DB_PASSWORD = encodeURIComponent(config.dbPassword);
const DB_NAME = encodeURIComponent(config.dbName);
const DB_HOST = encodeURIComponent(config.dbHost);
const MONGO_URI = `mongodb+srv://${USER}:${DB_PASSWORD}@${DB_HOST}/${DB_NAME}?retryWrites=true&w=majority`;
console.log("MONGO URI", MONGO_URI);
class MongoLib {
constructor() {
this.client = new MongoClient(MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
this.dbName = DB_NAME;
}
connect() {
if (!MongoLib.connection) {
MongoLib.connection = new Promise((resolve, reject) => {
this.client.connect((error) => {
if (error) {
reject(error);
}
resolve(this.client.db(this.dbName));
});
});
}
return MongoLib.connection;
}
async findByQuery(collection, query) {
const db = await this.connect();
return await db.collection(collection).find(query).toArray();
}
async findById(collection, id) {
const db = await this.connect();
return await db.collection(collection).findOne({ _id: ObjectId(id) });
}
async createOne(collection, data) {
const db = await this.connect();
const resultData = await db.collection(collection).insertOne(data);
return resultData.insertedId;
}
async updateOneById(collection, id, data) {
const db = await this.connect();
const resultData = await db
.collection(collection)
.updateOne({ _id: ObjectId(id) }, { $set: data }, { upsert: true });
return resultData.upsertedId || id;
}
async deleteOneById(collection, id) {
const db = await this.connect();
await db.collection(collection).deleteOne({ _id: ObjectId(id) });
return id;
}
}
module.exports = MongoLib;
| fbd9976046b9793f80813500e1724bd8bf817d6f | [
"JavaScript",
"Shell"
] | 5 | JavaScript | alexherlanda/cerros-api | 885b60da6c3a858b9a3a91fedf73a1b299aa403e | 86e2e3dba2f45c6496d4970521555106961d96c1 |
refs/heads/master | <repo_name>tosone/backend-golang<file_sep>/README.md
# OnlineSchool-backend
### 依赖管理
- Add new dependence `godep get package-name`
- After save it in vendor `godep save`
- Restore all of the denpendencies `godep restore`
<file_sep>/service/responseCode/code.go
package responseCode
var code map[string]int
func init() {
code = map[string]int{
"authErr": 10001,
"dbErr": 10002,
"loginErr": 10003,
}
}
<file_sep>/service/middleware/verify.go
package middleware
import (
iris "gopkg.in/kataras/iris.v8"
)
// Verify verift
func Verify(ctx *iris.Context) {
}
<file_sep>/router/register/register.go
package register
import (
"github.com/tosone/backend-golang/service/register"
"gopkg.in/kataras/iris.v8"
)
// Index 登陆注册
func Index(app *iris.Application) {
app.Post("/login", register.Login)
app.Post("/register", register.Register)
}
<file_sep>/router/index.go
package router
import (
"github.com/tosone/backend-golang/router/register"
"gopkg.in/kataras/iris.v8"
)
// Index 入口文件
func Index(app *iris.Application) {
register.Index(app)
}
<file_sep>/mongo/redis.go
package mongo
import (
"github.com/garyburd/redigo/redis"
)
// RedisPool redispool
var RedisPool *redis.Pool
func init() {
RedisPool = redis.NewPool(func() (redis.Conn, error) { return redis.Dial("tcp", "127.0.0.1") }, 10)
}
<file_sep>/main.go
package main
import (
"fmt"
// "github.com/iris-contrib/middleware/cors"
// "github.com/tosone/backend-golang/config"
"github.com/tosone/backend-golang/router"
"gopkg.in/kataras/iris.v8"
)
var (
// BuildStamp BuildStamp
BuildStamp = "Nothing Provided."
// GitHash GitHash
GitHash = "Nothing Provided."
)
func main() {
fmt.Printf("Git Commit Hash: %s\n", GitHash)
fmt.Printf("UTC Build Time: %s\n", BuildStamp)
app := iris.New()
// app.Adapt(
// iris.DevLogger(),
// cors.New(cors.Options{
// AllowedOrigins: []string{"*"},
// AllowCredentials: true,
// }))
router.Index(app)
app.Run(iris.Addr(":8080"))
}
<file_sep>/service/register/register.go
package register
import (
"log"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/satori/go.uuid"
"github.com/tosone/backend-golang/config"
"github.com/tosone/backend-golang/model"
"github.com/tosone/backend-golang/mongo"
"golang.org/x/crypto/bcrypt"
"gopkg.in/kataras/iris.v8"
"gopkg.in/mgo.v2/bson"
)
type registerForm struct {
Name string `form:"name"`
Password string `form:"password"`
}
// Login 注册
func Login(ctx iris.Context) {
var loginForm registerForm
ctx.ReadJSON(&loginForm)
DB := mongo.MgoDb{}
DB.Init()
defer DB.Close()
var userInfo model.UserRegisterForm
if err := DB.C("test").Find(bson.M{"name": loginForm.Name}).One(&userInfo); err != nil {
log.Println(err)
ctx.StatusCode(405)
ctx.JSON(iris.Map{"status": 405, "info": "MongoDB is error, please retry again."})
return
}
if err := checkPasswordHash(loginForm.Password+userInfo.Salt, userInfo.Hash); err != nil {
log.Println(err)
ctx.StatusCode(405)
ctx.JSON(iris.Map{"status": 405, "info": "Password or Username is wrong."})
return
}
mongo.RedisPool.Get().Do("Set", uuid.NewV4().String(), "EX", config.SessionExpire)
token := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.MapClaims{
"sid": uuid.NewV4().String(),
"exp": time.Now().Unix() + config.SessionExpire,
})
signedString, err := token.SignedString(config.SessionSecret)
if err != nil {
log.Println(err)
}
ctx.StatusCode(iris.StatusOK)
ctx.JSON(iris.Map{"authenticate": signedString})
}
// Register 注册
func Register(ctx iris.Context) {
var data registerForm
ctx.ReadJSON(&data)
var hash string
var err error
salt := uuid.NewV4().String()
if hash, err = hashPassword(data.Password + salt); err != nil {
log.Println(err)
}
userInfo := model.UserRegisterForm{
ID: bson.NewObjectId(),
Name: data.Name,
Hash: hash,
Salt: salt,
}
DB := mongo.MgoDb{}
DB.Init()
DB.C("test").Insert(userInfo)
defer DB.Close()
ctx.StatusCode(iris.StatusOK)
log.Println(userInfo)
ctx.JSON(iris.Map{})
}
func hashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return string(bytes), err
}
func checkPasswordHash(password, hash string) error {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err
}
<file_sep>/Makefile
BuildStamp=main.BuildStamp=`date '+%Y-%m-%d_%I:%M:%S%p'`
GitHash=main.GitHash=`git rev-parse HEAD`
all:
go run main.go
test:
go test .
authors:
echo "Authors\n=======\n\nProject's contributors:\n" > AUTHORS.md
git log --raw | grep "^Author: " | cut -d ' ' -f2- | cut -d '<' -f1 | sed 's/^/- /' | sort | uniq >> AUTHORS.md
build: clean
mkdir release
go build -o release/server -ldflags "-s -w -X ${BuildStamp} -X ${GitHash}" main.go
clean:
-rm -rf release
<file_sep>/config/config.go
package config
import (
"fmt"
"github.com/caarlos0/env"
)
var (
// IP 地址
IP = "127.0.0.1"
// PORT 端口
PORT = "8080"
// MongoURL mongo 连接字符串
MongoURL = ""
// MongoDatabase 链接 mongo 的数据库
MongoDatabase = "tosone"
// PriKeyPath 私钥
PriKeyPath = "keys/app.rsa"
// PubKeyPath 公钥
PubKeyPath = "keys/app.rsa.pub"
// PasswordSalt 用户密码的盐值
PasswordSalt = "<PASSWORD>"
// SessionExpire 最长的 session 过期时间
SessionExpire int64 = 24 * 60 * 60
// SessionSecret Session Secret
SessionSecret = "9787581d51ca21f452512ce58d98ceb4"
)
// config 配置
type config struct {
MongoHost string `env:"MongoHost" envDefault:"localhost"`
MongoPort string `env:"MongoPort" envDefault:"3000"`
MongoDB string `env:"MongoDB"`
MongoUser string `env:"MongoUser"`
MongoPass string `env:"MongoPass"`
}
func init() {
var cfg config
err := env.Parse(&cfg)
if err != nil {
fmt.Printf("%+v\n", err)
}
MongoURL = fmt.Sprintf("mongodb://%s:%s@%s:%s/%s", cfg.MongoUser, cfg.MongoPass, cfg.MongoHost, cfg.MongoPort, "admin")
}
<file_sep>/mongo/mongo.go
package mongo
import (
"log"
"github.com/tosone/backend-golang/config"
"gopkg.in/mgo.v2"
)
// MSession mongo Session
var MSession *mgo.Session
// MgoDb 链接数据库的对象
type MgoDb struct {
Session *mgo.Session
Db *mgo.Database
Col *mgo.Collection
}
func init() {
if MSession == nil {
var err error
MSession, err = mgo.Dial(config.MongoURL)
if err != nil {
log.Println(err)
}
MSession.SetMode(mgo.Monotonic, true)
}
}
// Init 初始化
func (mdb *MgoDb) Init() *mgo.Session {
mdb.Session = MSession.Copy()
mdb.Db = mdb.Session.DB(config.MongoDatabase)
return mdb.Session
}
// C 选择集合
func (mdb *MgoDb) C(collection string) *mgo.Collection {
return mdb.Db.C(collection)
}
// Close 关闭数据库
func (mdb *MgoDb) Close() bool {
defer mdb.Session.Close()
return true
}
// DropoDb 删除数据库
func (mdb *MgoDb) DropoDb() error {
err := mdb.Db.DropDatabase()
if err != nil {
return err
}
return nil
}
// RemoveAll 移除所有的集合
func (mdb *MgoDb) RemoveAll(collection string) bool {
mdb.Db.C(collection).RemoveAll(nil)
mdb.Col = mdb.Db.C(collection)
return true
}
// Index 返回所有的序号
func (mdb *MgoDb) Index(collection string, keys []string) bool {
index := mgo.Index{
Key: keys,
Unique: true,
DropDups: true,
Background: true,
Sparse: true,
}
err := mdb.Db.C(collection).EnsureIndex(index)
if err != nil {
log.Println(err)
return false
}
return true
}
// IsDup 检查是否连接
func (mdb *MgoDb) IsDup(err error) bool {
if mgo.IsDup(err) {
return true
}
return false
}
<file_sep>/model/user.go
package model
import "gopkg.in/mgo.v2/bson"
// UserRegisterForm 用户登录注册的信息
type UserRegisterForm struct {
ID bson.ObjectId `json:"id" bson:"_id"`
Name string `json:"name" bson:"name"`
Salt string `json:"salt" bson:"salt"`
Hash string `json:"hash" bson:"hash"`
}
<file_sep>/model/response.go
package model
// ResponseInfo 返回值信息
type ResponseInfo struct {
Status int `json:"status"`
Info string `json:"info"`
}
| cdd08c79cfdd10ca4fa5c2dd75898eb7b827be97 | [
"Markdown",
"Go",
"Makefile"
] | 13 | Markdown | tosone/backend-golang | 4ea52b393de6c0fbdcfa9bad08781a561949a7c8 | e6ae1f2ad86958f27b7f3d4ab47d200f485969fa |
refs/heads/master | <file_sep>let db = require('./db');
exports.selectArticle = (cb) => {
let query = 'SELECT * FROM article order by id desc'
db.query(query, (err, data) => {
if(!err) return cb(data)
cb(err)
})
}
//INSERT INTO article (content,`year`,title,img,mounth,`day`,jianjie) VALUES ('12','13','13','12','23','13','12');
exports.addArticle = (data, cb) => {
let query = 'INSERT INTO article SET ?'
db.query(query,data, (err, data) => {
if(!err) return cb(data)
cb(err)
})
}
exports.selectContent = (data, cb) => {
let query = 'SELECT * FROM `article` WHERE id=' + data.id
db.query(query,data, (err, data) => {
if(!err) return cb(data)
cb(err)
})
}
<file_sep>const express = require('express');
const {
selectArticle,
selectContent
} = require('../models/article');
// 创建子路由
const home = express.Router();
home.get('/', (req, res) => {
selectArticle((data) => {
res.render('index',{ data })
})
});
home.get('/about', (req, res) => {
res.render('about')
});
home.get('/many', (req, res) => {
selectContent({
id: req.query.id
}, (data) => {
res.render('many', {
data: data[0]
})
})
});
const path = require('path');
const multer = require('multer');
let storage = multer.diskStorage({
// 自定义存储位置
destination: function (req, file, cb) {
let root = path.join(__dirname, '..');
// 自定义路径
cb(null, path.join(root, 'public/uploads'));
},
// 自定义文件名称
filename: function (req, file, cb) {
// 文件后缀
let ext = path.extname(file.originalname);
cb(null, file.fieldname + '-' + Date.now() + ext);
}
})
let upload = multer({
storage: storage
})
home.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file 是 `avatar` 文件的信息
// req.body 将具有文本域数据,如果存在的话
// console.log(req.file);
res.json({
code: 10000,
path: path.join('uploads', req.file.filename)
})
})
module.exports = home;<file_sep>const path = require('path')
const express = require('express')
//图片上传
const multer = require('multer')
const admin = express.Router()
const { addArticle } = require('../models/article')
admin.get('/',(req, res) => {
res.render('write')
})
let storage = multer.diskStorage({
// 自定义存储位置
destination: function (req, file, cb) {
let root = path.join(__dirname, '..');
// 自定义路径
cb(null, path.join(root, 'public/uploads'));
},
// 自定义文件名称
filename: function (req, file, cb) {
// 文件后缀
let ext = path.extname(file.originalname);
cb(null, file.fieldname + '-' + Date.now() + ext);
}
})
let upload = multer({storage: storage})
admin.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file 是 `avatar` 文件的信息
// req.body 将具有文本域数据,如果存在的话
// console.log(req.file);
res.json({
code: 10000,
path: path.join('uploads', req.file.filename)
})
})
admin.post('/write', (req, res) => {
const { title, jianjie, content, img } = req.body
if(!(title && jianjie && content && img)) {
return res.json({status:400, data:'表单不完整'})
}
var date = new Date()
var data = {
title,
jianjie,
content,
img,
year: date.getFullYear(),
mounth: date.getMonth() + 1,
day: date.getDate()
}
addArticle(data, (data) => {
if(data) {
res.json({
status:200,
data:'添加成功'
})
}
})
})
module.exports = admin
<file_sep># blog
* 后台使用nodejs server API
* 前台使用H5C3构造前台页面博客
* 后台页面目前只有添加文章操作
<file_sep>
const express = require('express');
// 解析 post 中间件
const bodyParser = require('body-parser');
// 处理 session 中间件
const session = require('express-session');
// 引入子路由
const home = require('./routes/home');
const admin = require('./routes/admin');
const app = express();
// 监听端口
app.listen(3001);
// 配置模板引擎
app.set('view engine', 'xtpl');
app.set('views', './views');
// 设置静态资源
app.use(express.static('./public'));
// 中间件(解析 post 数据)
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
// session 配置
app.use(session({
secret: 'itcast',
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 3600 * 1000 * 24 * 30
}
}));
// 配置前台路由
app.use('/', home)
// 后台路由
app.use('/admin',admin)
| 4235621b7334caf78f3b83b627c8bbfe5cd5b46a | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | AmorRui/blog | 5d6b70db75a9a4671204191da5ec21b81a99f511 | 179abe6641b7007b973ee6be795a958f1e9479a0 |
refs/heads/master | <repo_name>keithing/fern<file_sep>/fern.py
import numpy as np
import matplotlib.pyplot as plt
# Read in the coefficients
coefs = np.genfromtxt('coefs.csv', delimiter=',', skip_header=True)
# Shape the transform matrices, intercepts
# and the probability vector
X = []
i = []
p = []
for row in coefs:
X.append(row[0:4].reshape(2,2))
i.append(row[4:6])
p.append(row[6])
# Affine transformation
def affine_transform(x, X, i):
return(np.dot(X,x) + i)
# Recursively apply the transformation
# with an amount of randomness as to
# which of the 4 transforms is
# performed.
def draw_fern(X, i, p, iters):
x = np.array([0,0])
xs = [x]
while len(xs) < iters:
n = np.random.choice(np.arange(len(X)), p=p)
x = affine_transform(x, X[n], i[n])
xs.append(x)
fern = [x for x in zip(*xs)]
return(fern)
# Main
if __name__ == "__main__":
fern = draw_fern(X, i, p, 10000)
plt.scatter(fern[0], fern[1], s=4, color='green')
plt.show()
<file_sep>/README.md
Script to draw a [Barnsley fern](http://en.wikipedia.org/wiki/Barnsley_fern), an example of a seemingly complex pattern that can be simply defined using recursion.
Editing the parameters in `coefs.csv` will produce substantially different "ferns". If you find any interesting ones, please pass along your `coefs.csv` to me!
| 5996fee27df91f201f3fab198c170562b82bd26d | [
"Markdown",
"Python"
] | 2 | Python | keithing/fern | e4bd9beeb9f398959f5cda3fa90426eb073ee6ce | 6aa6389ef64fe4fa63cf8373fe21b97a47dcf466 |
refs/heads/master | <file_sep># Vk Bot for .NET
# План развития
- [x] Авторизация бота.
- [x] Оповещение о начале работы бота.
- [ ] Отправка личных сообщений.
- [ ] Механизм ответов на комментарии.
- [ ] Интеграция с базой ответов бота.
- [ ] Анализ комментариев/сообщений и выбор наиболее подходящего ответа.
#References
При создании бота используется:
- [vknet](https://github.com/vknet/vk) - [VK Api](https://github.com/vknet/vk) VK Api для .NET
- [Json.Net](http://www.newtonsoft.com/json)
- [HtmlAgilityPack](http://htmlagilitypack.codeplex.com/)
<file_sep>using System;
using VkNet;
using VkNet.Enums.Filters;
using VkNet.Model.RequestParams;
namespace Brain
{
/// <summary>
/// Синглтон для создания единственного экземпляра VkApi. Создает один единственный токен для доступа к методам VkApi и проводит авторизацию.
/// </summary>
public class BotSingleton
{
private BotSingleton() { }
private static BotSingleton _instance;
private static Object _obj = new Object();
private static VkApi _api;
/// <summary>
/// Хранит и инициирует создание/возвращает экземпляр VkApi.
/// </summary>
public VkApi Api
{
get
{
if (_api != null)
return _api;
else {
GetApi();
return _api;
}
}
}
/// <summary>
/// Получение экземпляра VkApi.
/// </summary>
public static BotSingleton GetApi()
{
if (_api == null)
{
lock (_obj)
{
if (_api == null)
{
_api = new VkApi();
_instance = new BotSingleton();
Authorize();
}
}
}
return _instance;
}
/// <summary>
/// Авторизация и отпавка оповещающего поста на стену.
/// </summary>
private static void Authorize()
{
_api.Authorize(new ApiAuthParams
{
ApplicationId = 5393370,
Login = "<EMAIL>",
Password = "<PASSWORD>",
Settings = Settings.All,
});
//TODO: BotSingleton, Сообщение нужно брать из БД
var post = new WallPostParams();
post.OwnerId = 358536316;
post.Message = "%26%23128640; Вжжжнннвжжжннн! Полетелииии... \n\n\n(Бот начал работу)";
_api.Wall.Post(post);
}
}
}
<file_sep>using System;
using VkNet;
using VkNet.Model.RequestParams;
namespace Brain
{
public class BotWall
{
BotSingleton bot = BotSingleton.GetApi();
/// <summary>
/// Авторизация и отпавка оповещающего о начале работы бота поста на стену.
/// </summary>
public void BotWallPost()
{
//TODO: BotWall, Сообщение нужно брать из БД
var post = new WallPostParams();
post.OwnerId = 358536316;
post.Message = "BotWall";
bot.Api.Wall.Post(post);
}
}
}
| 6bb9d040b775925b58a69c984d07cf3ee1295a74 | [
"Markdown",
"C#"
] | 3 | Markdown | KolesoPrivet/BotVk | 9581a397c5849e51d9f90c0b03ecd76ede278b97 | dfd4aff40e4c0846bc3befb275d6f8bece56cc26 |
refs/heads/master | <file_sep>"""Modified to train on CIFAR-10/100 by Mark
Typical use:
from tensorflow.contrib.slim.python.slim.nets import
resnet_v1
ResNet-110 for image classification into 10 classes:
# inputs has shape [batch, 32, 32, 3]
with slim.arg_scope(resnet_v1.resnet_arg_scope()):
net, end_points = resnet_v1.resnet_v1_110(inputs, 10, is_training=False)
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib import layers
from tensorflow.contrib.framework.python.ops import add_arg_scope
from tensorflow.contrib.framework.python.ops import arg_scope
from tensorflow.contrib.layers.python.layers import layers as layers_lib
from tensorflow.contrib.layers.python.layers import utils
from tensorflow.contrib.slim.python.slim.nets import resnet_utils
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import variable_scope
resnet_arg_scope = resnet_utils.resnet_arg_scope
@add_arg_scope
def not_bottleneck(inputs,
depth,
stride,
rate=1,
outputs_collections=None,
scope=None):
with variable_scope.variable_scope(scope, 'not_bottleneck_v1', [inputs]) as sc:
depth_in = utils.last_dimension(inputs.get_shape(), min_rank=4)
if depth == depth_in:
shortcut = resnet_utils.subsample(inputs, stride, 'shortcut')
else:
shortcut = layers.conv2d(
inputs,
depth, [1, 1],
stride=stride,
activation_fn=None,
scope='shortcut')
residual = layers.conv2d(
inputs, depth, 3, stride, scope='conv1')
residual = layers.conv2d(
residual, depth, 3, stride=1, activation_fn=None, scope='conv2')
output = nn_ops.relu(shortcut + residual)
return utils.collect_named_outputs(outputs_collections, sc.name, output)
def resnet_v1(inputs,
blocks,
num_classes=None,
is_training=True,
global_pool=True,
output_stride=None,
include_root_block=True,
reuse=None,
scope=None):
with variable_scope.variable_scope(
scope, 'resnet_v1', [inputs], reuse=reuse) as sc:
end_points_collection = sc.original_name_scope + '_end_points'
with arg_scope(
[layers.conv2d, not_bottleneck, resnet_utils.stack_blocks_dense],
outputs_collections=end_points_collection):
with arg_scope([layers.batch_norm], is_training=is_training):
net = inputs
if include_root_block:
if output_stride is not None:
if output_stride % 4 != 0:
raise ValueError('The output_stride needs to be a multiple of 4.')
output_stride /= 4
net = resnet_utils.conv2d_same(net, 16, 3, stride=1, scope='conv1')
net = resnet_utils.stack_blocks_dense(net, blocks, output_stride)
if global_pool:
# Global average pooling.
net = math_ops.reduce_mean(net, [1, 2], name='pool5', keepdims=True)
if num_classes is not None:
net = layers.conv2d(
net,
num_classes, [1, 1],
activation_fn=None,
normalizer_fn=None,
scope='logits')
# Convert end_points_collection into a dictionary of end_points.
end_points = utils.convert_collection_to_dict(end_points_collection)
if num_classes is not None:
end_points['predictions'] = layers_lib.softmax(
net, scope='predictions')
return net, end_points
resnet_v1.default_image_size = 224
def resnet_v1_block(scope, base_depth, num_units, stride):
return resnet_utils.Block(scope, not_bottleneck, [{
'depth': base_depth,
'stride': stride
}] + (num_units - 1) * [{
'depth': base_depth,
'stride': 1
}])
def resnet_v1_110(inputs,
num_classes=None,
is_training=True,
global_pool=True,
output_stride=None,
reuse=None,
scope='resnet_v1_110'):
blocks = [
resnet_v1_block('block1', base_depth=16, num_units=18, stride=1),
resnet_v1_block('block2', base_depth=32, num_units=18, stride=2),
resnet_v1_block('block3', base_depth=64, num_units=18, stride=2),
]
return resnet_v1(
inputs,
blocks,
num_classes,
is_training,
global_pool,
output_stride,
include_root_block=True,
reuse=reuse,
scope=scope)
<file_sep># Temperature Scaling tensorflow
Tensorflow implementation of [On Calibration of Modern Neural Networks](https://arxiv.org/abs/1706.04599).
What this repo can do:
- Train ResNet_v1_110
- Calibrate it's output on CIFAR-10/100
- Using ```temp_scaling``` function to calibrate any of your networks using tensorflow.
What this repo *cannot* do:
- Calculate ECE (Expected Calibration Error)
Official PyTorch implementation by @gpleiss [here](https://github.com/gpleiss/temperature_scaling).
## Prerequisites
- Python 3.5
- [NumPy](http://www.numpy.org/)
- [TensorFlow 1.8](https://www.tensorflow.org/)
## Data
- [CIFAR-10/100](https://www.cs.toronto.edu/~kriz/cifar.html)
## Preparation
- Create `data/` folder, download and extract the python version from CIFAR webpage.
## Train
First, train the model (ResNet 110 in this case) using default parameters:
```bash
python main.py
```
Check out tunable hyper-parameters:
```bash
python main.py --help
```
## Temperature Scaling
Then, do temperature scaling to calibrate your model on the validation set.
```bash
python temp_scaling.py
```
Use the ```temp_var``` returned by ```temp_scaling``` function with your models logits to get calibrated output.
## Notes
- ResNet_v1_110 is trained for 250 epochs with other default parameters introduced in the original ResNet paper.
- The identity shortcut in ResNet_v1_110 is replaced with projection shortcut, meaning there are two additional convolutional layers.
- Validation accuracy and test accuracy on CIFAR-100 are around 70%.
- Issues are welcome!
## Resources
- [The paper](https://arxiv.org/abs/1706.04599).
- [Official PyTorch Implementation](https://github.com/gpleiss/temperature_scaling)
<file_sep>import os
import pdb
import pickle
import numpy as np
import tensorflow as tf
HEIGHT = 32
WIDTH = 32
DEPTH = 3
def _read_data(files):
"""Reads CIFAR-10 format data. Always returns NHWC format.
Returns:
images: np tensor of size [N, H, W, C]
labels: np tensor of size [N]
"""
images, labels = [], []
for file_name in files:
print (file_name)
with open(file_name, 'rb') as finp:
data = pickle.load(finp, encoding='bytes')
batch_images = data[b'data'].astype(np.float32) / 255.0
if 'cifar-100' in file_name:
batch_labels = np.array(data[b'fine_labels'], dtype=np.int32)
else:
batch_labels = np.array(data[b'labels'], dtype=np.int32)
images.append(batch_images)
labels.append(batch_labels)
images = np.concatenate(images, axis=0)
labels = np.concatenate(labels, axis=0)
images = np.reshape(images, [-1, 3, WIDTH, HEIGHT])
images = np.transpose(images, [0, 2, 3, 1])
return images, labels
def read_data(data_path, num_valids=5000):
print("Reading data from {}".format(data_path))
images, labels = {}, {}
if 'cifar-100' in data_path:
train_files = [
os.path.join(data_path, 'train')
]
test_file = [
os.path.join(data_path, 'test')
]
else:
train_files = [
os.path.join(data_path, 'data_batch_1'),
os.path.join(data_path, 'data_batch_2'),
os.path.join(data_path, 'data_batch_3'),
os.path.join(data_path, 'data_batch_4'),
os.path.join(data_path, 'data_batch_5'),
]
test_file = [
os.path.join(data_path, 'test_batch'),
]
images['train'], labels['train'] = _read_data(train_files)
if num_valids:
images['valid'] = images['train'][-num_valids:]
labels['valid'] = labels['train'][-num_valids:]
images['train'] = images['train'][:-num_valids]
labels['train'] = labels['train'][:-num_valids]
else:
images['valid'], labels['valid'] = None, None
images['test'], labels['test'] = _read_data(test_file)
print("Prepropcess: [subtract mean], [divide std]")
mean = np.mean(images['train'], axis=(0, 1, 2), keepdims=True)
std = np.std(images['train'], axis=(0, 1, 2), keepdims=True)
print("mean: {}".format(np.reshape(mean * 255.0, [-1])))
print("std: {}".format(np.reshape(std * 255.0, [-1])))
images['train'] = (images['train'] - mean) / std
if num_valids:
images['valid'] = (images['valid'] - mean) / std
images['test'] = (images['test'] - mean) / std
return images, labels
class CifarDataSet:
def __init__(self, batch_size, data_dir, eval_batch_size=100):
self.batch_size = batch_size
self.eval_batch_size = eval_batch_size
self.images_np, self.labels_np = read_data(data_dir)
self.validation = tf.placeholder(tf.bool)
def make_batch_train(self):
# Extract
dataset = tf.data.Dataset.from_tensor_slices((
tf.constant(self.images_np['train']), tf.constant(self.labels_np['train'])))
# Transform
dataset = dataset.apply(
tf.contrib.data.shuffle_and_repeat(10000))
dataset = dataset.apply(
tf.contrib.data.map_and_batch(self._pre_process, self.batch_size, num_parallel_batches=4))
dataset = dataset.prefetch(self.batch_size)
# Load
iterator = dataset.make_one_shot_iterator()
self.images_train, self.labels_train = iterator.get_next()
def make_batch_valid_or_test(self):
# Extract
images, labels = tf.cond(self.validation,
lambda: (self.images_np['valid'], self.labels_np['valid']),
lambda: (self.images_np['test'], self.labels_np['test']))
dataset = tf.data.Dataset.from_tensor_slices((images, labels))
# Transform
dataset = dataset.batch(self.eval_batch_size)
dataset = dataset.prefetch(self.eval_batch_size)
# Load
self.iterator_vt = dataset.make_initializable_iterator()
self.images_vt, self.labels_vt = self.iterator_vt.get_next()
def _pre_process(self, image, label):
image = tf.image.resize_image_with_crop_or_pad(image, 40, 40)
image = tf.random_crop(image, [HEIGHT, WIDTH, DEPTH])
image = tf.image.random_flip_left_right(image)
return image, label
<file_sep>import os
import pdb
import argparse
import numpy as np
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
from data_utils import CifarDataSet
import resnet_v1
slim = tf.contrib.slim
def temp_scaling(logits_nps, labels_nps, sess, maxiter=50):
temp_var = tf.get_variable("temp", shape=[1], initializer=tf.initializers.constant(1.5))
logits_tensor = tf.constant(logits_nps, name='logits_valid')
labels_tensor = tf.constant(labels_nps, name='labels_valid')
acc_op = tf.metrics.accuracy(labels_tensor, tf.argmax(logits_tensor, axis=1))
logits_w_temp = tf.divide(logits_tensor, temp_var)
# loss
nll_loss_op = tf.losses.sparse_softmax_cross_entropy(
labels=labels_tensor, logits=logits_w_temp)
org_nll_loss_op = tf.identity(nll_loss_op)
# optimizer
optim = tf.contrib.opt.ScipyOptimizerInterface(nll_loss_op, options={'maxiter': maxiter})
sess.run(temp_var.initializer)
sess.run(tf.local_variables_initializer())
org_nll_loss = sess.run(org_nll_loss_op)
optim.minimize(sess)
nll_loss = sess.run(nll_loss_op)
temperature = sess.run(temp_var)
acc = sess.run(acc_op)
print ("Original NLL: {:.3f}, validation accuracy: {:.3f}%".format(org_nll_loss, acc[0] * 100))
print ("After temperature scaling, NLL: {:.3f}, temperature: {:.3f}".format(
nll_loss, temperature[0]))
return temp_var
def main(args):
dataset = CifarDataSet(args.batch_size, args.data_dir)
dataset.make_batch_valid_or_test()
if 'cifar-100' in args.data_dir:
num_classes = 100
else:
num_classes = 10
model = resnet_v1.resnet_v1_110
# it's actually a 112 since there are 2 additional 1x1 conv for shortcuts
print ("Data loaded! Building model...")
with slim.arg_scope(resnet_v1.resnet_arg_scope()):
net, _ = model(dataset.images_vt, num_classes, is_training=False)
logits = tf.squeeze(net, [1, 2])
# tf saver, session
restorer = tf.train.Saver()
config = tf.ConfigProto(
allow_soft_placement=True,
gpu_options=tf.GPUOptions(
force_gpu_compatible=True,
allow_growth=True)
)
sess = tf.Session(config=config)
sess.run(dataset.iterator_vt.initializer, feed_dict={dataset.validation: True})
restorer.restore(sess, tf.train.latest_checkpoint(args.save_dir))
print ("Model built! Getting logits...")
logits_nps = []
num_eval_batches = dataset.images_np['valid'].shape[0] // dataset.eval_batch_size
for step in range(num_eval_batches):
logits_np = sess.run(logits)
logits_nps.append(logits_np)
logits_nps = np.concatenate(logits_nps)
print ("Logits get! Do temperature scaling...")
print ("=" * 80)
temp_var = temp_scaling(logits_nps, dataset.labels_np['valid'], sess)
# use temp_var with your logits to get calibrated output
print ("=" * 80)
print ("Done!")
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--batch-size',
type=int,
default=128,
help="batch size.")
parser.add_argument('--save-dir',
type=str,
default='./log',
help="Where to save the models.")
parser.add_argument('--data-dir',
type=str,
default='./data/cifar-100-python',
help="Where the data are saved")
args, unparsed = parser.parse_known_args()
if len(unparsed) != 0:
raise SystemExit("Unknown argument: {}".format(unparsed))
main(args)
<file_sep>import os
import pdb
import argparse
import numpy as np
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
from data_utils import CifarDataSet
import resnet_v1
slim = tf.contrib.slim
def get_train_ops(args, num_train_batches, loss_op):
print ("Model built, getting train ops...")
# global step
gstep_op = tf.train.get_or_create_global_step()
# learning rate decay
boundaries = [num_train_batches * epoch for epoch in [2, 100, 150, 200]]
values = [args.init_lr * decay for decay in [1, 10, 0.1, 0.01, 0.001]]
lr_op = tf.train.piecewise_constant(gstep_op, boundaries, values)
# optimizer
optim = tf.train.MomentumOptimizer(lr_op, args.momentum)
# compute gradient + apply gradient = mimimize
minimize_op = optim.minimize(loss_op, gstep_op)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
train_op = tf.group(minimize_op, update_ops)
# tf saver, session
saver = tf.train.Saver(max_to_keep=2)
config = tf.ConfigProto(
allow_soft_placement=True,
gpu_options=tf.GPUOptions(
force_gpu_compatible=True,
allow_growth=True)
)
sess = tf.Session(config=config)
sess.run(tf.global_variables_initializer())
return gstep_op, lr_op, train_op, saver, sess
def train(args):
dataset = CifarDataSet(args.batch_size, args.data_dir)
dataset.make_batch_train()
dataset.make_batch_valid_or_test()
if 'cifar-100' in args.data_dir:
num_classes = 100
else:
num_classes = 10
model = resnet_v1.resnet_v1_110
# it's actually a 112 since there are 2 additional 1x1 conv for shortcuts
print ("Data loaded! Building model...")
# for training
with slim.arg_scope(resnet_v1.resnet_arg_scope()):
net, end_points = model(dataset.images_train, num_classes)
logits = tf.squeeze(net, [1, 2], name='SqueezedLogits')
# for evaluating
with slim.arg_scope(resnet_v1.resnet_arg_scope()):
net_eval, _ = model(dataset.images_vt, num_classes, is_training=False, reuse=True)
predictions = tf.argmax(tf.squeeze(net_eval, [1, 2]), axis=-1)
cross_entropy_loss_op = tf.losses.sparse_softmax_cross_entropy(
labels=dataset.labels_train, logits=logits)
l2_loss_op = tf.losses.get_regularization_loss()
loss_op = cross_entropy_loss_op + l2_loss_op
num_train_batches = dataset.images_np['train'].shape[0] // args.batch_size
gstep_op, lr_op, train_op, saver, sess = get_train_ops(args, num_train_batches, loss_op)
print ("Train ops get! Start training...")
while True:
cross_entropy_loss, l2_loss, gstep, lr, _ = sess.run([
cross_entropy_loss_op, l2_loss_op, gstep_op, lr_op, train_op
])
cur_epoch = gstep // num_train_batches + 1
if gstep % args.log_every == 0:
log_string = "({:5d}/{:5d})".format(gstep, num_train_batches * args.epoch)
log_string += " cross entropy loss: {:.4f}, l2 loss: {:.4f},".format(cross_entropy_loss, l2_loss)
log_string += " lr: {:.4f}".format(lr)
log_string += " (ep: {:3d})".format(cur_epoch)
print (log_string)
if (gstep + 1) % num_train_batches == 0:
print ("Saving .ckpt and evaluating with validation set...")
saver.save(sess, os.path.join(args.save_dir, 'model.ckpt'), global_step=cur_epoch)
sess.run(dataset.iterator_vt.initializer, feed_dict={dataset.validation: True})
corrects = 0
num_eval_batches = dataset.images_np['valid'].shape[0] // dataset.eval_batch_size
for step in range(num_eval_batches):
preds, labels = sess.run([predictions, dataset.labels_vt])
corrects += np.sum(preds == labels)
print ("validation accuracy: {:.3f}% ({:4d}/{:4d})".format(
100 * corrects / dataset.images_np['valid'].shape[0],\
corrects, dataset.images_np['valid'].shape[0]
))
print ("=" * 80)
if (gstep + 1) % (num_train_batches * args.eval_every) == 0:
print ("Evaluating with test set...")
sess.run(dataset.iterator_vt.initializer, feed_dict={dataset.validation: False})
corrects = 0
num_eval_batches = dataset.images_np['test'].shape[0] // dataset.eval_batch_size
for step in range(num_eval_batches):
preds, labels = sess.run([predictions, dataset.labels_vt])
corrects += np.sum(preds == labels)
print ("test accuracy: {:.3f}% ({:5d}/{:5d})".format(
100 * corrects / dataset.images_np['test'].shape[0],
corrects, dataset.images_np['test'].shape[0]
))
print ("=" * 80)
if cur_epoch > args.epoch:
break
print ("Done!")
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--init_lr',
type=float,
default=1e-2,
help="initial learning rate.")
parser.add_argument('--momentum',
type=float,
default=9e-1,
help="Momentum for SGD.")
parser.add_argument('--epoch',
type=int,
default=250,
help="number of epochs to train.")
parser.add_argument('--batch-size',
type=int,
default=128,
help="batch size.")
parser.add_argument('--log-every',
type=int,
default=100,
help="Log every n iterations.")
parser.add_argument('--eval-every',
type=int,
default=5,
help="Evaluate with test set every m epochs.")
parser.add_argument('--save-dir',
type=str,
default='./log',
help="Where to save the models.")
parser.add_argument('--data-dir',
type=str,
default='./data/cifar-100-python',
help="Where the data are saved")
args, unparsed = parser.parse_known_args()
if len(unparsed) != 0:
raise SystemExit("Unknown argument: {}".format(unparsed))
train(args)
| 5ce484ff2c137a7dbcbeee7171b6c232f6a6ed12 | [
"Markdown",
"Python"
] | 5 | Python | myflooring/temperature-scaling-tensorflow | 6803d0ea0fc98faeee08958695022b4d72daab3f | 5a9cac85b524ab2e87308ab43c1a22ff65379118 |
refs/heads/master | <repo_name>derrickbozich/playlister-sinatra-cb-000<file_sep>/app/controllers/songs_controller.rb
class SongsController < ApplicationController
# use Rack::Flash
get '/songs' do
@songs = Song.all
erb :'/songs/index'
end
get '/songs/new' do
@artists = Artist.all
@genres = Genre.all
erb :'/songs/new'
end
get "/songs/:slug" do
@song = Song.find_by_slug(params[:slug])
erb :'/songs/show'
end
post '/songs' do
@song = Song.find_or_create_by(:name => params['name'] )
if params['artist_name'].empty?
@song.artist = Artist.find_by_id(params[:artist_id])
else
@song.artist = Artist.find_or_create_by(:name => params['artist_name'])
end
if params['genre_name'] != ""
genre = Genre.find_or_create_by(:name => params['genre_name'])
@song.genres << genre
end
if params['genres']
params['genres'].each do |g|
genre = Genre.find_or_create_by(:id => g)
@song.genres << genre
end
end
@song.save
# erb :"/songs/#{@song.slug}"
redirect("/songs/#{@song.slug}")
end
get '/songs/:slug/edit' do
@song = Song.find_by_slug(params[:slug])
@genres = @song.genres
erb :'/songs/edit'
end
patch '/songs/:slug' do
@song = Song.find_by_id(params['song_id'])
@song.artist = Artist.find_or_create_by(:name => params["artist_name"])
# @song.genre_ids = params['genres']
params['genres'].each do |g|
genre = Genre.find_or_create_by(:id => g)
@song.genres << genre
end
@song.save
redirect("/songs/#{@song.slug}")
end
end
<file_sep>/app/models/artist.rb
class Artist<ActiveRecord::Base
has_many :songs
has_many :genres, :through => :songs
def slug
slug = self.name.gsub(" ", "-").downcase
end
def self.find_by_slug(slug)
artist = Artist.all.find {|artist| artist.slug == slug}
end
end
class Song<ActiveRecord::Base
belongs_to :artist
has_many :song_genres
has_many :genres, :through => :song_genres
def slug
slug = self.name.gsub(" ", "-").downcase
end
def self.find_by_slug(slug)
song = Song.all.find {|song| song.slug == slug}
end
end
class Genre<ActiveRecord::Base
has_many :song_genres
has_many :songs, :through => :song_genres
has_many :artists, :through => :songs
def slug
slug = self.name.gsub(" ", "-").downcase
end
def self.find_by_slug(slug)
genre = Genre.all.find {|genre| genre.slug == slug}
end
end
class SongGenre<ActiveRecord::Base
belongs_to :song
belongs_to :genre
end
| 09d301cf5bb2a137f199a3f896aeda1cd8add4da | [
"Ruby"
] | 2 | Ruby | derrickbozich/playlister-sinatra-cb-000 | 633504f2e468d0497ae4d86393a38feedd7265dc | 396dbb84d27ed6b395f55c48f1232dc5237ed6c8 |
refs/heads/master | <repo_name>IceyFong/fyp_BNNwDithering<file_sep>/bnn/src/library/hls/qvalues.hpp
#ifndef QVALUES_HPP
#define QVALUES_HPP
template<unsigned NF, unsigned PE, unsigned Num,
typename TA, typename TR>
class Qvalues {
public:
TA m_qvalues[PE][NF][Num];
};
#endif | 3785820a7a23de1d0ee0b89125bb9323f14d3aaa | [
"C++"
] | 1 | C++ | IceyFong/fyp_BNNwDithering | 84b43de1f7a19dde6da9b5f2bee2d7dd053b8d44 | 560a6ca10d118a41760a1a267a3ccfe956dbf43c |
refs/heads/master | <repo_name>YevgeniiH/KP<file_sep>/target/generated-sources/annotations/domain/Bus_.java
package domain;
import model.Bus;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Bus.class)
public abstract class Bus_ {
public static volatile SingularAttribute<Bus, String> busNmb;
public static volatile SingularAttribute<Bus, String> busModel;
public static volatile SingularAttribute<Bus, Integer> colPlace;
}
<file_sep>/src/main/java/model/dao/DriverDao.java
package model.dao;
import model.Driver;
import java.util.Collection;
import java.util.List;
public interface DriverDao {
void add(Driver driver);
void update(Driver driver);
void delete(Driver driver);
Collection<Driver> getDriver(String search);
public List findByDriver(String busNmb, Integer idUser);
}
<file_sep>/src/main/java/model/dao/OrderDao.java
package model.dao;
import model.Order;
import java.util.Collection;
import java.util.List;
public interface OrderDao {
void add(Order order);
void update(Order order);
void delete(Order order);
Collection<Order> getOrder(String search);
public List findByOrder(Integer idTrip, Integer place, String statusO);
}
<file_sep>/src/main/java/model/dao/BusDao.java
package model.dao;
import model.Bus;
import java.awt.*;
import java.util.Collection;
import java.util.List;
public interface BusDao {
void add(Bus bus);
void update(Bus bus);
void delete(Bus bus);
Collection<Bus> getBus(String search);
public List findByBus(String busNmb, String busModel, Integer colPlace, Image busLayout);
}
<file_sep>/src/main/java/model/dao/impl/CompInfoDaoImpl.java
package model.dao.impl;
import model.CompInfo;
import model.dao.CompInfoDao;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Collection;
import java.util.List;
public class CompInfoDaoImpl implements CompInfoDao {
@PersistenceContext
private EntityManager emf;
}
<file_sep>/src/main/java/model/dao/impl/CashierDaoImpl.java
package model.dao.impl;
import model.Cashier;
import model.dao.CashierDao;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Collection;
import java.util.List;
public class CashierDaoImpl implements CashierDao {
@PersistenceContext
private EntityManager emf;
}
<file_sep>/src/main/java/service/IDriverService.java
package service;
import model.Driver;
public interface IDriverService extends IBaseService<Driver>{
}
<file_sep>/target/generated-sources/annotations/domain/User_.java
package domain;
import model.User;
import java.time.LocalDate;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(User.class)
public abstract class User_ {
public static volatile SingularAttribute<User, String> pass;
public static volatile SingularAttribute<User, LocalDate> dob;
public static volatile SingularAttribute<User, String> surname;
public static volatile SingularAttribute<User, String> name;
public static volatile SingularAttribute<User, Long> tel;
public static volatile SingularAttribute<User, String> login;
public static volatile SingularAttribute<User, String> email;
public static volatile SingularAttribute<User, String> status;
}
<file_sep>/src/main/java/service/impl/TownService.java
package service.impl;
import model.Town;
import service.ITownService;
public class TownService extends BaseService<Town> implements ITownService {
}
<file_sep>/src/main/java/service/ITownService.java
package service;
import model.Town;
public interface ITownService extends IBaseService<Town>{
}
<file_sep>/src/main/java/model/dao/impl/DriverDaoImpl.java
package model.dao.impl;
import model.Driver;
import model.dao.DriverDao;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Collection;
import java.util.List;
public class DriverDaoImpl implements DriverDao {
@PersistenceContext
private EntityManager emf;
}
<file_sep>/src/main/java/model/dao/impl/TownDaoImpl.java
package model.dao.impl;
import model.Town;
import model.dao.TownDao;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Collection;
import java.util.List;
public class TownDaoImpl implements TownDao {
@PersistenceContext
private EntityManager emf;
}
<file_sep>/target/generated-sources/annotations/domain/Trip_.java
package domain;
import model.Trip;
import java.time.LocalDate;
import java.time.LocalTime;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Trip.class)
public abstract class Trip_ {
public static volatile SingularAttribute<Trip, LocalTime> timeTripTo;
public static volatile SingularAttribute<Trip, LocalDate> dateTripTo;
public static volatile SingularAttribute<Trip, Double> price;
public static volatile SingularAttribute<Trip, LocalDate> dateTripFrom;
public static volatile SingularAttribute<Trip, LocalTime> timeTripFrom;
}
<file_sep>/src/main/java/model/dao/CarDao.java
package model.dao;
import model.Car;
import java.util.Collection;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: k.tagintsev
* Date: 05.10.13
* Time: 12:52
* To change this template use File | Settings | File Templates.
*/
public interface CarDao {
void add(Car car);
void update(Car car);
void delete(Car car);
Collection<Car> getCars(String search);
public List findByCar(String name, Long price);
}
<file_sep>/src/main/java/service/impl/BusService.java
package service.impl;
import model.Bus;
import service.IBusService;
public class BusService extends BaseService<Bus> implements IBusService {
}
| 5bd030ce5ad30f08c5b892fda0c989c4dac66efd | [
"Java"
] | 15 | Java | YevgeniiH/KP | 03bc515bc5ddd448828a853124f7ec45baf8721d | 1e7dbc96295071ca8448ab87d29c606c12cf96cb |
refs/heads/main | <file_sep>package com.example.demo.Service;
import java.util.Date;
import org.springframework.stereotype.Service;
import com.example.demo.DAO.EmployeeDetails;
import com.example.demo.DTO.AppointmentDto;
@Service
public interface EmployeeAppointService {
public EmployeeDetails saveEmployee(EmployeeDetails employee);
public EmployeeDetails getEmployee(Integer id);
public EmployeeDetails getEmployee(String mailId);
public String deleteEmployeeByMailId(String mailId);
public void cancelEmployeeAppointmentByDate(Date date,String mailId);
public AppointmentDto checkAvailabilityOnDate(String mailId,Date date);
}
<file_sep>server.port=8083
spring.datasource.driver-class=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/db_test
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
<file_sep>package com.example.demo.Repository;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.example.demo.DAO.CancelledAppointment;
@Repository
public interface CancelledAppointmentRepository extends JpaRepository<CancelledAppointment, Integer> {
@Query("from CancelledAppointment c where c.cancelledDate=?1 and c.appointment is null and c.employeeDetails is null")
public CancelledAppointment getCancellendAppointmentDate(Date cancelledDate);
}
<file_sep>package com.example.demo.Service;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Service;
import com.example.demo.DAO.Appointment;
import com.example.demo.DTO.AppointmentDto;
@Service
public interface AppointmentService {
public List<AppointmentDto> filterAppointmentByDate(Date date);
public AppointmentDto getAppointmentById(Integer id);
public AppointmentDto updateOrSaveAppointmentById(AppointmentDto appointment);
public Boolean deleteAppointmentById(Integer id);
public void cancelAllAppointmentOnDate(Date date);
public void cancelAppointmentOnDate(Date date,Integer id);
}
<file_sep>package com.example.demo.Controller;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.DAO.EmployeeDetails;
import com.example.demo.DTO.AppointmentDto;
import com.example.demo.Service.AppointmentService;
import com.example.demo.Service.EmployeeAppointService;
@RestController
public class EmployeeAppointmentController {
@Autowired
EmployeeAppointService employeeAppointment;
@Autowired
AppointmentService appointmentService;
@GetMapping("employee/{mailId}")
public EmployeeDetails getEmployeeDetailsBymail(@PathVariable("mailId") String mailId)
{
return employeeAppointment.getEmployee(mailId);
}
@DeleteMapping("employee/{mailId}")
public String deleteEmployeeDetailsBymailId(@PathVariable("mailId") String mailId)
{
return employeeAppointment.deleteEmployeeByMailId(mailId);
}
@PostMapping("employee")
public EmployeeDetails saveEmployeeDetails(@RequestBody EmployeeDetails detail)
{
return employeeAppointment.saveEmployee(detail);
}
@PostMapping("employee/{mailId}/appointments/cancel")
public void cancelEmployeeAppointmentsByDate(@RequestParam("date")@DateTimeFormat(pattern="yyyy-MM-dd") Date date,@PathVariable("mailId") String mailId)
{
employeeAppointment.cancelEmployeeAppointmentByDate(date, mailId);
}
@GetMapping("employee/{mailId}/availability")
public AppointmentDto checkAvailabilityOnDate(@RequestParam("date")@DateTimeFormat(pattern="yyyy-MM-dd") Date date, @PathVariable("mailId") String mailId,@RequestParam("hour") Integer hour,@RequestParam("minute") Integer minute)
{
date.setHours(hour);
date.setMinutes(minute);
AppointmentDto dto=new AppointmentDto();
dto=employeeAppointment.checkAvailabilityOnDate(mailId, date);
return dto;
}
}
<file_sep>package com.example.demo.DAO;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Table(name="appointment")
@Entity
@JsonIgnoreProperties(value = { "employeedetails","cancelledAppointments" })
public class Appointment implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@Column(name="id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id;
@Column(name="startDate")
Date startDate;
@Column(name="endDate")
Date endDate;
@Column(name="time")
String time;
@Column(name="duration")
String duration;
@Column(name="repeats")
Boolean repeats;
@Column(name="frequency")
String frequency;
public Boolean getRepeats() {
return repeats;
}
public void setRepeats(Boolean repeats) {
this.repeats = repeats;
}
public String getFrequency() {
return frequency;
}
public void setFrequency(String frequency) {
this.frequency = frequency;
}
@ManyToOne
@JoinColumn(name="empId",nullable=false)
EmployeeDetails employeedetails;
@OneToMany(mappedBy="appointment",cascade = CascadeType.ALL)
List<CancelledAppointment> cancelledAppointments;
public List<CancelledAppointment> getCancelledAppointments() {
return cancelledAppointments;
}
public void setCancelledAppointments(List<CancelledAppointment> cancelledAppointments) {
this.cancelledAppointments = cancelledAppointments;
}
public EmployeeDetails getEmployeedetails() {
return employeedetails;
}
public void setEmployeedetails(EmployeeDetails employeedetails) {
this.employeedetails = employeedetails;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
}
| 103b8dcfa13164848722639f7c81d4bebfccb1a1 | [
"Java",
"INI"
] | 6 | Java | mohamedusama88/Scheduler | fb1f945a531552de72172f6a4aad95991ffb458b | 075d6d9ef5d52384c4c6be41eba3d9bbaa562228 |
refs/heads/master | <file_sep># pharmacy-AWP-predictor
Used the pharmaceutical data sponsored by RxRefund to determine the most effective AWP price for a product.
Worked with:
<NAME>
<NAME>
We parsed the data for elements that we determined not to be outliers
and trained a regression model to predict AWP based on acquisition costs.
<file_sep>import sys
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
import random
from openpyxl import Workbook, load_workbook
def outputToExcel(fileName, list1, list2):
book = Workbook()
ws = book.active
for i in range(1,len(list1)+1):
ws['A' + str(i)] = list1[i][0]
ws['B' + str(i)] = list2[i][0]
if i % 10000 == 0:
print(str(i*2) + "%")
book.save(fileName)
def parse(string):
newString = ""
ignore = set('"$()%, ')
for i in string:
if i not in ignore:
newString += i
return newString.split("\t")
if __name__ == "__main__":
# Read file
fileName = "pharmacydata.txt"
fileReader = open(fileName,"r")
lines = fileReader.readlines()
totalSales = []
acq = []
awp = []
randomizedLines = lines[1:]
random.shuffle(randomizedLines)
# Fetch data that fall within certain criteria
for line in randomizedLines:
d,ndc,desc,qty,p,s,c,sales,acqCosts,profit,margin,dawcode,manu,acqUnit,price= parse(line)
sales = float(sales.strip())
acqCosts = float(acqCosts.strip())
margin = float(margin.strip())
price = float(price.strip())
if 400 > margin > 0 and price < 5000:
totalSales.append([sales])
acq.append([acqCosts])
awp.append([price])
# Split data into training data and testing data
x = acq
y = awp
trainingSize = len(lines) // 5
xTrain = x[:trainingSize]
xTest = x[trainingSize:]
yTrain = y[:trainingSize]
yTest = y[trainingSize:]
# Create linear regression model
model = linear_model.LinearRegression()
# Train model
model.fit(xTrain, yTrain)
model.score(xTrain, yTrain)
# Make predictions using testing set
predictions = model.predict(xTest)
print("Coefficients: ", model.coef_)
print("Intercept: ", model.intercept_)
print("Regression Equation: y = %.4fx+%.4f" %(model.coef_, model.intercept_))
print("Mean squared error: %.2f" % mean_squared_error(yTest, predictions))
print('Variance score: %.2f' % r2_score(yTest, predictions))
'''
# Plot outputs
plt.scatter(xTest, yTest, color='black')
plt.plot(xTest, predictions, color='blue', linewidth=3)
plt.xticks(())
plt.yticks(())
plt.show()
'''
while True:
inputVal = raw_input("Enter acquisition costs to determine AWP or press Enter to exit:")
if len(inputVal) == 0:
break
try:
calculatedAWP = model.coef_ * float(inputVal) + model.intercept_
print("Predicted AWP is : $%.2f" %(calculatedAWP))
except Exception:
print("Error:", Exception)
# outputToExcel(newFile, acq, awp)
# newFile = "results.csv"
# fileWriter = open(newFile,"w")
# for i in range(len(x)):
# toWrite = str(x[i][0]) + "," + str(y[i][0]) + "\n"
# fileWriter.write(toWrite) | 02575329f914b7c1357ab21e6ba1606eb4ec99e7 | [
"Markdown",
"Python"
] | 2 | Markdown | sayedkamal2016/pharmacy-AWP-predictor | 6d5ea09143831637c668946c3cf0dd11518f7902 | 807b74822b000cccc0d14ba6ae730b864bffa01b |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
# initializing empty envelops
necessityEnvelop = 0 # NEC, необходимые траты
freedomEnvelop = 0 # FFA, финансовая свобода
educationEnvelop = 0 # EDU, образование
longTermEnvelop = 0 # LTSS, резерв и на большие покупки
playEnvelop = 0 # PLAY, развлечения
giveEnvelop = 0 # GIVE, подарки
# initializing percent rate
necRate = 0.55
ffaRate = 0.1
eduRate = 0.1
ltssRate = 0.1
playRate = 0.1
giveRate = 0.05
# initializing expected income, expected necessity and other amounts
print """ How much do you expect to receive in this month?"""
expectedIncome = float(raw_input())
# invitation, greetings etc.
print """Hello.\n
We gonna fill your envelops by the money you input here!\n
Please input your amounts of money income and see the results.\n
Press Ctrl+c to exit script.
\n\n Enter the amount please:"""
# initializing handler for standard input
sum = 0
while (sum < expectedIncome):
line = float(raw_input())
sum += line
print "\n Enter the amount please:"
necessityEnvelop += sum * necRate
freedomEnvelop += sum * ffaRate
educationEnvelop += sum * eduRate
longTermEnvelop += sum * ltssRate
playEnvelop += sum * playRate
giveEnvelop += sum * giveRate
celebrate = giveEnvelop
# final output
print "At the end we have:\n\
Necessity Envelop has: " + str(float(necessityEnvelop)) + "\n\
Financial Freedom Envelop has: " + str(float(freedomEnvelop)) + "\n\
Education Envelop " + str(float(educationEnvelop)) + "\n\
Long Term Saving for Spending Envelop has: " + str(float(longTermEnvelop)) + "\n\
Play Envelop has: " + str(float(playEnvelop)) + "\n\
Give Envelop has: " + str(float(giveEnvelop)) + "\n\
_______________________________________________________________\n\
\
Thanks for using our software :)"
if celebrate > 100:
print "You can go to celebrate"
else:
print "You can not go to celebrate"<file_sep># -*- coding: utf-8 -*-
print """\nWelcome to the Providers\n
May I have your phone number?(first 3 number, Examples: 050)\n"""
number = raw_input()
print "I think!" if (number=="095" or number=="050" or number=="066" or number=="099" or number=="093" or number=="063" or number=="077" or number=="098" or number=="097" or number=="067") else "I don't this provider" ,
print "You are using Vodafone provider" if (number=="095" or number=="050" or number=="066" or number=="099") else "",
print "You are using Life provider" if (number=="093" or number=="063" or number=="077") else "",
print "You are using Kyivstar provider" if (number=="098" or number=="097" or number=="067") else ""
<file_sep># -*- coding: utf-8 -*-
# initializing fizz, buzz and number
print """\nWelcome to the fizz-buzz\n
Enter the fizz please:\n"""
fizz = int(raw_input())
print "\n Enter the buzz please:\n"
buzz = int(raw_input())
print "\n Enter the any number please:\n"
fizzbuzz = int(raw_input())
print "\n"
i = 1
# cycle and print
while i <= fizzbuzz:
if i%fizz==0 and i%buzz==0:
print "FB",
elif i%fizz==0:
print "F",
elif i%buzz==0:
print "B",
else:
print i,
i+=1
<file_sep># -*- coding: utf-8 -*-
print """\nWelcome to the Providers\n
May I have your phone number?(first 3 number, Examples: 050)\n"""
number = raw_input()
if number=="095" or number=="050" or number=="066":
print "You are using Vodafone provider"
elif number=="093" or number=="063" or number=="077":
print "You are using Life provider"
elif number=="098" or number=="097" or number=="067":
print "You are using Kyivstar provider"
else:
print "I don't know this provider"
| 3c23dc1d3072027f97d7c0f6b8030772b6f6055d | [
"Python"
] | 4 | Python | zanusilker/python | ce35edc5a194c7261252d84db6196b32a528a464 | c90ea8242832a648f46847a241f47a001a578ea4 |
refs/heads/master | <repo_name>dev-oswld/client-server-model<file_sep>/src/ClienteServidor/ServerGUI.java
package ClienteServidor;
import com.sun.management.OperatingSystemMXBean;
import java.awt.Desktop;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.hyperic.sigar.SigarException;
public class ServerGUI extends javax.swing.JFrame implements Runnable {
ServerSocket server;
static Socket cli;
static int RANK, RANKTEMP, RANK_COPY;
static boolean ESTADO;
static InetAddress ip;
static String returnMessage;
static RecursosDeTodo objeto = new RecursosDeTodo();
static String yoServer = null;
static List<String> lista_fila, lista_G, lista_R;
static DefaultTableModel model;
static int contador = 1;
static OperatingSystemMXBean bean; //Objeto de la obtencion de RAM
static Future<Double> ramcitaLlamda; //Objeto del HILO
static String ramActulizada;
ServerGUI nuevo;
public ServerGUI() {
initComponents();
try {
this.server = new ServerSocket(1717); //Con el mismo puerto
} catch (IOException ex) {
System.out.println("Error en el constructor" + ex.getMessage());
}
Thread hilo = new Thread(this);
hilo.start();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
jSeparator1 = new javax.swing.JSeparator();
TituloClientes = new javax.swing.JLabel();
btn_Salir = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
TablaGeneral = new javax.swing.JTable();
jScrollPane2 = new javax.swing.JScrollPane();
textogrande = new javax.swing.JTextArea();
txt_serverpuntos = new javax.swing.JLabel();
Titulo2 = new javax.swing.JLabel();
OtroTitulo1 = new javax.swing.JLabel();
txt_serverpuntosfinal = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("Servidor"), this, org.jdesktop.beansbinding.BeanProperty.create("title"));
bindingGroup.addBinding(binding);
TituloClientes.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
TituloClientes.setForeground(new java.awt.Color(51, 0, 204));
TituloClientes.setText("Clientes activos");
btn_Salir.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
btn_Salir.setText("Salir");
btn_Salir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_SalirActionPerformed(evt);
}
});
TablaGeneral.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Nombre", "IP", "", "", "", "", "", "Estado"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
TablaGeneral.setColumnSelectionAllowed(true);
TablaGeneral.getTableHeader().setReorderingAllowed(false);
jScrollPane1.setViewportView(TablaGeneral);
TablaGeneral.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
textogrande.setColumns(20);
textogrande.setRows(5);
jScrollPane2.setViewportView(textogrande);
txt_serverpuntos.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
txt_serverpuntos.setText("0.0");
Titulo2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
Titulo2.setForeground(new java.awt.Color(51, 0, 204));
Titulo2.setText("Monitoreo de recursos");
OtroTitulo1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
OtroTitulo1.setText("Calificacion del server:");
txt_serverpuntosfinal.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
txt_serverpuntosfinal.setText("0.0");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jScrollPane2)
.addComponent(TituloClientes, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 749, Short.MAX_VALUE)
.addComponent(btn_Salir, javax.swing.GroupLayout.Alignment.LEADING))
.addGroup(layout.createSequentialGroup()
.addComponent(OtroTitulo1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txt_serverpuntos)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_serverpuntosfinal))
.addComponent(Titulo2))
.addContainerGap(91, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(13, 13, 13)
.addComponent(Titulo2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OtroTitulo1)
.addComponent(txt_serverpuntos)
.addComponent(txt_serverpuntosfinal))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(21, 21, 21)
.addComponent(TituloClientes)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btn_Salir)
.addContainerGap(16, Short.MAX_VALUE))
);
bindingGroup.bind();
pack();
}// </editor-fold>//GEN-END:initComponents
private void btn_SalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_SalirActionPerformed
try {
server.close();
JOptionPane.showMessageDialog(null, "El Servidor sera cerrado", "Aviso Importante", JOptionPane.WARNING_MESSAGE);
System.out.println("Todo llega a su fin :)");
System.exit(0);
} catch (IOException ex) {
System.out.println("Error en cerrar conexion " + ex.getMessage());
}
}//GEN-LAST:event_btn_SalirActionPerformed
public static void main(String args[]) throws UnknownHostException {
Llamada();
System.out.println("Estoy en el lado del Servidor");
ip = InetAddress.getLocalHost();
System.out.println("IP de aqui: " + ip);
JOptionPane.showMessageDialog(null, "Tengo la IP: " + ip);
//Este sirve para la RAM dinamica
bean = (com.sun.management.OperatingSystemMXBean) ManagementFactory
.getOperatingSystemMXBean();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel OtroTitulo1;
private javax.swing.JTable TablaGeneral;
private javax.swing.JLabel Titulo2;
private javax.swing.JLabel TituloClientes;
private javax.swing.JButton btn_Salir;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JTextArea textogrande;
private javax.swing.JLabel txt_serverpuntos;
private javax.swing.JLabel txt_serverpuntosfinal;
private org.jdesktop.beansbinding.BindingGroup bindingGroup;
// End of variables declaration//GEN-END:variables
@Override
public void run() { //Creamos un hilo para aceptar las entradas
try {
while (true) { //Ciclo infinito para recibir datos constantemente
cli = server.accept();
DataInputStream flujo = new DataInputStream(cli.getInputStream());
String msg = flujo.readUTF(); //Aqui recibo mis propiedades del PC
FilaLlenado(msg);
String url = "https://www.youtube.com/watch?v=kRPMGp7n9Eg";
Desktop.getDesktop().browse(java.net.URI.create(url));
Peticion();
cli.close();
}
} catch (IOException ex) {
System.out.println("Estado de conexion: " + ex.getMessage());
} catch (SigarException ex) {
System.out.println("Con error por Sigar");
Logger.getLogger(ServerGUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException | ExecutionException ex) {
Logger.getLogger(ServerGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void Peticion() throws IOException {
//Enviando respuesta al cliente.
returnMessage = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(Calendar.getInstance().getTime());
OutputStream os = cli.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Operacion realizada con el cliente " + returnMessage);
bw.flush();
}
public static void Llamada() {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ServerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(() -> {
new ServerGUI().setVisible(true);
});
}
public void FilaLlenado(String msg) throws SigarException, InterruptedException, ExecutionException {
while (contador == 1) { //Fila del Servidor
yoServer = "CPU: " + objeto.ObtenerCPU() + ",Nucleos: " + objeto.ObtenerCores() + ",RAM: " + objeto.ObtenerRam() + "GB,DD: " + objeto.ObtenenerDiscoDuro() + "GB,OS: " + objeto.ObtenerSistema();
String filaX = "" + cli.getInetAddress().getHostName() + "," + cli.getInetAddress().getHostAddress() + "," + yoServer;
String filaInicio[] = filaX.split(",");
//lista_R = Arrays.asList(filaInicio); //System.out.println("Size: " + lista_R.size()); //Es 7
model = (DefaultTableModel) TablaGeneral.getModel();
model.addRow(filaInicio);
RankeoGeneral(yoServer);
String temp = "/ " + RANK;
txt_serverpuntosfinal.setText(temp); //System.out.println("Calif " + RANK);
contador++;
}
//Aqui empiezo con un HILO
ExecutorService servicio = Executors.newFixedThreadPool(1);
ramcitaLlamda = servicio.submit(new HiloRankeo());
ramActulizada = "RAM: " + String.format("%.2f", ramcitaLlamda.get());
//System.out.println("Mira lo nuevo " + ramActulizada);
RankeoDeRam(ramActulizada);
txt_serverpuntos.setText("" + RANK_COPY);
if (RANK_COPY <= 0) { //TimeUnit.SECONDS.sleep(5);
JOptionPane.showMessageDialog(null, "Ahora cambiare de modo", "Aviso de Switheo", JOptionPane.WARNING_MESSAGE);
nuevo.dispose();
guicliente clienteY = new guicliente();
clienteY.CrearInterfaz();
//clienteX.dispose();
//guiserver ServerX = new guiserver();
//ServerX.CrearInterfazServer();
// Switch
//ServerGUI nuevo = new ServerGUI();
//nuevo.setVisible(true);
}
String fila = "" + cli.getInetAddress().getHostName() + "," + cli.getInetAddress().getHostAddress() + "," + msg + "," + RANK + "";
String filacortada[] = fila.split(",");
lista_fila = Arrays.asList(filacortada);
//System.out.println("Size: " + lista_fila.size());
if (lista_fila.size() == 9) {
model = (DefaultTableModel) TablaGeneral.getModel();
model.addRow(filacortada);
RankeoGeneral(msg); //Lamo a mi algoritmo de RANKEO
textogrande.append("Nombre: " + cli.getInetAddress().getHostName() + "\nCalificación: " + RANK + ".\n\n");
} else if (lista_fila.size() == 4) {
textogrande.append("Nombre: " + cli.getInetAddress().getHostName() + "\nEstado: " + msg + ".\n\n");
}
}
public static void RankeoGeneral(String msg) {
Pattern cpu1 = Pattern.compile("CPU: AMD"); //¿A quien busco?
Pattern cpu2 = Pattern.compile("CPU: INTEL");
Matcher checkCPU1 = cpu1.matcher(msg);
Matcher checkCPU2 = cpu2.matcher(msg);
Pattern nucleosmin = Pattern.compile("\\b(Nucleos\\:\\ )[0-4]");
Pattern nucleosmax = Pattern.compile("\\b(Nucleos\\:\\ )[5-]");
Matcher checkCores1 = nucleosmin.matcher(msg);
Matcher checkCores2 = nucleosmax.matcher(msg);
Pattern ramMin = Pattern.compile("\\b(RAM\\:\\ )[0-2]");
Pattern ramMid = Pattern.compile("\\b(RAM\\:\\ )[3-4]");
Pattern ramMid1 = Pattern.compile("\\b(RAM\\:\\ )[5-6]");
Pattern ramMid2 = Pattern.compile("\\b(RAM\\:\\ )[7-8]");
Pattern ramMax = Pattern.compile("\\b(RAM\\:\\ )[9]");
Matcher checkRAM1 = ramMin.matcher(msg);
Matcher checkRAM2 = ramMid.matcher(msg);
Matcher checkRAM4 = ramMid1.matcher(msg);
Matcher checkRAM5 = ramMid2.matcher(msg);
Matcher checkRAM3 = ramMax.matcher(msg);
Pattern ddMin = Pattern.compile("\\b(DD\\:\\ )[0-4]");
Pattern ddMid = Pattern.compile("\\b(DD\\:\\ )[5-8]");
Pattern ddMax = Pattern.compile("\\b(DD\\:\\ )[9-]");
Matcher checkDD1 = ddMin.matcher(msg);
Matcher checkDD2 = ddMid.matcher(msg);
Matcher checkDD3 = ddMax.matcher(msg);
Pattern osMin = Pattern.compile("\\b(OS\\: Windows\\ )[7]");
Pattern osMid = Pattern.compile("\\b(OS\\: Windows\\ )[8]");
Pattern osMax = Pattern.compile("\\b(OS\\: Windows\\ )[10]");
Pattern osLL = Pattern.compile("\\b(OS\\: Linux)");
Matcher checkosLL = osLL.matcher(msg);
Matcher checkOS1 = osMin.matcher(msg);
Matcher checkOS2 = osMid.matcher(msg);
Matcher checkOS3 = osMax.matcher(msg);
RANK = 0; //Rankeo
if (checkCPU1.find()) {
RANK += 50;
} else if (checkCPU2.find()) {
RANK += 100;
}
if (checkCores1.find()) {
RANK += 100;
} else if (checkCores2.find()) {
RANK += 200;
}
if (checkRAM1.find()) {
RANK += 50;
} else if (checkRAM2.find()) {
RANK += 100;
} else if (checkRAM3.find()) {
RANK += 150;
} else if (checkRAM4.find()) {
RANK += 120;
} else if (checkRAM5.find()) {
RANK += 130;
}
if (checkDD1.find()) {
RANK += 30;
} else if (checkDD2.find()) {
RANK += 60;
} else if (checkDD3.find()) {
RANK += 90;
}
if (checkOS1.find()) {
RANK += 70;
} else if (checkOS2.find()) {
RANK -= 80;
} else if (checkOS3.find()) {
RANK += 100;
} else if (checkosLL.find()) {
RANK += 110;
}
}
public void RankeoDeRam(String msg) {
Pattern ramcita0 = Pattern.compile("\\b(RAM\\:\\ )-?[10-25]");
Pattern ramcita1 = Pattern.compile("\\b(RAM\\:\\ )-?[30-45]");
Pattern ramcita2 = Pattern.compile("\\b(RAM\\:\\ )-?[40-55]");
Pattern ramcita3 = Pattern.compile("\\b(RAM\\:\\ )-?[60-75]");
Pattern ramcita4 = Pattern.compile("\\b(RAM\\:\\ )-?[80-95]");
Matcher verRamcita0 = ramcita0.matcher(msg);
Matcher verRamcita1 = ramcita1.matcher(msg);
Matcher verRamcita2 = ramcita2.matcher(msg);
Matcher verRamcita3 = ramcita3.matcher(msg);
Matcher verRamcita4 = ramcita4.matcher(msg);
//RANK_COPY = RANK;
if (verRamcita0.find()) {
RANKTEMP -= 50;
} else if (verRamcita1.find()) {
RANKTEMP -= 80;
} else if (verRamcita2.find()) {
RANKTEMP -= 110;
} else if (verRamcita3.find()) {
RANKTEMP -= 140;
} else if (verRamcita4.find()) {
RANKTEMP -= 170;
}
RANK_COPY = RANK + RANKTEMP;
}
}
<file_sep>/README.md
# Modelo Cliente/Servidor :computer:
[](https://forthebadge.com)
## Definición del sistema
Este sistema esta basado en el modelo de Cliente/Servidor que utiliza las funcionalidades
de Sockets para establecer una conexión de TCP. Elaborado para la materia de _Sistemas Distribuidos y Paralelos_.
## Objetivo
Para este proyecto tiene diferentes objetivos base, el primero de ellos es crear una conexión
entre diferentes equipos donde esta sea administrable (LAN), además que a través de esta
conexión se realiza un algoritmo de puntaje en base a las características de cada equipo, para
obtener al mejor de ellos con lo cual se pasa al tercer objetivo que selecciona al mejor de ellos
para dedicarse como principal (bidireccionalidad), tomando en cuenta lo anterior se elaboró
una interfaz grafica para realizar el monitoreo de los resultados anteriores. En resumen, se
crea una simulación de cómo funciona un sistema distribuido en la vida real, elaborado en el
lenguaje de programación de Java.
:movie_camera: Un video de demostracción [aquí](https://www.youtube.com/watch?v=kntvGVsnLsw).
## Elementos importantes
- [Descarga de libreria Sigar](https://github.com/hyperic/sigar)
- [Ejemplos usando a Sigar](https://www.programcreek.com/java-api-examples/?api=org.hyperic.sigar.Sigar)
- [Multitarea e Hilos](https://jarroba.com/multitarea-e-hilos-facil-y-muchas-ventajas/)
- [Sockets en Java ](https://www.programacion.com.py/escritorio/java-escritorio/sockets-en-java-udp-y-tcp)
- [Video recomendado](https://www.youtube.com/watch?v=XN0J4rzj-NA)
<file_sep>/src/ClienteServidor/HiloRankeo.java
package ClienteServidor;
import static ClienteServidor.ServerGUI.bean;
import java.util.concurrent.Callable;
public class HiloRankeo implements Callable<Double> {
static double ramcita;
@Override //Metodo RUN
public Double call() throws Exception {
ramcita = bean.getSystemCpuLoad() * 1048576;
try { //Duermo y luego vuelvo
Thread.sleep(3000);
} catch (InterruptedException e) {
System.out.println("Tengo un error en Hilo Rankeo con " + e);
}
return ramcita;
}
}
| f215dd386c9e3f53c69713281cd740cbd1cca65d | [
"Markdown",
"Java"
] | 3 | Java | dev-oswld/client-server-model | e6ed572d6a5cb8eaa19274c95be55f660ec866ee | 86070fcc0fa1e2cd7d2313d06e386bfc237f7098 |
refs/heads/master | <repo_name>AircityScript/meteor-react-generate<file_sep>/client/layout/mainLayout.jsx
import React from 'react';
import AppBar from '../component/appBar';
const MainLayout = ({content}) => (
<div>
<header>
<AppBar/>
</header>
<main>
{content()}
</main>
</div>
);
export default MainLayout;
<file_sep>/client/lib/router.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import {mount} from 'react-mounter';
import MainLayout from '../layout/mainLayout';
import NoMatch from '../layout/noMatch';
import Home from '../template/home';
import Page from '../template/page';
import More from '../template/more';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
FlowRouter.route('/',{
action(){
mount(MainLayout, {
content: () => (<Home />)
});
}
})
FlowRouter.route('/page',{
action(){
mount(MainLayout,{
content: () => (<Page/>)
});
}
});
FlowRouter.route('/more',{
action(){
mount(MainLayout,{
content: () => (<More/>)
});
}
});
FlowRouter.notFound = {
name: '404 Not Found',
action(){
mount(NoMatch);
}
};
FlowRouter.initialize();
<file_sep>/README.md
Based on Meteor 1.2
Use kadira:flow-router
<file_sep>/client/template/home.jsx
import React from 'react';
import TextField from 'material-ui/lib/text-field';
import AutoComplete from 'material-ui/lib/auto-complete';
const Home = React.createClass({
mixins: [ReactMeteorData],
getMeteorData() {
return {
};
},
render() {
return (
<div>
<div>
<h1>Home</h1>
<div><a href="/page">Some page</a></div>
</div>
<br/>
<div className="clearfix">
<TextField
hintText="The hint text can be as long as you want, it will wrap."
multiLine={true} />
</div>
</div>
);
}
});
export default Home;
| d0edf5c735e0eea3dafa11cbb1781f25d4ff34fd | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | AircityScript/meteor-react-generate | 65527ab8f917b668cc6688d6f89443a7322a2647 | 2ba7717480c2ee29cd273a7686c1151ed74b625d |
refs/heads/master | <repo_name>unfold/toast<file_sep>/Makefile
OLD = ls -l | grep .js | sed -r 's/.+\s(\S+)/\1/'
NAME = ls src | sed -r 's/ender\.js|package\.json|\s+//' | sed -nr 's/(.+)\.js/\1/p'
VERSION = grep -m 1 Version src/\`${NAME}\`.js | sed -r 's/.*:\s*(.+)/\1/'
all: lint minify
lint:
@jshint src/`${NAME}`.js --config config/jshint.json
minify:
@rm -f `${OLD}`
@uglifyjs -nc src/`${NAME}`.js > `${NAME}`-`${VERSION}`.min.js
instdeps:
@npm install jshint -g
@npm install uglify-js -g<file_sep>/unit/runner.js
domReady(function(){
sink('toast',function(test,ok,before,after){
test('One resource',2,function(){
// One JS resource
toast(
'resources/a.js',
function(){
if(!window.a) return false;
ok(true,'One JS resource loaded');
}
);
// One CSS resource
toast(
'resources/a.css',
function(){
ok(document.styleSheets.length==1,'One CSS resource loaded');
}
);
});
test('Several resources',2,function(){
toast(
[
'resources/b.js',
'resources/b.css',
'resources/c.js',
'resources/c.css'
],
function(){
if(!window.b && !window.c) return false;
ok(true,'Four JS resources loaded');
ok(document.styleSheets.length==3,'Two CSS resources loaded');
}
);
});
test('One complex resource',2,function(){
// One JS resource
toast(
{href: 'resources/f.js', id: 'foo'},
function(){
if(!window.f) return false;
ok(true,'One JS resource loaded');
}
);
// One CSS resource
toast(
{src: 'resources/f.css', media: 'only screen and (max-device-width: 480px)'},
function(){
ok(document.styleSheets.length==4,'One CSS resource loaded');
}
);
});
});
start();
});
<file_sep>/src/toast.js
window.toast = (function(window, document) {
var head = document.getElementsByTagName('head')[0];
var createNode = function(type, attributes) {
var node = document.createElement(type);
if (attributes) {
for (var property in attributes) {
node[property] = attributes[property];
}
}
return node;
};
var toast = function(resources, callback) {
var pending;
var isComplete = function() {
if (!--pending && callback && callback() === false) {
setTimeout(isComplete);
}
};
var watchStyleSheet = function(node) {
if (node.sheet || node.styleSheet) {
isComplete();
} else{
setTimeout(function() {
watchStyleSheet(node);
});
}
};
var watchScript = function() {
if (/ded|co/.test(window.readyState)) {
isComplete();
}
};
if (head || setTimeout(toast)) {
if (!resources.pop) {
resources = [resources];
}
pending = resources.length;
for (var i = 0; i < resources.length; i++) {
var resource = resources[i];
var attributes = {};
var href = resource.href || resource.src || resource;
var node;
if (typeof resource == 'object') {
for (var property in resource) {
attributes[property] = resource[property];
}
}
if (/\.css$/.test(href)) {
attributes.rel = 'stylesheet';
attributes.href = href;
node = createNode('link', attributes);
watchStyleSheet(node);
} else {
attributes.src = href;
node = createNode('script', attributes);
if (node.onreadystatechange === null) {
node.onreadystatechange = watchScript;
} else {
node.onload = isComplete;
}
}
head.appendChild(node);
}
}
};
return toast;
})(this, this.document);<file_sep>/README.markdown
Toast 0.2.9
===========
Toast is a tiny resource loader for JS and CSS files.
Features
--------
- load resources as soon as possible to avoid FOUC issues (especially when loading stylesheets)
- infinite nesting
- advanced callback support
- tested against IE 5.5+, Chrome, Safari 3+, Opera 9+, Firefox 2+
Syntax
------
It accepts two parameters:
- a string or an array of strings representing resources to load
- an optional callback
Here's how toast loads resources:
// Load one css file for mobiles
toast('css/mobiles.css');
// Load several resources for desktops
if(screen.width>800){
toast([
'css/screens.css',
'js/modernizr.js',
'js/classie.js'
]);
}
And how callbacks are used:
// The callback is called when jQuery has been loaded
toast('scripts/jquery.js',function(){log('loaded');});
// Works, naturally, with several resources
toast(
[
'css/screens.css',
'js/modernizr.js',
'js/classie.js'
],
function(){
log('All is loaded');
}
);
Sometimes, on some browsers, scripts are not parsed yet when we want to use them (like calling a function from that script). To resolve that issue, toast provides a simple way:
toast(
'scripts/jquery.js',
function(){
// The callback will be called until `$` is not set
if(!window.$){
return false;
}
// jQuery actions
// .....
}
);
This is, returning `false` into the callback makes it called while it doesn't return another value than `false` (so, an `undefined` returned value won't make the callback to hang on).
Finally, as nested resources are fully supported, you can do that:
toast(
[
'css/screens.css',
[
[
'js/modernizr.js',
'js/respond.js',
[
'js/selectivizr.js',
function(){
log('Selectivizr has been loaded');
}
]
],
function(){
log('Modernizr, respond and selectivizr have been loaded');
}
],
'js/classie.js'
],
function(){
log('Screens.css, modernizr, respond, selectivizr and classie have been loaded');
}
);
License
-------
Toast is licensed under the MIT license. | 548ca5c84471bd415d71c9158ed21e3ccd92410f | [
"JavaScript",
"Makefile",
"Markdown"
] | 4 | Makefile | unfold/toast | c08137e75e8e90d75fccc646e0e04e7513206522 | 7c353a429b4bc234488fe26cd405e4409f32d1a3 |
refs/heads/main | <repo_name>cuiwen25/fe-better-practice<file_sep>/.umirc.ts
import { defineConfig } from 'dumi';
const GITHUB_REPOSITORY_NAME = 'fe-better-practice';
export default defineConfig({
title: 'fe-better-practice',
description: '基于 React 的前端项目最佳实践探索',
mode: 'doc',
// 配置 GitHub Pages
base: `/${GITHUB_REPOSITORY_NAME}`,
publicPath: `/${GITHUB_REPOSITORY_NAME}/`,
exportStatic: {},
// 默认仅使用中文
locales: [['zh-CN', '中文']],
// 使用 esbuild 打包
esbuild: {},
dynamicImport: {},
});
| 824bb62223d8672c0f90752c8fd4d5514b1e0b78 | [
"TypeScript"
] | 1 | TypeScript | cuiwen25/fe-better-practice | 1bd90825f838081ea6efc98229655a5c43e07b93 | 4b7d007cffe569bf3f9148680d611e3661b2a8b0 |
refs/heads/master | <repo_name>mcmonkeys1/arweave-bundles<file_sep>/src/ar-data-bundle.ts
import { DataItemJson } from ".";
import { Dependencies } from "./ar-data-base";
import { verify } from "./ar-data-verify";
/**
* Unbundles a transaction into an Array of DataItems.
*
* Takes either a json string or object. Will throw if given an invalid json
* string but otherwise, it will return an empty array if
*
* a) the json object is the wrong format
* b) the object contains no valid DataItems.
*
* It will verify all DataItems and discard ones that don't pass verification.
*
* @param deps
* @param txData
*/
export async function unbundleData(deps: Dependencies, txData: any): Promise<DataItemJson[]> {
if (typeof txData === 'string') {
txData = JSON.parse(txData);
}
if (typeof txData !== 'object' || !txData || !txData.items || !Array.isArray(txData.items)) {
console.warn(`Invalid bundle, should be a json string or obect with an items Array`)
return [];
}
const itemsArray = txData.items as DataItemJson[];
const verifications = await Promise.all(itemsArray.map(d => verify(deps, d)));
const failed = verifications.filter(v => !v).length;
if (failed > 0) {
console.warn(`${failed} peices of Data failed verification and will be discarded`);
return itemsArray.filter((x, idx) => verifications[idx]);
}
return itemsArray;
}
/**
* Verifies all datas and returns a json object with an items array.
* Throws if any of the data items fail verification.
*
* @param deps
* @param datas
*/
export async function bundleData(deps: Dependencies, datas: DataItemJson[]) {
await Promise.all(
datas.map(async d => { if (!(await verify(deps, d))) { throw new Error('Invalid Data') } })
)
return JSON.stringify({ items: datas });
}<file_sep>/src/ar-data-create.ts
import { Dependencies, DataItemJson, getSignatureData } from "./ar-data-base";
import { JWKPublicInterface, JWKInterface } from "./interface-jwk";
import { verifyEncodedTagsArray, MAX_TAG_COUNT, MAX_TAG_KEY_LENGTH_BYTES, MAX_TAG_VALUE_LENGTH_BYTES } from "./ar-data-verify";
/**
* Options for creation of a DataItem
*/
export interface DataItemCreateOptions {
data: string | Uint8Array
target?: string
nonce?: string
tags?: { name: string, value: string }[]
}
/**
* Create a DataItem, encoding tags and data, setting owner, but not
* sigining it.
*
* @param deps
* @param opts
* @param jwk
*/
export async function createData(deps: Dependencies, opts: DataItemCreateOptions, jwk: JWKPublicInterface): Promise<DataItemJson> {
const d = {
owner: jwk.n,
target: opts.target || '',
nonce: opts.nonce || '',
tags: opts.tags ?
opts.tags.map(t => ({ name: deps.utils.stringToB64Url(t.name), value: deps.utils.stringToB64Url(t.value) })) :
[],
data: typeof opts.data === 'string' ?
deps.utils.stringToB64Url(opts.data) :
deps.utils.bufferTob64Url(opts.data),
signature: '',
id: '',
}
if (!verifyEncodedTagsArray(deps, d.tags)) {
throw new Error(`Tags are invalid, a maximum of ${MAX_TAG_COUNT} tags, a key length of ${MAX_TAG_KEY_LENGTH_BYTES}, a value length of ${MAX_TAG_VALUE_LENGTH_BYTES} has been exceeded, or the tags are otherwise malformed.`)
}
return d;
}
export function addTag(deps: Dependencies, d: DataItemJson, name: string, value: string) {
d.tags.push({
name: deps.utils.stringToB64Url(name),
value: deps.utils.stringToB64Url(value)
})
}
/**
* Signs a data item and sets the `signature` and `id` fields to valid values.
*
* @param deps
* @param d
* @param jwk
*/
export async function sign(deps: Dependencies, d: DataItemJson, jwk: JWKInterface): Promise<DataItemJson> {
// Sign
const signatureData = await getSignatureData(deps, d);
const signatureBytes = await deps.crypto.sign(jwk, signatureData);
// Derive Id
const idBytes = await deps.crypto.hash(signatureBytes);
// Assign. TODO: Don't mutate. For familiarity with existing sign tx api we mutate.
d.signature = deps.utils.bufferTob64Url(signatureBytes);
d.id = deps.utils.bufferTob64Url(idBytes);
return d;
}
<file_sep>/src/ar-data-read.ts
import { Dependencies, DataItemJson } from "./ar-data-base";
/**
* Decode the data content of a DataItem, either to a string or Uint8Array of bytes
*
* @param deps
* @param d
* @param param2
*/
export async function decodeData(deps: Dependencies, d: DataItemJson, options: { string: boolean } = { string: false }): Promise<string | Uint8Array> {
if (options.string) {
return deps.utils.b64UrlToString(d.data);
} else {
return deps.utils.b64UrlToBuffer(d.data);
}
}
/**
* Decode an individual tag from a DataItem. Always decodes name and value as strings
*
* @param deps
* @param tag
*/
export async function decodeTag(deps: Dependencies, tag: { name: string, value: string} ) {
return { name: deps.utils.b64UrlToString(tag.name), value: deps.utils.b64UrlToString(tag.value)}
}
/**
* Decodes an individual tag from a DataItem at index. Throws if index is out of bounds.
*
*/
export async function decodeTagAt(deps: Dependencies, d: DataItemJson, index: number) {
if (d.tags.length < index-1) {
throw new Error(`Invalid index ${index} when tags array has ${d.tags.length} tags`);
}
return decodeTag(deps, d.tags[index]);
}
/**
* Unpack all tags in a DataItem into a key value map of
*
* `name: string | string[]`
*
* Always decodes as string values, maintains the order
* the tags were seriliazed in when converting a collection
* of tags with the same key.
*
* @param deps
* @param d
*/
export async function unpackTags(deps: Dependencies, d: DataItemJson): Promise<Record<string, (string | string[])>> {
const tags: Record<string, (string | string[])> = {}
for (let i = 0; i < d.tags.length; i++) {
const { name, value } = await decodeTag(deps, d.tags[i]);
if (!tags.hasOwnProperty(name)) {
tags[name] = value;
continue;
}
tags[name] = [ ...tags[name], value ]
}
return tags;
}<file_sep>/README.md
# arweave-bundles (ANS-102)
This library contains routines to create, read, and verify Arweave bundled data.
See [ANS-102](https://github.com/ArweaveTeam/arweave-standards/blob/master/ans/ANS-102.md) for more details.
## Install straight from GitHub
`npm install mcmonkeys1/arweave-bundles`
## Initializing the library
This is a self-contained library, so we need to initialize the API with a couple of dependencies:
```javascript
import Arweave from 'arweave'
import deepHash from 'arweave/node/lib/deepHash'
import ArweaveData from 'arweave-data'
const ArData = ArweaveData({
utils: Arweave.utils,
crypto: Arweave.crypto,
deepHash: deepHash,
})
```
~~## Unbundling from a Transaction containing DataItems~~
~~## Reading data and tags from a DataItem~~
No special instructions! 😃 You can now query and read the data from your bundled item transactions, just like any other fully fledged Arweave transaction
## Creating a DataItem
```javascript
const myTags = [
{ name: 'App-Name', value: 'myApp' },
{ name: 'App-Version', value: '1.0.0' }
]
let item = await ArData.createData(
{
to: 'wallet_address',
data: 'some message',
tags: myTags
},
wallet
);
// Add some more tags after creation.
ArData.addTag(item, 'MyTag', 'value1');
ArData.addTag(item, 'MyTag', 'value2');
// Sign the data, ready to be added to a bundle
const signed1 = await ArData.sign(item, wallet);
// ...construct a signed2 dataItem here for example...
```
## Bundling up DataItems and writing a transaction
```javascript
const dataItems = [signed1, signed2] //add more signed DataItems if you like
// Will ensure all items are valid and have been signed, throwing if any are not
const myBundle = await ArData.bundleData(dataItems);
// N.B. I have updated the return type of bundledData,
// just feed it straight into createTransaction like so:
const myTx = await arweave.createTransaction({ data: myBundle }, wallet);
myTx.addTag('Bundle-Format', 'json');
myTx.addTag('Bundle-Version', '1.0.0');
myTx.addTag('Content-Type', 'application/json');
await arweave.transactions.sign(tx, wallet);
await arweave.transactions.post(tx);
```
<file_sep>/src/tests/tests.spec.ts
import { expect } from 'chai';
import ArweaveData from '../'
// Import deps from Arweave-Js
import Arweave from 'arweave/node';
import deepHash from 'arweave/node/lib/deepHash';
import { readFileSync, fstat, writeFileSync } from 'fs';
// Just used for some checks.
const _arweave = Arweave.init({ host: 'arweave.net', port: '443', protocol: 'https' });
const wallet0 = JSON.parse(readFileSync(__dirname + '/test_key0.json').toString());
const wallet1 = JSON.parse(readFileSync(__dirname + '/test_key1.json').toString());
const TEST_STRING = 'HELLOWORLD_TEST_STRING';
const TEST_TAGS = [ { name: 'MyTag', value: '0'}, {name: "OtherTag", value: "Foo" }, { name: "MyTag", value: '1' } ];
const VALID_BASE64U = 'LS0t'
const INVALID_BASE64U = 'LS0t*&'
const deps = {
utils: Arweave.utils,
crypto: Arweave.crypto,
deepHash: deepHash,
}
const Data = ArweaveData(deps);
describe('Data API - basic', function() {
it('should encode and decode string data', async function() {
const item = await Data.createData({ data: TEST_STRING }, wallet0);
expect(item.data).to.not.equal(TEST_STRING);
expect(await Data.decodeData(item, { string: true })).to.equal(TEST_STRING)
})
})
describe('Data API - verification', function() {
it('should verify a valid signed DataItem', async function() {
const item0 = await Data.createData({ data: TEST_STRING, tags: TEST_TAGS }, wallet0);
const signed = await Data.sign(item0, wallet0);
const verified = await Data.verify(signed);
expect(verified).to.equal(true);
})
it('should fail to verify a DataItem with no signature or id', async function() {
const item0 = await Data.createData({ data: 'TESTSTRINGA'}, wallet0);
expect(
await Data.verify(item0)
).to.equal(false);
const signed = await Data.sign(item0, wallet0);
signed.id = '';
expect(
await Data.verify(signed)
).to.equal(false);
const signed2 = await Data.sign(item0, wallet0);
signed.signature = '';
expect(
await Data.verify(signed2)
).to.equal(false);
})
it('should fail to verify a DataItem with a invalid owner', async function() {
const item0 = await Data.createData({ data: 'TESTSTRINGA'}, wallet0);
const signed = await Data.sign(item0, wallet0);
expect(
await Data.verify(signed)
).to.equal(true);
signed.owner = wallet1.n;
expect(
await Data.verify(signed)
).to.equal(false);
})
it('should fail to verify a DataItem with a modified or invalid id or signature', async function() {
const item0 = await Data.createData({ data: 'TESTSTRINGA' }, wallet0);
const signed = await Data.sign(item0, wallet0);
const correctId = signed.id;
signed.id = `XXXX${signed.id.substr(4)}`
expect(
await Data.verify(signed)
).to.equal(false);
signed.id = `FOO`
expect(
await Data.verify(signed)
).to.equal(false);
signed.id = INVALID_BASE64U
expect(
await Data.verify(signed)
).to.equal(false);
signed.id = correctId
expect(
await Data.verify(signed)
).to.equal(true);
const signed2 = await Data.sign(item0, wallet0);
const correctSignature = signed2.signature;
signed2.signature = ''
expect(
await Data.verify(signed)
).to.equal(false);
signed2.signature = VALID_BASE64U
expect(
await Data.verify(signed)
).to.equal(false);
signed2.signature = INVALID_BASE64U
expect(
await Data.verify(signed)
).to.equal(false);
signed2.signature = correctSignature
expect(
await Data.verify(signed)
).to.equal(true);
})
it('should fail to verify a DataItem with a modified nonce', async function() {
const item0 = await Data.createData({ data: 'TESTSTRINGA', nonce: VALID_BASE64U }, wallet0);
const signed = await Data.sign(item0, wallet0);
signed.nonce = signed.nonce + VALID_BASE64U;
expect(
await Data.verify(signed)
).to.equal(false);
})
it('should fail to verify a DataItem with invalid Base64', async function() {
const item0 = await Data.createData({ data: 'TESTSTRINGA', nonce: VALID_BASE64U }, wallet0);
const signed = await Data.sign(item0, wallet0);
signed.data = INVALID_BASE64U
expect(
await Data.verify(signed)
).to.equal(false);
})
it('should fail to verify a DataItem with modified tags', async function() {
const item0 = await Data.createData({ data: 'TESTSTRINGA', tags: TEST_TAGS, nonce: VALID_BASE64U }, wallet0);
const signed = await Data.sign(item0, wallet0);
expect(
await Data.verify(signed)
).to.equal(true);
signed.tags = signed.tags.slice(1);
expect(
await Data.verify(signed)
).to.equal(false);
})
it('should fail to verify a DataItem with invalid tags', async function() {
const item0 = await Data.createData({ data: 'TESTSTRINGA', tags: TEST_TAGS, nonce: VALID_BASE64U }, wallet0);
const signed = await Data.sign(item0, wallet0);
signed.tags[0].name = INVALID_BASE64U;
expect(
await Data.verify(signed)
).to.equal(false);
})
describe('Data API - Bundling', function() {
it('should bundle a number of items', async function() {
const item0 = await Data.createData({ data: 'TESTSTRINGA', tags: TEST_TAGS, nonce: VALID_BASE64U }, wallet0);
const signed0 = await Data.sign(item0, wallet0);
const item1 = await Data.createData({ data: 'TESTSTRINGB', tags: TEST_TAGS, nonce: VALID_BASE64U }, wallet0);
const signed1 = await Data.sign(item0, wallet0);
const item2 = await Data.createData({ data: 'TESTSTRINGC', tags: TEST_TAGS, nonce: VALID_BASE64U }, wallet0);
const signed2 = await Data.sign(item0, wallet0);
const bundle = await Data.bundleData([signed0, signed1, signed2]);
expect(bundle).to.have.length.greaterThan(0)
//writeFileSync(__dirname + '/bundle0.json', JSON.stringify(bundle, undefined, 2));
})
it('should unbundle a number of items', async function() {
const json = readFileSync(__dirname + '/bundle0.json').toString();
const items = await Data.unbundleData(json);
expect(items.length).to.equal(3);
})
it('should unbundle and discard invalid items', async function() {
const json = readFileSync(__dirname + '/bundle1-invaliditem0.json').toString();
const items = await Data.unbundleData(json);
expect(items.length).to.equal(2);
})
})
})
<file_sep>/dist/index.d.ts
import { Dependencies } from './ar-data-base';
import { getSignatureData, DataItemJson } from './ar-data-base';
import { createData, sign, DataItemCreateOptions } from './ar-data-create';
import { decodeData, decodeTag, decodeTagAt, unpackTags } from './ar-data-read';
import { verify } from './ar-data-verify';
export { createData as create, sign, decodeData, decodeTag, decodeTagAt, unpackTags, verify, DataItemCreateOptions, DataItemJson, getSignatureData };
export default function ArweaveData(deps: Dependencies): {
createData: (opts: DataItemCreateOptions, jwk: import("./interface-jwk").JWKPublicInterface) => Promise<DataItemJson>;
sign: (d: DataItemJson, jwk: import("./interface-jwk").JWKInterface) => Promise<DataItemJson>;
addTag: (d: DataItemJson, name: string, value: string) => void;
verify: (d: DataItemJson) => Promise<boolean>;
decodeData: (d: DataItemJson, options?: {
string: boolean;
} | undefined) => Promise<string | Uint8Array>;
decodeTag: (tag: {
name: string;
value: string;
}) => Promise<{
name: string;
value: string;
}>;
decodeTagAt: (d: DataItemJson, index: number) => Promise<{
name: string;
value: string;
}>;
unpackTags: (d: DataItemJson) => Promise<Record<string, string | string[]>>;
bundleData: (datas: DataItemJson[]) => Promise<string>;
unbundleData: (txData: any) => Promise<DataItemJson[]>;
};
<file_sep>/src/index.ts
import { Dependencies } from './ar-data-base';
import { getSignatureData, DataItemJson } from './ar-data-base';
import { createData, sign, addTag, DataItemCreateOptions } from './ar-data-create';
import { decodeData, decodeTag, decodeTagAt, unpackTags } from './ar-data-read';
import { bundleData, unbundleData } from './ar-data-bundle'
import { verify } from './ar-data-verify';
export { createData as create, sign, decodeData, decodeTag, decodeTagAt, unpackTags, verify, DataItemCreateOptions, DataItemJson, getSignatureData }
export default function ArweaveData(deps: Dependencies) {
return {
createData: createData.bind(null, deps),
sign: sign.bind(null, deps),
addTag: addTag.bind(null, deps),
verify: verify.bind(null, deps),
decodeData: decodeData.bind(null, deps),
decodeTag: decodeTag.bind(null, deps),
decodeTagAt: decodeTagAt.bind(null, deps),
unpackTags: unpackTags.bind(null, deps),
bundleData: bundleData.bind(null, deps),
unbundleData: unbundleData.bind(null, deps),
}
}
<file_sep>/src/ar-data-verify.ts
import { Dependencies, DataItemJson, getSignatureData } from "./ar-data-base";
export const MAX_TAG_KEY_LENGTH_BYTES = 1024 * 1;
export const MAX_TAG_VALUE_LENGTH_BYTES = 1024 * 3;
export const MAX_TAG_COUNT = 128;
/**
* Verifies a DataItem is valid.
*
* @param deps
* @param d
* @param jwk
*/
export async function verify(deps: Dependencies, d: DataItemJson): Promise<boolean> {
// Try-catch all so malformed data like invalid base64 or something just returns false.
try {
// Get signature data and signature present in di.
const signatureData = await getSignatureData(deps, d);
const signatureBytes = deps.utils.b64UrlToBuffer(d.signature);
// Verifiy Id is correct
const idBytes = await deps.crypto.hash(signatureBytes);
const idOk = deps.utils.bufferTob64Url(idBytes) === d.id;
if (!idOk) {
return false;
}
// Verify Signature is correct
const signatureOk = await deps.crypto.verify(d.owner, signatureData, signatureBytes);
if (!signatureOk) {
return false;
}
// Verify tags array is valid.
if (!verifyEncodedTagsArray(deps, d.tags)) {
return false;
}
// Everything passed.
return true;
}
catch (e) {
console.warn(e)
return false;
}
}
/**
*
* Verify an array of tags only contains objects with exactly two keys, `name` and `value`
* that they are both non-empty strings, and are with the bounds of tag sizes.
*
* @param tags
*/
export function verifyEncodedTagsArray(deps: Dependencies, tags: any[]) {
if (tags.length > MAX_TAG_COUNT) {
return false;
}
// Search for something invalid.
const invalid = tags.find(t =>
Object.keys(t).length !== 2
||
typeof t.name !== 'string'
||
typeof t.value !== 'string'
||
!verifyEncodedTagSize(deps, t)
);
return !invalid;
}
/**
* Verifies the tag name or value does not exceed reasonable bounds in bytes.
*
* @param deps
* @param tag
*/
export function verifyEncodedTagSize(deps: Dependencies, tag: { name: string, value: string } ) {
const nameLen = deps.utils.b64UrlToBuffer(tag.name).length;
if (nameLen < 1 || nameLen > MAX_TAG_KEY_LENGTH_BYTES) {
return false;
}
const valueLen = deps.utils.b64UrlToBuffer(tag.value).length;
if (valueLen < 1 || nameLen > MAX_TAG_VALUE_LENGTH_BYTES) {
return false;
}
return true;
} | 618090a0c2e7195dbf431c4ec410507bc4dc1673 | [
"Markdown",
"TypeScript"
] | 8 | TypeScript | mcmonkeys1/arweave-bundles | d925f084dd17d56f19748011065b47bbba5c641c | 0b2d3039d8d2c3d5ff8d87e3723a8bf566bca76e |
refs/heads/master | <repo_name>piotrklobukowski/timekeeper<file_sep>/TimekeeperTests/SettingsTests.swift
//
// SettingsTests.swift
// TimekeeperTests
//
// Created by <NAME> on 14/02/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import XCTest
@testable import Timekeeper
class SettingsTests: XCTestCase {
var settings: Settings!
var coreData: TestCoreData!
override func setUp() {
super.setUp()
coreData = TestCoreData(coreDataModelName: String.CoreData.dataModel.rawValue)
settings = Settings(context: coreData.managedObjectContext)
}
override func tearDown() {
settings = nil
coreData = nil
super.tearDown()
}
func testAllContainersAreEmpty() {
XCTAssertTrue(settings.durationSettings.isEmpty)
XCTAssertTrue(settings.breaksNumberSettings.isEmpty)
XCTAssertTrue(settings.soundSettings.isEmpty)
XCTAssertTrue(settings.anotherInformations.isEmpty)
XCTAssertTrue(settings.clockworkConfigurations.isEmpty)
}
func testAddDefaultSettings() {
settings.loadAllSettings()
XCTAssertEqual(settings.breaksNumberSettings.count, 1)
XCTAssertEqual(settings.durationSettings.count, 3)
XCTAssertEqual(settings.soundSettings.count, 1)
XCTAssertEqual(settings.anotherInformations.count, 1)
XCTAssertEqual(settings.clockworkConfigurations.count, 4)
settings.loadAllSettings()
XCTAssertNotEqual(settings.breaksNumberSettings.count, 4)
XCTAssertNotEqual(settings.durationSettings.count, 6)
XCTAssertNotEqual(settings.soundSettings.count, 2)
XCTAssertNotEqual(settings.anotherInformations.count, 2)
XCTAssertEqual(settings.breaksNumberSettings.count, 1)
XCTAssertEqual(settings.durationSettings.count, 3)
XCTAssertEqual(settings.soundSettings.count, 1)
XCTAssertEqual(settings.anotherInformations.count, 1)
}
func testLoadSpecificSettings() {
settings.loadAllSettings()
settings = nil
settings = Settings(context: coreData.managedObjectContext)
var specificSettings = try! settings.loadSpecificSetting(for: SettingsDetailsType.focusTime)
let focusTime = specificSettings.first
XCTAssertNotNil(focusTime)
XCTAssertEqual(focusTime?.amount, 25.0)
XCTAssertEqual(focusTime?.descriptionOfSetting, "Duration of focus time")
XCTAssertNil(focusTime?.settingString)
specificSettings = try! settings.loadSpecificSetting(for: SettingsDetailsType.shortBreak)
let shortBreak = specificSettings.first
XCTAssertNotNil(shortBreak)
XCTAssertEqual(shortBreak?.amount, 5.0)
XCTAssertEqual(shortBreak?.descriptionOfSetting, "Duration of short break")
XCTAssertNil(shortBreak?.settingString)
specificSettings = try! settings.loadSpecificSetting(for: SettingsDetailsType.longBreak)
let longBreak = specificSettings.first
XCTAssertNotNil(longBreak)
XCTAssertEqual(longBreak?.amount, 20.0)
XCTAssertEqual(longBreak?.descriptionOfSetting, "Duration of long break")
XCTAssertNil(longBreak?.settingString)
specificSettings = try! settings.loadSpecificSetting(for: SettingsDetailsType.shortBreaksNumber)
let shortBreaksNumber = specificSettings.first
XCTAssertNotNil(shortBreaksNumber)
XCTAssertEqual(shortBreaksNumber?.amount, 3.0)
XCTAssertEqual(shortBreaksNumber?.descriptionOfSetting, "Number of short breaks")
XCTAssertNil(shortBreaksNumber?.settingString)
specificSettings = try! settings.loadSpecificSetting(for: SettingsDetailsType.alertSound)
let alertSetting = specificSettings.first
XCTAssertNotNil(alertSetting)
XCTAssertEqual(alertSetting?.amount, 0.0)
XCTAssertEqual(alertSetting?.descriptionOfSetting, "Sound for alert")
XCTAssertEqual(alertSetting?.settingString, "Bell_Sound_Ring")
}
func testSave() {
settings.loadAllSettings()
settings = nil
settings = Settings(context: coreData.managedObjectContext)
settings.loadAllSettings()
let focusTimeChange = 30.0
let shortBreakDurationChange = 10.0
let longBreakDurationChange = 28.0
let shortBreaksAmount = 8.0
let soundTitleChange = "Japanese_Temple_Bell_Small"
settings.save(focusTimeChange, for: settings.durationSettings[0], of: .focusTime)
settings.save(shortBreakDurationChange, for: settings.durationSettings[1], of: .shortBreak)
settings.save(longBreakDurationChange, for: settings.durationSettings[2], of: .longBreak)
settings.save(shortBreaksAmount, for: settings.breaksNumberSettings[0], of: .shortBreaksNumber)
settings.save(soundTitleChange, for: settings.soundSettings[0], of: .alertSound)
settings = nil
settings = Settings(context: coreData.managedObjectContext)
settings.loadAllSettings()
XCTAssertEqual(settings.durationSettings[0].amount, focusTimeChange)
XCTAssertEqual(settings.durationSettings[1].amount, shortBreakDurationChange)
XCTAssertEqual(settings.durationSettings[2].amount, longBreakDurationChange)
XCTAssertEqual(settings.breaksNumberSettings[0].amount, shortBreaksAmount)
XCTAssertEqual(settings.soundSettings[0].settingString, soundTitleChange)
}
}
<file_sep>/TimekeeperTests/ToDoListTests.swift
//
// ToDoListTests.swift
// TimekeeperTests
//
// Created by <NAME> on 13/02/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import XCTest
@testable import Timekeeper
class ToDoListTests: XCTestCase {
var toDoList: ToDoList!
var coreData: TestCoreData!
private let names = ["Play a game" ,"Create toDoList code", "Play a game", "compose symphony", "wash dishes"]
override func setUp() {
super.setUp()
coreData = TestCoreData(coreDataModelName: String.CoreData.dataModel.rawValue)
toDoList = ToDoList(context: coreData.managedObjectContext)
}
override func tearDown() {
toDoList = nil
coreData = nil
super.tearDown()
}
func testToDoListIsEmpty() {
XCTAssertEqual(toDoList.tasks.count, 0)
}
func testToDoListTaskCountAfterAddingNewTasks() {
addTasks()
XCTAssertEqual(toDoList.tasks.count, names.count)
}
func testToDoListTaskRemoval() {
addTasks()
toDoList.deleteTask(withID: toDoList.tasks[0].identifier)
XCTAssertEqual(toDoList.tasks.count, (names.count - 1))
XCTAssertFalse(toDoList.tasks[0].descriptionOfTask == "Play a game")
XCTAssertEqual(toDoList.tasks[0].descriptionOfTask, "Create toDoList code")
}
func testMarkingTaskAsDone() {
addTasks()
toDoList.taskIsDone(id: toDoList.tasks[0].identifier)
XCTAssertEqual(toDoList.tasks[0].isDone, true)
}
func testSaveAndLoadTasks() {
addTasks()
toDoList = nil
toDoList = ToDoList(context: coreData.managedObjectContext)
toDoList.loadToDoList()
XCTAssertEqual(toDoList.tasks.count, names.count)
XCTAssertEqual(toDoList.tasks[0].descriptionOfTask, names[0])
XCTAssertEqual(toDoList.tasks[2].descriptionOfTask, names[2])
XCTAssertEqual(toDoList.tasks[4].descriptionOfTask, names[4])
}
private func addTasks() {
names.forEach {
toDoList.addTask(description: $0)
}
}
}
<file_sep>/Timekeeper/Delegates/MainViewContentUpdateDelegate.swift
//
// MainViewContentUpdateDelegate.swift
// Timekeeper
//
// Created by <NAME> on 16/01/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
protocol MainViewContentUpdateDelegate: AnyObject {
func updateTaskLabel(with taskID: Int64)
func updateMainVCwithSettings()
}
<file_sep>/Timekeeper/Model/ToDoList.swift
//
// ToDoList.swift
// Timekeeper
//
// Created by <NAME> on 16/01/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import CoreData
struct ToDoList {
init(context: NSManagedObjectContext = (UIApplication.shared.delegate as! AppDelegate).coreDataStack.managedObjectContext) {
self.context = context
}
private let context: NSManagedObjectContext
var tasks = [Task]()
mutating func addTask(description: String) {
let task = Task(context: context)
task.identifier = Int64(UUID().hashValue)
task.descriptionOfTask = description
task.isDone = false
task.order = (tasks.sorted(by: { $0.order > $1.order }).first?.order ?? 0) + 1
tasks.append(task)
saveToDoList()
}
mutating func deleteTask(withID id: Int64) {
guard let position = searchForTask(idNumber: id) else { return }
context.delete(tasks[position])
tasks.remove(at: position)
saveToDoList()
}
mutating func taskIsDone(id: Int64) {
let position = searchForTask(idNumber: id)
guard let unwrappedPosition = position else { return }
tasks[unwrappedPosition].isDone = true
saveToDoList()
}
func searchForTask(idNumber: Int64) -> Array<Task>.Index? {
let number = tasks.firstIndex() { task in
task.identifier == idNumber
}
guard let numberOfIndex = number else { return number }
return numberOfIndex
}
// MARK: - Model Manipulation Methods
private func saveToDoList() {
do {
try context.save()
} catch {
print("Error saving context \(error)")
}
}
mutating func loadToDoList() {
let request : NSFetchRequest<Task> = Task.fetchRequest()
do {
let loadedTasks = try context.fetch(request)
tasks = loadedTasks.sorted(by: { $0.order < $1.order })
} catch {
print("Error fetching data \(error)")
}
}
}
<file_sep>/Timekeeper/Controller/CreditsViewController.swift
//
// CreditsViewController.swift
// Timekeeper
//
// Created by <NAME> on 04/03/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class CreditsViewController: UIViewController, SettingsDetailsInterface {
var detailsType: SettingsDetailsType?
var credits: ClockworkSettings?
var settings: Settings?
var delegate: SettingsUpdateDelegate?
@IBOutlet var creditsTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
do {
credits = try loadSoundSettings()
fillWithLoadedSettings()
} catch {
print("Error loading credits")
}
}
private func loadSoundSettings() throws -> ClockworkSettings? {
guard let detailsType = detailsType else { return nil }
return try settings?.loadSpecificSetting(for: detailsType).first
}
private func fillWithLoadedSettings() {
creditsTextView.text = credits?.settingString
}
}
<file_sep>/TimekeeperTests/SettingsTableViewControllerTests.swift
//
// SettingsTableViewControllerTests.swift
// TimekeeperTests
//
// Created by <NAME> on 18/02/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import XCTest
@testable import Timekeeper
class SettingsTableViewControllerTests: XCTestCase {
var coreData: TestCoreData!
var settingsTableViewController: SettingsTableViewController!
override func setUp() {
super.setUp()
let storyboard = UIStoryboard(name: String.StoryboardIdentifiers.main.rawValue, bundle: Bundle.main)
settingsTableViewController = storyboard.instantiateViewController(withIdentifier: String.StoryboardIdentifiers.settingsTableViewControllerID.rawValue) as? SettingsTableViewController
coreData = TestCoreData(coreDataModelName: String.CoreData.dataModel.rawValue)
settingsTableViewController.settings = Settings(context: coreData.managedObjectContext)
let _ = settingsTableViewController.view
}
override func tearDown() {
coreData = nil
settingsTableViewController = nil
super.tearDown()
}
func testNumberOfSections() {
let numberOfSections = settingsTableViewController.numberOfSections(in: settingsTableViewController.tableView)
XCTAssertEqual(numberOfSections, 4)
}
func testTitleForHeaderInSection() {
var sectionsTitles = [String]()
for section in 0...3 {
guard let sectionTitle = settingsTableViewController.tableView(settingsTableViewController.tableView, titleForHeaderInSection: section) else { return }
sectionsTitles.append(sectionTitle)
}
XCTAssertEqual(sectionsTitles[0], "Duration")
XCTAssertEqual(sectionsTitles[1], "Number of breaks")
XCTAssertEqual(sectionsTitles[2], "Sound settings")
XCTAssertEqual(sectionsTitles[3], "Other")
XCTAssertNotEqual(sectionsTitles[0], "nil")
XCTAssertNotEqual(sectionsTitles[1], "nil")
XCTAssertNotEqual(sectionsTitles[2], "nil")
XCTAssertNotEqual(sectionsTitles[3], "nil")
}
func testNumberOfRowsInSection() {
var SectionsRowsCount = [Int]()
for section in 0...3 {
let numberOfRowsInSection = settingsTableViewController.tableView(settingsTableViewController.tableView, numberOfRowsInSection: section)
SectionsRowsCount.append(numberOfRowsInSection)
}
XCTAssertEqual(SectionsRowsCount[0], 3)
XCTAssertEqual(SectionsRowsCount[1], 1)
XCTAssertEqual(SectionsRowsCount[2], 1)
XCTAssertEqual(SectionsRowsCount[3], 1)
}
func testDetailsForCell() {
let focusTimeCell = settingsTableViewController.tableView(settingsTableViewController.tableView, cellForRowAt: IndexPath(row: 0, section: 0))
let shortBreakCell = settingsTableViewController.tableView(settingsTableViewController.tableView, cellForRowAt: IndexPath(row: 1, section: 0))
let longBreakCell = settingsTableViewController.tableView(settingsTableViewController.tableView, cellForRowAt: IndexPath(row: 2, section: 0))
let shortBreaksAmountCell = settingsTableViewController.tableView(settingsTableViewController.tableView, cellForRowAt: IndexPath(row: 0, section: 1))
let soundCell = settingsTableViewController.tableView(settingsTableViewController.tableView, cellForRowAt: IndexPath(row: 0, section: 2))
XCTAssertEqual(focusTimeCell.textLabel?.text, "Duration of focus time")
XCTAssertEqual(focusTimeCell.detailTextLabel?.text, "00:25")
XCTAssertEqual(shortBreakCell.textLabel?.text, "Duration of short break")
XCTAssertEqual(shortBreakCell.detailTextLabel?.text, "00:05")
XCTAssertEqual(longBreakCell.textLabel?.text, "Duration of long break")
XCTAssertEqual(longBreakCell.detailTextLabel?.text, "00:20")
XCTAssertEqual(shortBreaksAmountCell.textLabel?.text, "Number of short breaks")
XCTAssertEqual(shortBreaksAmountCell.detailTextLabel?.text, "3")
XCTAssertEqual(soundCell.textLabel?.text, "Sound for alert")
XCTAssertEqual(soundCell.accessoryType, .disclosureIndicator)
}
func testDetailsForCellsWhenDataChanged() {
let focusTimeChange = 85.0
let shortBreakDurationChange = 1825.0
let longBreakDurationChange = 28.0
let shortBreaksAmount = 8.0
guard let durationSettings = settingsTableViewController.settings?.durationSettings[0],
let shortBreakSettings = settingsTableViewController.settings?.durationSettings[1],
let longBreakSettings = settingsTableViewController.settings?.durationSettings[2],
let shortBreaksAmountSetitngs = settingsTableViewController.settings?.breaksNumberSettings[0] else { return }
settingsTableViewController.settings?.save(focusTimeChange, for: durationSettings, of: .focusTime)
settingsTableViewController.settings?.save(shortBreakDurationChange, for: shortBreakSettings, of: .shortBreak)
settingsTableViewController.settings?.save(longBreakDurationChange, for: longBreakSettings, of: .longBreak)
settingsTableViewController.settings?.save(shortBreaksAmount, for: shortBreaksAmountSetitngs , of: .shortBreaksNumber)
let focusTimeCell = settingsTableViewController.tableView(settingsTableViewController.tableView, cellForRowAt: IndexPath(row: 0, section: 0))
let shortBreakCell = settingsTableViewController.tableView(settingsTableViewController.tableView, cellForRowAt: IndexPath(row: 1, section: 0))
let longBreakCell = settingsTableViewController.tableView(settingsTableViewController.tableView, cellForRowAt: IndexPath(row: 2, section: 0))
let shortBreaksAmountCell = settingsTableViewController.tableView(settingsTableViewController.tableView, cellForRowAt: IndexPath(row: 0, section: 1))
let soundCell = settingsTableViewController.tableView(settingsTableViewController.tableView, cellForRowAt: IndexPath(row: 0, section: 2))
XCTAssertEqual(focusTimeCell.textLabel?.text, "Duration of focus time")
XCTAssertEqual(focusTimeCell.detailTextLabel?.text, "01:25")
XCTAssertEqual(shortBreakCell.textLabel?.text, "Duration of short break")
XCTAssertEqual(shortBreakCell.detailTextLabel?.text, "30:25")
XCTAssertEqual(longBreakCell.textLabel?.text, "Duration of long break")
XCTAssertEqual(longBreakCell.detailTextLabel?.text, "00:28")
XCTAssertEqual(shortBreaksAmountCell.textLabel?.text, "Number of short breaks")
XCTAssertEqual(shortBreaksAmountCell.detailTextLabel?.text, "8")
XCTAssertEqual(soundCell.textLabel?.text, "Sound for alert")
XCTAssertEqual(soundCell.accessoryType, .disclosureIndicator)
}
}
<file_sep>/Timekeeper/Controller/DurationSettingsViewController.swift
//
// DurationSettingsViewController.swift
// Timekeeper
//
// Created by <NAME> on 05/02/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class DurationSettingsViewController: UIViewController, SettingsDetailsInterface {
@IBOutlet var descriptionLabel: UILabel!
@IBOutlet var viewForSettingPickerView: UIView!
@IBOutlet var settingPickerView: UIPickerView!
@IBOutlet var saveButton: UIButton!
@IBOutlet var colon: UILabel!
weak var delegate: SettingsUpdateDelegate?
let minutes = String.timeSixty
let seconds = String.timeSixty
var settings: Settings?
var detailsType: SettingsDetailsType?
private var durationSettings: ClockworkSettings?
private lazy var formatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.allowedUnits = [.minute, .second]
formatter.zeroFormattingBehavior = .pad
return formatter
}()
private lazy var numberFormatter: NumberFormatter = {
return NumberFormatter()
}()
override func viewDidLoad() {
super.viewDidLoad()
settingPickerView.delegate = self
settingPickerView.dataSource = self
loadSettingsAndView()
}
@IBAction func saveButtonPressed(_ sender: UIButton) {
guard let selectedTime = transformValueFromPicker(),
let type = detailsType,
let newSetting = durationSettings else { return }
settings?.save(selectedTime, for: newSetting, of: type)
delegate?.settingsDidUpdate()
navigationController?.popViewController(animated: true)
print("Perform save for new value: \(selectedTime)")
}
func loadSettingsAndView() {
do {
durationSettings = try loadDurationSettings()
} catch {
return
}
fillWithLoadedSettings()
}
private func transformValueFromPicker() -> Double? {
guard let selectedMinutesRow = settingPickerView?.selectedRow(inComponent: Components.minutes),
let selectedSecondsRow = settingPickerView?.selectedRow(inComponent: Components.seconds) else { return nil }
let selectedMinutes = minutes[selectedMinutesRow]
let selectedSeconds = seconds[selectedSecondsRow]
guard let minutes = numberFormatter.number(from: selectedMinutes)?.doubleValue,
let seconds = numberFormatter.number(from: selectedSeconds)?.doubleValue
else { return nil }
let double: Double = {
var value = minutes * 60 + seconds
if value < 5.0 {
value = 5.0
}
return value
}()
return double
}
private func provideValueForPickerView(value: Double) {
guard let timeString = formatter.clockFormat(from: value) else { return }
let substrings = timeString.split(separator: ":")
let minutes = String(substrings[0])
let seconds = String(substrings[1])
guard let minutesIndex = self.minutes.firstIndex(of: minutes) else { return }
guard let secondsIndex = self.seconds.firstIndex(of: seconds) else { return }
settingPickerView.selectRow(minutesIndex, inComponent: Components.minutes, animated: false)
settingPickerView.selectRow(secondsIndex, inComponent: Components.seconds, animated: false)
}
private func loadDurationSettings() throws -> ClockworkSettings? {
guard let detailsType = detailsType else { return nil }
return try settings?.loadSpecificSetting(for: detailsType).first
}
private func fillWithLoadedSettings() {
guard let value = durationSettings?.amount else { return }
provideValueForPickerView(value: value)
descriptionLabel.text = durationSettings?.descriptionOfSetting
}
}
extension DurationSettingsViewController: UIPickerViewDelegate, UIPickerViewDataSource {
private enum Components {
static var minutes = 0
static var seconds = 2
static var colon = 1
static var comoponentsCount = 3
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return Components.comoponentsCount
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch component {
case Components.minutes:
return minutes.count
case Components.seconds:
return seconds.count
default:
return 0
}
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
var label: UILabel
if let vw = view as? UILabel {
label = vw
} else {
label = UILabel()
}
label.textColor = UIColor.trackColor
label.font = .systemFont(ofSize: (viewForSettingPickerView.frame.size.height * 0.45))
colon.textColor = UIColor.trackColor
colon.font = .systemFont(ofSize: (viewForSettingPickerView.frame.size.height * 0.45))
colon.textAlignment = .center
switch component {
case Components.minutes:
label.textAlignment = .right
label.text = minutes[row]
case Components.seconds:
label.textAlignment = .left
label.text = seconds[row]
default:
label.textAlignment = .center
label.text = nil
}
return label
}
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
switch component {
case Components.minutes, Components.seconds:
return (settingPickerView.frame.size.width * 0.4)
case Components.colon:
return (settingPickerView.frame.size.width * 0.2)
default:
return 1
}
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return viewForSettingPickerView.frame.size.height
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
guard pickerView.selectedRow(inComponent: Components.minutes) == minutes.firstIndex(of: "00") else { return }
guard let minValue = seconds.firstIndex(of: "05") else { return }
guard pickerView.selectedRow(inComponent: Components.seconds) < minValue else { return }
pickerView.selectRow(minValue, inComponent: Components.seconds, animated: true)
}
}
extension DurationSettingsViewController: UIPickerViewAccessibilityDelegate {
func pickerView(_ pickerView: UIPickerView, accessibilityLabelForComponent component: Int) -> String? {
switch component {
case Components.minutes:
return "minutes"
case Components.seconds:
return "seconds"
default:
return nil
}
}
}
<file_sep>/Timekeeper/Model/ClockSettings.swift
//
// ClockSettings.swift
// Timekeeper
//
// Created by <NAME> on 25/02/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
struct ClockSettings {
let workTimeDuration: Double
let shortBreakDuration: Double
let longBreakDuration: Double
let shortBreaksCount: Int
}
<file_sep>/TimekeeperTests/SoundSettingsViewControllerTests.swift
//
// SoundSettingsViewControllerTests.swift
// TimekeeperTests
//
// Created by <NAME> on 12/03/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import XCTest
@testable import Timekeeper
class SoundSettingsViewControllerTests: XCTestCase {
var coreData: TestCoreData!
var soundViewController: SoundSettingViewController!
override func setUp() {
super.setUp()
let storyboard = UIStoryboard(name: String.StoryboardIdentifiers.main.rawValue, bundle: Bundle.main)
soundViewController = storyboard.instantiateViewController(withIdentifier: String.StoryboardIdentifiers.soundSettingsViewControllerID.rawValue) as? SoundSettingViewController
coreData = TestCoreData(coreDataModelName: String.CoreData.dataModel.rawValue)
soundViewController.settings = Settings(context: coreData.managedObjectContext)
soundViewController.settings?.loadAllSettings()
soundViewController.detailsType = .alertSound
let _ = soundViewController.view
}
override func tearDown() {
coreData = nil
soundViewController = nil
super.tearDown()
}
func testLoadDataInController() {
let soundIndex = soundViewController.settingPickerView.selectedRow(inComponent: 0)
let soundRow = soundViewController.settingPickerView.view(forRow: soundIndex, forComponent: 0) as! UILabel
XCTAssertEqual(soundViewController.descriptionLabel.text, "Sound for alert")
XCTAssertEqual(soundRow.text, "Bell Sound Ring")
}
func testSaveDataAndLoadController() {
soundViewController.settingPickerView.selectRow(2, inComponent: 0, animated: false)
soundViewController.saveButtonPressed(soundViewController.saveButton)
XCTAssertEqual(soundViewController.settings?.soundSettings[0].settingString, "Japanese_Temple_Bell_Small")
soundViewController.loadSettingsAndView()
let soundIndex = soundViewController.settingPickerView.selectedRow(inComponent: 0)
let soundRow = soundViewController.settingPickerView.view(forRow: soundIndex, forComponent: 0) as! UILabel
XCTAssertEqual(soundViewController.descriptionLabel.text, "Sound for alert")
XCTAssertEqual(soundRow.text, "Japanese Temple Bell Small")
}
}
<file_sep>/Timekeeper/Model/ToDoListModelProtocol.swift
//
// ToDoListModelProtocol.swift
// Timekeeper
//
// Created by <NAME> on 17/02/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
protocol ToDoListModelProtocol {
mutating func addTask(description: String)
mutating func deleteTask(withID id: Int64)
mutating func taskIsDone(id: Int64)
func searchForTask(idNumber: Int64) -> Array<Task>.Index?
}
<file_sep>/TimekeeperUITests/MainViewUITests.swift
//
// MainViewUITests.swift
// TimekeeperUITests
//
// Created by <NAME> on 30/03/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import XCTest
class MainViewUITests: XCTestCase {
let app = XCUIApplication()
override func setUp() {
super.setUp()
continueAfterFailure = true
app.launchArguments = ["IS_RUNNING_UITEST"]
app.launch()
let mainViewElements = MainViewElements(app: app)
let toDoListElements = ToDoListElements(app: app, numberOfCells: 1)
mainViewElements.toDoListButton.tap()
toDoListElements.addingTasks()
toDoListElements.cells[0].tap()
}
override func tearDown() {
super.tearDown()
}
func testPauseButtonStopsPomodoroClockwork() {
let mainViewElements = MainViewElements(app: app)
let exp = expectation(description: "2 seconds passed")
let expPause = expectation(description: "2 seconds after pause passed")
mainViewElements.clockOnButton.tap()
XCTAssertEqual(mainViewElements.clockOnButton.label, "Pause")
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
exp.fulfill()
}
wait(for: [exp], timeout: 2)
mainViewElements.clockOnButton.tap()
XCTAssertEqual(mainViewElements.clockOnButton.label, "Continue")
XCTAssertEqual(mainViewElements.clockworkLabel.label, "00:03")
XCTAssertEqual(mainViewElements.breaksLabel.label, "Short Breaks: 0/2")
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
expPause.fulfill()
}
wait(for: [expPause], timeout: 2)
XCTAssertEqual(mainViewElements.clockOnButton.label, "Continue")
XCTAssertEqual(mainViewElements.clockworkLabel.label, "00:03")
XCTAssertEqual(mainViewElements.breaksLabel.label, "Short Breaks: 0/2")
}
func testPauseButtonStopsAndResumeClockwork() {
let mainViewElements = MainViewElements(app: app)
let exp = expectation(description: "1 seconds passed")
let expPause = expectation(description: "2 seconds of pause")
let expResume = expectation(description: "2 seconds after pause passed")
mainViewElements.clockOnButton.tap()
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
exp.fulfill()
}
wait(for: [exp], timeout: 1)
mainViewElements.clockOnButton.tap()
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
expPause.fulfill()
}
wait(for: [expPause], timeout: 2)
mainViewElements.clockOnButton.tap()
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
expResume.fulfill()
}
wait(for: [expResume], timeout: 2)
XCTAssertEqual(mainViewElements.clockOnButton.label, "Pause")
XCTAssertEqual(mainViewElements.clockworkLabel.label, "00:02")
XCTAssertEqual(mainViewElements.breaksLabel.label, "Short Breaks: 0/2")
}
func testPomodoroClockworkSwithToShortBreakAfterGivenTime() {
let mainViewElements = MainViewElements(app: app)
let exp = expectation(description: "One focus period passed")
mainViewElements.clockOnButton.tap()
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
exp.fulfill()
}
wait(for: [exp], timeout: 5)
XCTAssertEqual(mainViewElements.clockworkLabel.label, "00:06")
XCTAssertEqual(mainViewElements.breaksLabel.label, "Short Break")
}
func testPomodoroClockworkSwitchToFocusPhaseAfterShortBreak() {
let mainViewElements = MainViewElements(app: app)
let exp = expectation(description: "One focus period and one short break passed")
mainViewElements.clockOnButton.tap()
DispatchQueue.main.asyncAfter(deadline: .now() + 11) {
exp.fulfill()
}
wait(for: [exp], timeout: 11)
XCTAssertEqual(mainViewElements.clockworkLabel.label, "00:05")
XCTAssertEqual(mainViewElements.breaksLabel.label, "Short Breaks: 1/2")
}
func testPomodoroClockworkSwitchToLongBreakAfterGivenAmountOfShortBreaks() {
let mainViewElements = MainViewElements(app: app)
let exp = expectation(description: "Three focus periods and two short breaks passed")
mainViewElements.clockOnButton.tap()
DispatchQueue.main.asyncAfter(deadline: .now() + 27) {
exp.fulfill()
}
wait(for: [exp], timeout: 27)
XCTAssertEqual(mainViewElements.clockworkLabel.label, "00:07")
XCTAssertEqual(mainViewElements.breaksLabel.label, "Long Break")
}
func testPomodoroClockworkSwitchToWorkTimeAfterLongBreak() {
let mainViewElements = MainViewElements(app: app)
let exp = expectation(description: "Three focus periods, two short breaks and one long break passed")
mainViewElements.clockOnButton.tap()
DispatchQueue.main.asyncAfter(deadline: .now() + 34) {
exp.fulfill()
}
wait(for: [exp], timeout: 34)
XCTAssertEqual(mainViewElements.clockworkLabel.label, "00:05")
XCTAssertEqual(mainViewElements.breaksLabel.label, "Short Breaks: 0/2")
}
func testPomodoroCLockworkSwitchToShortBreakAfterOneLongBreakAndWorkTime() {
let mainViewElements = MainViewElements(app: app)
let exp = expectation(description: "Four focus periods, two short breaks, one long break passed")
mainViewElements.clockOnButton.tap()
DispatchQueue.main.asyncAfter(deadline: .now() + 39) {
exp.fulfill()
}
wait(for: [exp], timeout: 39)
XCTAssertEqual(mainViewElements.clockworkLabel.label, "00:06")
XCTAssertEqual(mainViewElements.breaksLabel.label, "Short Break")
}
func testPomodoroClockworkWorksInAllPhases() {
let mainViewElements = MainViewElements(app: app)
let exp1FocusTime = expectation(description: "First focus time passed")
let exp1shortBreak = expectation(description: "First short break passed")
let exp2FocusTime = expectation(description: "Second focus time passed")
let exp2shortBreak = expectation(description: "Second short break passed")
let exp3FocusTime = expectation(description: "Third focus time passed")
let expLongBreak = expectation(description: "Long break passed")
mainViewElements.clockOnButton.tap()
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
exp1FocusTime.fulfill()
}
wait(for: [exp1FocusTime], timeout: 5)
XCTAssertEqual(mainViewElements.clockworkLabel.label, "00:06")
XCTAssertEqual(mainViewElements.breaksLabel.label, "Short Break")
DispatchQueue.main.asyncAfter(deadline: .now() + 6) {
exp1shortBreak.fulfill()
}
wait(for: [exp1shortBreak], timeout: 6)
XCTAssertEqual(mainViewElements.clockworkLabel.label, "00:05")
XCTAssertEqual(mainViewElements.breaksLabel.label, "Short Breaks: 1/2")
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
exp2FocusTime.fulfill()
}
wait(for: [exp2FocusTime], timeout: 5)
XCTAssertEqual(mainViewElements.clockworkLabel.label, "00:06")
XCTAssertEqual(mainViewElements.breaksLabel.label, "Short Break")
DispatchQueue.main.asyncAfter(deadline: .now() + 6) {
exp2shortBreak.fulfill()
}
wait(for: [exp2shortBreak], timeout: 6)
XCTAssertEqual(mainViewElements.clockworkLabel.label, "00:05")
XCTAssertEqual(mainViewElements.breaksLabel.label, "Short Breaks: 2/2")
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
exp3FocusTime.fulfill()
}
wait(for: [exp3FocusTime], timeout: 5)
XCTAssertEqual(mainViewElements.clockworkLabel.label, "00:07")
XCTAssertEqual(mainViewElements.breaksLabel.label, "Long Break")
DispatchQueue.main.asyncAfter(deadline: .now() + 7) {
expLongBreak.fulfill()
}
wait(for: [expLongBreak], timeout: 7)
XCTAssertEqual(mainViewElements.clockworkLabel.label, "00:05")
XCTAssertEqual(mainViewElements.breaksLabel.label, "Short Breaks: 0/2")
}
}
<file_sep>/Timekeeper/Protocols/SettingsDetailsInterface.swift
//
// SettingsDetailsInterface.swift
// Timekeeper
//
// Created by <NAME> on 09/03/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
protocol SettingsDetailsInterface {
var detailsType: SettingsDetailsType? { get set }
var settings: Settings? { get set }
var delegate: SettingsUpdateDelegate? { get set }
}
<file_sep>/Timekeeper/Model/SettingsDetailsType.swift
//
// SettingsDetailsType.swift
// Timekeeper
//
// Created by <NAME> on 09/03/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
enum SettingsDetailsType: Int {
case focusTime
case shortBreak
case longBreak
case shortBreaksNumber
case alertSound
case credits
}
<file_sep>/Timekeeper/Controller/ToDoListTableViewController.swift
//
// ToDoListTableViewController.swift
// Timekeeper
//
// Created by <NAME> on 11/01/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class ToDoListTableViewController: UITableViewController {
var toDoList: ToDoList?
weak var mainViewContentUpdateDelegate: MainViewContentUpdateDelegate?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = String.toDoListTitle
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(showAlertForTaskAdding))
navigationController?.delegate = self
setupToDoList()
toDoList?.loadToDoList()
}
fileprivate func setupToDoList() {
if toDoList == nil {
toDoList = ToDoList()
}
}
@objc func showAlertForTaskAdding() {
let ac = UIAlertController(title: String.addTask, message: nil, preferredStyle: .alert)
ac.addTextField()
ac.addAction(UIAlertAction(title: String.add, style: .default) {
[weak self, weak ac] _ in
guard let taskDescription = ac?.textFields?[0].text else { return }
self?.toDoList?.addTask(description: taskDescription)
guard let row = self?.toDoList?.tasks.count else { return }
let indexPath = IndexPath(row: row - 1, section: 0)
self?.tableView.insertRows(at: [indexPath], with: .automatic)
})
ac.addAction(UIAlertAction(title: String.cancel, style: .cancel))
present(ac, animated: true)
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let numberOfRows = toDoList?.tasks.count else { return 0 }
return numberOfRows
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String.StoryboardIdentifiers.toDoListCell.rawValue, for: indexPath)
guard let task = toDoList?.tasks[indexPath.row] else { return cell }
cell.accessibilityIdentifier = "TaskCell_\(indexPath.row)"
cell.textLabel?.text = task.descriptionOfTask
cell.accessoryType = task.isDone ? .checkmark : .none
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let taskIdentifier = toDoList?.tasks[indexPath.row].identifier else { return }
mainViewContentUpdateDelegate?.updateTaskLabel(with: taskIdentifier)
navigationController?.popViewController(animated: true)
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let position = indexPath.row
guard let id = toDoList?.tasks[position].identifier else { return }
toDoList?.deleteTask(withID: id)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
}
extension ToDoListTableViewController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
guard let mainVC = viewController as? MainViewController else { return }
if toDoList?.searchForTask(idNumber: mainVC.taskIdentifier) == nil {
mainViewContentUpdateDelegate?.updateTaskLabel(with: 0)
}
}
}
<file_sep>/Timekeeper/Model/Settings.swift
//
// ClockworkSettings.swift
// Timekeeper
//
// Created by <NAME> on 28/01/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import CoreData
import UIKit
class Settings {
init(context: NSManagedObjectContext = (UIApplication.shared.delegate as! AppDelegate).coreDataStack.managedObjectContext) {
self.context = context
}
private let context: NSManagedObjectContext
var durationSettings = [ClockworkSettings]()
var breaksNumberSettings = [ClockworkSettings]()
var soundSettings = [ClockworkSettings]()
var anotherInformations = [ClockworkSettings]()
var clockworkConfigurations: [Int:[ClockworkSettings]] = [:]
private func addDefaultSettings() {
guard durationSettings.isEmpty && breaksNumberSettings.isEmpty && soundSettings.isEmpty && anotherInformations.isEmpty else { return }
let shortBreaksLimit = provideDefaults(
withID: SettingsDetailsType.shortBreaksNumber.rawValue,
of: "Number of short breaks",
withAmount: 3,
withString: nil)
breaksNumberSettings.append(contentsOf: [shortBreaksLimit])
let longBreakDuration = provideDefaults(
withID: SettingsDetailsType.longBreak.rawValue,
of: "Duration of long break",
withAmount: 1200,
withString: nil)
let shortBreakDuration = provideDefaults(
withID: SettingsDetailsType.shortBreak.rawValue,
of: "Duration of short break",
withAmount: 300,
withString: nil)
let workTimeDuration = provideDefaults(
withID: SettingsDetailsType.focusTime.rawValue,
of: "Duration of focus time",
withAmount: 1500,
withString: nil)
durationSettings.append(contentsOf: [workTimeDuration, shortBreakDuration, longBreakDuration])
let soundForAlert = provideDefaults(
withID: SettingsDetailsType.alertSound.rawValue,
of: "Sound for alert",
withAmount: nil,
withString: "Bell_Sound_Ring")
soundSettings.append(soundForAlert)
let creditsInformation = provideDefaults(
withID: SettingsDetailsType.credits.rawValue,
of: "Credits",
withAmount: nil,
withString: """
Timekeeper
Created by <NAME> on 28/01/2020.
Copyright © 2020 <NAME>. All rights reserved.
In this project were used:
iOS CircleProgressView - Copyright Cardinal Solutions 2013. Licensed under the MIT license.
sounds:
Bell Sound Ring - Mike Koenig
Japanese Temple Small Bell - Mike Koenig
Ship Bell - Mike Koenig
Front Desk Bells - <NAME>
""")
anotherInformations.append(creditsInformation)
buildClockworkConfiguration()
saveSettings()
}
private func provideDefaults(withID id: Int, of description: String, withAmount amount: Double?, withString string: String?) -> ClockworkSettings {
let clockworkSettings = ClockworkSettings(context: context)
clockworkSettings.descriptionOfSetting = description
clockworkSettings.id = Int32(id)
if let providedAmount = amount {
clockworkSettings.amount = providedAmount
}
if let providedString = string {
clockworkSettings.settingString = providedString
}
return clockworkSettings
}
// MARK: - Model Manipulation Methods
private func saveSettings() {
do {
try context.save()
} catch {
print("Error saving context \(error)")
}
}
func save(_ newValue: Any, for setting: ClockworkSettings, of type: SettingsDetailsType) {
switch type {
case .focusTime, .longBreak, .shortBreak, .shortBreaksNumber:
guard let valueToSave = newValue as? Double else { return }
setting.setValue(valueToSave, forKey: String.CoreData.amountKey.rawValue)
case .alertSound:
guard let valueToSave = newValue as? String else { return }
setting.setValue(valueToSave, forKey: String.CoreData.settingStringKey.rawValue)
case .credits:
return
}
saveSettings()
}
func loadSpecificSetting(for type: SettingsDetailsType) throws -> [ClockworkSettings] {
let request: NSFetchRequest<ClockworkSettings> = ClockworkSettings.fetchRequest()
let predicate = NSPredicate(format: "id == %d", type.rawValue)
request.predicate = predicate
return try context.fetch(request)
}
func loadAllSettings() {
let settingsTypes: [SettingsDetailsType] = [.focusTime, .shortBreak, .longBreak]
let requestDuration = makeFetchRequest(with: settingsTypes.map { $0.rawValue })
let requestNumberOfBreaks = makeFetchRequest(with: [SettingsDetailsType.shortBreaksNumber.rawValue])
let requestSound = makeFetchRequest(with: [SettingsDetailsType.alertSound.rawValue])
let requestAnotherInformations = makeFetchRequest(with: [SettingsDetailsType.credits.rawValue])
do {
durationSettings = try context.fetch(requestDuration)
breaksNumberSettings = try context.fetch(requestNumberOfBreaks)
soundSettings = try context.fetch(requestSound)
anotherInformations = try context.fetch(requestAnotherInformations)
} catch {
print("Error fetching data \(error)")
}
buildClockworkConfiguration()
addDefaultSettings()
}
private func buildClockworkConfiguration() {
clockworkConfigurations = [
0: durationSettings,
1: breaksNumberSettings,
2: soundSettings,
3: anotherInformations
]
}
private func makeFetchRequest(with identifiers: [Int]) -> NSFetchRequest<ClockworkSettings> {
let request : NSFetchRequest<ClockworkSettings> = ClockworkSettings.fetchRequest()
let predicates: [NSPredicate] = identifiers.map { NSPredicate(format: "id == %d", $0) }
let compoundPredicate = NSCompoundPredicate(type: .or, subpredicates: predicates)
let sortDescriptor = NSSortDescriptor(key: String.CoreData.idKey.rawValue, ascending: true)
request.predicate = compoundPredicate
request.sortDescriptors = [sortDescriptor]
return request
}
}
<file_sep>/Timekeeper/AppDelegate.swift
//
// AppDelegate.swift
// Timekeeper
//
// Created by <NAME> on 09/01/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var coreDataStack: CoreDataStack = {
var coreDataStack: CoreDataStack
if CommandLine.arguments.contains("IS_RUNNING_UITEST") {
coreDataStack = TestCoreData(coreDataModelName: String.CoreData.dataModel.rawValue)
} else {
coreDataStack = CoreDataStack(coreDataModelName: String.CoreData.dataModel.rawValue)
}
return coreDataStack
}()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if CommandLine.arguments.contains("IS_RUNNING_UITEST") {
let settings = Settings()
settings.loadAllSettings()
settings.save(5.0, for: settings.durationSettings[0], of: .focusTime)
settings.save(6.0, for: settings.durationSettings[1], of: .shortBreak)
settings.save(7.0, for: settings.durationSettings[2], of: .longBreak)
settings.save(2.0, for: settings.breaksNumberSettings[0], of: .shortBreaksNumber)
}
return true
}
func applicationWillTerminate(_ application: UIApplication) {
coreDataStack.saveContext()
}
}
<file_sep>/TimekeeperTests/PomodoroClockworkTest.swift
//
// ClockworkTest.swift
// TimekeeperTests
//
// Created by <NAME> on 26/02/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import XCTest
@testable import Timekeeper
class PomodoroClockworkTest: XCTestCase {
var sut: PomodoroClockwork!
override func setUp() {
super.setUp()
sut = PomodoroClockwork(
settings: ClockSettings(
workTimeDuration: 1,
shortBreakDuration: 1,
longBreakDuration: 2,
shortBreaksCount: 2)
)
}
override func tearDown() {
sut = nil
super.tearDown()
}
func testPauseMethodWorksProperrly() {
let exp = expectation(description: "It's 1 second later")
sut.start()
sut.pause()
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
exp.fulfill()
})
wait(for: [exp], timeout: 2)
XCTAssertEqual(sut.currentPhase, PomodoroPhases.work)
}
func testTerminateMethodWorksProperrly() {
let exp = expectation(description: "It's 1 seconds later")
sut.start()
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
exp.fulfill()
})
wait(for: [exp], timeout: 2)
sut.terminate()
XCTAssertEqual(sut.currentPhase, PomodoroPhases.work)
XCTAssertEqual(sut.currentPhaseTime, "00:00")
}
func testResumeMethodWorksProperrly() {
let exp = expectation(description: "It's 1 second later")
sut.start()
sut.pause()
sut.start()
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
exp.fulfill()
})
wait(for: [exp], timeout: 2)
XCTAssertEqual(sut.currentPhase, PomodoroPhases.shortBreak)
}
func testSwitchToShortBreakAfterGivenTime() {
let exp = expectation(description: "It's 1 second later")
sut.start()
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
exp.fulfill()
})
wait(for: [exp], timeout: 2)
XCTAssertEqual(sut.currentPhase, PomodoroPhases.shortBreak)
XCTAssertEqual(sut.currentPhaseTime, "00:00")
}
func testSwitchToWorkTimeAfterShortBreak() {
let exp = expectation(description: "It's 2 seconds later.")
sut.start()
DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
exp.fulfill()
})
wait(for: [exp], timeout: 3)
XCTAssertEqual(sut.currentPhase, PomodoroPhases.work)
XCTAssertEqual(sut.currentPhaseTime, "00:00")
}
func testSwitchToLongBreakAfterGivenNumberOfShortBreaks() {
let exp = expectation(description: "It's 5 seconds later.")
sut.start()
DispatchQueue.main.asyncAfter(deadline: .now() + 5, execute: {
exp.fulfill()
})
wait(for: [exp], timeout: 6)
XCTAssertEqual(sut.currentPhase, PomodoroPhases.longBreak)
XCTAssertEqual(sut.currentPhaseTime, "00:00")
}
func testSwitchToWorkTimeAfterLongBreak() {
let exp = expectation(description: "It's 7 seconds later.")
sut.start()
DispatchQueue.main.asyncAfter(deadline: .now() + 7, execute: {
exp.fulfill()
})
wait(for: [exp], timeout: 8)
XCTAssertEqual(sut.currentPhase, PomodoroPhases.work)
XCTAssertEqual(sut.currentPhaseTime, "00:00")
}
func testSwitchToShortBreakAfterOneLongBreakAndWorkTime() {
let exp = expectation(description: "It's 8 seconds later")
sut.start()
DispatchQueue.main.asyncAfter(deadline: .now() + 8, execute: {
exp.fulfill()
})
wait(for: [exp], timeout: 9)
XCTAssertEqual(sut.currentPhase, PomodoroPhases.shortBreak)
XCTAssertEqual(sut.currentPhaseTime, "00:00")
}
/*
- pomodoro switches between work and break phases, defined by provided settings, based on passed time
1. test if pomodoro switches to short break if defined work time ends
2. test if pomodoro switches to work if defined short break time ends
3. test if pomodoro switches to long break if defined number of short breaks ends
4. test if pomodoro switches to work if defined long break time ends
5. test if pomodoro switches to short break if defined work time after long break ends
*/
}
<file_sep>/Timekeeper/Extensions/DateComponentsFormatter+Extension.swift
//
// DateComponentsFormatter+Extension.swift
// Timekeeper
//
// Created by <NAME> on 07/03/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
extension DateComponentsFormatter {
func clockFormat(from value: TimeInterval) -> String? {
guard let string = self.string(from: value) else { return nil }
let substrings = string.split(separator: ":")
var clockFormatParts = [String]()
for substring in substrings {
if substring.count == 1 {
let element = "0" + substring
clockFormatParts.append(element)
} else {
clockFormatParts.append(String(substring))
}
}
return clockFormatParts.joined(separator: ":")
}
}
<file_sep>/Timekeeper/Extensions/String+Extension.swift
//
// String+Extension.swift
// Timekeeper
//
// Created by <NAME> on 24/02/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
extension String {
static var timeSixty: [String] {
return (0..<60).map { String(format: "%02d", $0) }
}
static var breaksAmount: [String] {
return (1..<10).map { String($0) }
}
static var sounds: [String] {
return ["Bell Sound Ring", "Front Desk Bells", "Japanese Temple Bell Small", "Ship Bell"]
}
enum StoryboardIdentifiers: String {
case main = "Main"
case segueOpenDurationSettings = "OpenDurationSettings"
case segueOpenBreaksAmountSettings = "OpenBreakAmountSettings"
case segueOpenSoundSettings = "OpenSoundSettings"
case segueOpenCredits = "OpenCredits"
case segueShowToDoList = "showToDoList"
case segueShowSettings = "showSettings"
case toDoListCell = "Task Cell"
case settingCell = "Setting Cell"
case toDoListTableViewControllerID = "ToDoListTableViewControllerID"
case settingsTableViewControllerID =
"SettingsTableViewControllerID"
case durationSettingsViewControllerID =
"DurationSettingsViewControllerID"
case breaksAmountSettingsViewControllerID =
"BreaksAmountSettingsViewControllerID"
case soundSettingsViewControllerID =
"SoundSettingsViewControllerID"
}
enum CoreData: String {
case dataModel = "DataModel"
case amountKey = "amount"
case descriptionOfSettingKey = "descriptionOfSetting"
case idKey = "id"
case settingStringKey = "settingString"
}
static let resume = "Continue"
static let start = "Start"
static let pause = "Pause"
static let finishText = "All your tasks are complete!"
static let welcomeText = "Choose task from To-do list"
static let toDoListTitle = "Your To-do List"
static let addTask = "Add task"
static let add = "Add"
static let cancel = "Cancel"
}
<file_sep>/TimekeeperUITests/Controls.swift
//
// Controls.swift
// TimekeeperUITests
//
// Created by <NAME> on 21/03/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
struct Controls {
struct Buttons {
static var ok: String = "OK"
static var toDoList: String = "To-Do List"
static var add: String = "Add"
static var cancel: String = "Cancel"
static var finishTask: String = "Finish Task"
static var start: String = "pauseButton"
static var delete: String = "Delete"
static var settings: String = "Settings"
static var save: String = "Save"
static var back: String = "Back"
static var playSound: String = "Play sound"
}
struct NavigationBars {
static var yourToDoList = "Your To-do List"
}
struct Alerts {
static var addTask = "Add task"
static var notMuchTime = "Not much time"
}
struct Tables {
static var emptyList = "Empty list"
}
struct SettingsCells {
static var FocusTimeDuration = "Duration of focus time"
static var shortBreakDuration = "Duration of short break"
static var longBreakDuration = "Duration of long break"
static var shortBreaksAmount = "Number of short breaks"
static var alertSound = "Sound for alert"
}
struct PickerComponents {
static var minutes = "minutes"
static var seconds = "seconds"
}
struct Labels {
static var clockworkLabel = "clockworkLabel"
static var breaksLabel = "breaksLabel"
}
}
<file_sep>/TimekeeperUITests/SettingsUITests.swift
//
// SettingsUITests.swift
// TimekeeperUITests
//
// Created by <NAME> on 21/03/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import XCTest
@testable import Timekeeper
class SettingsUITests: XCTestCase {
let app = XCUIApplication()
override func setUp() {
super.setUp()
app.launchArguments = ["IS_RUNNING_UITEST"]
app.launch()
continueAfterFailure = true
}
override func tearDown() {
super.tearDown()
}
func testSettingsChanges_UpdatesMainViewWhenClockDoesntWorking() {
let settingsElements = SettingsElements(app: app)
let mainViewElements = MainViewElements(app: app)
mainViewElements.settingsButton.tap()
settingsElements.settingCells.focusTime.element.tap()
let minutesValue = settingsElements.minutesComponent.value as! String
let secondsValue = settingsElements.secondsComponent.value as! String
XCTAssertEqual(app.staticTexts.firstMatch.label,
Controls.SettingsCells.FocusTimeDuration)
XCTAssertEqual(minutesValue, "00")
XCTAssertEqual(secondsValue, "05")
settingsElements.minutesComponent.adjust(toPickerWheelValue: "01")
settingsElements.secondsComponent.adjust(toPickerWheelValue: "05")
settingsElements.saveButton.tap()
XCTAssertTrue(settingsElements.settingCells.focusTime.staticTexts["01:05"].exists)
settingsElements.settingCells.shortBreaksAmount.element.tap()
let breaksValue = settingsElements.settingPickerView.pickerWheels.firstMatch.value as! String
XCTAssertEqual(app.staticTexts.firstMatch.label,
Controls.SettingsCells.shortBreaksAmount)
XCTAssertEqual(breaksValue, "2")
settingsElements.component.adjust(toPickerWheelValue: "7")
settingsElements.saveButton.tap()
XCTAssertTrue(settingsElements.settingCells.shortBreaksAmount.staticTexts["7"].exists)
settingsElements.backButton.tap()
XCTAssertEqual(mainViewElements.clockworkLabel.label, "01:05")
XCTAssertEqual(mainViewElements.breaksLabel.label, "Short Breaks: 0/7")
}
func testSoundSettings() {
let settingsElements = SettingsElements(app: app)
let mainViewElements = MainViewElements(app: app)
mainViewElements.settingsButton.tap()
settingsElements.settingCells.alertSound.element.tap()
let soundDefaultValue = settingsElements.component.value as! String
XCTAssertEqual(app.staticTexts.firstMatch.label, Controls.SettingsCells.alertSound)
XCTAssertEqual(soundDefaultValue, "Bell Sound Ring")
XCTAssertTrue(app.buttons[Controls.Buttons.playSound].isEnabled)
settingsElements.playButton.tap()
XCTAssertFalse(app.buttons[Controls.Buttons.playSound].isEnabled)
sleep(4)
XCTAssertTrue(app.buttons[Controls.Buttons.playSound].isEnabled)
settingsElements.component.adjust(toPickerWheelValue: "Japanese Temple Bell Small")
settingsElements.playButton.tap()
sleep(4)
settingsElements.saveButton.tap()
settingsElements.settingCells.alertSound.element.tap()
let soundValue = settingsElements.component.value as! String
XCTAssertEqual(soundValue, "Japanese Temple Bell Small")
settingsElements.playButton.tap()
sleep(4)
}
func testForceUserChooseMinimalValue() {
let settingsElements = SettingsElements(app: app)
app.buttons[Controls.Buttons.settings].tap()
provideValueLessThanMinimalValue(for: settingsElements.settingCells.focusTime.element, of: settingsElements)
XCTAssertFalse(settingsElements.settingCells.focusTime.staticTexts["00:00"].exists)
XCTAssertTrue(settingsElements.settingCells.focusTime.staticTexts["00:05"].exists)
provideValueLessThanMinimalValue(for: settingsElements.settingCells.shortBreakTime.element, of: settingsElements)
XCTAssertFalse(settingsElements.settingCells.shortBreakTime.staticTexts["00:00"].exists)
XCTAssertTrue(settingsElements.settingCells.shortBreakTime.staticTexts["00:05"].exists )
provideValueLessThanMinimalValue(for: settingsElements.settingCells.longBreakTime.element, of: settingsElements)
XCTAssertFalse(settingsElements.settingCells.longBreakTime.staticTexts["00:00"].exists)
XCTAssertTrue(settingsElements.settingCells.longBreakTime.staticTexts["00:05"].exists)
}
func testSettingsChanges_ClockWorksUsingGivenChanges() {
let settingsElements = SettingsElements(app: app)
let mainViewElements = MainViewElements(app: app)
let toDoListElements = ToDoListElements(app: app, numberOfCells: 1)
let exp1FocusTime = expectation(description: "First focus time passed")
let exp1shortBreak = expectation(description: "First short break passed")
let exp2FocusTime = expectation(description: "Second focus time passed")
let exp2shortBreak = expectation(description: "Second short break passed")
let exp3FocusTime = expectation(description: "Third focus time passed")
mainViewElements.settingsButton.tap()
settingsElements.changeSettings(for: settingsElements.settingCells.focusTime.element, of: settingsElements, withMinutes: "00", andSeconds: "10", or: nil)
settingsElements.changeSettings(for: settingsElements.settingCells.shortBreakTime.element, of: settingsElements, withMinutes: "00", andSeconds: "06", or: nil)
settingsElements.changeSettings(for: settingsElements.settingCells.longBreakTime.element, of: settingsElements, withMinutes: "00", andSeconds: "07", or: nil)
settingsElements.changeSettings(for: settingsElements.settingCells.shortBreaksAmount.element, of: settingsElements, withMinutes: nil, andSeconds: nil, or: "2")
settingsElements.backButton.tap()
mainViewElements.toDoListButton.tap()
toDoListElements.addTask(name: "test")
toDoListElements.cells[0].tap()
mainViewElements.clockOnButton.tap()
DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
exp1FocusTime.fulfill()
}
wait(for: [exp1FocusTime], timeout: 10)
XCTAssertEqual(mainViewElements.clockworkLabel.label, "00:06")
XCTAssertEqual(mainViewElements.breaksLabel.label, "Short Break")
DispatchQueue.main.asyncAfter(deadline: .now() + 6) {
exp1shortBreak.fulfill()
}
wait(for: [exp1shortBreak], timeout: 6)
XCTAssertEqual(mainViewElements.clockworkLabel.label, "00:10")
XCTAssertEqual(mainViewElements.breaksLabel.label, "Short Breaks: 1/2")
DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
exp2FocusTime.fulfill()
}
wait(for: [exp2FocusTime], timeout: 10)
XCTAssertEqual(mainViewElements.clockworkLabel.label, "00:06")
XCTAssertEqual(mainViewElements.breaksLabel.label, "Short Break")
DispatchQueue.main.asyncAfter(deadline: .now() + 6) {
exp2shortBreak.fulfill()
}
wait(for: [exp2shortBreak], timeout: 7)
XCTAssertEqual(mainViewElements.clockworkLabel.label, "00:10")
XCTAssertEqual(mainViewElements.breaksLabel.label, "Short Breaks: 2/2")
DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
exp3FocusTime.fulfill()
}
wait(for: [exp3FocusTime], timeout: 10)
XCTAssertEqual(mainViewElements.clockworkLabel.label, "00:07")
XCTAssertEqual(mainViewElements.breaksLabel.label, "Long Break")
}
private func provideValueLessThanMinimalValue(for element: XCUIElement, of settingsElements: SettingsElements) {
element.tap()
settingsElements.minutesComponent.adjust(toPickerWheelValue: "00")
settingsElements.secondsComponent.adjust(toPickerWheelValue: "00")
let minutesValue = settingsElements.minutesComponent.value as! String
let secondsValue = settingsElements.secondsComponent.value as! String
XCTAssertEqual(minutesValue, "00")
XCTAssertEqual(secondsValue, "05")
settingsElements.saveButton.tap()
}
}
<file_sep>/TimekeeperTests/DurationSettingsViewControllerTests.swift
//
// DurationSettingsViewControllerTests.swift
// TimekeeperTests
//
// Created by <NAME> on 09/03/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import XCTest
@testable import Timekeeper
class DurationSettingsViewControllerTests: XCTestCase {
var coreData: TestCoreData!
var durationViewController: DurationSettingsViewController!
override func setUp() {
super.setUp()
let storyboard = UIStoryboard(name: String.StoryboardIdentifiers.main.rawValue, bundle: Bundle.main)
durationViewController = storyboard.instantiateViewController(withIdentifier: String.StoryboardIdentifiers.durationSettingsViewControllerID.rawValue) as? DurationSettingsViewController
coreData = TestCoreData(coreDataModelName: String.CoreData.dataModel.rawValue)
durationViewController.settings = Settings(context: coreData.managedObjectContext)
durationViewController.settings?.loadAllSettings()
let _ = durationViewController.view
}
override func tearDown() {
coreData = nil
durationViewController = nil
super.tearDown()
}
func testShortBreakInitialForPickerView() {
durationViewController.detailsType = .shortBreak
durationViewController.loadSettingsAndView()
XCTAssertEqual(durationViewController.descriptionLabel.text, "Duration of short break")
XCTAssertEqual(durationViewController.settingPickerView.selectedRow(inComponent: 0), 0)
XCTAssertEqual(durationViewController.settingPickerView.selectedRow(inComponent: 2), 5)
}
func testFocusTimeInitialValueForPickerView() {
durationViewController.detailsType = .focusTime
durationViewController.loadSettingsAndView()
XCTAssertEqual(durationViewController.descriptionLabel.text, "Duration of focus time")
XCTAssertEqual(durationViewController.settingPickerView.selectedRow(inComponent: 0), 0)
XCTAssertEqual(durationViewController.settingPickerView.selectedRow(inComponent: 2), 25)
}
func testLongBreakInitialValueForPickerView() {
durationViewController.detailsType = .longBreak
durationViewController.loadSettingsAndView()
XCTAssertEqual(durationViewController.descriptionLabel.text, "Duration of long break")
XCTAssertEqual(durationViewController.settingPickerView.selectedRow(inComponent: 0), 0)
XCTAssertEqual(durationViewController.settingPickerView.selectedRow(inComponent: 2), 20)
}
func testSaveFocusTimeSettings() {
durationViewController.detailsType = .focusTime
durationViewController.loadSettingsAndView()
durationViewController.settingPickerView.selectRow(10, inComponent: 0, animated: false)
durationViewController.settingPickerView.selectRow(0, inComponent: 2, animated: false)
durationViewController.saveButtonPressed(durationViewController.saveButton)
XCTAssertEqual(durationViewController.settings?.durationSettings[0].amount, 600.0)
}
func testSaveShortBreakSettings() {
durationViewController.detailsType = .shortBreak
durationViewController.loadSettingsAndView()
durationViewController.settingPickerView.selectRow(8, inComponent: 0, animated: false)
durationViewController.settingPickerView.selectRow(20, inComponent: 2, animated: false)
durationViewController.saveButtonPressed(durationViewController.saveButton)
XCTAssertEqual(durationViewController.settings?.durationSettings[1].amount, 500.0)
}
func testSaveLongBreakSettings() {
durationViewController.detailsType = .longBreak
durationViewController.loadSettingsAndView()
durationViewController.settingPickerView.selectRow(1, inComponent: 0, animated: false)
durationViewController.settingPickerView.selectRow(0, inComponent: 2, animated: false)
durationViewController.saveButtonPressed(durationViewController.saveButton)
XCTAssertEqual(durationViewController.settings?.durationSettings[2].amount, 60.0)
}
func testSaveMaxFocusTimeSettings() {
durationViewController.detailsType = .focusTime
durationViewController.loadSettingsAndView()
durationViewController.settingPickerView.selectRow(0, inComponent: 0, animated: false)
durationViewController.settingPickerView.selectRow(59, inComponent: 2, animated: false)
durationViewController.saveButtonPressed(durationViewController.saveButton)
XCTAssertEqual(durationViewController.settings?.durationSettings[0].amount, 59.0)
}
}
<file_sep>/TimekeeperTests/BreaksAmountViewControllerTests.swift
//
// BreaksAmountViewControllerTests.swift
// TimekeeperTests
//
// Created by <NAME> on 12/03/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import XCTest
@testable import Timekeeper
class BreaksAmountViewControllerTests: XCTestCase {
var coreData: TestCoreData!
var amountViewController: BreaksAmountSettingViewController!
override func setUp() {
super.setUp()
let storyboard = UIStoryboard(name: String.StoryboardIdentifiers.main.rawValue, bundle: Bundle.main)
amountViewController = storyboard.instantiateViewController(withIdentifier: String.StoryboardIdentifiers.breaksAmountSettingsViewControllerID.rawValue) as? BreaksAmountSettingViewController
coreData = TestCoreData(coreDataModelName: String.CoreData.dataModel.rawValue)
amountViewController.settings = Settings(context: coreData.managedObjectContext)
amountViewController.settings?.loadAllSettings()
amountViewController.detailsType = .shortBreaksNumber
let _ = amountViewController.view
}
override func tearDown() {
coreData = nil
amountViewController = nil
super.tearDown()
}
func testLoadValue() {
XCTAssertEqual(amountViewController.descriptionLabel.text, "Number of short breaks")
XCTAssertEqual(amountViewController.settingPickerView.selectedRow(inComponent: 0), 2)
}
func testSave() {
amountViewController.settingPickerView.selectRow(8, inComponent: 0, animated: false)
amountViewController.saveButtonPressed(amountViewController.saveButton)
XCTAssertEqual(amountViewController.settings?.breaksNumberSettings[0].amount, 9.0)
amountViewController.settingPickerView.selectRow(0, inComponent: 0, animated: false)
amountViewController.saveButtonPressed(amountViewController.saveButton)
XCTAssertEqual(amountViewController.settings?.breaksNumberSettings[0].amount, 1.0)
}
}
<file_sep>/README.md
# Timekeeper
Timekeeper has Pomodoro timer and to-do list in one app. This project was created with Swift for iOS 13.5.
## Technologies
* Swift 5
* UIKit
* XCTest (unit and UI tests)
* AVFoundation
* Storyboards
* Core Data
## Launch
To run this app you need clone this project and open it in Xcode. You have to open file with .xcworkspace extension.
## Third Party Libraries used in project
CircleProgressView by Cardinal Solutions (link to repo: https://github.com/CardinalNow/iOS-CircleProgressView )
## Other Informations
Repository includes short video presentation of app
### Sounds used in project
* Bell Sound Ring - <NAME>
* Front Desk Bells - <NAME>
* Japanese Temple Small Bell - <NAME>
* Ship Bell - <NAME>
<file_sep>/Timekeeper/Managers/CoreDataStack.swift
//
// CoreDataManager.swift
// Timekeeper
//
// Created by <NAME> on 13/02/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
import CoreData
class CoreDataStack {
let modelName: String
init(coreDataModelName: String) {
self.modelName = coreDataModelName
}
private(set) lazy var managedObjectContext: NSManagedObjectContext = {
let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator
return managedObjectContext
}()
lazy var managedObjectModel: NSManagedObjectModel = {
guard let modelURL = Bundle.main.url(forResource: modelName, withExtension: "momd") else {
fatalError("Unable to find Data Model")
}
guard let managedObjectModel = NSManagedObjectModel(contentsOf: modelURL) else {
fatalError("Unable to load Data Model")
}
return managedObjectModel
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let fileManager = FileManager.default
let storeName = "\(self.modelName).sqlite"
let documentsDirectoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let persistentStoreURL = documentsDirectoryURL.appendingPathComponent(storeName)
do {
try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: persistentStoreURL, options: nil)
} catch {
fatalError("Unable to Load Persistent Store. Fail in adding Persistent Store at Documents Directory by Persistent Store Coordinatior")
}
return persistentStoreCoordinator
}()
func saveContext () {
let context = self.managedObjectContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
<file_sep>/Timekeeper/Controller/MainViewController.swift
//
// ViewController.swift
// Timekeeper
//
// Created by <NAME> on 09/01/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import CircleProgressView
import AVFoundation
class MainViewController: UIViewController {
@IBOutlet var toDoListButton: UIButton!
@IBOutlet var circleProgressView: CircleProgressView!
@IBOutlet var clockworkLabel: UILabel!
@IBOutlet var breaksLabel: UILabel!
@IBOutlet var pauseButton: UIButton!
@IBOutlet var finishButton: UIButton!
@IBOutlet weak var settingsButton: UIBarButtonItem!
var toDoList = ToDoList()
var settings: Settings?
var pomodoroClockwork: PomodoroClockwork?
var player = AVPlayer()
var clockworkIsOn = false {
didSet {
if clockworkIsOn == true {
pauseButton.setTitle("Pause", for: .normal)
settingsButton.isEnabled = false
} else {
pauseButton.setTitle("Continue", for: .normal)
settingsButton.isEnabled = true
}
}
}
var taskIdentifier: Int64 = 0 {
didSet {
if taskIdentifier == 0 {
finishButton.isEnabled = false
pauseButton.isEnabled = false
pomodoroClockwork?.terminate()
} else {
finishButton.isEnabled = true
pauseButton.isEnabled = true
}
}
}
private lazy var formatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.allowedUnits = [.minute, .second]
formatter.zeroFormattingBehavior = .pad
return formatter
}()
override func viewDidLoad() {
super.viewDidLoad()
setupSettings()
settings?.loadAllSettings()
toDoList.loadToDoList()
pauseButton.setTitle("Start", for: .normal)
finishButton.isEnabled = false
pauseButton.isEnabled = false
guard let workTime = settings?.durationSettings[0].amount,
let shortBreakTime = settings?.durationSettings[1].amount,
let longBreakTime = settings?.durationSettings[2].amount,
let shortBreaksCount = settings?.breaksNumberSettings[0].amount else { return }
pomodoroClockwork = PomodoroClockwork(settings:
ClockSettings(
workTimeDuration: workTime,
shortBreakDuration: shortBreakTime,
longBreakDuration: longBreakTime,
shortBreaksCount: Int(shortBreaksCount)))
clockworkLabel.text = formatter.clockFormat(from: workTime)
breaksLabel.text = "Short Breaks: 0/\(pomodoroClockwork?.settings.shortBreaksCount ?? Int(shortBreaksCount))"
pomodoroClockwork?.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
toDoList.loadToDoList()
settings?.loadAllSettings()
}
private func setupSettings() {
if settings == nil {
settings = Settings()
}
}
@IBAction func openToDoList(_ sender: UIButton) {
performSegue(withIdentifier: String.StoryboardIdentifiers.segueShowToDoList.rawValue, sender: self)
}
@IBAction func stopAndStartClockwork(_ sender: UIButton) {
clockworkIsOn = !clockworkIsOn
clockworkIsOn ? pomodoroClockwork?.start() : pomodoroClockwork?.pause()
}
@IBAction func finishTask(_ sender: UIButton) {
toDoList.taskIsDone(id: taskIdentifier)
guard let indexNumber = toDoList.searchForTask(idNumber: taskIdentifier) else { return }
var nextTask: Task?
if indexNumber != toDoList.tasks.index(before: toDoList.tasks.endIndex) {
for taskIndex in toDoList.tasks.index(after: indexNumber)..<toDoList.tasks.endIndex {
if toDoList.tasks[taskIndex].isDone == false {
nextTask = toDoList.tasks[taskIndex]
break
}
}
} else {
nextTask = toDoList.tasks.first {
$0.isDone == false
}
}
if let taskToShow = nextTask {
self.navigationItem.title = taskToShow.descriptionOfTask
taskIdentifier = taskToShow.identifier
} else {
self.navigationItem.title = String.finishText
taskIdentifier = 0
finishButton.isEnabled = false
pauseButton.isEnabled = false
}
}
@IBAction func openSettings(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: String.StoryboardIdentifiers.segueShowSettings.rawValue, sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == String.StoryboardIdentifiers.segueShowToDoList.rawValue {
let destinationVC = segue.destination as? ToDoListTableViewController
destinationVC?.mainViewContentUpdateDelegate = self
} else if segue.identifier == String.StoryboardIdentifiers.segueShowSettings.rawValue {
let destinationVC = segue.destination as? SettingsTableViewController
destinationVC?.mainVCdelegate = self
destinationVC?.settings = settings
}
}
private func play(url: URL) {
let item = AVPlayerItem(url: url)
player = AVPlayer(playerItem: item)
player.play()
}
}
extension MainViewController: MainViewContentUpdateDelegate {
func updateMainVCwithSettings() {
guard let workTime = settings?.durationSettings[0].amount,
let shortBreakTime = settings?.durationSettings[1].amount,
let longBreakTime = settings?.durationSettings[2].amount,
let shortBreaksCount = settings?.breaksNumberSettings[0].amount else { return }
pomodoroClockwork = PomodoroClockwork(settings: ClockSettings(
workTimeDuration: workTime,
shortBreakDuration: shortBreakTime,
longBreakDuration: longBreakTime,
shortBreaksCount: Int(shortBreaksCount)))
pomodoroClockwork?.delegate = self
resetDataForClockworkRepresentation(numberOfShortBreaks: 0)
}
func updateTaskLabel(with taskID: Int64) {
toDoList.loadToDoList()
guard let indexNumber = toDoList.searchForTask(idNumber: taskID) else {
self.navigationItem.title = String.welcomeText
return
}
self.navigationItem.title = toDoList.tasks[indexNumber].descriptionOfTask
taskIdentifier = taskID
}
}
extension MainViewController: PomodoroClockworkDelegate {
func updateTimeInClockworkLabel(currentTime: CFTimeInterval, phase: PomodoroPhases) {
guard let workTime = pomodoroClockwork?.settings.workTimeDuration, let shortBreakDuration = pomodoroClockwork?.settings.shortBreakDuration, let longBreakDuration = pomodoroClockwork?.settings.longBreakDuration else { return }
let endTime: Double = {
switch phase {
case .work:
return workTime
case .shortBreak:
return shortBreakDuration
case .longBreak:
return longBreakDuration
}
}()
let countdown: Double = {
return endTime - currentTime
}()
let newProgress: Double = {
return currentTime/endTime
}()
print(currentTime)
clockworkLabel.text = formatter.clockFormat(from: countdown)
circleProgressView.setProgress(newProgress, animated: true)
}
func changeBreakInformationLabel(phase: PomodoroPhases, numberOfShortBreaks: Int?) {
guard let workTime = pomodoroClockwork?.settings.workTimeDuration,
let shortBreaksCount = pomodoroClockwork?.settings.shortBreaksCount,
let shortBreakDuration = pomodoroClockwork?.settings.shortBreakDuration,
let longBreakDuration = pomodoroClockwork?.settings.longBreakDuration,
let alert = settings?.soundSettings[0].settingString,
let url = Bundle.main.url(forResource: alert, withExtension: "mp3") else { return }
play(url: url)
switch phase {
case .work:
clockworkLabel.text = formatter.clockFormat(from: workTime)
breaksLabel.text = "Short Breaks: \(numberOfShortBreaks ?? 0)/\(shortBreaksCount)"
case .shortBreak:
clockworkLabel.text = formatter.clockFormat(from: shortBreakDuration)
breaksLabel.text = "Short Break"
case .longBreak:
clockworkLabel.text = formatter.clockFormat(from: longBreakDuration)
breaksLabel.text = "Long Break"
}
}
func resetDataForClockworkRepresentation(numberOfShortBreaks: Int) {
guard let workTime = pomodoroClockwork?.settings.workTimeDuration, let shortBreaksCount = pomodoroClockwork?.settings.shortBreaksCount else { return }
circleProgressView.setProgress(0.0, animated: true)
clockworkIsOn = false
pauseButton.setTitle("Start", for: .normal)
clockworkLabel.text = formatter.clockFormat(from: workTime)
breaksLabel.text = "Short Breaks: \(numberOfShortBreaks)/\(shortBreaksCount)"
}
}
<file_sep>/TimekeeperUITests/MainViewElements.swift
//
// MainViewElements.swift
// TimekeeperUITests
//
// Created by <NAME> on 30/03/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import XCTest
class MainViewElements {
let toDoListButton: XCUIElement
let settingsButton: XCUIElement
let clockOnButton: XCUIElement
let clockworkLabel: XCUIElement
let breaksLabel: XCUIElement
init(app: XCUIApplication) {
self.toDoListButton = app.buttons[Controls.Buttons.toDoList]
self.settingsButton = app.buttons[Controls.Buttons.settings]
self.clockOnButton = app.buttons[Controls.Buttons.start]
self.clockworkLabel = app.staticTexts[Controls.Labels.clockworkLabel]
self.breaksLabel = app.staticTexts[Controls.Labels.breaksLabel]
}
}
<file_sep>/TimekeeperUITests/SettingsElements.swift
//
// SettingsElements.swift
// TimekeeperUITests
//
// Created by <NAME> on 30/03/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import XCTest
class SettingsElements {
let table: XCUIElement
let settingPickerView: XCUIElement
let component: XCUIElement
let minutesComponent: XCUIElement
let secondsComponent: XCUIElement
let saveButton: XCUIElement
let playButton: XCUIElement
let backButton: XCUIElement
let settingCells: Cells
let alert: XCUIElement
init(app: XCUIApplication) {
self.table = app.tables.firstMatch
self.settingPickerView = app.pickers.firstMatch
self.saveButton = app.buttons[Controls.Buttons.save]
self.playButton = app.buttons[Controls.Buttons.playSound]
let navigationBar = app.navigationBars.firstMatch
self.backButton = navigationBar.buttons[Controls.Buttons.back]
self.component = app.pickerWheels.firstMatch
self.minutesComponent = {
let predicate = NSPredicate(format: "label BEGINSWITH '\(Controls.PickerComponents.minutes)'")
let component = app.pickers.firstMatch.pickerWheels.element(matching: predicate)
return component
}()
self.secondsComponent = {
let predicate = NSPredicate(format: "label BEGINSWITH '\(Controls.PickerComponents.seconds)'")
let component = app.pickers.firstMatch.pickerWheels.element(matching: predicate)
return component
}()
self.settingCells = Cells(table: table)
self.alert = app.alerts[Controls.Alerts.notMuchTime]
}
struct Cells {
let focusTime: XCUIElementQuery
let shortBreakTime: XCUIElementQuery
let longBreakTime: XCUIElementQuery
let shortBreaksAmount: XCUIElementQuery
let alertSound: XCUIElementQuery
init(table: XCUIElement) {
let predicateFocusTime = NSPredicate(format: "label BEGINSWITH '\(Controls.SettingsCells.FocusTimeDuration)'")
let predicateShortBreakTime = NSPredicate(format: "label BEGINSWITH '\(Controls.SettingsCells.shortBreakDuration)'")
let predicateLongBreakTime = NSPredicate(format: "label BEGINSWITH '\(Controls.SettingsCells.longBreakDuration)'")
let predicateShortBreaksAmount = NSPredicate(format: "label BEGINSWITH '\(Controls.SettingsCells.shortBreaksAmount)'")
let predicateSound = NSPredicate(format: "label BEGINSWITH '\(Controls.SettingsCells.alertSound)'")
self.focusTime = table.cells.containing(predicateFocusTime)
self.shortBreakTime = table.cells.containing(predicateShortBreakTime)
self.longBreakTime = table.cells.containing(predicateLongBreakTime)
self.shortBreaksAmount = table.cells.containing(predicateShortBreaksAmount)
self.alertSound = table.cells.containing(predicateSound)
}
}
func changeSettings(for element: XCUIElement, of settingsElements: SettingsElements, withMinutes minutes: String?, andSeconds seconds: String?, or breaksAmount: String?) {
element.tap()
if let min = minutes, let sec = seconds {
settingsElements.minutesComponent.adjust(toPickerWheelValue: min)
settingsElements.secondsComponent.adjust(toPickerWheelValue: sec)
}
if let brksAmnt = breaksAmount {
settingsElements.component.adjust(toPickerWheelValue: brksAmnt)
}
settingsElements.saveButton.tap()
}
}
<file_sep>/Timekeeper/Controller/SoundSettingViewController.swift
//
// SoundSettingViewController.swift
// Timekeeper
//
// Created by <NAME> on 04/03/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import AVFoundation
class SoundSettingViewController: UIViewController, SettingsDetailsInterface {
var detailsType: SettingsDetailsType?
var settings: Settings?
var delegate: SettingsUpdateDelegate?
private var soundSettings: ClockworkSettings?
private let sounds = String.sounds
private var player = AVPlayer()
@IBOutlet var descriptionLabel: UILabel!
@IBOutlet var viewForSettingPickerView: UIView!
@IBOutlet var settingPickerView: UIPickerView!
@IBOutlet var playButton: UIButton!
@IBOutlet var saveButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
settingPickerView.delegate = self
settingPickerView.dataSource = self
loadSettingsAndView()
}
func loadSettingsAndView() {
do {
soundSettings = try loadSoundSettings()
} catch {
return
}
fillWithLoadedSettings()
}
private func loadSoundSettings() throws -> ClockworkSettings? {
guard let detailsType = detailsType else { return nil }
return try settings?.loadSpecificSetting(for: detailsType).first
}
private func fillWithLoadedSettings() {
guard let soundSettingsString = soundSettings?.settingString else { return }
let transformedTitle = soundSettingsString.replacingOccurrences(of: "_", with: " ")
guard let soundIndex = sounds.firstIndex(of: transformedTitle) else { return }
settingPickerView.selectRow(soundIndex, inComponent: 0, animated: false)
descriptionLabel.text = soundSettings?.descriptionOfSetting
}
@IBAction func playButtonPressed(_ sender: UIButton) {
sender.isEnabled = false
let index = settingPickerView.selectedRow(inComponent: 0)
let sound = sounds[index]
let soundTitle = sound.replacingOccurrences(of: " ", with: "_")
guard let url = Bundle.main.url(forResource: soundTitle, withExtension: "mp3") else { sender.isEnabled = true; return }
play(url: url)
}
@IBAction func saveButtonPressed(_ sender: UIButton) {
guard let newValue = transformValueFromPicker(),
let type = detailsType,
let soundSettings = soundSettings else { return }
settings?.save(newValue, for: soundSettings, of: type)
navigationController?.popViewController(animated: true)
}
private func transformValueFromPicker() -> String? {
let index = settingPickerView.selectedRow(inComponent: 0)
let sound = sounds[index]
return sound.replacingOccurrences(of: " ", with: "_")
}
private func play(url: URL) {
let item = AVPlayerItem(url: url)
NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying(sender:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item)
player = AVPlayer(playerItem: item)
player.play()
}
@objc func playerDidFinishPlaying(sender: Notification) {
playButton.isEnabled = true
}
}
extension SoundSettingViewController: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return sounds.count
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
var label: UILabel
if let vw = view as? UILabel {
label = vw
} else {
label = UILabel()
}
label.textColor = UIColor.trackColor
label.font = UIFont.systemFont(ofSize: (viewForSettingPickerView.frame.size.height * 0.25))
label.adjustsFontSizeToFitWidth = true
label.textAlignment = .center
label.numberOfLines = 2
label.text = sounds[row]
return label
}
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return settingPickerView.frame.size.width
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return viewForSettingPickerView.frame.size.height
}
}
<file_sep>/Timekeeper/Extensions/RoundedButton.swift
//
// RoundedButton.swift
// Timekeeper
//
// Created by <NAME> on 03/03/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class RoundedButton: UIButton {
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = bounds.height / 2
}
private func startAnimatingPressActions() {
addTarget(self, action: #selector(animateDown), for: [.touchDown, .touchDragEnter])
addTarget(self, action: #selector(animateUp), for: [.touchDragExit, .touchCancel, .touchUpInside, .touchUpOutside])
}
private func setEnabledOrDisabledAnimation(button: UIButton, isEnabled: Bool) {
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.5,
initialSpringVelocity: 3,
options: [.curveEaseInOut],
animations: {
if isEnabled {
button.backgroundColor = UIColor.buttonColor
button.tintColor = UIColor.fontColor
} else {
button.backgroundColor = UIColor.darkGray
button.tintColor = UIColor.lightGray
}
}, completion: nil)
}
@objc private func animateDown(sender: UIButton) {
animate(sender, transform: CGAffineTransform.identity.scaledBy(x: 0.95, y: 0.95), animatedColor: UIColor.trackColor, animatedTextColor: nil)
}
@objc private func animateUp(sender: UIButton) {
sender.isEnabled ? animate(sender, transform: .identity, animatedColor: UIColor.buttonColor, animatedTextColor: nil) : animate(sender, transform: .identity, animatedColor: UIColor.darkGray, animatedTextColor: UIColor.lightGray)
}
private func animate(_ button: UIButton, transform: CGAffineTransform, animatedColor: UIColor, animatedTextColor: UIColor?) {
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.5,
initialSpringVelocity: 3,
options: [.curveEaseInOut ],
animations: {
button.transform = transform
button.backgroundColor = animatedColor
if let animTxtCl = animatedTextColor {
button.tintColor = animTxtCl
}
}, completion: nil)
}
override open var isHighlighted : Bool {
didSet {
startAnimatingPressActions()
}
}
override open var isEnabled: Bool {
didSet {
isEnabled ? setEnabledOrDisabledAnimation(button: self, isEnabled: true) : setEnabledOrDisabledAnimation(button: self, isEnabled: false)
}
}
}
<file_sep>/Timekeeper/Controller/SettingsTableViewController.swift
//
// SettingsTableViewController.swift
// Timekeeper
//
// Created by <NAME> on 11/01/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
protocol SettingsUpdateDelegate: AnyObject {
func settingsDidUpdate()
}
class SettingsTableViewController: UITableViewController {
weak var mainVCdelegate: MainViewContentUpdateDelegate?
var settings: Settings?
var pomodoroAndClockSettingsChanged = false
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.delegate = self
settings?.loadAllSettings()
}
private func clockworkConfiguration(at index: IndexPath) -> Double {
let clockworkSettings = settings?.clockworkConfigurations[index.section]
let settingsForIndex = clockworkSettings?[index.row]
return settingsForIndex?.amount ?? 0
}
private lazy var formatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.allowedUnits = [.minute, .second]
formatter.zeroFormattingBehavior = .pad
return formatter
}()
private func settingsType(for index: IndexPath) -> SettingsDetailsType? {
switch index.section {
case SettingsSections.duration.rawValue:
switch index.row {
case 0: return SettingsDetailsType.focusTime
case 1: return SettingsDetailsType.shortBreak
case 2: return SettingsDetailsType.longBreak
default: return nil
}
case SettingsSections.numberOfBreaks.rawValue:
switch index.row {
case 0: return SettingsDetailsType.shortBreaksNumber
default: return nil
}
default: return nil
}
}
// MARK: - Table view data source
private enum SettingsSections: Int {
case duration
case numberOfBreaks
case soundSettings
case other
}
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.tintColor = UIColor.backgroundColor
let header = view as! UITableViewHeaderFooterView
header.textLabel?.textColor = UIColor.fontColor
}
override func numberOfSections(in tableView: UITableView) -> Int {
guard let amountOfSections = settings?.clockworkConfigurations.count else { return 0 }
return amountOfSections
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
guard let settingsSection = SettingsSections(rawValue: section) else { return nil }
switch settingsSection {
case .duration:
return "Duration"
case .numberOfBreaks:
return "Number of breaks"
case .soundSettings:
return "Sound settings"
case .other:
return "Other"
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let numOfRowsInSect = settings?.clockworkConfigurations[section]?.count else { return 0 }
return numOfRowsInSect
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String.StoryboardIdentifiers.settingCell.rawValue, for: indexPath)
cell.textLabel?.text = settings?.clockworkConfigurations[indexPath.section]?[indexPath.row].descriptionOfSetting
if let settingsSection = SettingsSections(rawValue: indexPath.section) {
switch settingsSection {
case .duration:
let duration = clockworkConfiguration(at: indexPath)
cell.detailTextLabel?.text = formatter.clockFormat(from: duration)
case .numberOfBreaks:
let numberOfBreaks = Int(clockworkConfiguration(at: indexPath))
cell.detailTextLabel?.text = String(format: "%i", numberOfBreaks)
default:
cell.accessoryType = .disclosureIndicator
}
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let settingsSection = SettingsSections(rawValue: indexPath.section) else { return }
switch settingsSection {
case .duration:
performSegue(withIdentifier: String.StoryboardIdentifiers.segueOpenDurationSettings.rawValue, sender: self)
case .numberOfBreaks:
performSegue(withIdentifier: String.StoryboardIdentifiers.segueOpenBreaksAmountSettings.rawValue, sender: self)
case .soundSettings:
performSegue(withIdentifier: String.StoryboardIdentifiers.segueOpenSoundSettings.rawValue, sender: self)
case .other:
performSegue(withIdentifier: String.StoryboardIdentifiers.segueOpenCredits.rawValue, sender: self)
}
}
// MARK: - Segue Preparation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let senderIndexPath = (sender as? SettingsTableViewController)?.tableView.indexPathForSelectedRow,
var settingsDetails = segue.destination as? SettingsDetailsInterface {
settingsDetails.settings = settings
settingsDetails.delegate = self
switch segue.identifier {
case String.StoryboardIdentifiers.segueOpenDurationSettings.rawValue:
settingsDetails.detailsType = settingsType(for: senderIndexPath)
case String.StoryboardIdentifiers.segueOpenBreaksAmountSettings.rawValue:
settingsDetails.detailsType = settingsType(for: senderIndexPath)
case String.StoryboardIdentifiers.segueOpenSoundSettings.rawValue:
settingsDetails.detailsType = .alertSound
case String.StoryboardIdentifiers.segueOpenCredits.rawValue:
settingsDetails.detailsType = .credits
default:
return
}
}
}
}
extension SettingsTableViewController: SettingsUpdateDelegate {
func settingsDidUpdate() {
tableView.reloadData()
pomodoroAndClockSettingsChanged = true
}
}
extension SettingsTableViewController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
guard let mainVC = viewController as? MainViewController else { return }
if pomodoroAndClockSettingsChanged {
mainVC.updateMainVCwithSettings()
} else {
mainVC.settings = settings
}
}
}
<file_sep>/TimekeeperUITests/ToDoListUITests.swift
//
// ToDoListUITests.swift
// TimekeeperUITests
//
// Created by <NAME> on 09/01/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import XCTest
@testable import Timekeeper
class ToDoListUITests: XCTestCase {
let app = XCUIApplication()
override func setUp() {
super.setUp()
app.launchArguments = ["IS_RUNNING_UITEST"]
app.launch()
continueAfterFailure = true
}
override func tearDown() {
super.tearDown()
}
func testAddingAndDeletingTasks() {
app.buttons[Controls.Buttons.toDoList].tap()
let toDoListElements = ToDoListElements(app: app, numberOfCells: 4)
XCTAssertEqual(toDoListElements.emptyListTable.cells.count, 0)
toDoListElements.addTask(name: toDoListElements.testTexts[0])
XCTAssertEqual(toDoListElements.table.cells.count, 1)
XCTAssertEqual(toDoListElements.cells[0].staticTexts.firstMatch.label, toDoListElements.testTexts[0])
toDoListElements.addTask(name: toDoListElements.testTexts[1], cancelAction: true)
XCTAssertEqual(toDoListElements.table.cells.count, 1)
XCTAssertNotEqual(toDoListElements.cells[0].staticTexts.firstMatch.label, toDoListElements.testTexts[1])
XCTAssertEqual(toDoListElements.cells[0].staticTexts.firstMatch.label, toDoListElements.testTexts[0])
toDoListElements.addTask(name: toDoListElements.testTexts[2])
XCTAssertEqual(toDoListElements.table.cells.count, 2)
XCTAssertEqual(toDoListElements.cells[1].staticTexts.firstMatch.label, toDoListElements.testTexts[2])
XCTAssertEqual(toDoListElements.cells[0].staticTexts.firstMatch.label, toDoListElements.testTexts[0])
toDoListElements.addTask(name: toDoListElements.testTexts[3])
XCTAssertEqual(toDoListElements.table.cells.count, 3)
XCTAssertEqual(toDoListElements.cells[2].staticTexts.firstMatch.label, toDoListElements.testTexts[3])
XCTAssertEqual(toDoListElements.cells[1].staticTexts.firstMatch.label, toDoListElements.testTexts[2])
XCTAssertEqual(toDoListElements.cells[0].staticTexts.firstMatch.label, toDoListElements.testTexts[0])
toDoListElements.cells[0].tap()
app.buttons[Controls.Buttons.finishTask].tap()
app.buttons[Controls.Buttons.toDoList].tap()
toDoListElements.deleteTask(inCell: 1)
XCTAssertEqual(toDoListElements.table.cells.count, 2)
XCTAssertEqual(toDoListElements.cells[0].staticTexts.firstMatch.label, toDoListElements.testTexts[0])
XCTAssertEqual(toDoListElements.cells[2].staticTexts.firstMatch.label, toDoListElements.testTexts[3])
toDoListElements.deleteTask(inCell: 2)
XCTAssertEqual(toDoListElements.table.cells.count, 1)
XCTAssertEqual(toDoListElements.cells[0].staticTexts.firstMatch.label, toDoListElements.testTexts[0])
toDoListElements.deleteTask(inCell: 0)
XCTAssertEqual(toDoListElements.table.cells.count, 0)
}
func testMarkingTasksAsDone() {
XCTAssertFalse(app.buttons[Controls.Buttons.finishTask].isEnabled)
XCTAssertFalse(app.buttons[Controls.Buttons.start].isEnabled)
let toDoListElements = ToDoListElements(app: app, numberOfCells: 4)
app.buttons[Controls.Buttons.toDoList].tap()
toDoListElements.addingTasks()
toDoListElements.cells[2].tap()
XCTAssertTrue(app.buttons[Controls.Buttons.finishTask].isEnabled)
XCTAssertTrue(app.buttons[Controls.Buttons.start].isEnabled)
XCTAssertEqual(app.staticTexts.firstMatch.label, toDoListElements.testTexts[2])
app.buttons[Controls.Buttons.finishTask].tap()
XCTAssertEqual(app.staticTexts.firstMatch.label, toDoListElements.testTexts[3])
app.buttons[Controls.Buttons.finishTask].tap()
XCTAssertEqual(app.staticTexts.firstMatch.label, toDoListElements.testTexts[0])
app.buttons[Controls.Buttons.toDoList].tap()
XCTAssertEqual(toDoListElements.cells[0].staticTexts.firstMatch.label, toDoListElements.testTexts[0])
XCTAssertFalse(toDoListElements.cellsAccessoryTypes[0].exists)
XCTAssertEqual(toDoListElements.cells[1].staticTexts.firstMatch.label, toDoListElements.testTexts[1])
XCTAssertFalse(toDoListElements.cellsAccessoryTypes[1].exists)
XCTAssertEqual(toDoListElements.cells[2].staticTexts.firstMatch.label, toDoListElements.testTexts[2])
XCTAssertEqual(toDoListElements.cellsAccessoryTypes[2].label, "checkmark")
XCTAssertEqual(toDoListElements.cells[3].staticTexts.firstMatch.label, toDoListElements.testTexts[3])
XCTAssertEqual(toDoListElements.cellsAccessoryTypes[3].label, "checkmark")
}
func testOrderOfMarkingTasksAsDone() {
let toDoListElements = ToDoListElements(app: app, numberOfCells: 10)
app.buttons[Controls.Buttons.toDoList].tap()
toDoListElements.addingTasks()
toDoListElements.cells[7].tap()
app.buttons[Controls.Buttons.finishTask].tap()
XCTAssertEqual(app.staticTexts.firstMatch.label, toDoListElements.testTexts[8])
app.buttons[Controls.Buttons.finishTask].tap()
XCTAssertEqual(app.staticTexts.firstMatch.label, toDoListElements.testTexts[9])
app.buttons[Controls.Buttons.toDoList].tap()
XCTAssertFalse(toDoListElements.cellsAccessoryTypes[0].exists)
XCTAssertFalse(toDoListElements.cellsAccessoryTypes[1].exists)
XCTAssertFalse(toDoListElements.cellsAccessoryTypes[2].exists)
XCTAssertFalse(toDoListElements.cellsAccessoryTypes[3].exists)
XCTAssertFalse(toDoListElements.cellsAccessoryTypes[4].exists)
XCTAssertFalse(toDoListElements.cellsAccessoryTypes[5].exists)
XCTAssertFalse(toDoListElements.cellsAccessoryTypes[6].exists)
XCTAssertEqual(toDoListElements.cellsAccessoryTypes[7].label, "checkmark")
XCTAssertEqual(toDoListElements.cellsAccessoryTypes[8].label, "checkmark")
XCTAssertFalse(toDoListElements.cellsAccessoryTypes[9].exists)
toDoListElements.cells[4].tap()
app.buttons[Controls.Buttons.finishTask].tap()
XCTAssertEqual(app.staticTexts.firstMatch.label, toDoListElements.testTexts[5])
app.buttons[Controls.Buttons.finishTask].tap()
XCTAssertEqual(app.staticTexts.firstMatch.label, toDoListElements.testTexts[6])
app.buttons[Controls.Buttons.toDoList].tap()
XCTAssertFalse(toDoListElements.cellsAccessoryTypes[0].exists)
XCTAssertFalse(toDoListElements.cellsAccessoryTypes[1].exists)
XCTAssertFalse(toDoListElements.cellsAccessoryTypes[2].exists)
XCTAssertFalse(toDoListElements.cellsAccessoryTypes[3].exists)
XCTAssertEqual(toDoListElements.cellsAccessoryTypes[4].label, "checkmark")
XCTAssertEqual(toDoListElements.cellsAccessoryTypes[5].label, "checkmark")
XCTAssertFalse(toDoListElements.cellsAccessoryTypes[6].exists)
XCTAssertEqual(toDoListElements.cellsAccessoryTypes[7].label, "checkmark")
XCTAssertEqual(toDoListElements.cellsAccessoryTypes[8].label, "checkmark")
XCTAssertFalse(toDoListElements.cellsAccessoryTypes[9].exists)
toDoListElements.cells[2].tap()
app.buttons[Controls.Buttons.finishTask].tap()
XCTAssertEqual(app.staticTexts.firstMatch.label, toDoListElements.testTexts[3])
app.buttons[Controls.Buttons.finishTask].tap()
XCTAssertEqual(app.staticTexts.firstMatch.label, toDoListElements.testTexts[6])
app.buttons[Controls.Buttons.finishTask].tap()
XCTAssertEqual(app.staticTexts.firstMatch.label, toDoListElements.testTexts[9])
app.buttons[Controls.Buttons.finishTask].tap()
XCTAssertEqual(app.staticTexts.firstMatch.label, toDoListElements.testTexts[0])
app.buttons[Controls.Buttons.finishTask].tap()
XCTAssertEqual(app.staticTexts.firstMatch.label, toDoListElements.testTexts[1])
app.buttons[Controls.Buttons.finishTask].tap()
XCTAssertEqual(app.staticTexts.firstMatch.label, "All your tasks are complete!")
app.buttons[Controls.Buttons.toDoList].tap()
XCTAssertEqual(toDoListElements.cellsAccessoryTypes[0].label, "checkmark")
XCTAssertEqual(toDoListElements.cellsAccessoryTypes[1].label, "checkmark")
XCTAssertEqual(toDoListElements.cellsAccessoryTypes[2].label, "checkmark")
XCTAssertEqual(toDoListElements.cellsAccessoryTypes[3].label, "checkmark")
XCTAssertEqual(toDoListElements.cellsAccessoryTypes[4].label, "checkmark")
XCTAssertEqual(toDoListElements.cellsAccessoryTypes[5].label, "checkmark")
XCTAssertEqual(toDoListElements.cellsAccessoryTypes[6].label, "checkmark")
XCTAssertEqual(toDoListElements.cellsAccessoryTypes[7].label, "checkmark")
XCTAssertEqual(toDoListElements.cellsAccessoryTypes[8].label, "checkmark")
XCTAssertEqual(toDoListElements.cellsAccessoryTypes[9].label, "checkmark")
}
func testOrderOfMakingTasksDoneWhenTasksInTheMiddleWereDeleted() {
let toDoListElements = ToDoListElements(app: app, numberOfCells: 5)
app.buttons[Controls.Buttons.toDoList].tap()
toDoListElements.addingTasks()
toDoListElements.deleteTask(inCell: 2)
toDoListElements.deleteTask(inCell: 3)
toDoListElements.cells[1].tap()
app.buttons[Controls.Buttons.finishTask].tap()
XCTAssertEqual(app.staticTexts.firstMatch.label, toDoListElements.testTexts[4])
app.buttons[Controls.Buttons.finishTask].tap()
XCTAssertEqual(app.staticTexts.firstMatch.label, toDoListElements.testTexts[0])
}
func testMainViewUpdateWhenCurrentTaskWasDeleted() {
let toDoListElements = ToDoListElements(app: app, numberOfCells: 3)
app.buttons[Controls.Buttons.toDoList].tap()
toDoListElements.addingTasks()
toDoListElements.cells[1].tap()
app.buttons[Controls.Buttons.toDoList].tap()
toDoListElements.deleteTask(inCell: 1)
app.buttons[Controls.Buttons.back].tap()
XCTAssertEqual(app.staticTexts.firstMatch.label, "Choose task from To-do list")
}
}
<file_sep>/TimekeeperUITests/ToDoListElements.swift
//
// ToDoListElements.swift
// TimekeeperUITests
//
// Created by <NAME> on 30/03/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import XCTest
class ToDoListElements {
var testTexts: [String]
let addButton: XCUIElement
let textFieldAlert: XCUIElement
let addTaskAlert: XCUIElement
let alertAddButton: XCUIElement
let alertCancelButton: XCUIElement
let emptyListTable: XCUIElement
let table: XCUIElement
var cells = [XCUIElement]()
var cellsAccessoryTypes = [XCUIElement]()
init(app: XCUIApplication, numberOfCells: Int) {
self.testTexts = {
return (0..<numberOfCells).map({ String(format: "test%d", $0)})
}()
let toDoListNavigationBar = app.navigationBars[Controls.NavigationBars.yourToDoList]
self.addButton = toDoListNavigationBar.buttons[Controls.Buttons.add]
self.addTaskAlert = app.alerts[Controls.Alerts.addTask]
self.textFieldAlert = self.addTaskAlert.textFields.firstMatch
self.alertAddButton = self.addTaskAlert.buttons[Controls.Buttons.add]
self.alertCancelButton = self.addTaskAlert.buttons[Controls.Buttons.cancel]
self.emptyListTable = app.tables[Controls.Tables.emptyList]
self.table = app.tables.firstMatch
self.cells = {
return (0..<numberOfCells).map({
table.cells.element(matching: .cell, identifier: "TaskCell_\($0)")
})
}()
self.cellsAccessoryTypes = {
return (0..<numberOfCells).map({
table.cells["TaskCell_\($0)"].buttons.firstMatch
})
}()
}
func addTask(name: String, cancelAction: Bool = false) {
addButton.tap()
textFieldAlert.tap()
textFieldAlert.typeText(name)
if cancelAction {
alertCancelButton.tap()
} else {
alertAddButton.tap()
}
}
func addingTasks() {
testTexts.forEach { addTask(name: $0) }
}
func deleteTask(inCell number: Int) {
cells[number].swipeLeft()
cells[number].buttons[Controls.Buttons.delete].tap()
}
}
<file_sep>/Timekeeper/Model/PomodoroClockwork.swift
//
// Clockwork.swift
// Timekeeper
//
// Created by <NAME> on 03/02/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class PomodoroClockwork {
private let clock = Clock()
private (set) var settings: ClockSettings
private (set) var currentPhase: PomodoroPhases
private var shortBreaksElapsed: Int = 0
weak var delegate: PomodoroClockworkDelegate?
init(settings: ClockSettings, startingPhase: PomodoroPhases = .work) {
self.settings = settings
self.currentPhase = startingPhase
self.clock.delegate = self
}
var currentPhaseTime: String {
return clock.currentTimeText ?? "00:00"
}
func start() {
clock.startTimer()
}
func pause() {
clock.pauseTimer()
}
func terminate() {
clock.terminateTimer()
currentPhase = .work
shortBreaksElapsed = 0
delegate?.resetDataForClockworkRepresentation(numberOfShortBreaks: shortBreaksElapsed)
}
private func resetClock() {
clock.terminateTimer()
clock.startTimer()
}
}
extension PomodoroClockwork: ClockDelegate {
func timeDidChange() {
guard let ct = clock.currentTime else { return }
let currentTime = ct.rounded(.down)
delegate?.updateTimeInClockworkLabel(currentTime: currentTime, phase: currentPhase)
switch currentPhase {
case .work:
guard currentTime >= settings.workTimeDuration else { return }
if shortBreaksElapsed >= settings.shortBreaksCount {
currentPhase = .longBreak
delegate?.changeBreakInformationLabel(phase: .longBreak, numberOfShortBreaks: nil)
resetClock()
} else {
currentPhase = .shortBreak
delegate?.changeBreakInformationLabel(phase: .shortBreak, numberOfShortBreaks: nil)
resetClock()
}
case .shortBreak:
if currentTime >= settings.shortBreakDuration {
currentPhase = .work
shortBreaksElapsed += 1
delegate?.changeBreakInformationLabel(phase: .work, numberOfShortBreaks: shortBreaksElapsed)
resetClock()
}
case .longBreak:
if currentTime >= settings.longBreakDuration {
currentPhase = .work
shortBreaksElapsed = 0
delegate?.changeBreakInformationLabel(phase: .work, numberOfShortBreaks: shortBreaksElapsed)
resetClock()
}
}
}
}
enum PomodoroPhases {
case work
case shortBreak
case longBreak
}
<file_sep>/Timekeeper/Model/TestCoreData.swift
//
// CoreDataUnitTest.swift
// TimekeeperTests
//
// Created by <NAME> on 14/02/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
import CoreData
class TestCoreData: CoreDataStack {
override init(coreDataModelName: String) {
super.init(coreDataModelName: String.CoreData.dataModel.rawValue)
self.persistentStoreCoordinator = {
let psCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
do {
try psCoordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil)
} catch {
fatalError("Unable to load PersistentStoreCoordinator for Unit Tests")
}
return psCoordinator
}()
}
}
<file_sep>/Timekeeper/Extensions/UIColor+Extension.swift
//
// UIColor+Extension.swift
// Timekeeper
//
// Created by <NAME> on 03/03/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
extension UIColor {
static let backgroundColor: UIColor = UIColor(red:0.11, green:0.15, blue:0.17, alpha:1.0)
static let buttonColor: UIColor = UIColor(red:0.06, green:0.30, blue:0.46, alpha:1.0)
static let trackColor: UIColor = UIColor(red:0.20, green:0.51, blue:0.72, alpha:1.0)
static let fontColor: UIColor = UIColor(red:0.73, green:0.88, blue:0.98, alpha:1.0)
}
<file_sep>/Timekeeper/Model/Clock.swift
//
// Clock.swift
// Timekeeper
//
// Created by <NAME> on 26/02/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
protocol ClockDelegate: AnyObject {
func timeDidChange()
}
class Clock {
weak var delegate: ClockDelegate?
var currentTimeText: String?
var currentTime: CFTimeInterval?
private var timer: Timer?
private var startTime: CFTimeInterval?
private var totalTimeElapsed: CFTimeInterval?
private lazy var formatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.allowedUnits = [.minute, .second]
formatter.zeroFormattingBehavior = .pad
return formatter
}()
func startTimer() {
timer = createTimer()
startTime = CACurrentMediaTime()
timer?.fire()
}
func pauseTimer() {
guard let start = startTime, let createdTimer = timer else { return }
createdTimer.invalidate()
totalTimeElapsed = (totalTimeElapsed ?? 0) + (CACurrentMediaTime() - start)
startTime = nil
}
func terminateTimer() {
timer?.invalidate()
currentTime = nil
currentTimeText = nil
totalTimeElapsed = nil
startTime = nil
}
private func createTimer() -> Timer {
let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) {
[weak self] _ in
guard let start = self?.startTime else { return }
let elapsed = (self?.totalTimeElapsed ?? 0) + CACurrentMediaTime() - start
self?.setCurrentTimeValues(with: elapsed)
self?.delegate?.timeDidChange()
}
RunLoop.current.add(timer, forMode: RunLoop.Mode.common)
timer.tolerance = 0.2
return timer
}
private func setCurrentTimeValues(with newValue: CFTimeInterval) {
currentTime = newValue
currentTimeText = formatter.clockFormat(from: newValue)
}
}
<file_sep>/TimekeeperTests/ClockTest.swift
//
// ClockTest.swift
// TimekeeperTests
//
// Created by <NAME> on 25/02/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import XCTest
@testable import Timekeeper
class ClockTest: XCTestCase {
var sut: Clock!
override func setUp() {
super.setUp()
sut = Clock()
}
override func tearDown() {
sut = nil
super.tearDown()
}
func testTimeFormatToTextProperrly() {
let exp = expectation(description: "It's 2 seconds later")
sut.startTimer()
DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
exp.fulfill()
})
wait(for: [exp], timeout: 3)
XCTAssertEqual(sut.currentTimeText, "00:02")
}
func testClockChangesAfterOneSecond() {
let exp = expectation(description: "It's one second later")
sut.startTimer()
let time = sut.currentTime
let currentTimeText = sut.currentTimeText
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
exp.fulfill()
})
wait(for: [exp], timeout: 2)
XCTAssertNotNil(time)
XCTAssertNotEqual(time, sut.currentTime)
XCTAssertNotEqual(currentTimeText, sut.currentTimeText)
}
func testClockDoesntChangeIfTimeFromLastChangeIsLessThanOneSecond() {
let exp = expectation(description: "It's less than one second later")
sut.startTimer()
let time = sut.currentTime
let currentTimeText = sut.currentTimeText
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
exp.fulfill()
})
wait(for: [exp], timeout: 1)
XCTAssertNotNil(currentTimeText)
XCTAssertNotNil(time)
XCTAssertEqual(currentTimeText, sut.currentTimeText)
XCTAssertEqual(time, sut.currentTime)
}
func testClockPauseFunctionalityWorksProperrly() {
let exp1 = expectation(description: "It's one second later")
let exp2 = expectation(description: "It's one second later")
sut.startTimer()
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
exp1.fulfill()
})
wait(for: [exp1], timeout: 2)
let time = sut.currentTime
let currentTimeText = sut.currentTimeText
sut.pauseTimer()
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
exp2.fulfill()
})
wait(for: [exp2], timeout: 2)
XCTAssertNotNil(time)
XCTAssertNotNil(currentTimeText)
XCTAssertEqual(time, sut.currentTime)
XCTAssertEqual(currentTimeText, sut.currentTimeText)
}
func testClockPauseAndContinueWorksProperrly() {
let exp1 = expectation(description: "It's one second later")
let exp2 = expectation(description: "It's one second later")
let exp3 = expectation(description: "It's one second later")
sut.startTimer()
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
exp1.fulfill()
})
wait(for: [exp1], timeout: 2)
let time = sut.currentTime
let currentTimeText = sut.currentTimeText
sut.pauseTimer()
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
exp2.fulfill()
})
wait(for: [exp2], timeout: 2)
sut.startTimer()
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
exp3.fulfill()
})
wait(for: [exp3], timeout: 2)
XCTAssertNotNil(time)
XCTAssertNotNil(currentTimeText)
XCTAssertNotEqual(time, sut.currentTime)
XCTAssertNotEqual(currentTimeText, sut.currentTimeText)
}
func testTerminateTimer() {
let exp = expectation(description: "It's 1 second later")
sut.startTimer()
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
exp.fulfill()
})
wait(for: [exp], timeout: 2)
let time = sut.currentTime
let currentTimeText = sut.currentTimeText
sut.terminateTimer()
XCTAssertNotEqual(time, sut.currentTime)
XCTAssertNotEqual(currentTimeText, sut.currentTimeText)
XCTAssertNil(sut.currentTime)
XCTAssertNil(sut.currentTimeText)
}
func testTerminateAndStartAnotherTimerProperrly() {
let exp1 = expectation(description: "It's 1 second later")
let exp2 = expectation(description: "It's 1 second later")
sut.startTimer()
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
exp1.fulfill()
})
wait(for: [exp1], timeout: 2)
sut.terminateTimer()
sut.startTimer()
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
exp2.fulfill()
})
wait(for: [exp2], timeout: 2)
XCTAssertNotNil(sut.currentTime)
XCTAssertNotNil(sut.currentTimeText)
}
}
<file_sep>/Timekeeper/Controller/BreaksAmountSettingViewController.swift
//
// BreaksAmountSettingViewController.swift
// Timekeeper
//
// Created by <NAME> on 04/03/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class BreaksAmountSettingViewController: UIViewController, SettingsDetailsInterface {
var detailsType: SettingsDetailsType?
var settings : Settings?
var delegate: SettingsUpdateDelegate?
@IBOutlet var descriptionLabel: UILabel!
@IBOutlet var viewForSettingPickerView: UIView!
@IBOutlet var settingPickerView: UIPickerView!
@IBOutlet var saveButton: UIButton!
private let breaksAmount = String.breaksAmount
private var amountSettings : ClockworkSettings?
override func viewDidLoad() {
super.viewDidLoad()
settingPickerView.delegate = self
settingPickerView.dataSource = self
loadSettingsAndView()
}
@IBAction func saveButtonPressed(_ sender: UIButton) {
guard let newValue = transformValueFromPicker(),
let type = detailsType,
let breaksAmountSettings = amountSettings else { return }
settings?.save(newValue, for: breaksAmountSettings, of: type)
delegate?.settingsDidUpdate()
navigationController?.popViewController(animated: true)
}
func loadSettingsAndView() {
do {
amountSettings = try loadBreaksAmountSettings()
} catch {
return
}
fillWithLoadedSettings()
}
private func transformValueFromPicker() -> Double? {
let index = settingPickerView.selectedRow(inComponent: 0)
guard let value = Double(breaksAmount[index]) else { return nil}
return value
}
private func loadBreaksAmountSettings() throws -> ClockworkSettings? {
guard let detailsType = detailsType else { return nil }
return try settings?.loadSpecificSetting(for: detailsType).first
}
private func fillWithLoadedSettings() {
guard let value = amountSettings?.amount else { return }
let stringValue = String(format: "%i", Int(value))
guard let valueIndex = breaksAmount.firstIndex(of: stringValue) else { return }
settingPickerView.selectRow(valueIndex, inComponent: 0, animated: false)
descriptionLabel.text = amountSettings?.descriptionOfSetting
}
}
extension BreaksAmountSettingViewController: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return breaksAmount.count
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
var label: UILabel
if let vw = view as? UILabel {
label = vw
} else {
label = UILabel()
}
label.textColor = UIColor.trackColor
label.font = UIFont.systemFont(ofSize: (viewForSettingPickerView.frame.size.height * 0.45))
label.textAlignment = .center
label.text = breaksAmount[row]
return label
}
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return settingPickerView.frame.size.width * 0.4
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return viewForSettingPickerView.frame.size.height
}
}
<file_sep>/Timekeeper/Delegates/PomodoroClockworkDelegate.swift
//
// PomodoroClockworkDelegate.swift
// Timekeeper
//
// Created by <NAME> on 13/03/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
protocol PomodoroClockworkDelegate: AnyObject {
func updateTimeInClockworkLabel(currentTime: CFTimeInterval, phase: PomodoroPhases)
func changeBreakInformationLabel(phase: PomodoroPhases, numberOfShortBreaks: Int?)
func resetDataForClockworkRepresentation(numberOfShortBreaks: Int)
}
<file_sep>/TimekeeperTests/ToDoListTableViewControllerTests.swift
//
// ToDoListTableViewControllerTests.swift
// TimekeeperTests
//
// Created by <NAME> on 17/02/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import XCTest
@testable import Timekeeper
class ToDoListTableViewControllerTests: XCTestCase {
var coreData: TestCoreData!
var tableViewController: ToDoListTableViewController!
private let names = ["Play a game", "Create toDoList code", "Play a game", "compose symphony", "wash dishes", "make dinner", "Create CoreData code"]
private let positions = [1,2,4,6]
override func setUp() {
super.setUp()
let storyboard = UIStoryboard(name: String.StoryboardIdentifiers.main.rawValue, bundle: Bundle.main)
tableViewController = storyboard.instantiateViewController(withIdentifier: String.StoryboardIdentifiers.toDoListTableViewControllerID.rawValue) as? ToDoListTableViewController
coreData = TestCoreData(coreDataModelName: String.CoreData.dataModel.rawValue)
tableViewController.toDoList = ToDoList(context: coreData.managedObjectContext)
let _ = tableViewController.view
}
override func tearDown() {
guard let tasksIsEmpty = tableViewController.toDoList?.tasks.isEmpty else { return }
if !tasksIsEmpty {
guard let tasks = tableViewController.toDoList?.tasks else { return }
for task in tasks {
tableViewController.toDoList?.deleteTask(withID: task.identifier)
}
}
super.tearDown()
}
func testTableHasNoCells() {
let numberOfRows = tableViewController.tableView(tableViewController.tableView, numberOfRowsInSection: 0)
XCTAssertEqual(numberOfRows, 0)
XCTAssertEqual(numberOfRows, tableViewController.toDoList?.tasks.count)
XCTAssertNil(tableViewController.tableView.cellForRow(at: IndexPath(row: 3, section: 0)))
}
func testNumberOfRows() {
addTasks()
let numberOfRows = tableViewController.tableView(tableViewController.tableView, numberOfRowsInSection: 0)
XCTAssertEqual(tableViewController.toDoList?.tasks.count, names.count)
XCTAssertEqual(numberOfRows, names.count)
XCTAssertEqual(numberOfRows, tableViewController.toDoList?.tasks.count)
}
func testInformationsMatchingWithCells() {
addTasks()
var cells = [UITableViewCell]()
for row in names.startIndex ..< names.endIndex {
let cell = tableViewController.tableView(tableViewController.tableView, cellForRowAt: IndexPath(row: row, section: 0))
cells.append(cell)
}
XCTAssertEqual(cells[0].textLabel?.text, names[0])
XCTAssertTrue(cells[0].accessoryType == .none)
XCTAssertEqual(cells[1].textLabel?.text, names[1])
XCTAssertTrue(cells[1].accessoryType == .checkmark)
XCTAssertEqual(cells[2].textLabel?.text, names[2])
XCTAssertTrue(cells[2].accessoryType == .checkmark)
XCTAssertEqual(cells[3].textLabel?.text, names[3])
XCTAssertTrue(cells[3].accessoryType == .none)
XCTAssertEqual(cells[4].textLabel?.text, names[4])
XCTAssertTrue(cells[4].accessoryType == .checkmark)
XCTAssertEqual(cells[5].textLabel?.text, names[5])
XCTAssertTrue(cells[5].accessoryType == .none)
XCTAssertEqual(cells[6].textLabel?.text, names[6])
XCTAssertTrue(cells[6].accessoryType == .checkmark)
}
func testRemoveCellsFromTableView() {
addTasks()
tableViewController.tableView(tableViewController.tableView, commit: .delete, forRowAt: IndexPath(row: 5, section: 0))
XCTAssertNotEqual(tableViewController.toDoList?.tasks[5].descriptionOfTask, "make dinner")
tableViewController.tableView(tableViewController.tableView, commit: .delete, forRowAt: IndexPath(row: 5, section: 0))
XCTAssertNil(tableViewController.tableView.cellForRow(at: IndexPath(row: 5, section: 0)))
}
private func addTasks() {
names.forEach {
tableViewController.toDoList?.addTask(description: $0)
}
positions.forEach {
guard let id = tableViewController.toDoList?.tasks[$0].identifier else { return }
tableViewController.toDoList?.taskIsDone(id: id)
}
}
}
| 38d3b7df3e86546de0549dbfc00bdd9513d465b3 | [
"Swift",
"Markdown"
] | 41 | Swift | piotrklobukowski/timekeeper | b9dce6c84d8d94bd478a435768b584753d53ed8b | c0999726774a0ba404661151e4cdd2560df658f9 |
refs/heads/main | <file_sep>import React, { Fragment, useState } from 'react';
import { Drawer } from 'antd';
import { createCatAction } from '../../../../actions/catActions';
import { useDispatch, useSelector } from 'react-redux';
import ImgCrop from 'antd-img-crop';
import { AiOutlineInbox } from 'react-icons/ai';
import './Create.css';
import CatForm from './Form';
import FileUpload from './FileUpload';
const initialValues = {
name: '',
image: '',
};
const Create = ({ onCatClose, visible }) => {
const [values, setValues] = useState(initialValues);
const handleChange = (e) => {
setValues({ ...values, [e.target.name]: e.target.value });
};
const { userLogin } = useSelector((state) => ({ ...state }));
let dispatch = useDispatch();
const handleSubmit = (e) => {
e.preventDefault();
dispatch(createCatAction(userLogin.token, values));
};
return (
<>
<Drawer
title="Create a new category"
width={400}
onClose={onCatClose}
visible={visible}
bodyStyle={{ paddingBottom: 80 }}
className="drawer"
footer={
<div
style={{
textAlign: 'right',
}}
></div>
}
>
<FileUpload setValues={setValues} values={values} />
<CatForm
handleChange={handleChange}
values={values}
handleSubmit={handleSubmit}
/>
</Drawer>
</>
);
};
export default Create;
| a692233d87f2eafd48942cd9c12d3fb8fbcb63a5 | [
"JavaScript"
] | 1 | JavaScript | ahmedmagdy491/silks-kashimr | 750d6e69305d0d1572900b98bc6d8b66952c4013 | cc29e326a5d576811f61e16e8aad84b161671ae1 |
refs/heads/master | <file_sep>## 介绍:
这是一个基于uni极简的生成微信小程序海报的组件,可以快速绘制海报图。使用便捷功能可拆分,支持生成小程序二维码。提供Poster.js文件,在满足海报开发之余,对 canvas Api 进行了封装,只需要配置参数就可以完成绘制。
**[uniapp插件市场](https://ext.dcloud.net.cn/plugin?id=3604)**
**[gitee地址](https://gitee.com/yonggecode/yong_we-chat-poster-of-uniapp)**
国内推荐使用gitee,两个项目会同步更新
****
## 功能:
1. 组件化开发,无需处理图片和二维码下载等异步事件,只需关注配置参数
2. 展示图只用于展示,生成海报的图片归类于绘制内容,需要在绘制内容中配置
3. 可以直接生成小程序二维码并绘制入海报。可能需要根据后端接口修改 appletCode.js 中的请求二维码函数
4. 提供了两个插槽 header 和 save。自定义标题和保存(保存按钮或者别的什么都行)
5. 默认点击图片生成海报图,你也可以换别的触发条件,手动调用内部 createImage 函数
6. Poster.js 功能独立上手简单易配置。无需引入其他组件,只需要canvas标签即可。
7. Poster.js 功能上支持: 图片、文字、矩形、非填充矩形(中间是透的)、圆、直线、曲线。
8. 直线与曲线,直线与曲线,曲线与曲线 之间连接顺畅,配置便利。
## 属性:
imageUrl :目前是必传。只用来展示
imageWidth:展示图片的宽 单位 rpx
imageHeight:展示图片的高 单位 rpx
imageUrl:展示图片的url
drawData:绘制海报的数据参数
config:海报的配置参数
wechatCode:是否需要小程序二维码
wechatCodeConfig:小程序二维码的配置参数
## 配置属性介绍:
drawData:数组内每一个对象都是海报的一个基础绘制单元。目前可绘制(图片、文字、矩形、圆、直线、曲线)
- 属性类型:Array
- 可配置对象:Object
```js
[
{
// 图片类型
type: 'image',
config: {
// 图片地址
url: 'http://yongblog.top/image-1607244573571.png',
// 以画布左上角为顶点,图片的水平位置x,垂直位置y(必填)
// 图片的宽(px),高(px)(必填)
x: 0,
y: 0,
w: 275,
h: 490
},
},
{
// 文本类型
type: 'text',
config: {
text: '这个小程序生成海报插件做的太好啦',
// 以画布左上角为顶点,文本的水平位置x, 垂直位置y (必填)
x: 140,
y: 60,
// 文本属性 颜色(选填,默认black)字体(选填,默认根节点字体)对齐方式(选填,默认center)
color: '#E60012',
font: 'normal bold 16px 仿宋', //同 canvas 对象的 font 属性
textAlign: 'center'// 可选 left right center
}
},
{
// 圆类型
type:'arc',
config:{
// 圆的 水平位置x, 垂直位置y, 半径r, 起始角度sAngle, 结束角度eAngle (必填)
x:200,
y:400,
r:50,
sAngle:0,
eAngle:2 * Math.PI,
// 填充颜色 fillStyle, 边线的粗细lineWidth, 边线的颜色strokeStyle (选填)
fillStyle:'#b8e994',
lineWidth:2,
strokeStyle:'#f6b93b'
}
},
{
// 矩形类型
type:'rect',
config:{
// 矩形的 水平位置x, 垂直位置y, 宽w ,高h (必填)
x:130,
y:500,
w:150,
h:75,
// 填充颜色 fillStyle, 边线的粗细lineWidth, 边线的颜色strokeStyle (选填)
fillStyle:'#b8e994',
lineWidth:2,
strokeStyle:'#f6b93b'
}
},
{
// 非填充矩形类型
type:'stroke_rect',
config:{
// 矩形的 水平位置x, 垂直位置y, 宽w ,高h (必填)
x:130,
y:640,
w:150,
h:75,
// 边线的粗细lineWidth, 边线的颜色strokeStyle (选填)
lineWidth:4,
strokeStyle:'#f6b93b'
}
},
{
// 线类型
type:'line',
config:{
// path 用来描述一段线的路径和类型
path:[{
// points 内的每个对象都是对一段线或多段线的描述
points:[{
// 点的类型 起始点 (必填)
type:'moveTo',
point:[130,780]
},{
// 点的类型 连接点 (必填)
type:'lineTo',
point:[280,780]
}],
// 线头的连接方式 (选填)
lineJoin:'round',
// 线帽的类型 (选填)
lineCap:'round',
// 显得粗细 (选填)
lineWidth:3,
// 线的颜色 (选填)
strokeStyle:'red'
}],
}
},
{
// 线(曲线) 曲线与线相同,都在线这一类中,只不过点与点的连接方式不同而已
type:'line',
config:{
path:[{
points:[{
// 起始点 (必填)
type:'moveTo',
point:[130,1040]
},{
// 连接点 (曲线连接) 这里曲线使用 二次贝塞尔曲线实现的 (必填)
type:'bezierCurveTo',
// 连接点坐标
point:[260,1040],
// 二次贝塞尔曲线的控制点,如果两个点一样可以只穿 P1 (必填)
P1:[195,1100],
//P2:[195,1100],
}],
// 选填
lineWidth:3,
strokeStyle:'red'
}]
}
},
{
// 多段线的配置
type:'line',
config:{
path:[{
// 可以简写成一个二位数组
points:[[130,840],[280,840],[280,890],[260,870]],
lineJoin:'round',
lineCap:'round',
lineWidth:3,
strokeStyle:'red'
},{
//每个 points 就是一个线的开的和结束,每个 point 代表直线的点时也可以不写 type,曲线同理
points:[{
point:[130,920]
},{
point:[160,890]
},{
point:[190,980]
},{
point:[220,920]
}],
lineJoin:'round',
lineCap:'round',
lineWidth:3,
strokeStyle:'red'
}],
}
}
];
```
config:配置最后生成的海报图片
- 属性类型:Object
```js
{
// 图片模式同 uni image组件
imageMode: 'aspectFit',
// 最后海报图片的高度,posterHeight/posterWdith 两者可填一个或两个都填。考虑到图片可能变形建议使用,imageMode:'aspectFit',配置posterHeight即可
posterHeight: '80%',
// 最后海报图片的高度
posterWdith:'auto'
},
```
wechatCodeConfig:生成小程序二维码的配置。这里是服务端调用 https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=ACCESS_TOKEN 接口的方式请求的二维码。我这里调用的是Java同学写好的接口。返回给我的小程序二维码的 buffer 文件。所有在使用的过程中可能需要根据后台同学接口书写的不同需要修改appletCode.js文件。理论上传参和返值应该都差不多。
- 属性类型:Object
```js
{
serverUrl: 'https://xxx.xxx.com/xxx/xxx',
// 请求的服务地址
scene: '123123',
// 所携二维码所携带的数据
config: {
x: 84.5,
y: 320,
w: 100,
h: 100
}
}
```
**如果你的二维码不需要携带用户数据,可以在微信平台上生成一个永久有效的二维码,将图片存至服务器。将二维码当图片以配置drawData的方式处理**
<file_sep>import {base64src} from "@u/base64src.js";
/**
* 微信获取小程序二维码
* @param {String} url 微信服务器地址
* @param {String} scene 二维码所携带的信息
* @return {Object} 返回的二维码对象
**/
export function getWechatCode (url,scene) {
return new Promise((resolve,reject)=>{
wx.request({
url: url,
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
// 二维码携带的信息
data: {
scene: scene
},
success(res) {
//将base64图片转换成本地路径
base64src("data:image/PNG;base64," + res.data.qcode, res => {
// 获取图片信息
wx.getImageInfo({
src: res,
success(res) {
resolve(res);
},
fail(err) {
reject(err);
}
})
})
},
fail(err){
reject(err);
}
})
})
}
<file_sep>const path = require("path");
function resolve(dir) {
return path.join(__dirname, dir);
}
const name = "勇哥的app";
module.exports = {
lintOnSave: process.env.NODE_ENV === "development",
// 路径别名
configureWebpack: {
name: name,
devServer: {
disableHostCheck: true
},
resolve: {
alias: {
"@c": resolve("/components"),
"@u": resolve("/utils"),
},
},
},
}
| 067c40364c28dd9738219dada39eb825c97e4bfc | [
"Markdown",
"JavaScript"
] | 3 | Markdown | yonggeCode/wechat_applet-poster | 789c0ec156c1ae0677593c50c82f15e59adf03a1 | f8b98e80ebb1db3c9cd3da3f4715e35be0d72ae3 |
refs/heads/master | <repo_name>Mantux99/02-06-uzduotis<file_sep>/index.php
<?php
include_once './app/php/php.php'
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" type="text/css" href="./assets/css/bootstrap-grid.css">
<link rel="stylesheet" type="text/css" href="./assets/css/bootstrap-reboot.css">
<link rel="stylesheet" type="text/css" href="./assets/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="./assets/css/style.css">
<title>Hello, world!</title>
</head>
<body>
<form method="GET">
<section class="container mt-5">
<div class="form-row d-flex justify-content-center">
<div class="form-group col-md-2">
<label for="inputname">Vardas</label>
<input type="text" class="form-control" id="inputname" name="name">
</div>
<div class="form-group col-md-2">
<label for="inputyears">Amzius</label>
<input type="text" class="form-control" id="inputyears" name="year">
</div>
<div class="form-group col-md-2">
<label for="inputcity">Miestas</label>
<input type="text" class="form-control" id="inputcity" name="city">
</div>
<div class="form-group col-md-2">
<label for="inputcountry">Salis</label>
<input type="text" class="form-control" id="inputcountry" name="country">
</div>
<button type="submit" class="btn">Sign in</button>
</div>
<table class="table">
<thead>
<?php foreach ($_GET as $key => $value):?>
<th>
<?php print $key; ?>
</th>
<?php endforeach; ?>
</thead>
<tr>
<?php foreach ($_GET as $value):?>
<td><?php
if (!empty($value)) {
print $value;
} ?></td>
<?php endforeach; ?>
</tr>
</table>
</section>
</form>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://kit.fontawesome.com/f41043dc75.js"></script>
<script type="text/javascript" src="./assets/js/jquery.js"></script>
<script type="text/javascript" src="./assets/js/bootstrap.bundle.js"></script>
<script type="text/javascript" src="./assets/js/bootstrap.js"></script>
</body>
</html><file_sep>/app/php/php.php
<?php
//Pirma uzduotis. Formos pagalba $_GET metodu puslapiui perduodami 4 kintamieji: a, b, c, d. Atspausdinkite juos lenteleje ciklo pagalba,
//lenteles eilutes generuojamos dinamiskai. t.y butinai ciklu. Jeigu kintamieji neivedami formoje, jie lenteleje nerodomi, t.y eilute su kintamojo
//reiksme ir pavadinimu nerodoma. Forma generuojama taip pat dinamiskai, t.y ciklo pagalba. Kintamuju sarasas nurodomas masyve.
//t.y gaunama galimybe lengvai papildyti nauju kintamuoju forma, aprasant ji tik masyve.
?> | 63991d23e737d2914d75e2741d7bcba079c1413a | [
"PHP"
] | 2 | PHP | Mantux99/02-06-uzduotis | cecc6a3605ba8a9af956853b49cfa26b8fbb219a | c67d2b76209b2af7bbb323d11280fedde6982e99 |
refs/heads/master | <file_sep>#include "stdafx.h"
#include "n2v.h"
#ifdef USE_OPENMP
#include <omp.h>
#endif
void ParseArgs(int& argc, char* argv[], TStr& InFile, TStr& OutFile,
int& Dimensions, int& WalkLen, int& NumWalks, int& WinSize, int& Iter,
bool& Verbose, double& ParamP, double& ParamQ, bool& Directed, bool& Weighted,
bool& OutputWalks, TStr& InitInFile, TStr& DefaultEmbFile, bool& Sticky, bool& CustomDefault, bool& Cbow)
{
Env = TEnv(argc, argv, TNotify::StdNotify);
Env.PrepArgs(TStr::Fmt("\nAn algorithmic framework for representational learning on graphs."));
InFile = Env.GetIfArgPrefixStr("-i:", "graph/karate.edgelist",
"Input graph path");
InitInFile = Env.GetIfArgPrefixStr("-ie:", "", "Initial embeddings input file. Default is None.");
DefaultEmbFile = Env.GetIfArgPrefixStr("-de:", "", "Default initial embeddings input file. Default is None.");
OutFile = Env.GetIfArgPrefixStr("-o:", "emb/karate.emb",
"Output graph path");
Dimensions = Env.GetIfArgPrefixInt("-d:", 128,
"Number of dimensions. Default is 128");
WalkLen = Env.GetIfArgPrefixInt("-l:", 80,
"Length of walk per source. Default is 80");
NumWalks = Env.GetIfArgPrefixInt("-r:", 10,
"Number of walks per source. Default is 10");
WinSize = Env.GetIfArgPrefixInt("-k:", 10,
"Context size for optimization. Default is 10");
Iter = Env.GetIfArgPrefixInt("-e:", 1,
"Number of epochs in SGD. Default is 1");
ParamP = Env.GetIfArgPrefixFlt("-p:", 1,
"Return hyperparameter. Default is 1");
ParamQ = Env.GetIfArgPrefixFlt("-q:", 1,
"Inout hyperparameter. Default is 1");
Verbose = Env.IsArgStr("-v", "Verbose output.");
Directed = Env.IsArgStr("-dr", "Graph is directed.");
Weighted = Env.IsArgStr("-w", "Graph is weighted.");
Sticky = Env.IsArgStr("-s", "Using \"sticky\" factor.");
OutputWalks = Env.IsArgStr("-ow", "Output random walks instead of embeddings.");
Cbow = Env.IsArgStr("-cbow", "Using CBOW for model training.");
if (Cbow == false)
printf("Using skip-gram for model training.");
if (InitInFile.Len() != 0)
printf("Using node-specific initial embeddings.\n");
if (DefaultEmbFile.Len() != 0)
{
printf("Using custom default embedding values\n\n");
CustomDefault = true;
}
else
CustomDefault = false;
}
//read edgelist graph from input file and construct graph
void ReadGraph(TStr& InFile, bool& Directed, bool& Weighted, bool& Verbose, PWNet& InNet)
{
TFIn FIn(InFile);
int64 LineCnt = 0;
try
{
while (!FIn.Eof())
{
TStr Ln;
FIn.GetNextLn(Ln);
TStr Line, Comment;
Ln.SplitOnCh(Line,'#',Comment);
TStrV Tokens;
Line.SplitOnWs(Tokens);
//isolated nodes show up in edgelist as a single node id, alone on the line
if(Tokens.Len()==1)
{
int64 NId = Tokens[0].GetInt();
if (!InNet->IsNode(NId)){ InNet->AddNode(NId); }
}
if(Tokens.Len()<2){ continue; }
int64 SrcNId = Tokens[0].GetInt();
int64 DstNId = Tokens[1].GetInt();
double Weight = 1.0;
if (Weighted) { Weight = Tokens[2].GetFlt(); }
if (!InNet->IsNode(SrcNId)){ InNet->AddNode(SrcNId); }
if (!InNet->IsNode(DstNId)){ InNet->AddNode(DstNId); }
InNet->AddEdge(SrcNId,DstNId,Weight);
if (!Directed){ InNet->AddEdge(DstNId,SrcNId,Weight); }
LineCnt++;
}
if (Verbose) { printf("Read %lld lines from %s\n", (long long)LineCnt, InFile.CStr()); }
}
catch (PExcept Except)
{
if (Verbose)
{
printf("Read %lld lines from %s, then %s\n", (long long)LineCnt, InFile.CStr(),
Except->GetStr().CStr());
}
}
}
//read initial embeddings values from file, save to hash
//assumes the sticky factors given are quality, so flip them (1-val) to get true sticky factor
void ReadInitialEmbeddings(TStr& InitInFile, TStr& DefaultEmbFile, TIntFltVH& InitEmbeddingsHV, bool& Sticky, TIntFltH& StickyFactorsH, TFltV& DefaultEmbeddingV, TFltV& EmbeddingVariabilityV, bool& Verbose, int Dimensions)
{
//read node-specific initial embeddings
if (InitInFile.Len() != 0)
{
TFIn FIn(InitInFile);
int64 LineCnt = 0;
try
{
while (!FIn.Eof())
{
//get next line of file
TStr Ln;
FIn.GetNextLn(Ln);
//split out comments
TStr Line, Comment;
Ln.SplitOnCh(Line,'#',Comment);
//tokenize the line
TStrV Tokens;
Line.SplitOnWs(Tokens);
//too few tokens, skip this line
if(Tokens.Len() < Dimensions+1){ continue; }
//extract tokens
int64 NId = Tokens[0].GetInt(); //node id
//printf("%ld ", NId);
//params for this node
TFltV CurrV(Dimensions);
for (int i = 0; i < Dimensions; i++)
{
//get embedding value
CurrV[i] = Tokens[i+1].GetFlt();
//printf("%f ", CurrV[i]);
}
InitEmbeddingsHV.AddDat(NId, CurrV); //add vector to this node's initial embeddings
//sticky factor if we have it
if (Sticky && Tokens.Len() >= Dimensions+2)
{
TFlt CurrStick = 1 - Tokens[Dimensions+1].GetFlt();
//printf("(%f)", CurrStick);
StickyFactorsH.AddDat(NId, CurrStick);
}
//printf("\n");
LineCnt++;
}
if (Verbose) { printf("Read %lld lines from %s\n", (long long)LineCnt, InitInFile.CStr()); }
}
catch (PExcept Except)
{
if (Verbose)
{
printf("Read %lld lines from %s, then %s\n", (long long)LineCnt, InitInFile.CStr(),
Except->GetStr().CStr());
}
}
}
//read default values for non-specified initial embeddings
if (DefaultEmbFile.Len() != 0)
{
TFIn FIn(DefaultEmbFile);
try
{
//one line per embedding dimensions, each with two values
//default embedding value for this position, and allowable variability percentage
//example: 0.5 0.15 set embedding to 0.5, += 15% of 0.5
for (int64 i = 0; i < Dimensions; i++)
{
//get next line of file
TStr Line;
FIn.GetNextLn(Line);
//tokenize the line
TStrV Tokens;
Line.SplitOnWs(Tokens);
//extract values
DefaultEmbeddingV[i] = Tokens[0].GetFlt(); //embedding value
EmbeddingVariabilityV[i] = Tokens[1].GetFlt(); //variability percentage
//printf("%f %f\n", DefaultEmbeddingV[i], EmbeddingVariabilityV[i]);
}
if (Verbose) { printf("Read default embedding values\n"); }
}
catch (PExcept Except)
{
if (Verbose)
{
printf("Reading from %s, then %s\n", InitInFile.CStr(),
Except->GetStr().CStr());
}
}
}
}
//dump embeddings (and optional walks) to output file
void WriteOutput(TStr& OutFile, TIntFltVH& EmbeddingsHV, TVVec<TInt, int64>& WalksVV,
bool& OutputWalks)
{
TFOut FOut(OutFile);
if (OutputWalks)
{
for (int64 i = 0; i < WalksVV.GetXDim(); i++)
{
for (int64 j = 0; j < WalksVV.GetYDim(); j++)
{
FOut.PutInt(WalksVV(i,j));
if(j+1==WalksVV.GetYDim())
{
FOut.PutLn();
}
else
{
FOut.PutCh(' ');
}
}
}
return;
}
bool First = 1;
for (int i = EmbeddingsHV.FFirstKeyId(); EmbeddingsHV.FNextKeyId(i);)
{
if (First)
{
FOut.PutInt(EmbeddingsHV.Len());
FOut.PutCh(' ');
FOut.PutInt(EmbeddingsHV[i].Len());
FOut.PutLn();
First = 0;
}
FOut.PutInt(EmbeddingsHV.GetKey(i));
for (int64 j = 0; j < EmbeddingsHV[i].Len(); j++)
{
FOut.PutCh(' ');
FOut.PutFlt(EmbeddingsHV[i][j]);
}
FOut.PutLn();
}
}
int main(int argc, char* argv[])
{
TStr InFile, InitInFile, DefaultEmbFile, OutFile;
int Dimensions, WalkLen, NumWalks, WinSize, Iter;
double ParamP, ParamQ;
bool Directed, Weighted, Verbose, OutputWalks, Sticky, CustomDefault, Cbow;
//parse command line args
ParseArgs(argc, argv, InFile, OutFile, Dimensions, WalkLen, NumWalks, WinSize,
Iter, Verbose, ParamP, ParamQ, Directed, Weighted, OutputWalks, InitInFile, DefaultEmbFile, Sticky, CustomDefault, Cbow);
PWNet InNet = PWNet::New(); //network object
TIntFltVH EmbeddingsHV; //embeddings object - hash int to vector of floats
TVVec <TInt, int64> WalksVV; //walks?
TIntFltVH InitEmbeddingsHV; //initial embedding object setting: hash int to vector of floats
TIntFltH StickyFactorsH; //sticky factors: hash int node id to float
TFltV DefaultEmbeddingV(Dimensions), EmbeddingVariabilityV(Dimensions); //default embedding value and associated variability percentage (one pair per dimension)
ReadGraph(InFile, Directed, Weighted, Verbose, InNet); //read graph from edgelist
//read initial embeddings and/or default embedding values
if (InitInFile.Len() != 0 or DefaultEmbFile.Len() != 0)
ReadInitialEmbeddings(InitInFile, DefaultEmbFile, InitEmbeddingsHV, Sticky, StickyFactorsH, DefaultEmbeddingV, EmbeddingVariabilityV, Verbose, Dimensions);
//run node2vec: network, configuration parameters, objects for walks and embeddings
node2vec(InNet, ParamP, ParamQ, Dimensions, WalkLen, NumWalks, WinSize, Iter,
Verbose, OutputWalks, WalksVV, EmbeddingsHV, InitEmbeddingsHV, StickyFactorsH, DefaultEmbeddingV, EmbeddingVariabilityV, CustomDefault, Cbow);
//dump results
WriteOutput(OutFile, EmbeddingsHV, WalksVV, OutputWalks);
printf("Results written to output file.\n");
return 0;
}
<file_sep>#include "stdafx.h"
#include "word2vec.h"
#ifdef USE_OPENMP
#include <omp.h>
#endif
void ParseArgs(int& argc, char* argv[], TStr& InFile, TStr& OutFile,
int& Dimensions, int& WinSize, int& Iter,
bool& Verbose, TStr& InitInFile, TStr& DefaultEmbFile, bool& Sticky, bool& CustomDefault, bool& Cbow)
{
Env = TEnv(argc, argv, TNotify::StdNotify);
Env.PrepArgs(TStr::Fmt("\nAn algorithmic framework for representational learning on graphs."));
InFile = Env.GetIfArgPrefixStr("-i:", "graph/test.walks",
"Input walks path");
InitInFile = Env.GetIfArgPrefixStr("-ie:", "", "Initial embeddings input file. Default is None.");
DefaultEmbFile = Env.GetIfArgPrefixStr("-de:", "", "Default initial embeddings input file. Default is None.");
OutFile = Env.GetIfArgPrefixStr("-o:", "emb/karate.emb",
"Output embeddings path");
Dimensions = Env.GetIfArgPrefixInt("-d:", 128,
"Number of dimensions. Default is 128");
WinSize = Env.GetIfArgPrefixInt("-k:", 10,
"Context size for optimization. Default is 10");
Iter = Env.GetIfArgPrefixInt("-e:", 1,
"Number of epochs in SGD. Default is 1");
Verbose = Env.IsArgStr("-v", "Verbose output.");
Sticky = Env.IsArgStr("-s", "Using \"sticky\" factor.");
Cbow = Env.IsArgStr("-cbow", "Use CBOW for model training. Default is skip-gram.");
if (Cbow == false)
printf("Using skip-gram for model training.\n");
if (InitInFile.Len() != 0)
printf("Using node-specific initial embeddings.\n");
if (DefaultEmbFile.Len() != 0)
{
printf("Using custom default embedding values\n\n");
CustomDefault = true;
}
else
CustomDefault = false;
}
//read walks from input file
//words/nodes should be represented by integers, excluding 0 (used as sentinel by word2vec code - I think)
void ReadWalks(TStr& InFile, bool& Verbose, TVVec<TInt, int64>& WalksVV)
{
TFIn FIn(InFile);
int64 WalkCnt = 0;
int64 NumWalks, MaxLen;
try
{
//read the first line: number of walks to read and max length
TStr Line;
TStrV Tokens;
FIn.GetNextLn(Line);
Line.SplitOnWs(Tokens);
NumWalks = Tokens[0].GetInt();
MaxLen = Tokens[1].GetInt();
//size the walk container
WalksVV = TVVec<TInt, int64>(NumWalks, MaxLen);
//read remaining lines, one per walk
while (!FIn.Eof())
{
FIn.GetNextLn(Line);
//if entire line is comment, move to next
if (Line[0] == '#')
continue;
//split out comments
TStr Comment;
Line.SplitOnCh(Line,'#',Comment);
Line.SplitOnWs(Tokens);
//loop tokens (words/nodes)
int word;
for (int i = 0; i < Tokens.Len(); i++)
{
word = Tokens[i].GetInt();
WalksVV.PutXY(WalkCnt, i, word);
}
if (Tokens.Len() != 0)
WalkCnt++;
}
if (Verbose) { printf("Read %lld walks with max length %lld from %s\n", (long long)WalkCnt, (long long)MaxLen, InFile.CStr()); }
}
catch (PExcept Except)
{
printf("bad fail\n");
if (Verbose)
{
printf("Read %lld walks from %s, then %s\n", (long long)WalkCnt, InFile.CStr(),
Except->GetStr().CStr());
}
}
}
//read initial embeddings values from file, save to hash
//assumes the sticky factors given are quality, so flip them (1-val) to get true sticky factor
void ReadInitialEmbeddings(TStr& InitInFile, TStr& DefaultEmbFile, TIntFltVH& InitEmbeddingsHV, bool& Sticky, TIntFltH& StickyFactorsH, TFltV& DefaultEmbeddingV, TFltV& EmbeddingVariabilityV, bool& Verbose, int Dimensions)
{
//read node-specific initial embeddings
if (InitInFile.Len() != 0)
{
TFIn FIn(InitInFile);
int64 LineCnt = 0;
try
{
while (!FIn.Eof())
{
//get next line of file
TStr Ln;
FIn.GetNextLn(Ln);
//split out comments
TStr Line, Comment;
Ln.SplitOnCh(Line,'#',Comment);
//tokenize the line
TStrV Tokens;
Line.SplitOnWs(Tokens);
//too few tokens, skip this line
if(Tokens.Len() < Dimensions+1){ continue; }
//extract tokens
int64 NId = Tokens[0].GetInt(); //node id
//printf("%ld ", NId);
//params for this node
TFltV CurrV(Dimensions);
for (int i = 0; i < Dimensions; i++)
{
//get embedding value
CurrV[i] = Tokens[i+1].GetFlt();
//printf("%f ", CurrV[i]);
}
InitEmbeddingsHV.AddDat(NId, CurrV); //add vector to this node's initial embeddings
//sticky factor if we have it
if (Sticky && Tokens.Len() >= Dimensions+2)
{
TFlt CurrStick = 1 - Tokens[Dimensions+1].GetFlt();
//printf("(%f)", CurrStick);
StickyFactorsH.AddDat(NId, CurrStick);
}
//printf("\n");
LineCnt++;
}
if (Verbose) { printf("Read %lld lines from %s\n", (long long)LineCnt, InitInFile.CStr()); }
}
catch (PExcept Except)
{
if (Verbose)
{
printf("Read %lld lines from %s, then %s\n", (long long)LineCnt, InitInFile.CStr(),
Except->GetStr().CStr());
}
}
}
//read default values for non-specified initial embeddings
if (DefaultEmbFile.Len() != 0)
{
TFIn FIn(DefaultEmbFile);
try
{
//one line per embedding dimensions, each with two values
//default embedding value for this position, and allowable variability percentage
//example: 0.5 0.15 set embedding to 0.5, += 15% of 0.5
for (int64 i = 0; i < Dimensions; i++)
{
//get next line of file
TStr Line;
FIn.GetNextLn(Line);
//tokenize the line
TStrV Tokens;
Line.SplitOnWs(Tokens);
//extract values
DefaultEmbeddingV[i] = Tokens[0].GetFlt(); //embedding value
EmbeddingVariabilityV[i] = Tokens[1].GetFlt(); //variability percentage
//printf("%f %f\n", DefaultEmbeddingV[i], EmbeddingVariabilityV[i]);
}
if (Verbose) { printf("Read default embedding values\n"); }
}
catch (PExcept Except)
{
if (Verbose)
{
printf("Reading from %s, then %s\n", InitInFile.CStr(),
Except->GetStr().CStr());
}
}
}
}
//dump embeddings (and optional walks) to output file
void WriteOutput(TStr& OutFile, TIntFltVH& EmbeddingsHV)
{
TFOut FOut(OutFile);
bool First = 1;
for (int i = EmbeddingsHV.FFirstKeyId(); EmbeddingsHV.FNextKeyId(i);)
{
if (First)
{
FOut.PutInt(EmbeddingsHV.Len());
FOut.PutCh(' ');
FOut.PutInt(EmbeddingsHV[i].Len());
FOut.PutLn();
First = 0;
}
FOut.PutInt(EmbeddingsHV.GetKey(i));
for (int64 j = 0; j < EmbeddingsHV[i].Len(); j++)
{
FOut.PutCh(' ');
FOut.PutFlt(EmbeddingsHV[i][j]);
}
FOut.PutLn();
}
}
int main(int argc, char* argv[])
{
TStr InFile, InitInFile, DefaultEmbFile, OutFile;
int Dimensions, WinSize, Iter;
bool Verbose, Sticky, CustomDefault, Cbow;
//parse command line args
ParseArgs(argc, argv, InFile, OutFile, Dimensions, WinSize,
Iter, Verbose, InitInFile, DefaultEmbFile, Sticky, CustomDefault, Cbow);
TIntFltVH EmbeddingsHV; //embeddings object - hash int to vector of floats
TVVec <TInt, int64> WalksVV; //walks
TIntFltVH InitEmbeddingsHV; //initial embedding object setting: hash int to vector of floats
TIntFltH StickyFactorsH; //sticky factors: hash int node id to float
TFltV DefaultEmbeddingV(Dimensions), EmbeddingVariabilityV(Dimensions); //default embedding value and associated variability percentage (one pair per dimension)
ReadWalks(InFile, Verbose, WalksVV); //read walks from input file
//read initial embeddings and/or default embedding values
if (InitInFile.Len() != 0 or DefaultEmbFile.Len() != 0)
ReadInitialEmbeddings(InitInFile, DefaultEmbFile, InitEmbeddingsHV, Sticky, StickyFactorsH, DefaultEmbeddingV, EmbeddingVariabilityV, Verbose, Dimensions);
//run word2vec to get embeddings
LearnEmbeddings(WalksVV, Dimensions, WinSize, Iter, Verbose, EmbeddingsHV, InitEmbeddingsHV, StickyFactorsH, CustomDefault, DefaultEmbeddingV, EmbeddingVariabilityV, Cbow);
//dump results
WriteOutput(OutFile, EmbeddingsHV);
printf("Results written to output file %s\n", OutFile.CStr());
return 0;
}
<file_sep>#
# Makefile for non-Microsoft compilers
#
all: MakeAll
MakeAll:
$(MAKE) -C snap-core
$(MAKE) -C drivers
clean:
$(MAKE) clean -C snap-core
$(MAKE) clean -C drivers
rm -rf Debug Release ipch
| c2296059bb1e9f4c7a3275e80cc44c30b33d2b84 | [
"Makefile",
"C++"
] | 3 | C++ | rkrohn/node2vec_param_infer | e96684744fd5ff5993310d354530f03b91adead4 | 8f017e0594f1f870c0935472f9da29c493b25181 |
refs/heads/master | <file_sep>using MahApps.Metro;
using System.Windows;
using System.Windows.Media;
namespace HonglornWPF.ViewModels.ColorMenuData
{
class AccentColorMenuData : ColorMenuData
{
public AccentColorMenuData(string name, Brush borderColorBrush, Brush fillColorBrush) : base(name, borderColorBrush, fillColorBrush) { }
protected override void ChangeColor()
{
ThemeManager.ChangeAppStyle(Application.Current, ThemeManager.GetAccent(Name), ThemeManager.DetectAppStyle(Application.Current).Item1);
}
}
}<file_sep>using System.Collections.Generic;
namespace HonglornBL.Import
{
abstract class StudentImporter : IStudentImporter
{
protected const string SurnameHeaderColumn = "Nachname";
protected const string ForenameHeaderColumn = "Vorname";
protected const string CoursenameHeaderColumn = "Kursbezeichnung";
protected const string SexHeaderColumn = "Geschlecht";
protected const string YearofbirthHeaderColumn = "Geburtsjahr";
public abstract ICollection<ImportedStudentRecord> ReadStudentsFromFile(string filePath);
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Data;
using HonglornBL.Models.Entities;
namespace HonglornWPF
{
class CompetitionDisciplineValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
ValidationResult result = ValidationResult.ValidResult;
BindingGroup bindingGroup = value as BindingGroup;
if (bindingGroup != null)
{
foreach (var bindingSource in bindingGroup.Items)
{
CompetitionDiscipline discipline = bindingSource as CompetitionDiscipline;
StringBuilder validationMessageBuilder = new StringBuilder();
if (string.IsNullOrWhiteSpace(discipline.Name))
{
validationMessageBuilder.AppendLine("The name of the discipline must not be empty.");
}
if (string.IsNullOrWhiteSpace(discipline.Unit))
{
validationMessageBuilder.AppendLine("The unit of the discipline must not be empty.");
}
if (validationMessageBuilder.Length > 0)
{
result = new ValidationResult(false, validationMessageBuilder.ToString());
}
}
}
return result;
}
}
}<file_sep>using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace HonglornWPF.Converter
{
[ValueConversion(typeof(string), typeof(Visibility))]
class StringToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Visibility trueValue;
Visibility falseValue;
if (parameter == null || !(bool)parameter)
{
trueValue = Visibility.Visible;
falseValue = Visibility.Collapsed;
}
else
{
trueValue = Visibility.Collapsed;
falseValue = Visibility.Visible;
}
return !string.IsNullOrWhiteSpace(value?.ToString()) ? trueValue : falseValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}<file_sep>using HonglornBL.Models.Entities;
namespace HonglornBL
{
class CompetitionDisciplineContainer : DisciplineContainer<CompetitionDiscipline> { }
}<file_sep>using System;
namespace HonglornBL.Calculation.Traditional
{
abstract class ScoreCalculator : IScoreCalculator
{
protected readonly float ConstantA;
protected readonly float ConstantC;
protected readonly float Measurement;
protected ScoreCalculator(float constantA, float constantC, float measurement)
{
ConstantA = constantA;
ConstantC = constantC;
Measurement = measurement;
}
/// <summary>
/// Sets the score to 0 if negative and cuts off all decimal places.
/// </summary>
/// <returns>The score ready to be shown to the user.</returns>
public ushort CalculateScore()
{
double rawScore = CalculateRawScore();
return CleanScore(rawScore);
}
protected abstract double CalculateRawScore();
static ushort CleanScore(double rawScore)
{
return (ushort)Math.Max(0, Math.Floor(rawScore));
}
}
}<file_sep>namespace HonglornWPF.Views
{
/// <summary>
/// Interaction logic for CreateCompetitionDisciplineView.xaml
/// </summary>
partial class CreateCompetitionDisciplineView
{
public CreateCompetitionDisciplineView()
{
InitializeComponent();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using HonglornBL.Enums;
namespace HonglornBL.Calculation.Competition
{
class CompetitionCalculator
{
readonly ICollection<Tuple<Guid, RawMeasurement>> studentMeasurements;
readonly bool sprintLowIsBetter;
readonly bool jumpLowIsBetter;
readonly bool throwLowIsBetter;
readonly bool middleDistanceLowIsBetter;
internal CompetitionCalculator(bool sprintLowIsBetter, bool jumpLowIsBetter, bool throwLowIsBetter, bool middleDistanceLowIsBetter)
{
studentMeasurements = new List<Tuple<Guid, RawMeasurement>>();
this.sprintLowIsBetter = sprintLowIsBetter;
this.jumpLowIsBetter = jumpLowIsBetter;
this.throwLowIsBetter = throwLowIsBetter;
this.middleDistanceLowIsBetter = middleDistanceLowIsBetter;
}
internal void AddStudentMeasurement(Guid identifier, float? sprint, float? jump, float? @throw, float? middleDistance)
{
studentMeasurements.Add(new Tuple<Guid, RawMeasurement>(identifier, new RawMeasurement(sprint, jump, @throw, middleDistance)));
}
internal IEnumerable<ICompetitionResult> Results()
{
ICollection<CompetitionCalculatorContainer> containers = (from s in studentMeasurements
select new CompetitionCalculatorContainer(s.Item1, s.Item2.Sprint, s.Item2.Jump, s.Item2.Throw, s.Item2.MiddleDistance)).ToList();
CalculateScoresForDiscipline(containers, sprintLowIsBetter, c => c.SprintValue, c => c.SprintScore, (c, s) => c.SprintScore = s);
CalculateScoresForDiscipline(containers, jumpLowIsBetter, c => c.JumpValue, c => c.JumpScore, (c, s) => c.JumpScore = s);
CalculateScoresForDiscipline(containers, throwLowIsBetter, c => c.ThrowValue, c => c.ThrowScore, (c, s) => c.ThrowScore = s);
CalculateScoresForDiscipline(containers, middleDistanceLowIsBetter, c => c.MiddleDistanceValue, c => c.MiddleDistanceScore, (c, s) => c.MiddleDistanceScore = s);
CalculateScoresForDiscipline(containers, true, c => c.TotalScore, c => c.Rank, (c, r) => c.Rank = r);
containers = containers.OrderBy(c => c.Rank).ToList();
int lastRank = containers.First().Rank;
var currentCertificate = Certificate.Honorary;
var count = 0;
foreach (CompetitionCalculatorContainer container in containers)
{
if (container.Rank != lastRank)
{
float percentile = (float) count / containers.Count * 100;
if (percentile > 70)
{
currentCertificate = Certificate.Participation;
}
else if (percentile > 20)
{
currentCertificate = Certificate.Victory;
}
lastRank = container.Rank;
}
container.Certificate = currentCertificate;
count++;
}
return containers;
}
static void CalculateScoresForDiscipline(ICollection<CompetitionCalculatorContainer> containers, bool lowIsBetter, Func<CompetitionCalculatorContainer, float?> selectValue, Func<CompetitionCalculatorContainer, ushort> selectScore, Action<CompetitionCalculatorContainer, ushort> setScore)
{
if (lowIsBetter)
{
containers = containers.OrderBy(c => selectValue(c) == null).ThenBy(selectValue).ToList();
}
else
{
containers = containers.OrderBy(c => selectValue(c) == null).ThenByDescending(selectValue).ToList();
}
float? lastValue = selectValue(containers.First());
ushort lastScore = 1;
ushort count = 1;
foreach (CompetitionCalculatorContainer c in containers)
{
if (selectValue(c) == lastValue)
{
setScore(c, lastScore);
}
else
{
setScore(c, count);
lastScore = selectScore(c);
lastValue = selectValue(c);
}
count++;
}
}
}
}<file_sep>using System.ComponentModel.DataAnnotations;
namespace HonglornBL.Models.Entities
{
public class CompetitionDiscipline : Discipline
{
/// <summary>
/// Indicates whether a lower value in this discipline indicates a better performance of the student.
/// </summary>
/// <remarks>
/// Primarily used for running disciplines, where less time is better.
/// </remarks>
[Required]
public bool LowIsBetter { get; set; }
public CompetitionDiscipline Clone()
{
return new CompetitionDiscipline
{
Name = Name,
Type = Type,
Unit = Unit,
LowIsBetter = LowIsBetter
};
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
using HonglornBL.Enums;
namespace HonglornBL.Models.Entities
{
[DebuggerDisplay("{Forename} {Surname}, {Sex}, YOB: {YearOfBirth}, ID: {PKey}")]
public class Student
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid PKey { get; set; } = Guid.NewGuid();
[Required]
[StringLength(45)]
public string Surname { get; set; }
[Required]
[StringLength(45)]
public string Forename { get; set; }
[Required]
public Sex Sex { get; set; }
[Required]
public short YearOfBirth { get; set; }
public virtual ICollection<Competition> Competitions { get; set; }
public virtual ICollection<StudentCourseRel> StudentCourseRel { get; set; }
public Student()
{
Competitions = new HashSet<Competition>();
StudentCourseRel = new HashSet<StudentCourseRel>();
}
internal Student(string forename, string surname, Sex sex, short yearOfBirth) : this()
{
Forename = forename;
Surname = surname;
Sex = sex;
YearOfBirth = yearOfBirth;
}
internal void AddStudentCourseRel(short year, string courseName)
{
var rel = new StudentCourseRel
{
Year = year,
CourseName = courseName
};
StudentCourseRel.Add(rel);
}
}
}<file_sep>using System;
using System.Globalization;
using System.Linq;
using System.Windows.Data;
namespace HonglornWPF.Converter
{
[ValueConversion(typeof(object[]), typeof(bool))]
class ObjectsNotNullToBoolConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values.All(i => i != null);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}<file_sep>using System;
using System.Windows.Markup;
namespace HonglornWPF.Extensions
{
public class EnumBindingSourceExtension : MarkupExtension
{
readonly Type enumType;
public EnumBindingSourceExtension(Type enumType)
{
this.enumType = enumType;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return Enum.GetValues(enumType);
}
}
}<file_sep># Honglorn
## Description
A program to calculate results for the German sports event "Bundesjugendspiele".
The ultimate goal will be to fully support everything mentioned in the official [manual](https://www.bundesjugendspiele.de/downloads/handbuch/handbuch_komplett_15_07_2017.pdf).
***work in progress***
## Continuous Integration
### Master
[](https://danghor.visualstudio.com/Honglorn/_build?definitionId=3)
### Develop
[](https://danghor.visualstudio.com/Honglorn/_build?definitionId=4)
## Analyzer
[](https://sonarcloud.io/dashboard?id=Honglorn)
## Chat
[](https://gitter.im/Honglorn)
## Requirements/Contribution
- Visual Studio 2017 or higher (C# 7)
- MySQL Database
- .NET Framework 4 for Application, 4.7 for Unit Testing
<file_sep>namespace HonglornBL
{
class RawMeasurement
{
internal float? Sprint { get; }
internal float? Jump { get; }
internal float? Throw { get; }
internal float? MiddleDistance { get; }
internal RawMeasurement(float? sprint, float? jump, float? @throw, float? middleDistance)
{
Sprint = sprint;
Jump = jump;
Throw = @throw;
MiddleDistance = middleDistance;
}
}
}<file_sep>using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Xml.Serialization;
using HonglornBL.Models.Entities;
using HonglornBL.Properties;
namespace HonglornBL.Models.Framework
{
class HonglornDbInitializer<T> : CreateDatabaseIfNotExists<T> where T : HonglornDb
{
protected override void Seed(T context)
{
InitializeEntity<TraditionalDiscipline>(Resources.ArrayOfTraditionalDiscipline, context.TraditionalDiscipline);
InitializeEntity<TraditionalReportMeta>(Resources.ArrayOfTraditionalReportMeta, context.TraditionalReportMeta);
base.Seed(context);
}
static void InitializeEntity<TEntity>(string xmlContent, DbSet set)
{
var serializer = new XmlSerializer(typeof(TEntity[]));
using (var reader = new StringReader(xmlContent))
{
set.AddRange((IEnumerable<TEntity>) serializer.Deserialize(reader));
}
}
}
}<file_sep>using HonglornBL.Enums;
using HonglornBL.Models.Entities;
namespace HonglornBL.Calculation.Traditional
{
class TraditionalCalculator
{
readonly TraditionalDiscipline discipline;
readonly float? value;
public TraditionalCalculator(TraditionalDiscipline discipline, float? value)
{
this.discipline = discipline;
this.value = value;
}
/// <summary>
/// Calculates the score based on the given discipline and value.
/// </summary>
/// <returns>The score calculated by designated formulas.</returns>
internal ushort CalculateScore()
{
IScoreCalculator calculator = GetCalculator();
return calculator.CalculateScore();
}
IScoreCalculator GetCalculator()
{
IScoreCalculator calculator;
if (value == null)
{
calculator = new ZeroScoreCalculator();
}
else if (discipline.Type == DisciplineType.Sprint || discipline.Type == DisciplineType.MiddleDistance)
{
calculator = new RunningScoreCalculator(value.Value, discipline.Distance.Value, discipline.ConstantA, discipline.ConstantC, discipline.Overhead);
}
else
{
calculator = new JumpThrowScoreCalculator(value.Value, discipline.ConstantA, discipline.ConstantC);
}
return calculator;
}
}
}<file_sep>using System.IO;
using Microsoft.VisualStudio.TestTools.UITesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace HonglornCUT
{
/// <summary>
/// Summary description for CodedUITest1
/// </summary>
[CodedUITest]
public class CodedUITest1
{
public TestContext TestContext { get; set; }
readonly UIMap uiMap = new UIMap();
ApplicationUnderTest app;
public CodedUITest1() { }
[TestInitialize]
public void Initialize()
{
app = ApplicationUnderTest.Launch(Path.Combine(new DirectoryInfo(TestContext.TestDir).Parent.Parent.FullName, @"HonglornWPF\bin\debug\HonglornWPF.exe"), "", "memory");
}
[TestCleanup]
public void Cleanup()
{
app.Close();
}
[TestMethod]
public void CodedUiTestMethod1()
{
// To generate code for this test, select "Generate Code for Coded UI Test" from the shortcut menu and select one of the menu items.
uiMap.ErrorShownOnImportEmptyPath();
uiMap.AssertMethod1();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Common;
using MySql.Data.MySqlClient;
namespace HonglornBL.Models.Framework
{
class HonglornDbFactory
{
static readonly IDictionary<string, Tuple<Func<string, DbConnection>, Func<DbConnection, HonglornDb>>> ProviderMap = new Dictionary<string, Tuple<Func<string, DbConnection>, Func<DbConnection, HonglornDb>>>
{
{
"MySql.Data.MySqlClient",
new Tuple<Func<string, DbConnection>, Func<DbConnection, HonglornDb>> (conString => new MySqlConnection(conString), con => new HonglornMySqlDb(con))
}
};
DbConnection Connection { get; }
internal Func<HonglornDb> CreateContext { get; }
internal HonglornDbFactory(ConnectionStringSettings settings)
{
Tuple<Func<string, DbConnection>, Func<DbConnection, HonglornDb>> functions = ProviderMap[settings.ProviderName];
Connection = functions.Item1(settings.ConnectionString);
CreateContext = () => functions.Item2(Connection);
}
internal HonglornDbFactory(DbConnection connection)
{
Connection = connection;
CreateContext = () => new HonglornDb(Connection);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using HonglornBL.Calculation.Competition;
using HonglornBL.Calculation.Traditional;
using HonglornBL.Enums;
using HonglornBL.Import;
using HonglornBL.Interfaces;
using HonglornBL.Models.Entities;
using HonglornBL.Models.Framework;
using static HonglornBL.Prerequisites;
namespace HonglornBL
{
public class Honglorn
{
HonglornDbFactory ContextFactory { get; }
public Honglorn(System.Configuration.ConnectionStringSettings connectionStringSettings)
{
if (string.IsNullOrWhiteSpace(connectionStringSettings.ProviderName))
{
throw new ArgumentException(nameof(connectionStringSettings.ProviderName));
}
if (string.IsNullOrWhiteSpace(connectionStringSettings.ConnectionString))
{
throw new ArgumentException(nameof(connectionStringSettings.ConnectionString));
}
ContextFactory = new HonglornDbFactory(connectionStringSettings);
}
public Honglorn(DbConnection connection)
{
ContextFactory = new HonglornDbFactory(connection);
}
public IEnumerable<IStudentPerformance> StudentPerformances(string course, short year)
{
using (HonglornDb db = ContextFactory.CreateContext())
{
var result = new List<IStudentPerformance>();
IQueryable<Student> relevantStudents = (from s in db.Student
where s.StudentCourseRel.Any(rel => rel.Year == year && rel.CourseName == course)
orderby s.Surname, s.Forename, s.YearOfBirth descending
select s).Include(s => s.Competitions);
foreach (Student student in relevantStudents)
{
Competition competition = student.Competitions.SingleOrDefault(c => c.Year == year);
result.Add(new StudentPerformance(student.PKey, student.Forename, student.Surname, competition?.Sprint, competition?.Jump, competition?.Throw, competition?.MiddleDistance));
}
return result;
}
}
ICollection<Student> GetStudents(string course, short year)
{
using (HonglornDb db = ContextFactory.CreateContext())
{
return (from s in db.Student
where s.StudentCourseRel.Any(rel => rel.Year == year && rel.CourseName == course)
orderby s.Surname, s.Forename, s.YearOfBirth descending
select s).Include(s => s.Competitions).ToArray();
}
}
public Task<IEnumerable<IResult>> GetResultsAsync(string course, short year)
{
return Task.Factory.StartNew(() => GetResults(course, year));
}
IEnumerable<IResult> GetResults(string course, short year)
{
IEnumerable<IResult> results;
IEnumerable<Student> students = GetStudents(course, year);
string className = GetClassName(course);
using (HonglornDb db = ContextFactory.CreateContext())
{
DisciplineCollection disciplines = (from d in db.DisciplineCollection
where d.ClassName == className
&& d.Year == year
select d).SingleOrDefault();
if (disciplines == null)
{
throw new DataException($"No disciplines have been configured for class {className} in year {year}. Therefore, no results can be calculated.");
}
Discipline[] disciplineArray = { disciplines.MaleSprint, disciplines.MaleJump, disciplines.MaleThrow, disciplines.MaleMiddleDistance, disciplines.FemaleSprint, disciplines.FemaleJump, disciplines.FemaleThrow, disciplines.FemaleMiddleDistance };
if (disciplineArray.All(d => d is TraditionalDiscipline))
{
var disciplineContainer = new TraditionalDisciplineContainer
{
MaleSprint = disciplines.MaleSprint as TraditionalDiscipline,
MaleJump = disciplines.MaleJump as TraditionalDiscipline,
MaleThrow = disciplines.MaleThrow as TraditionalDiscipline,
MaleMiddleDistance = disciplines.MaleMiddleDistance as TraditionalDiscipline,
FemaleSprint = disciplines.FemaleSprint as TraditionalDiscipline,
FemaleJump = disciplines.FemaleJump as TraditionalDiscipline,
FemaleThrow = disciplines.FemaleThrow as TraditionalDiscipline,
FemaleMiddleDistance = disciplines.FemaleMiddleDistance as TraditionalDiscipline
};
results = CalculateTraditionalResults(students, year, disciplineContainer);
}
else if (disciplineArray.All(d => d is CompetitionDiscipline))
{
var disciplineContainer = new CompetitionDisciplineContainer
{
MaleSprint = disciplines.MaleSprint as CompetitionDiscipline,
MaleJump = disciplines.MaleJump as CompetitionDiscipline,
MaleThrow = disciplines.MaleThrow as CompetitionDiscipline,
MaleMiddleDistance = disciplines.MaleMiddleDistance as CompetitionDiscipline,
FemaleSprint = disciplines.FemaleSprint as CompetitionDiscipline,
FemaleJump = disciplines.FemaleJump as CompetitionDiscipline,
FemaleThrow = disciplines.FemaleThrow as CompetitionDiscipline,
FemaleMiddleDistance = disciplines.FemaleMiddleDistance as CompetitionDiscipline
};
results = CalculateCompetitionResults(students, year, disciplineContainer);
}
else
{
throw new DataException($"For class {className} in year {year}, some configured disciplines are traditional disciplines, while other disciplines are competition disciplines. A result can only be calculated when all disciplines are of the same type.");
}
}
return results;
}
IEnumerable<IResult> CalculateCompetitionResults(IEnumerable<Student> students, short year, CompetitionDisciplineContainer disciplineCollection)
{
var competitionResults = new List<ICompetitionResult>();
using (HonglornDb db = ContextFactory.CreateContext())
{
IEnumerable<string> classes = (from s in students
join rel in db.StudentCourseRel on s.PKey equals rel.StudentPKey
where rel.Year == year
select GetClassName(rel.CourseName)).Distinct();
foreach (string @class in classes)
{
IEnumerable<Student> maleStudents = (from s in db.Student
join rel in db.StudentCourseRel on s.PKey equals rel.StudentPKey
where s.Sex == Sex.Male && rel.Year == year
select new { s, rel.CourseName }).AsEnumerable().Where(i => GetClassName(i.CourseName) == @class).Select(i => i.s).ToList();
IEnumerable<Student> femaleStudents = (from s in db.Student
join rel in db.StudentCourseRel on s.PKey equals rel.StudentPKey
where s.Sex == Sex.Female && rel.Year == year
select new { s, rel.CourseName }).AsEnumerable().Where(i => GetClassName(i.CourseName) == @class).Select(i => i.s).ToList();
if (maleStudents.Any())
{
var maleCalculator = new CompetitionCalculator(disciplineCollection.MaleSprint.LowIsBetter, disciplineCollection.MaleJump.LowIsBetter, disciplineCollection.MaleThrow.LowIsBetter, disciplineCollection.MaleMiddleDistance.LowIsBetter);
foreach (Student maleStudent in maleStudents)
{
Competition competition = (from sc in maleStudent.Competitions
where sc.Year == year
select sc).SingleOrDefault() ?? new Competition();
maleCalculator.AddStudentMeasurement(maleStudent.PKey, competition.Sprint, competition.Jump, competition.Throw, competition.MiddleDistance);
}
competitionResults.AddRange(maleCalculator.Results());
}
if (femaleStudents.Any())
{
var femaleCalculator = new CompetitionCalculator(disciplineCollection.FemaleSprint.LowIsBetter, disciplineCollection.FemaleJump.LowIsBetter, disciplineCollection.FemaleThrow.LowIsBetter, disciplineCollection.FemaleMiddleDistance.LowIsBetter);
foreach (Student femaleStudent in femaleStudents)
{
Competition competition = (from sc in femaleStudent.Competitions
where sc.Year == year
select sc).SingleOrDefault() ?? new Competition();
femaleCalculator.AddStudentMeasurement(femaleStudent.PKey, competition.Sprint, competition.Jump, competition.Throw, competition.MiddleDistance);
}
competitionResults.AddRange(femaleCalculator.Results());
}
}
}
return from c in competitionResults
join s in students on c.Identifier equals s.PKey
orderby s.Surname, s.Forename, s.YearOfBirth descending
select new Result(s.Forename, s.Surname, c.SprintScore, c.JumpScore, c.ThrowScore, c.MiddleDistanceScore, c.Rank, (ushort)(c.SprintScore + c.JumpScore + c.ThrowScore + c.MiddleDistanceScore), c.Certificate);
}
IEnumerable<IResult> CalculateTraditionalResults(IEnumerable<Student> students, short year, TraditionalDisciplineContainer disciplineCollection)
{
ICollection<IResult> results = new List<IResult>();
foreach (Student student in students)
{
Competition competition = (from sc in student.Competitions
where sc.Year == year
select sc).SingleOrDefault() ?? new Competition();
TraditionalDiscipline[] disciplines;
if (student.Sex == Sex.Male)
{
disciplines = new[] { disciplineCollection.MaleSprint, disciplineCollection.MaleJump, disciplineCollection.MaleThrow, disciplineCollection.MaleMiddleDistance };
}
else
{
disciplines = new[] { disciplineCollection.FemaleSprint, disciplineCollection.FemaleJump, disciplineCollection.FemaleThrow, disciplineCollection.FemaleMiddleDistance };
}
var scores = new List<ushort>();
var disciplineValuePairs = new Dictionary<TraditionalDiscipline, float?>
{
{ disciplines[0], competition.Sprint },
{ disciplines[1], competition.Jump },
{ disciplines[2], competition.Throw },
{ disciplines[3], competition.MiddleDistance }
};
foreach (var pair in disciplineValuePairs)
{
var calculator = new TraditionalCalculator(pair.Key, pair.Value);
scores.Add(calculator.CalculateScore());
}
var totalScore = (ushort)scores.OrderByDescending(s => s).Take(3).Sum(s => s);
int studentAge = year - student.YearOfBirth;
results.Add(new Result(student.Forename, student.Surname, scores[0], scores[1], scores[2], scores[3], 0, totalScore, DetermineTraditionalCertificate(student.Sex, studentAge, totalScore)));
}
return results;
}
Certificate DetermineTraditionalCertificate(Sex sex, int age, ushort totalScore)
{
Certificate result;
using (HonglornDb db = ContextFactory.CreateContext())
{
//bug: exception when students are too young to be in this list
var scoreBoundaries = (from meta in db.TraditionalReportMeta
where meta.Sex == sex
&& meta.Age <= age
orderby meta.Age descending
select new { meta.Age, meta.HonoraryCertificateScore, meta.VictoryCertificateScore }).First();
if (totalScore >= scoreBoundaries.HonoraryCertificateScore)
{
result = Certificate.Honorary;
}
else if (totalScore >= scoreBoundaries.VictoryCertificateScore)
{
result = Certificate.Victory;
}
else
{
result = Certificate.Participation;
}
}
return result;
}
public void UpdateSingleStudentCompetition(Guid studentPKey, short year, float? sprint, float? jump, float? @throw, float? middleDistance)
{
using (HonglornDb db = ContextFactory.CreateContext())
{
Student student = db.Student.Find(studentPKey);
if (student != null)
{
Competition existingCompetition = (from c in student.Competitions
where c.Year == year
select c).SingleOrDefault();
if ((sprint ?? jump ?? @throw ?? middleDistance) == null)
{
// Delete
if (existingCompetition != null)
{
db.Competition.Remove(existingCompetition);
}
}
else
{
if (existingCompetition == null)
{
// Create
student.Competitions.Add(new Competition
{
Year = year,
Sprint = sprint,
Jump = jump,
Throw = @throw,
MiddleDistance = middleDistance
});
}
else
{
// Update
existingCompetition.Sprint = sprint;
existingCompetition.Jump = jump;
existingCompetition.Throw = @throw;
existingCompetition.MiddleDistance = middleDistance;
}
}
db.SaveChanges();
}
else
{
throw new ArgumentException($"No {nameof(Student)} with such key in database: {studentPKey}");
}
}
}
public ICollection<IDiscipline> FilteredCompetitionDisciplines(DisciplineType disciplineType)
{
using (HonglornDb db = ContextFactory.CreateContext())
{
return (from d in db.CompetitionDiscipline
where d.Type == disciplineType
select d).OrderBy(d => d.Name).ToArray();
}
}
public ICollection<IDiscipline> FilteredTraditionalDisciplines(DisciplineType disciplineType, Sex sex)
{
using (HonglornDb db = ContextFactory.CreateContext())
{
return (from d in db.TraditionalDiscipline
where d.Type == disciplineType && d.Sex == sex
select d).OrderBy(d => d.Name).ToArray();
}
}
public ICollection<CompetitionDiscipline> AllCompetitionDisciplines()
{
using (HonglornDb db = ContextFactory.CreateContext())
{
return db.CompetitionDiscipline.ToArray();
}
}
public IDisciplineCollection AssignedDisciplines(string className, short year)
{
using (HonglornDb db = ContextFactory.CreateContext())
{
return (from col in db.DisciplineCollection
where col.ClassName == className && col.Year == year
select col).SingleOrDefault();
}
}
public void CreateCompetitionDiscipline(DisciplineType type, string name, string unit, bool lowIsBetter)
{
using (HonglornDb db = ContextFactory.CreateContext())
{
db.CompetitionDiscipline.Add(new CompetitionDiscipline
{
Type = type,
Name = name,
Unit = unit,
LowIsBetter = lowIsBetter
});
db.SaveChanges();
}
}
public void UpdateCompetitionDiscipline(Guid disciplinePKey, DisciplineType type, string name, string unit, bool lowIsBetter)
{
using (HonglornDb db = ContextFactory.CreateContext())
{
CompetitionDiscipline competition = db.CompetitionDiscipline.Find(disciplinePKey);
if (competition == null)
{
throw new ArgumentException($"A {nameof(CompetitionDiscipline)} with PKey {disciplinePKey} does not exist in the database.", nameof(disciplinePKey));
}
competition.Type = type;
competition.Name = name;
competition.Unit = unit;
competition.LowIsBetter = lowIsBetter;
db.SaveChanges();
}
}
public void DeleteCompetitionDiscipline(Guid disciplinePKey)
{
try
{
using (HonglornDb db = ContextFactory.CreateContext())
{
var discipline = new CompetitionDiscipline
{
PKey = disciplinePKey
};
db.Entry(discipline).State = EntityState.Deleted;
db.SaveChanges();
}
}
catch (DbUpdateConcurrencyException ex)
{
throw new ArgumentException($"A {nameof(CompetitionDiscipline)} with PKey {disciplinePKey} does not exist in the database.", nameof(disciplinePKey), ex);
}
}
/// <summary>
/// Return the GameType currently set in DisciplineMeta for the selected class name and year or nothing, if no GameType
/// is set.
/// </summary>
/// <param name="className">The class name of the class the GameType is to be returned.</param>
/// <param name="year">The year for which the GameType is valid.</param>
/// <returns>
/// A member of the Enum GameType that represents the GameType set in DisciplineMeta for the corresponding class
/// in the given year.
/// </returns>
/// <remarks></remarks>
public Game? GetGameType(string className, short year)
{
Game? result = null;
using (HonglornDb db = ContextFactory.CreateContext())
{
DisciplineCollection disciplineCollection = (from c in db.DisciplineCollection
where c.ClassName == className
&& c.Year == year
select c).SingleOrDefault();
if (disciplineCollection != null)
{
Discipline[] disciplines = { disciplineCollection.MaleSprint, disciplineCollection.MaleJump, disciplineCollection.MaleThrow, disciplineCollection.MaleMiddleDistance, disciplineCollection.FemaleSprint, disciplineCollection.FemaleJump, disciplineCollection.FemaleThrow, disciplineCollection.FemaleMiddleDistance };
if (disciplines.All(d => d is CompetitionDiscipline))
{
result = Game.Competition;
}
else if (disciplines.All(d => d is TraditionalDiscipline))
{
result = Game.Traditional;
}
}
}
return result;
}
public void CreateOrUpdateDisciplineCollection(string className, short year, Guid maleSprintPKey, Guid maleJumpPKey, Guid maleThrowPKey, Guid maleMiddleDistancePKey, Guid femaleSprintPKey, Guid femaleJumpPKey, Guid femaleThrowPKey, Guid femaleMiddleDistancePKey)
{
using (HonglornDb db = ContextFactory.CreateContext())
{
IEnumerable<Discipline> disciplines = (from d in new[] { maleSprintPKey, maleJumpPKey, maleThrowPKey, maleMiddleDistancePKey, femaleSprintPKey, femaleJumpPKey, femaleThrowPKey, femaleMiddleDistancePKey }
select db.Set<Discipline>().Find(d)).ToArray();
if (disciplines.All(d => d is CompetitionDiscipline) || disciplines.All(d => d is TraditionalDiscipline))
{
DisciplineCollection existingCollection = (from col in db.DisciplineCollection
where col.ClassName == className && col.Year == year
select col).SingleOrDefault();
if (existingCollection == null)
{
// Create
db.DisciplineCollection.Add(new DisciplineCollection
{
ClassName = className,
Year = year,
MaleSprintPKey = maleSprintPKey,
MaleJumpPKey = maleJumpPKey,
MaleThrowPKey = maleThrowPKey,
MaleMiddleDistancePKey = maleMiddleDistancePKey,
FemaleSprintPKey = femaleSprintPKey,
FemaleJumpPKey = femaleJumpPKey,
FemaleThrowPKey = femaleThrowPKey,
FemaleMiddleDistancePKey = femaleMiddleDistancePKey
});
}
else
{
// Update
existingCollection.MaleSprintPKey = maleSprintPKey;
existingCollection.MaleJumpPKey = maleJumpPKey;
existingCollection.MaleThrowPKey = maleThrowPKey;
existingCollection.MaleMiddleDistancePKey = maleMiddleDistancePKey;
existingCollection.FemaleSprintPKey = femaleSprintPKey;
existingCollection.FemaleJumpPKey = femaleJumpPKey;
existingCollection.FemaleThrowPKey = femaleThrowPKey;
existingCollection.FemaleMiddleDistancePKey = femaleMiddleDistancePKey;
}
db.SaveChanges();
}
else
{
throw new ArgumentException("Could not save Discipline Collection. All discipline pkeys must be either entirely from competition disciplines, or from traditional disciplines, but you cannot mix them.");
}
}
}
/// <summary>
/// Get the years for which student data is present in the database.
/// </summary>
/// <returns>A short collection representing the valid years.</returns>
public ICollection<short> YearsWithStudentData()
{
using (HonglornDb db = ContextFactory.CreateContext())
{
return (from relations in db.StudentCourseRel
select relations.Year).Distinct().OrderByDescending(year => year).ToArray();
}
}
/// <summary>
/// Get a the course names for which there is at least one student present in the given year.
/// </summary>
/// <param name="year">The year for which the valid course names should be retrieved.</param>
/// <returns>All valid course names.</returns>
public ICollection<string> ValidCourseNames(short year)
{
using (HonglornDb db = ContextFactory.CreateContext())
{
return (from r in db.StudentCourseRel
where r.Year == year
select r.CourseName).Distinct().OrderBy(name => name).ToArray();
}
}
/// <summary>
/// Get a String Array representing the class names for which there is at least one student present in the given year.
/// </summary>
/// <param name="year">The year for which the valid class names should be retrieved.</param>
/// <returns>A String Array representing the valid class names.</returns>
/// <remarks></remarks>
public ICollection<string> ValidClassNames(short year)
{
return ValidCourseNames(year).Select(GetClassName).Distinct().ToArray();
}
static readonly Dictionary<string, Sex> SexDictionary = new Dictionary<string, Sex>
{
{"W", Sex.Female},
{"M", Sex.Male}
};
//todo: currently only works with a "perfect" Excel sheet
//todo: test inserting an already existing student
/// <summary>
/// Imports an Excel sheet containing data for multiple students into the database.
/// </summary>
/// <param name="filePath">The full path to the Excel file to be imported.</param>
/// <param name="year">The year in which the imported data is valid (relevant for mapping the courses).</param>
/// <param name="progress"></param>
public async Task<ICollection<ImportedStudentRecord>> ImportStudentsFromFileAsync(string filePath, short year, IProgress<ProgressReport> progress)
{
if (!IsValidYear(year))
{
throw new ArgumentException($"{year} is not a valid year.");
}
progress.Report(new ProgressReport(0, "Lese Daten aus Datei...", true));
ICollection<ImportedStudentRecord> studentsFromExcelSheet = await Task.Factory.StartNew(() => GetImporter(filePath).ReadStudentsFromFile(filePath));
var currentlyImported = 0;
progress.Report(new ProgressReport(0, "Schreibe Daten in die Datenbank...", false));
foreach (ImportedStudentRecord importStudent in studentsFromExcelSheet)
{
if (importStudent.Errors == null)
{
var student = new Student
{
Forename = importStudent.ImportedForename,
Surname = importStudent.ImportedSurname,
Sex = SexDictionary[importStudent.ImportedSex],
YearOfBirth = short.Parse(importStudent.ImportedYearOfBirth)
};
await Task.Factory.StartNew(() => ImportSingleStudent(student.Forename, student.Surname, student.Sex, student.YearOfBirth, importStudent.ImportedCourseName, year));
}
currentlyImported++;
progress.Report(new ProgressReport(PercentageValue(currentlyImported, studentsFromExcelSheet.Count), "Schreibe Daten in die Datenbank...", false));
}
progress.Report(new ProgressReport(100, "Schreibe Daten in die Datenbank...", false));
return studentsFromExcelSheet;
}
static readonly IDictionary<string, Func<IStudentImporter>> ExtensionImporterMap = new Dictionary<string, Func<IStudentImporter>>
{
{ ".xlsx", () => new ExcelImporter() },
{ ".csv", () => new CsvImporter() }
};
static IStudentImporter GetImporter(string filePath)
{
string extension = Path.GetExtension(filePath);
if (string.IsNullOrWhiteSpace(extension))
{
throw new ArgumentException($"The file {filePath} has no extension.", filePath);
}
try
{
return ExtensionImporterMap[extension]();
}
catch (KeyNotFoundException e)
{
throw new NotSupportedException($"Importing students from a file with the extension {extension} is not supported. Supported are {string.Join(", ", ExtensionImporterMap.Keys)}", e);
}
}
//todo: make this method private and create new public method that performs validation
/// <summary>
/// Adds a single student to the database
/// </summary>
/// <param name="forename">The student's forename.</param>
/// <param name="surname">The student's surname.</param>
/// <param name="courseName">The name of the course this student is part of, for the given year.</param>
/// <param name="sex">The student's gender.</param>
/// <param name="yearOfBirth">The year the student was born in.</param>
/// <param name="year">The year this record is valid in. This is usually the current year.</param>
public void ImportSingleStudent(string forename, string surname, Sex sex, short yearOfBirth, string courseName, short year)
{
//todo: handle exception
GetClassName(courseName); //check whether the course name can be mapped to a class name
//todo: verify year
using (HonglornDb db = ContextFactory.CreateContext())
{
IQueryable<Student> studentQuery = from s in db.Student
where s.Forename == forename
&& s.Surname == surname
&& s.Sex == sex
&& s.YearOfBirth == yearOfBirth
select s;
Student existingStudent = studentQuery.SingleOrDefault();
if (existingStudent == null)
{
var newStudent = new Student(forename, surname, sex, yearOfBirth);
newStudent.AddStudentCourseRel(year, courseName);
db.Student.Add(newStudent);
}
else
{
IEnumerable<StudentCourseRel> courseInformationQuery = from r in existingStudent.StudentCourseRel
where r.Year == year
select r;
StudentCourseRel existingCourseInformation = courseInformationQuery.SingleOrDefault();
if (existingCourseInformation == null)
{
existingStudent.AddStudentCourseRel(year, courseName);
}
else
{
existingCourseInformation.CourseName = courseName;
}
}
db.SaveChanges();
}
}
}
}<file_sep>using HonglornBL.Enums;
namespace HonglornBL
{
public class Result : IResult
{
public string Forename { get; }
public string Surname { get; }
public ushort SprintScore { get; }
public ushort JumpScore { get; }
public ushort ThrowScore { get; }
public ushort MiddleDistanceScore { get; }
public ushort Rank { get; }
public ushort TotalScore { get; }
public Certificate Certificate { get; }
internal Result(string forename, string surname, ushort sprintScore, ushort jumpScore, ushort throwScore, ushort middleDistanceScore, ushort rank, ushort totalScore, Certificate certificate)
{
Forename = forename;
Surname = surname;
SprintScore = sprintScore;
JumpScore = jumpScore;
ThrowScore = throwScore;
MiddleDistanceScore = middleDistanceScore;
Rank = rank;
TotalScore = totalScore;
Certificate = certificate;
}
}
}<file_sep>using HonglornBL;
using System;
namespace HonglornWPF
{
class StudentPerformance : IStudentPerformance
{
public Guid StudentPKey { get; }
public string Forename { get; }
public string Surname { get; }
public float? Sprint { get; set; }
public float? Jump { get; set; }
public float? Throw { get; set; }
public float? MiddleDistance { get; set; }
internal StudentPerformance(IStudentPerformance interfaceObject)
{
StudentPKey = interfaceObject.StudentPKey;
Forename = interfaceObject.Forename;
Surname = interfaceObject.Surname;
Sprint = interfaceObject.Sprint;
Jump = interfaceObject.Jump;
Throw = interfaceObject.Throw;
MiddleDistance = interfaceObject.MiddleDistance;
}
}
}<file_sep>using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using HonglornBL.Enums;
namespace HonglornBL.Models.Entities
{
public class TraditionalReportMeta
{
[Key]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Sex Sex { get; set; }
[Key]
[Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public byte Age { get; set; }
[Required]
public short HonoraryCertificateScore { get; set; }
[Required]
public short VictoryCertificateScore { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace HonglornBL.Import
{
class CsvImporter : StudentImporter
{
public override ICollection<ImportedStudentRecord> ReadStudentsFromFile(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentException("File path is null, empty or consist of only white-space characters.");
}
ICollection<ImportedStudentRecord> extractedStudents = new List<ImportedStudentRecord>();
using (var reader = new StreamReader(filePath))
{
if (!reader.EndOfStream)
{
string[] headerValues = reader.ReadLine()?.Split(',');
if (!headerValues.SequenceEqual(new[] { SurnameHeaderColumn, ForenameHeaderColumn, CoursenameHeaderColumn, SexHeaderColumn, YearofbirthHeaderColumn }))
{
throw new ArgumentException("Header row was not in the expected condition.");
}
}
while (!reader.EndOfStream)
{
string[] row = reader.ReadLine()?.Split(',');
extractedStudents.Add(new ImportedStudentRecord(row?[0], row?[1], row?[2], row?[3], row?[4]));
}
}
return extractedStudents;
}
}
}<file_sep>using HonglornBL;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Windows.Input;
namespace HonglornWPF.ViewModels
{
class ClassResultsViewModel : ViewModel
{
public ObservableCollection<string> Courses { get; } = new ObservableCollection<string>();
public ObservableCollection<short> Years { get; } = new ObservableCollection<short>();
public ObservableCollection<IResult> Results { get; } = new ObservableCollection<IResult>();
public ICommand RefreshYears { get; }
bool isLoading;
public bool IsLoading
{
get => isLoading;
private set => OnPropertyChanged(out isLoading, value);
}
string message;
public string Message
{
get => message;
private set => OnPropertyChanged(out message, value);
}
short currentYear;
public short CurrentYear
{
get => currentYear;
set
{
OnPropertyChanged(out currentYear, value);
string previouslySelectedCourse = CurrentCourse;
LoadCourseNames();
//todo: move to superclass
CurrentCourse = Courses.Contains(previouslySelectedCourse) ? previouslySelectedCourse : Courses.FirstOrDefault();
}
}
string currentCourse;
public string CurrentCourse
{
get => currentCourse;
set
{
OnPropertyChanged(out currentCourse, value);
if (CurrentCourse != null)
{
LoadResults();
}
}
}
public ClassResultsViewModel()
{
RefreshYears = new RelayCommand(RefreshYearsFromDb);
RefreshYearsFromDb();
}
void RefreshYearsFromDb()
{
short previouslySelectedYear = CurrentYear;
LoadYears();
CurrentYear = Years.Contains(previouslySelectedYear) ? previouslySelectedYear : Years.FirstOrDefault();
}
void LoadCourseNames() => ClearAndFill(Courses, Honglorn.ValidCourseNames(CurrentYear));
void LoadYears() => ClearAndFill(Years, Honglorn.YearsWithStudentData());
async void LoadResults()
{
Message = null;
IsLoading = true;
try
{
ClearAndFill(Results, await Honglorn.GetResultsAsync(CurrentCourse, CurrentYear));
}
catch (DataException ex)
{
Message = ex.Message;
}
finally
{
IsLoading = false;
}
}
}
}<file_sep>using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace HonglornWPF.Converter
{
[ValueConversion(typeof(bool), typeof(Enum))]
public class EnumToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => parameter.Equals(value);
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => (bool)value ? parameter : DependencyProperty.UnsetValue;
}
}<file_sep>using System;
namespace HonglornBL.Interfaces
{
public interface IDiscipline
{
Guid PKey { get; }
string ToString();
}
}<file_sep>using System;
namespace HonglornBL
{
public interface IStudentPerformance
{
Guid StudentPKey { get; }
string Forename { get; }
string Surname { get; }
float? Sprint { get; }
float? Jump { get; }
float? Throw { get; }
float? MiddleDistance { get; }
}
}<file_sep>namespace HonglornBL.Enums
{
public enum Measurement
{
Manual = 0,
Electronic = 1
}
}<file_sep>using System.ComponentModel.DataAnnotations;
using HonglornBL.Enums;
namespace HonglornBL.Models.Entities
{
public class TraditionalDiscipline : Discipline
{
[Required]
public Sex Sex { get; set; }
public short? Distance { get; set; }
public float? Overhead { get; set; }
public float ConstantA { get; set; }
public float ConstantC { get; set; }
public Measurement? Measurement { get; set; }
public override string ToString()
{
return Type == DisciplineType.Sprint ? $"{base.ToString()} ({Measurement})" : base.ToString();
}
}
}<file_sep>using System.Collections.Generic;
namespace HonglornBL.Import
{
interface IStudentImporter
{
ICollection<ImportedStudentRecord> ReadStudentsFromFile(string filePath);
}
}<file_sep>using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using HonglornBL.Enums;
using HonglornBL.Interfaces;
namespace HonglornBL.Models.Entities
{
public abstract class Discipline : IDiscipline
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid PKey { get; set; } = Guid.NewGuid();
[Required]
public DisciplineType Type { get; set; }
[Required]
[StringLength(45)]
public string Name { get; set; }
[Required]
[StringLength(25)]
public string Unit { get; set; }
public override string ToString() => Name;
}
}<file_sep>using HonglornBL.Enums;
using System;
using System.Globalization;
using System.Windows.Data;
namespace HonglornWPF.Converter
{
[ValueConversion(typeof(DisciplineType), typeof(string))]
class DisciplineTypeToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Enum.Parse(typeof(DisciplineType), value.ToString());
}
}
}<file_sep>using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using HonglornBL.Interfaces;
namespace HonglornBL.Models.Entities
{
public class DisciplineCollection : IDisciplineCollection
{
[Key]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[StringLength(1)]
public string ClassName { get; set; }
[Key]
[Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public short Year { get; set; }
// Male
public Guid? MaleSprintPKey { get; set; }
public Guid? MaleJumpPKey { get; set; }
public Guid? MaleThrowPKey { get; set; }
public Guid? MaleMiddleDistancePKey { get; set; }
// Female
public Guid? FemaleSprintPKey { get; set; }
public Guid? FemaleJumpPKey { get; set; }
public Guid? FemaleThrowPKey { get; set; }
public Guid? FemaleMiddleDistancePKey { get; set; }
// Male
public virtual Discipline MaleSprint { get; set; }
public virtual Discipline MaleJump { get; set; }
public virtual Discipline MaleThrow { get; set; }
public virtual Discipline MaleMiddleDistance { get; set; }
// Female
public virtual Discipline FemaleSprint { get; set; }
public virtual Discipline FemaleJump { get; set; }
public virtual Discipline FemaleThrow { get; set; }
public virtual Discipline FemaleMiddleDistance { get; set; }
}
}<file_sep>namespace HonglornBL.Calculation.Traditional
{
sealed class ZeroScoreCalculator : IScoreCalculator
{
public ushort CalculateScore() => 0;
}
}<file_sep>namespace HonglornWPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
partial class MainWindow
{
internal MainWindow()
{
InitializeComponent();
}
}
}<file_sep>using System.Diagnostics;
using System.Windows.Input;
using System.Windows.Media;
namespace HonglornWPF.ViewModels.ColorMenuData
{
[DebuggerDisplay("{Name} {BorderColorBrush} {FillColorBrush}")]
abstract class ColorMenuData
{
public string Name { get; }
public Brush BorderColorBrush { get; }
public Brush FillColorBrush { get; }
public ICommand ChangeColorCommand { get; }
protected ColorMenuData(string name, Brush borderColorBrush, Brush fillColorBrush)
{
Name = name;
BorderColorBrush = borderColorBrush;
FillColorBrush = fillColorBrush;
ChangeColorCommand = new RelayCommand(ChangeColor);
}
protected abstract void ChangeColor();
}
}<file_sep>using System;
using System.Diagnostics;
using HonglornBL.Enums;
namespace HonglornBL.Calculation.Competition
{
[DebuggerDisplay("({SprintValue},{SprintScore})({JumpValue},{JumpScore})({ThrowValue},{ThrowScore})({MiddleDistanceValue},{MiddleDistanceScore}) {Rank} {Certificate}")]
class CompetitionCalculatorContainer : ICompetitionResult
{
public Guid Identifier { get; set; }
public float? SprintValue { get; set; }
public float? JumpValue { get; set; }
public float? ThrowValue { get; set; }
public float? MiddleDistanceValue { get; set; }
public ushort SprintScore { get; set; }
public ushort JumpScore { get; set; }
public ushort ThrowScore { get; set; }
public ushort MiddleDistanceScore { get; set; }
public ushort Rank { get; set; }
public Certificate Certificate { get; set; }
internal CompetitionCalculatorContainer(Guid identifier, float? sprintValue, float? jumpValue, float? throwValue, float? middleDistanceValue)
{
Identifier = identifier;
SprintValue = sprintValue;
JumpValue = jumpValue;
ThrowValue = throwValue;
MiddleDistanceValue = middleDistanceValue;
}
internal ushort TotalScore => (ushort) (SprintScore + JumpScore + ThrowScore + MiddleDistanceScore);
}
}<file_sep>namespace HonglornWPF.Views
{
/// <summary>
/// Interaction logic for ClassResultsView.xaml
/// </summary>
partial class ClassResultsView
{
public ClassResultsView()
{
InitializeComponent();
}
}
}<file_sep>using HonglornBL;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace HonglornWPF.ViewModels
{
abstract class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected Honglorn Honglorn { get; }
protected ViewModel()
{
Honglorn = HonglornApi.Instance;
}
protected void OnPropertyChanged<T>(out T field, T value, [CallerMemberName] string propertyName = null)
{
field = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected static void ClearAndFill<T>(ObservableCollection<T> collection, IEnumerable<T> content)
{
collection.Clear();
foreach (T item in content)
{
collection.Add(item);
}
}
}
}<file_sep>using System;
using System.Windows.Input;
namespace HonglornWPF.ViewModels
{
class RelayCommand : ICommand
{
Action Action { get; }
bool enabled;
internal bool Enabled
{
get => enabled;
set
{
enabled = value;
CanExecuteChanged?.Invoke(this, null);
}
}
public event EventHandler CanExecuteChanged;
internal RelayCommand(Action action)
{
Action = action;
Enabled = true;
}
public bool CanExecute(object parameter) => Enabled;
public void Execute(object parameter)
{
Action?.Invoke();
}
}
}<file_sep>using System.Data.Common;
using System.Data.Entity;
using MySql.Data.Entity;
namespace HonglornBL.Models.Framework
{
[DbConfigurationType(typeof(MySqlEFConfiguration))]
class HonglornMySqlDb : HonglornDb
{
internal HonglornMySqlDb(DbConnection connection) : base(connection)
{
Database.SetInitializer(new HonglornDbInitializer<HonglornMySqlDb>());
}
}
}<file_sep>namespace HonglornWPF.Views
{
/// <summary>
/// Interaction logic for ImportStudentsView.xaml
/// </summary>
partial class ImportStudentsView
{
public ImportStudentsView()
{
InitializeComponent();
}
}
}<file_sep>using System;
namespace HonglornBL.Calculation.Traditional
{
sealed class JumpThrowScoreCalculator : ScoreCalculator
{
public JumpThrowScoreCalculator(float meters, float constantA, float constantC) : base(constantA, constantC, meters) { }
protected override double CalculateRawScore()
{
return (Math.Sqrt(Measurement) - ConstantA) / ConstantC;
}
}
}<file_sep>namespace HonglornBL.Enums
{
public enum DisciplineType
{
Sprint = 0,
Jump = 1,
Throw = 2,
MiddleDistance = 3
}
}<file_sep>using System;
using System.Configuration;
using HonglornBL;
using System.ComponentModel;
namespace HonglornWPF
{
static class HonglornApi
{
public static Honglorn Instance => Lazy.Value;
static readonly Lazy<Honglorn> Lazy = new Lazy<Honglorn>(() =>
{
#if DEBUG
Honglorn result;
string[] cmdArgs = Environment.GetCommandLineArgs();
if (LicenseManager.UsageMode == LicenseUsageMode.Designtime || cmdArgs.Length >= 2 && cmdArgs[1] == "memory")
{
result = new Honglorn(Effort.DbConnectionFactory.CreateTransient());
}
else
{
result = new Honglorn(ConfigurationManager.ConnectionStrings["HonglornDb"]);
}
return result;
#else
return new Honglorn(ConfigurationManager.ConnectionStrings["HonglornDb"]);
#endif
});
}
}<file_sep>namespace HonglornBL.Import
{
public class FieldErrorInfo
{
public string FieldName { get; }
public string FieldContent { get; }
public string Message { get; }
public FieldErrorInfo(string fieldName, string fieldContent, string message)
{
FieldName = fieldName;
FieldContent = fieldContent;
Message = message;
}
}
}<file_sep>using System;
using HonglornBL.Enums;
namespace HonglornBL
{
interface ICompetitionResult
{
Guid Identifier { get; }
ushort SprintScore { get; set; }
ushort JumpScore { get; set; }
ushort ThrowScore { get; set; }
ushort MiddleDistanceScore { get; set; }
ushort Rank { get; set; }
Certificate Certificate { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using HonglornBL.Properties;
namespace HonglornBL
{
static class Prerequisites
{
static readonly IEnumerable<Tuple<string, Func<string, string>>> ClassNameFunctionMap = new[]
{
new Tuple<string, Func<string, string>>("0[5-9][A-Za-z]", c => c[1].ToString()),
new Tuple<string, Func<string, string>>("[5-9][A-Za-z]", c => c[0].ToString()),
new Tuple<string, Func<string, string>>("(E|e)(0[1-9]|[1-9][0-9])", c => "E")
};
internal static string GetClassName(string courseName)
{
Tuple<string, Func<string, string>> pair = ClassNameFunctionMap.FirstOrDefault(tuple => Regex.IsMatch(courseName, $"^{tuple.Item1}$"));
if (pair == null)
{
throw new ArgumentException($"Invalid course name: {courseName}. Automatic mapping to class name failed.");
}
return pair.Item2(courseName);
}
/// <summary>
/// Calculates the fraction of x and y in percentage.
/// </summary>
/// <param name="x">The numerator.</param>
/// <param name="y">The denominator.</param>
/// <returns>The rounded fraction in percentage.</returns>
internal static byte PercentageValue(int x, int y) => (byte)Math.Round(100d * x / y);
static readonly ISet<char> ValidClassnames = new HashSet<char> { '5', '6', '7', '8', '9', 'E' };
/// <summary>
/// Returns true iff the given character is a valid class name that can be used at all in the application.
/// </summary>
/// <param name="className">The class name to be validated.</param>
/// <returns>True iff the given class name is a valid class name.</returns>
/// <remarks>Valid class names: 5, 6, 7, 8, 9, E</remarks>
internal static bool IsValidClassName(char className) => ValidClassnames.Contains(className);
/// <summary>
/// Returns true iff the given input year is valid based on the lower and upper bounds defined in the settings.
/// </summary>
/// <param name="year">The year to be validated.</param>
/// <returns>True iff the given year is a valid year.</returns>
internal static bool IsValidYear(short year)
{
return year >= Settings.Default.MinValidYear && year <= Settings.Default.MaxValidYear;
}
}
}<file_sep>using HonglornBL.Enums;
using HonglornBL.Models.Entities;
using HonglornWPF.Views;
using MahApps.Metro.Controls.Dialogs;
using System.Collections.ObjectModel;
using System.Windows.Input;
namespace HonglornWPF.ViewModels
{
class EditDisciplinesViewModel : ViewModel
{
public ObservableCollection<CompetitionDiscipline> Disciplines { get; } = new ObservableCollection<CompetitionDiscipline>();
public ICommand ShowCreateCompetitionDisciplineViewCommand { get; }
public ICommand EditDisciplineCommand { get; }
public ICommand DeleteDisciplineCommand { get; }
readonly IDialogCoordinator dialogCoordinator;
CompetitionDiscipline currentDiscipline;
public CompetitionDiscipline CurrentDiscipline
{
get => currentDiscipline;
set => OnPropertyChanged(out currentDiscipline, value);
}
public EditDisciplinesViewModel(IDialogCoordinator dialogCoordinator)
{
this.dialogCoordinator = dialogCoordinator;
ShowCreateCompetitionDisciplineViewCommand = new RelayCommand(ShowCreateCompetitionDisciplineView);
EditDisciplineCommand = new RelayCommand(EditDiscipline);
DeleteDisciplineCommand = new RelayCommand(DeleteDiscipline);
LoadDisciplines();
}
async void ShowCreateCompetitionDisciplineView()
{
var customDialog = new CustomDialog();
var dialogViewModel = new CreateCompetitionDisciplineViewModel(instance =>
{
CreateDiscipline(instance.CurrentDiscipline.Type, instance.CurrentDiscipline.Name, instance.CurrentDiscipline.Unit, instance.CurrentDiscipline.LowIsBetter);
dialogCoordinator.HideMetroDialogAsync(this, customDialog);
},
instance =>
{
dialogCoordinator.HideMetroDialogAsync(this, customDialog);
});
customDialog.Content = new CreateCompetitionDisciplineView
{
DataContext = dialogViewModel
};
await dialogCoordinator.ShowMetroDialogAsync(this, customDialog);
}
async void EditDiscipline()
{
var customDialog = new CustomDialog();
var dialogViewModel = new CreateCompetitionDisciplineViewModel(instance =>
{
UpdateDiscipline(instance.CurrentDiscipline.Type, instance.CurrentDiscipline.Name, instance.CurrentDiscipline.Unit, instance.CurrentDiscipline.LowIsBetter);
dialogCoordinator.HideMetroDialogAsync(this, customDialog);
},
instance =>
{
dialogCoordinator.HideMetroDialogAsync(this, customDialog);
}, CurrentDiscipline.Clone());
customDialog.Content = new CreateCompetitionDisciplineView
{
DataContext = dialogViewModel
};
await dialogCoordinator.ShowMetroDialogAsync(this, customDialog);
}
void LoadDisciplines() => ClearAndFill(Disciplines, Honglorn.AllCompetitionDisciplines());
void DeleteDiscipline()
{
Honglorn.DeleteCompetitionDiscipline(currentDiscipline.PKey);
LoadDisciplines();
}
void CreateDiscipline(DisciplineType type, string name, string unit, bool lowIsBetter)
{
Honglorn.CreateCompetitionDiscipline(type, name, unit, lowIsBetter);
LoadDisciplines();
}
void UpdateDiscipline(DisciplineType type, string name, string unit, bool lowIsBetter)
{
Honglorn.UpdateCompetitionDiscipline(CurrentDiscipline.PKey, type, name, unit, lowIsBetter);
LoadDisciplines();
}
}
}<file_sep>namespace HonglornCUT
{
public partial class UIMap { }
}<file_sep>using HonglornBL.Enums;
using HonglornBL.Interfaces;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
namespace HonglornWPF.ViewModels
{
class AssignDisciplinesViewModel : ViewModel
{
public ObservableCollection<string> Classes { get; } = new ObservableCollection<string>();
public ObservableCollection<short> Years { get; } = new ObservableCollection<short>();
public ObservableCollection<IDiscipline> MaleSprintDisciplines { get; } = new ObservableCollection<IDiscipline>();
public ObservableCollection<IDiscipline> MaleJumpDisciplines { get; } = new ObservableCollection<IDiscipline>();
public ObservableCollection<IDiscipline> MaleThrowDisciplines { get; } = new ObservableCollection<IDiscipline>();
public ObservableCollection<IDiscipline> MaleMiddleDistanceDisciplines { get; } = new ObservableCollection<IDiscipline>();
public ObservableCollection<IDiscipline> FemaleSprintDisciplines { get; } = new ObservableCollection<IDiscipline>();
public ObservableCollection<IDiscipline> FemaleJumpDisciplines { get; } = new ObservableCollection<IDiscipline>();
public ObservableCollection<IDiscipline> FemaleThrowDisciplines { get; } = new ObservableCollection<IDiscipline>();
public ObservableCollection<IDiscipline> FemaleMiddleDistanceDisciplines { get; } = new ObservableCollection<IDiscipline>();
public ICommand RefreshYears { get; }
public RelayCommand SaveDisciplineCollectionCommand { get; }
short currentYear;
public short CurrentYear
{
get { return currentYear; }
set
{
OnPropertyChanged(out currentYear, value);
string previouslySelectedClass = CurrentClass;
LoadClassNames();
CurrentClass = Classes.Contains(previouslySelectedClass) ? previouslySelectedClass : Classes.FirstOrDefault();
}
}
string currentClass;
public string CurrentClass
{
get { return currentClass; }
set
{
OnPropertyChanged(out currentClass, value);
Game = Honglorn.GetGameType(CurrentClass, CurrentYear);
}
}
Game? game;
public Game? Game
{
get { return game; }
set
{
OnPropertyChanged(out game, value);
switch (value)
{
case HonglornBL.Enums.Game.Traditional:
LoadAllTraditionalDisciplines();
SelectSavedDisiciplines();
break;
case HonglornBL.Enums.Game.Competition:
LoadAllCompetitionDisciplines();
SelectSavedDisiciplines();
break;
case null:
SetSelectedDisciplinesToNull();
break;
}
}
}
IDiscipline currentMaleSprintDiscipline;
public IDiscipline CurrentMaleSprintDiscipline
{
get { return currentMaleSprintDiscipline; }
set { OnPropertyChanged(out currentMaleSprintDiscipline, value); }
}
IDiscipline currentMaleJumpDiscipline;
public IDiscipline CurrentMaleJumpDiscipline
{
get { return currentMaleJumpDiscipline; }
set { OnPropertyChanged(out currentMaleJumpDiscipline, value); }
}
IDiscipline currentMaleThrowDiscipline;
public IDiscipline CurrentMaleThrowDiscipline
{
get { return currentMaleThrowDiscipline; }
set { OnPropertyChanged(out currentMaleThrowDiscipline, value); }
}
IDiscipline currentMaleMiddleDistanceDiscipline;
public IDiscipline CurrentMaleMiddleDistanceDiscipline
{
get { return currentMaleMiddleDistanceDiscipline; }
set { OnPropertyChanged(out currentMaleMiddleDistanceDiscipline, value); }
}
IDiscipline currentFemaleSprintDiscipline;
public IDiscipline CurrentFemaleSprintDiscipline
{
get { return currentFemaleSprintDiscipline; }
set { OnPropertyChanged(out currentFemaleSprintDiscipline, value); }
}
IDiscipline currentFemaleJumpDiscipline;
public IDiscipline CurrentFemaleJumpDiscipline
{
get { return currentFemaleJumpDiscipline; }
set { OnPropertyChanged(out currentFemaleJumpDiscipline, value); }
}
IDiscipline currentFemaleThrowDiscipline;
public IDiscipline CurrentFemaleThrowDiscipline
{
get { return currentFemaleThrowDiscipline; }
set { OnPropertyChanged(out currentFemaleThrowDiscipline, value); }
}
IDiscipline currentFemaleMiddleDistanceDiscipline;
public IDiscipline CurrentFemaleMiddleDistanceDiscipline
{
get { return currentFemaleMiddleDistanceDiscipline; }
set { OnPropertyChanged(out currentFemaleMiddleDistanceDiscipline, value); }
}
void LoadClassNames()
{
ClearAndFill(Classes, Honglorn.ValidClassNames(CurrentYear));
}
void LoadYears()
{
ClearAndFill(Years, Honglorn.YearsWithStudentData());
}
void LoadAllCompetitionDisciplines()
{
ICollection<IDiscipline> sprintDisciplines = Honglorn.FilteredCompetitionDisciplines(DisciplineType.Sprint);
ICollection<IDiscipline> jumpDisciplines = Honglorn.FilteredCompetitionDisciplines(DisciplineType.Jump);
ICollection<IDiscipline> throwDisciplines = Honglorn.FilteredCompetitionDisciplines(DisciplineType.Throw);
ICollection<IDiscipline> middleDistanceDisciplines = Honglorn.FilteredCompetitionDisciplines(DisciplineType.MiddleDistance);
ClearAndFill(MaleSprintDisciplines, sprintDisciplines);
ClearAndFill(MaleJumpDisciplines, jumpDisciplines);
ClearAndFill(MaleThrowDisciplines, throwDisciplines);
ClearAndFill(MaleMiddleDistanceDisciplines, middleDistanceDisciplines);
ClearAndFill(FemaleSprintDisciplines, sprintDisciplines);
ClearAndFill(FemaleJumpDisciplines, jumpDisciplines);
ClearAndFill(FemaleThrowDisciplines, throwDisciplines);
ClearAndFill(FemaleMiddleDistanceDisciplines, middleDistanceDisciplines);
}
void LoadAllTraditionalDisciplines()
{
ClearAndFill(MaleSprintDisciplines, Honglorn.FilteredTraditionalDisciplines(DisciplineType.Sprint, Sex.Male));
ClearAndFill(MaleJumpDisciplines, Honglorn.FilteredTraditionalDisciplines(DisciplineType.Jump, Sex.Male));
ClearAndFill(MaleThrowDisciplines, Honglorn.FilteredTraditionalDisciplines(DisciplineType.Throw, Sex.Male));
ClearAndFill(MaleMiddleDistanceDisciplines, Honglorn.FilteredTraditionalDisciplines(DisciplineType.MiddleDistance, Sex.Male));
ClearAndFill(FemaleSprintDisciplines, Honglorn.FilteredTraditionalDisciplines(DisciplineType.Sprint, Sex.Female));
ClearAndFill(FemaleJumpDisciplines, Honglorn.FilteredTraditionalDisciplines(DisciplineType.Jump, Sex.Female));
ClearAndFill(FemaleThrowDisciplines, Honglorn.FilteredTraditionalDisciplines(DisciplineType.Throw, Sex.Female));
ClearAndFill(FemaleMiddleDistanceDisciplines, Honglorn.FilteredTraditionalDisciplines(DisciplineType.MiddleDistance, Sex.Female));
}
void SelectSavedDisiciplines()
{
IDisciplineCollection disciplineCollection = Honglorn.AssignedDisciplines(CurrentClass, CurrentYear);
if (disciplineCollection == null)
{
SetSelectedDisciplinesToNull();
}
else
{
CurrentMaleSprintDiscipline = MaleSprintDisciplines.SingleOrDefault(d => d.PKey == disciplineCollection.MaleSprintPKey);
CurrentMaleJumpDiscipline = MaleJumpDisciplines.SingleOrDefault(d => d.PKey == disciplineCollection.MaleJumpPKey);
CurrentMaleThrowDiscipline = MaleThrowDisciplines.SingleOrDefault(d => d.PKey == disciplineCollection.MaleThrowPKey);
CurrentMaleMiddleDistanceDiscipline = MaleMiddleDistanceDisciplines.SingleOrDefault(d => d.PKey == disciplineCollection.MaleMiddleDistancePKey);
CurrentFemaleSprintDiscipline = FemaleSprintDisciplines.SingleOrDefault(d => d.PKey == disciplineCollection.FemaleSprintPKey);
CurrentFemaleJumpDiscipline = FemaleJumpDisciplines.SingleOrDefault(d => d.PKey == disciplineCollection.FemaleJumpPKey);
CurrentFemaleThrowDiscipline = FemaleThrowDisciplines.SingleOrDefault(d => d.PKey == disciplineCollection.FemaleThrowPKey);
CurrentFemaleMiddleDistanceDiscipline = FemaleMiddleDistanceDisciplines.SingleOrDefault(d => d.PKey == disciplineCollection.FemaleMiddleDistancePKey);
}
}
void SetSelectedDisciplinesToNull()
{
CurrentMaleSprintDiscipline = null;
CurrentMaleJumpDiscipline = null;
CurrentMaleThrowDiscipline = null;
CurrentMaleMiddleDistanceDiscipline = null;
CurrentFemaleSprintDiscipline = null;
CurrentFemaleJumpDiscipline = null;
CurrentFemaleThrowDiscipline = null;
CurrentFemaleMiddleDistanceDiscipline = null;
}
public AssignDisciplinesViewModel()
{
SaveDisciplineCollectionCommand = new RelayCommand(SaveDisciplineCollection);
RefreshYears = new RelayCommand(RefreshYearsFromDb);
RefreshYearsFromDb();
}
void RefreshYearsFromDb()
{
short previouslySelectedYear = CurrentYear;
LoadYears();
CurrentYear = Years.Contains(previouslySelectedYear) ? previouslySelectedYear : Years.FirstOrDefault();
}
void SaveDisciplineCollection()
{
Honglorn.CreateOrUpdateDisciplineCollection(CurrentClass, CurrentYear, CurrentMaleSprintDiscipline.PKey, CurrentMaleJumpDiscipline.PKey, CurrentMaleThrowDiscipline.PKey, CurrentMaleMiddleDistanceDiscipline.PKey, CurrentFemaleSprintDiscipline.PKey, CurrentFemaleJumpDiscipline.PKey, CurrentFemaleThrowDiscipline.PKey, CurrentFemaleMiddleDistanceDiscipline.PKey);
}
}
}<file_sep>using HonglornBL.Enums;
namespace HonglornBL
{
public interface IResult
{
string Forename { get; }
string Surname { get; }
ushort SprintScore { get; }
ushort JumpScore { get; }
ushort ThrowScore { get; }
ushort MiddleDistanceScore { get; }
ushort Rank { get; }
ushort TotalScore { get; }
Certificate Certificate { get; }
}
}<file_sep>using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace HonglornBL.Models.Entities
{
public class StudentCourseRel
{
[Key]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid StudentPKey { get; set; }
[Key]
[Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public short Year { get; set; }
[Required]
[StringLength(3)]
public string CourseName { get; set; }
[ForeignKey(nameof(StudentPKey))]
public virtual Student Student { get; set; }
}
}<file_sep>namespace HonglornBL.Enums
{
public enum Game
{
Traditional = 0,
Competition = 1
}
}<file_sep>using HonglornBL.Models.Entities;
using System;
using System.Windows.Input;
namespace HonglornWPF.ViewModels
{
class CreateCompetitionDisciplineViewModel : ViewModel
{
public CompetitionDiscipline CurrentDiscipline { get; }
public ICommand AcceptCommand { get; }
public ICommand AbortCommand { get; }
public CreateCompetitionDisciplineViewModel(Action<CreateCompetitionDisciplineViewModel> acceptHandle, Action<CreateCompetitionDisciplineViewModel> abortHandle, CompetitionDiscipline discipline = null)
{
AcceptCommand = new RelayCommand(() => acceptHandle(this));
AbortCommand = new RelayCommand(() => abortHandle(this));
CurrentDiscipline = discipline ?? new CompetitionDiscipline();
}
}
}<file_sep>using HonglornBL;
using HonglornBL.Import;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using Microsoft;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using OpenFileDialog = Microsoft.Win32.OpenFileDialog;
namespace HonglornWPF.ViewModels
{
class ImportStudentsViewModel : ViewModel
{
bool isIndeterminate;
public bool IsIndeterminate
{
get => isIndeterminate;
set => OnPropertyChanged(out isIndeterminate, value);
}
int statusPercentage;
public int StatusPercentage
{
get => statusPercentage;
set => OnPropertyChanged(out statusPercentage, value);
}
string statusMessage;
public string StatusMessage
{
get => statusMessage;
set => OnPropertyChanged(out statusMessage, value);
}
short year;
public short Year
{
get => year;
set => OnPropertyChanged(out year, value);
}
string path;
public string Path
{
get => path;
set => OnPropertyChanged(out path, value);
}
public ICommand OpenFileDialogCommand { get; }
public RelayCommand ImportStudentsAsyncCommand { get; }
public ImportStudentsViewModel()
{
Year = (short)DateTime.Now.Year;
OpenFileDialogCommand = new RelayCommand(OpenFileDialog);
ImportStudentsAsyncCommand = new RelayCommand(ImportStudentsAsync);
}
void OpenFileDialog()
{
var dialog = new OpenFileDialog
{
ReadOnlyChecked = true,
Filter = "Microsoft Excel, CSV (*.xlsx; *.csv) |*.xlsx;*.csv",
Title = "Schülerdatei"
};
if (dialog.ShowDialog() == true)
{
Path = dialog.FileName;
}
}
async void ImportStudentsAsync()
{
var mainWindow = (MetroWindow)System.Windows.Application.Current.MainWindow;
try
{
ICollection<ImportedStudentRecord> importedStudents = await Honglorn.ImportStudentsFromFileAsync(Path, Year, new Progress<ProgressReport>(OnProgressChanged));
ICollection<ImportedStudentRecord> unsuccessfullyImported = importedStudents.Where(s => s.Errors != null).ToList();
var messageBuilder = new StringBuilder($"Successfully imported {importedStudents.Count - unsuccessfullyImported.Count} of {importedStudents.Count} students.");
if (unsuccessfullyImported.Any())
{
messageBuilder.AppendLine();
messageBuilder.AppendLine("The following students could not be imported: ");
foreach (ImportedStudentRecord student in unsuccessfullyImported)
{
messageBuilder.AppendLine();
messageBuilder.AppendLine();
messageBuilder.AppendLine($"{student.ImportedForename} {student.ImportedSurname}, {student.ImportedSex}, born in {student.ImportedYearOfBirth}, in Course {student.ImportedCourseName}");
foreach (FieldErrorInfo error in student.Errors)
{
messageBuilder.AppendLine();
messageBuilder.AppendLine($"Field name: {error.FieldName}");
messageBuilder.AppendLine($"Field content: {error.FieldContent}");
messageBuilder.AppendLine($"Message: {error.Message}");
}
}
}
await mainWindow.ShowMessageAsync("Notification", messageBuilder.ToString());
}
catch (Exception ex)
{
await mainWindow.ShowMessageAsync("Error", ex.Message);
}
finally
{
StatusPercentage = 0;
IsIndeterminate = false;
StatusMessage = string.Empty;
ImportStudentsAsyncCommand.Enabled = true;
}
}
void OnProgressChanged(ProgressReport report)
{
StatusMessage = report.Message;
IsIndeterminate = report.IsIndeterminate;
StatusPercentage = report.Percentage;
}
}
}<file_sep>namespace HonglornWPF.Views
{
/// <summary>
/// Interaction logic for EditPerformanceView.xaml
/// </summary>
partial class EditPerformanceView
{
public EditPerformanceView()
{
InitializeComponent();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Globalization;
using System.IO;
using System.Linq;
using HonglornBL;
using HonglornBL.Enums;
using HonglornBL.Import;
using HonglornBL.Interfaces;
using HonglornBL.Models.Entities;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace HonglornAUT
{
[TestClass]
[DeploymentItem("EntityFramework.SqlServer.dll")]
public class HonglornTest
{
static DbConnection CreateConnection() => Effort.DbConnectionFactory.CreateTransient();
public TestContext TestContext { get; set; }
string GetData(string tagName) => TestContext.DataRow[tagName] as string;
float GetFloat(string tagName) => float.Parse(GetData(tagName), CultureInfo.InvariantCulture);
ushort GetUshort(string tagName) => ushort.Parse(GetData(tagName), CultureInfo.InvariantCulture);
short GetShort(string tagName) => short.Parse(GetData(tagName), CultureInfo.InvariantCulture);
bool GetBool(string tagName) => bool.Parse(GetData(tagName));
static readonly Random Random = new Random();
static string RandomString()
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
return new string(Enumerable.Repeat(chars, 5).Select(s => s[Random.Next(s.Length)]).ToArray());
}
[TestMethod]
public void ImportSingleStudent_Regular_StudentSuccessfullyAdded()
{
const string forename = "Cave";
const string surname = "Johnson";
const string courseName = "08B";
const short year = 2018;
var sut = new Honglorn(CreateConnection());
sut.ImportSingleStudent(forename, surname, Sex.Male, 1928, courseName, year);
IStudentPerformance studentPerformance = sut.StudentPerformances(courseName, year).Single();
Assert.AreEqual(forename, studentPerformance.Forename);
Assert.AreEqual(surname, studentPerformance.Surname);
Assert.IsNull(studentPerformance.Sprint);
Assert.IsNull(studentPerformance.Jump);
Assert.IsNull(studentPerformance.Throw);
Assert.IsNull(studentPerformance.MiddleDistance);
}
[TestMethod]
public void ImportStudentsFromFileAsync_BlessedFile_NoErrors()
{
const short currentYear = 2018;
const string expectedSurname = "Coleman";
const string expectedForename = "Bruce";
const string expectedCourse = "05A";
string tempFilePath = Path.Combine(Environment.CurrentDirectory, $"{Guid.NewGuid().ToString()}.xlsx");
File.WriteAllBytes(tempFilePath, Properties.Resources.ImportTemplate);
var sut = new Honglorn(CreateConnection());
ICollection<ImportedStudentRecord> importedStudents = sut.ImportStudentsFromFileAsync(tempFilePath, 2018, new Progress<ProgressReport>()).Result;
File.Delete(tempFilePath);
var importedStudent = importedStudents.Single();
var studentInDatabase = sut.StudentPerformances(expectedCourse, currentYear).Single();
Assert.AreEqual(1, importedStudents.Count);
Assert.AreEqual(expectedSurname, importedStudent.ImportedSurname);
Assert.AreEqual(expectedForename, importedStudent.ImportedForename);
Assert.AreEqual(expectedCourse, importedStudent.ImportedCourseName);
Assert.AreEqual("M", importedStudent.ImportedSex);
Assert.AreEqual("2005", importedStudent.ImportedYearOfBirth);
Assert.AreEqual(expectedSurname, studentInDatabase.Surname);
Assert.AreEqual(expectedForename, studentInDatabase.Forename);
}
[TestMethod]
public void UpdateSingleStudentCompetition_CompetitionDataAdded_SuccessfullySaved()
{
const string forename = "Cave";
const string surname = "Johnson";
const string courseName = "08B";
const short year = 2018;
const float sprintPerformance = 12.56f;
const float throwPerformance = 22.59f;
var sut = new Honglorn(CreateConnection());
sut.ImportSingleStudent(forename, surname, Sex.Male, 1928, courseName, year);
Guid pKey = sut.StudentPerformances(courseName, year).Single().StudentPKey;
sut.UpdateSingleStudentCompetition(pKey, year, sprintPerformance, null, throwPerformance, null);
IStudentPerformance studentPerformance = sut.StudentPerformances(courseName, year).Single();
Assert.AreEqual(forename, studentPerformance.Forename);
Assert.AreEqual(surname, studentPerformance.Surname);
Assert.AreEqual(sprintPerformance, studentPerformance.Sprint);
Assert.IsNull(studentPerformance.Jump);
Assert.AreEqual(throwPerformance, studentPerformance.Throw);
Assert.IsNull(studentPerformance.MiddleDistance);
}
[TestMethod]
public void UpdateSingleStudentCompetition_CompetitionDataChanged_SuccessfullyChanged()
{
const string forename = "Cave";
const string surname = "Johnson";
const string courseName = "08B";
const short year = 2018;
const float sprintPerformance = 5;
const float jumpPerformance = 6;
const float throwPerformance = 7;
const float middleDistancePerformance = 8;
var sut = new Honglorn(CreateConnection());
sut.ImportSingleStudent(forename, surname, Sex.Male, 1928, courseName, year);
Guid pKey = sut.StudentPerformances(courseName, year).Single().StudentPKey;
sut.UpdateSingleStudentCompetition(pKey, year, 1, 2, 3, 4);
sut.UpdateSingleStudentCompetition(pKey, year, sprintPerformance, jumpPerformance, throwPerformance, middleDistancePerformance);
IStudentPerformance studentPerformance = sut.StudentPerformances(courseName, year).Single();
Assert.AreEqual(forename, studentPerformance.Forename);
Assert.AreEqual(surname, studentPerformance.Surname);
Assert.AreEqual(sprintPerformance, studentPerformance.Sprint);
Assert.AreEqual(jumpPerformance, studentPerformance.Jump);
Assert.AreEqual(throwPerformance, studentPerformance.Throw);
Assert.AreEqual(middleDistancePerformance, studentPerformance.MiddleDistance);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void UpdateSingleStudentCompetition_UnknownStudent_ThrowsException()
{
var sut = new Honglorn(CreateConnection());
sut.UpdateSingleStudentCompetition(new Guid(), 2018, 1, 2, 3, 4);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void GetResults_NoDisciplinesSet_ThrowsException()
{
var sut = new Honglorn(CreateConnection());
try
{
IEnumerable<IResult> unused = sut.GetResultsAsync("A", 2000).Result;
}
catch (AggregateException e)
{
throw e.InnerExceptions.Single();
}
}
[TestMethod]
[DeploymentItem("TestData\\TraditionalResults.xml")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestData\\TraditionalResults.xml", "Row", DataAccessMethod.Sequential)]
public void GetResults_TraditionalCompetition_CorrectScoresAndCertificatesCalculated()
{
const string course = "08D";
var sex = (Sex)Enum.Parse(typeof(Sex), GetData("Sex"));
short year = GetShort("Year");
var sut = new Honglorn(CreateConnection());
sut.ImportSingleStudent("Kim", "Pennington", sex, GetShort("YearOfBirth"), course, year);
Guid getDisciplineKey(DisciplineType type, string name) => sut.FilteredTraditionalDisciplines(type, sex).Single(d => d.ToString() == GetData(name)).PKey;
Guid sprintPKey = getDisciplineKey(DisciplineType.Sprint, "SprintName");
Guid jumpPKey = getDisciplineKey(DisciplineType.Jump, "JumpName");
Guid throwPKey = getDisciplineKey(DisciplineType.Throw, "ThrowName");
Guid middleDistancePKey = getDisciplineKey(DisciplineType.MiddleDistance, "MiddleDistanceName");
string className = sut.ValidClassNames(year).Single();
sut.CreateOrUpdateDisciplineCollection(className, year, sprintPKey, jumpPKey, throwPKey, middleDistancePKey, sprintPKey, jumpPKey, throwPKey, middleDistancePKey);
Guid studentPKey = sut.StudentPerformances(course, year).Single().StudentPKey;
sut.UpdateSingleStudentCompetition(studentPKey, year, GetFloat("SprintPerformance"), GetFloat("JumpPerformance"), GetFloat("ThrowPerformance"), GetFloat("MiddleDistancePerformance"));
IResult result = sut.GetResultsAsync(course, year).Result.Single();
Assert.AreEqual(GetUshort("SprintScore"), result.SprintScore);
Assert.AreEqual(GetUshort("JumpScore"), result.JumpScore);
Assert.AreEqual(GetUshort("ThrowScore"), result.ThrowScore);
Assert.AreEqual(GetUshort("MiddleDistanceScore"), result.MiddleDistanceScore);
Assert.AreEqual(GetUshort("TotalScore"), result.TotalScore);
Assert.AreEqual(Enum.Parse(typeof(Certificate), GetData("Certificate")), result.Certificate);
}
[TestMethod]
public void GetResults_TraditionalCompetitionNullValues_ZeroScore()
{
const string course = "08D";
const Sex sex = Sex.Male;
const short year = 2017;
var sut = new Honglorn(CreateConnection());
sut.ImportSingleStudent("Kim", "Pennington", sex, 2008, course, year);
Guid getDisciplineKey(DisciplineType type, string name) => sut.FilteredTraditionalDisciplines(type, sex).Single(d => d.ToString() == name).PKey;
Guid sprintPKey = getDisciplineKey(DisciplineType.Sprint, "Sprint 100 m (Manual)");
Guid jumpPKey = getDisciplineKey(DisciplineType.Jump, "Weitsprung");
Guid throwPKey = getDisciplineKey(DisciplineType.Throw, "Kugelstoß");
Guid middleDistancePKey = getDisciplineKey(DisciplineType.MiddleDistance, "Lauf 1000 m");
string className = sut.ValidClassNames(year).Single();
sut.CreateOrUpdateDisciplineCollection(className, year, sprintPKey, jumpPKey, throwPKey, middleDistancePKey, sprintPKey, jumpPKey, throwPKey, middleDistancePKey);
Guid studentPKey = sut.StudentPerformances(course, year).Single().StudentPKey;
sut.UpdateSingleStudentCompetition(studentPKey, year, null, null, null, null);
IResult result = sut.GetResultsAsync(course, year).Result.Single();
Assert.AreEqual(0, result.SprintScore);
Assert.AreEqual(0, result.JumpScore);
Assert.AreEqual(0, result.ThrowScore);
Assert.AreEqual(0, result.MiddleDistanceScore);
Assert.AreEqual(0, result.TotalScore);
Assert.AreEqual(Certificate.Participation, result.Certificate);
}
[TestMethod]
public void AllCompetitionDisciplines_CreateCompetitionDiscipline_SuccessfullyCreated()
{
const DisciplineType type = DisciplineType.Sprint;
const string name = "Run very fast";
const string unit = "seconds";
const bool lowIsBetter = true;
var sut = new Honglorn(CreateConnection());
sut.CreateCompetitionDiscipline(type, name, unit, lowIsBetter);
CompetitionDiscipline discipline = sut.AllCompetitionDisciplines().Single();
Assert.AreEqual(type, discipline.Type);
Assert.AreEqual(name, discipline.Name);
Assert.AreEqual(unit, discipline.Unit);
Assert.AreEqual(lowIsBetter, discipline.LowIsBetter);
}
[TestMethod]
public void DeleteCompetitionDisciplineByPKey_DeleteDiscipline_SuccessfullyDeleted()
{
var sut = new Honglorn(CreateConnection());
sut.CreateCompetitionDiscipline(DisciplineType.Sprint, "Run very fast", "seconds", true);
Guid disciplinePKey = sut.AllCompetitionDisciplines().Single().PKey;
sut.DeleteCompetitionDiscipline(disciplinePKey);
bool competitionDisciplinesExist = sut.AllCompetitionDisciplines().Any();
Assert.IsFalse(competitionDisciplinesExist);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void DeleteCompetitionDisciplineByPKey_UnknownDiscipline_ThrowsException()
{
var sut = new Honglorn(CreateConnection());
sut.DeleteCompetitionDiscipline(Guid.Empty);
}
[TestMethod]
[DeploymentItem("TestData\\CompetitionResults.xml")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestData\\CompetitionResults.xml", "Row", DataAccessMethod.Sequential)]
public void GetResults_CompetitionResults_CorrectScoresAndCertificatesCalculated()
{
short year = GetShort("Year");
ICollection<CompetitionStudent> students = new List<CompetitionStudent>();
foreach (DataRow courseRow in TestContext.DataRow.GetChildRows("Row_Course"))
{
string courseName = courseRow["Name"].ToString();
foreach (DataRow student in courseRow.GetChildRows("Course_Student"))
{
var sex = (Sex)Enum.Parse(typeof(Sex), student["Sex"].ToString());
float sprint = float.Parse(student["Sprint"].ToString(), CultureInfo.InvariantCulture);
float jump = float.Parse(student["Jump"].ToString(), CultureInfo.InvariantCulture);
float @throw = float.Parse(student["Throw"].ToString(), CultureInfo.InvariantCulture);
float middleDistance = float.Parse(student["MiddleDistance"].ToString(), CultureInfo.InvariantCulture);
ushort sprintScore = ushort.Parse(student["SprintScore"].ToString());
ushort jumpScore = ushort.Parse(student["JumpScore"].ToString());
ushort throwScore = ushort.Parse(student["ThrowScore"].ToString());
ushort middleDistanceScore = ushort.Parse(student["MiddleDistanceScore"].ToString());
ushort rank = ushort.Parse(student["Rank"].ToString());
var certificate = (Certificate)Enum.Parse(typeof(Certificate), student["Certificate"].ToString());
students.Add(new CompetitionStudent(courseName, RandomString(), RandomString(), sex, sprint, jump, @throw, middleDistance, sprintScore, jumpScore, throwScore, middleDistanceScore, rank, certificate));
}
}
var sut = new Honglorn(CreateConnection());
foreach (CompetitionStudent s in students)
{
sut.ImportSingleStudent(s.Forename, s.Surname, s.Sex, (short)(DateTime.Now.Year - 10), s.Course, year);
}
sut.CreateCompetitionDiscipline(DisciplineType.Sprint, "A", "a", GetBool("SprintLowIsBetterMale"));
sut.CreateCompetitionDiscipline(DisciplineType.Jump, "B", "b", GetBool("JumpLowIsBetterMale"));
sut.CreateCompetitionDiscipline(DisciplineType.Throw, "C", "c", GetBool("ThrowLowIsBetterMale"));
sut.CreateCompetitionDiscipline(DisciplineType.MiddleDistance, "D", "d", GetBool("MiddleDistanceLowIsBetterMale"));
sut.CreateCompetitionDiscipline(DisciplineType.Sprint, "E", "e", GetBool("SprintLowIsBetterFemale"));
sut.CreateCompetitionDiscipline(DisciplineType.Jump, "F", "f", GetBool("JumpLowIsBetterFemale"));
sut.CreateCompetitionDiscipline(DisciplineType.Throw, "G", "g", GetBool("ThrowLowIsBetterFemale"));
sut.CreateCompetitionDiscipline(DisciplineType.MiddleDistance, "H", "h", GetBool("MiddleDistanceLowIsBetterFemale"));
Guid maleSprintGuid = sut.FilteredCompetitionDisciplines(DisciplineType.Sprint).Single(d => d.ToString() == "A").PKey;
Guid maleJumpGuid = sut.FilteredCompetitionDisciplines(DisciplineType.Jump).Single(d => d.ToString() == "B").PKey;
Guid maleThrowGuid = sut.FilteredCompetitionDisciplines(DisciplineType.Throw).Single(d => d.ToString() == "C").PKey;
Guid maleMiddleDistanceGuid = sut.FilteredCompetitionDisciplines(DisciplineType.MiddleDistance).Single(d => d.ToString() == "D").PKey;
Guid femaleSprintGuid = sut.FilteredCompetitionDisciplines(DisciplineType.Sprint).Single(d => d.ToString() == "E").PKey;
Guid femaleJumpGuid = sut.FilteredCompetitionDisciplines(DisciplineType.Jump).Single(d => d.ToString() == "F").PKey;
Guid femaleThrowGuid = sut.FilteredCompetitionDisciplines(DisciplineType.Throw).Single(d => d.ToString() == "G").PKey;
Guid femaleMiddleDistanceGuid = sut.FilteredCompetitionDisciplines(DisciplineType.MiddleDistance).Single(d => d.ToString() == "H").PKey;
foreach (string className in sut.ValidClassNames(year))
{
sut.CreateOrUpdateDisciplineCollection(className, year, maleSprintGuid, maleJumpGuid, maleThrowGuid, maleMiddleDistanceGuid, femaleSprintGuid, femaleJumpGuid, femaleThrowGuid, femaleMiddleDistanceGuid);
}
foreach (string course in students.Select(s => s.Course).Distinct())
{
IEnumerable<IStudentPerformance> performances = sut.StudentPerformances(course, year).ToList();
foreach (CompetitionStudent student in students.Where(s => s.Course == course))
{
Guid studentKey = performances.Single(p => p.Forename == student.Forename).StudentPKey;
sut.UpdateSingleStudentCompetition(studentKey, year, student.Sprint, student.Jump, student.Throw, student.MiddleDistance);
}
}
foreach (string course in students.Select(s => s.Course).Distinct())
{
IEnumerable<IResult> results = sut.GetResultsAsync(course, year).Result.ToList();
foreach (CompetitionStudent student in students.Where(s => s.Course == course))
{
IResult studentResult = results.Single(r => r.Forename == student.Forename && r.Surname == student.Surname);
Assert.AreEqual(student.SprintScore + student.JumpScore + student.ThrowScore + student.MiddleDistanceScore, studentResult.TotalScore);
Assert.AreEqual(student.Rank, studentResult.Rank);
Assert.AreEqual(student.Certificate, studentResult.Certificate);
}
}
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ImportStudentsFromFile_EmptyFileName_ThrowsException()
{
var sut = new Honglorn(CreateConnection());
try
{
ICollection<ImportedStudentRecord> unused = sut.ImportStudentsFromFileAsync(string.Empty, 2018, new Progress<ProgressReport>()).Result;
}
catch (AggregateException e)
{
throw e.InnerExceptions.Single();
}
}
[TestMethod]
public void GetGameType_EmptyStringAndZero_Null()
{
var sut = new Honglorn(CreateConnection());
Game? gameType = sut.GetGameType(string.Empty, 0);
Assert.IsNull(gameType);
}
[TestMethod]
public void GetGameType_CompetitionDisciplines_CompetitionGame()
{
const string className = "7";
const int year = 2015;
var sut = new Honglorn(CreateConnection());
sut.CreateCompetitionDiscipline(DisciplineType.Sprint, "Sprinten", "Sekunden", true);
sut.CreateCompetitionDiscipline(DisciplineType.Jump, "Springen", "Meter", false);
sut.CreateCompetitionDiscipline(DisciplineType.Throw, "Werfen", "Meter", false);
sut.CreateCompetitionDiscipline(DisciplineType.MiddleDistance, "LangLaufen", "Minuten", true);
Guid sprintKey = sut.FilteredCompetitionDisciplines(DisciplineType.Sprint).Single().PKey;
Guid jumpKey = sut.FilteredCompetitionDisciplines(DisciplineType.Jump).Single().PKey;
Guid throwKey = sut.FilteredCompetitionDisciplines(DisciplineType.Throw).Single().PKey;
Guid middleDistanceKey = sut.FilteredCompetitionDisciplines(DisciplineType.MiddleDistance).Single().PKey;
sut.CreateOrUpdateDisciplineCollection(className, year, sprintKey, jumpKey, throwKey, middleDistanceKey, sprintKey, jumpKey, throwKey, middleDistanceKey);
Game? gameType = sut.GetGameType(className, year);
Assert.AreEqual(Game.Competition, gameType);
}
[TestMethod]
public void GetGameType_TraditionalDisciplines_TraditionalGame()
{
const string className = "7";
const int year = 2015;
var sut = new Honglorn(CreateConnection());
sut.CreateCompetitionDiscipline(DisciplineType.Sprint, "Sprinten", "Sekunden", true);
sut.CreateCompetitionDiscipline(DisciplineType.Jump, "Springen", "Meter", false);
sut.CreateCompetitionDiscipline(DisciplineType.Throw, "Werfen", "Meter", false);
sut.CreateCompetitionDiscipline(DisciplineType.MiddleDistance, "LangLaufen", "Minuten", true);
Guid getDiscipline(DisciplineType t, Sex s) => sut.FilteredTraditionalDisciplines(t, s).First().PKey;
Guid maleSprintKey = getDiscipline(DisciplineType.Sprint, Sex.Male);
Guid maleJumpKey = getDiscipline(DisciplineType.Jump, Sex.Male);
Guid maleThrowKey = getDiscipline(DisciplineType.Throw, Sex.Male);
Guid malemMiddleDistanceKey = getDiscipline(DisciplineType.MiddleDistance, Sex.Male);
Guid femaleSprintKey = getDiscipline(DisciplineType.Sprint, Sex.Female);
Guid femaleJumpKey = getDiscipline(DisciplineType.Jump, Sex.Female);
Guid femaleThrowKey = getDiscipline(DisciplineType.Throw, Sex.Female);
Guid femalemMddleDistanceKey = getDiscipline(DisciplineType.MiddleDistance, Sex.Female);
sut.CreateOrUpdateDisciplineCollection(className, year, maleSprintKey, maleJumpKey, maleThrowKey, malemMiddleDistanceKey, femaleSprintKey, femaleJumpKey, femaleThrowKey, femalemMddleDistanceKey);
Game? gameType = sut.GetGameType(className, year);
Assert.AreEqual(Game.Traditional, gameType);
}
[TestMethod]
public void ValidCourseNames_StudentInserted_CourseNowValid()
{
short year = 2019;
string courseName = "6D";
var sut = new Honglorn(CreateConnection());
sut.ImportSingleStudent("Cave", "Johnson", Sex.Male, 1980, "6D", year);
var validCourse = sut.ValidCourseNames(year).Single();
Assert.AreEqual(courseName, validCourse);
}
[TestMethod]
public void YearsWithStudentDate_StudentInserted_YearReturned()
{
short year = 2019;
var sut = new Honglorn(CreateConnection());
sut.ImportSingleStudent("Cave", "Johnson", Sex.Male, 1980, "6D", year);
var yearWithStudentData = sut.YearsWithStudentData().Single();
Assert.AreEqual(year, yearWithStudentData);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Constructor_NoProviderName_ThrowsException()
{
var settings = new ConnectionStringSettings("Foo", "Bar");
var unused = new Honglorn(settings);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Constructor_NoConnectionString_ThrowsException()
{
var settings = new ConnectionStringSettings
{
ProviderName = "Foobar"
};
var unused = new Honglorn(settings);
}
[TestMethod]
public void AssignedDisciplines_CompetitionDisciplines_AssignedCorrectly()
{
const string className = "7";
const int year = 2015;
var sut = new Honglorn(CreateConnection());
sut.CreateCompetitionDiscipline(DisciplineType.Sprint, "Sprinten", "Sekunden", true);
sut.CreateCompetitionDiscipline(DisciplineType.Jump, "Springen", "Meter", false);
sut.CreateCompetitionDiscipline(DisciplineType.Throw, "Werfen", "Meter", false);
sut.CreateCompetitionDiscipline(DisciplineType.MiddleDistance, "LangLaufen", "Minuten", true);
Guid sprintKey = sut.FilteredCompetitionDisciplines(DisciplineType.Sprint).Single().PKey;
Guid jumpKey = sut.FilteredCompetitionDisciplines(DisciplineType.Jump).Single().PKey;
Guid throwKey = sut.FilteredCompetitionDisciplines(DisciplineType.Throw).Single().PKey;
Guid middleDistanceKey = sut.FilteredCompetitionDisciplines(DisciplineType.MiddleDistance).Single().PKey;
sut.CreateOrUpdateDisciplineCollection(className, year, sprintKey, jumpKey, throwKey, middleDistanceKey, sprintKey, jumpKey, throwKey, middleDistanceKey);
IDisciplineCollection assignedDisciplines = sut.AssignedDisciplines(className, year);
Assert.AreEqual(sprintKey, assignedDisciplines.MaleSprintPKey);
Assert.AreEqual(jumpKey, assignedDisciplines.MaleJumpPKey);
Assert.AreEqual(throwKey, assignedDisciplines.MaleThrowPKey);
Assert.AreEqual(middleDistanceKey, assignedDisciplines.MaleMiddleDistancePKey);
Assert.AreEqual(sprintKey, assignedDisciplines.FemaleSprintPKey);
Assert.AreEqual(jumpKey, assignedDisciplines.FemaleJumpPKey);
Assert.AreEqual(throwKey, assignedDisciplines.FemaleThrowPKey);
Assert.AreEqual(middleDistanceKey, assignedDisciplines.FemaleMiddleDistancePKey);
}
[TestMethod]
[ExpectedException(typeof(DataException))]
public void GetResults_NoDisciplinesConfigured_ThrowsException()
{
var sut = new Honglorn(CreateConnection());
try
{
IEnumerable<IResult> unused = sut.GetResultsAsync("6A", 2014).Result;
}
catch (AggregateException ex)
{
throw ex.InnerExceptions.Single();
}
}
}
}<file_sep>using HonglornBL.Models.Entities;
namespace HonglornBL
{
class TraditionalDisciplineContainer : DisciplineContainer<TraditionalDiscipline> { }
}<file_sep>using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace HonglornWPF.Converter
{
[ValueConversion(typeof(bool), typeof(Visibility))]
class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Visibility trueValue;
Visibility falseValue;
if (parameter == null || !(bool) parameter)
{
trueValue = Visibility.Visible;
falseValue = Visibility.Collapsed;
}
else
{
trueValue = Visibility.Collapsed;
falseValue = Visibility.Visible;
}
return value == null || (bool) value ? trueValue : falseValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}<file_sep>using System.Collections.Generic;
using System.Linq;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
namespace HonglornBL.Import
{
class ExcelImporter : StudentImporter
{
/// <summary>
/// Reads student data from an Excel file and returns a collection containing the students.
/// </summary>
/// <param name="filePath">The file path of the Excel file containing the relevant data.</param>
public override ICollection<ImportedStudentRecord> ReadStudentsFromFile(string filePath)
{
var extractedStudents = new List<ImportedStudentRecord>();
using (SpreadsheetDocument document = SpreadsheetDocument.Open(filePath, false))
{
WorkbookPart workbookPart = document.WorkbookPart;
StringValue sheetId = workbookPart.Workbook.Descendants<Sheet>().First().Id;
SharedStringTablePart stringTable = workbookPart.GetPartsOfType<SharedStringTablePart>().First();
var worksheetPart = (WorksheetPart) workbookPart.GetPartById(sheetId);
IEnumerable<Cell> cells = worksheetPart.Worksheet.Descendants<Cell>();
string[] valueList = cells.Select(cell => cell.DataType?.Value == CellValues.SharedString ? stringTable.SharedStringTable.ElementAt(int.Parse(cell.InnerText)).InnerText : cell.InnerText).ToArray();
for (var offset = 5; offset <= valueList.Length - 5; offset += 5)
{
extractedStudents.Add(new ImportedStudentRecord(valueList[offset], valueList[offset + 1], valueList[offset + 2], valueList[offset + 3], valueList[offset + 4]));
}
}
return extractedStudents;
}
}
}<file_sep>namespace HonglornBL.Calculation
{
interface IScoreCalculator
{
ushort CalculateScore();
}
}<file_sep>using HonglornWPF.ViewModels.ColorMenuData;
using MahApps.Metro;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Media;
namespace HonglornWPF.ViewModels
{
class MainWindowViewModel : ViewModel
{
public IEnumerable<AppThemeMenuData> AppThemes { get; }
public IEnumerable<AccentColorMenuData> AccentColors { get; }
public MainWindowViewModel()
{
AppThemes = ThemeManager.AppThemes.Select(a => new AppThemeMenuData(a.Name, (Brush)a.Resources["BlackColorBrush"], (Brush)a.Resources["WhiteColorBrush"]));
AccentColors = ThemeManager.Accents.Select(a => new AccentColorMenuData(a.Name, null, (Brush)a.Resources["AccentColorBrush"]));
}
}
}<file_sep>namespace HonglornBL.Calculation.Traditional
{
sealed class RunningScoreCalculator : ScoreCalculator
{
readonly short distance;
readonly float overhead;
public RunningScoreCalculator(float seconds, short distance, float constantA, float constantC, float? overhead) : base(constantA, constantC, seconds)
{
this.distance = distance;
this.overhead = overhead ?? 0;
}
protected override double CalculateRawScore()
{
return (distance / (Measurement + overhead) - ConstantA) / ConstantC;
}
}
}<file_sep>using MahApps.Metro;
using System.Windows;
using System.Windows.Media;
namespace HonglornWPF.ViewModels.ColorMenuData
{
class AppThemeMenuData : ColorMenuData
{
public AppThemeMenuData(string name, Brush borderColorBrush, Brush fillColorBrush) : base(name, borderColorBrush, fillColorBrush) { }
protected override void ChangeColor()
{
ThemeManager.ChangeAppTheme(Application.Current, Name);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using HonglornBL.Properties;
namespace HonglornBL.Import
{
public class ImportedStudentRecord
{
public string ImportedSurname { get; }
public string ImportedForename { get; }
public string ImportedCourseName { get; }
public string ImportedSex { get; }
public string ImportedYearOfBirth { get; }
public IEnumerable<FieldErrorInfo> Errors { get; }
public ImportedStudentRecord(string importedSurname, string importedForename, string importedCourseName, string importedSex, string importedYearOfBirth)
{
ImportedSurname = importedSurname;
ImportedForename = importedForename;
ImportedCourseName = importedCourseName;
ImportedSex = importedSex;
ImportedYearOfBirth = importedYearOfBirth;
Errors = FieldErrors();
}
IEnumerable<FieldErrorInfo> FieldErrors()
{
var fieldErrors = new List<FieldErrorInfo>
{
FieldError(nameof(ImportedSurname), ImportedSurname, IsValidName, "Surname cannot be empty or contain any digits."),
FieldError(nameof(ImportedForename), ImportedForename, IsValidName, "Forename cannot be empty or contain any digits."),
FieldError(nameof(ImportedCourseName), ImportedCourseName, IsValidCourseName, "The course name has to match the regular expression 0?[5-9][A-Za-z]|(E|e)(0[1-9]|[1-9][0-9])."),
FieldError(nameof(ImportedSex), ImportedSex, IsValidSex, "Sex can only be 'M', 'm', 'W' or 'w'."),
FieldError(nameof(ImportedYearOfBirth), ImportedYearOfBirth, IsValidYearOfBirth, $"Year of birth must be a four-digit number between {Settings.Default.MinValidYear} and {Settings.Default.MaxValidYear}.")
};
fieldErrors.RemoveAll(e => e == null);
return fieldErrors.Any() ? fieldErrors : null;
}
static FieldErrorInfo FieldError(string fieldName, string fieldContent, Func<string, bool> isValid, string errorMessage)
{
return isValid(fieldContent) ? null : new FieldErrorInfo(fieldName, fieldContent, errorMessage);
}
static readonly Func<string, bool> IsValidName = (name) =>
{
return !string.IsNullOrWhiteSpace(name) && !name.Any(char.IsDigit);
};
static readonly Func<string, bool> IsValidCourseName = (courseName) =>
{
var isValid = true;
try
{
Prerequisites.GetClassName(courseName);
}
catch
{
isValid = false;
}
return isValid;
};
static readonly Func<string, bool> IsValidSex = (sex) =>
{
return sex.Equals("W", StringComparison.InvariantCultureIgnoreCase) || sex.Equals("M", StringComparison.InvariantCultureIgnoreCase);
};
static readonly Func<string, bool> IsValidYearOfBirth = (year) =>
{
bool isValid = false;
if (short.TryParse(year, out short shortYear))
{
isValid = Prerequisites.IsValidYear(shortYear);
}
return isValid;
};
}
}<file_sep>using System;
namespace HonglornBL
{
class StudentPerformance : IStudentPerformance
{
public Guid StudentPKey { get; }
public string Forename { get; }
public string Surname { get; }
public float? Sprint { get; }
public float? Jump { get; }
public float? Throw { get; }
public float? MiddleDistance { get; }
internal StudentPerformance(Guid studentPKey, string forename, string surname, float? sprint, float? jump, float? @throw, float? middleDistance)
{
StudentPKey = studentPKey;
Forename = forename;
Surname = surname;
Sprint = sprint;
Jump = jump;
Throw = @throw;
MiddleDistance = middleDistance;
}
}
}<file_sep>namespace HonglornBL.Enums
{
public enum Certificate
{
Honorary = 0,
Victory = 1,
Participation = 2
}
}<file_sep>using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace HonglornBL.Models.Entities
{
public class Competition
{
[Key]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid StudentPKey { get; set; }
[Key]
[Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public short Year { get; set; }
public float? Sprint { get; set; }
public float? Jump { get; set; }
public float? Throw { get; set; }
public float? MiddleDistance { get; set; }
[ForeignKey(nameof(StudentPKey))]
public virtual Student Student { get; set; }
}
}<file_sep>using HonglornWPF.ViewModels;
using MahApps.Metro.Controls.Dialogs;
namespace HonglornWPF.Views
{
/// <summary>
/// Interaction logic for EditDisciplinesView.xaml
/// </summary>
partial class EditDisciplinesView
{
public EditDisciplinesView()
{
DataContext = new EditDisciplinesViewModel(DialogCoordinator.Instance);
InitializeComponent();
}
}
}<file_sep>using System;
using System.Globalization;
using System.Windows.Data;
namespace HonglornWPF.Converter
{
class CompetitionValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => value;
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => string.IsNullOrWhiteSpace(value as string) ? null : value;
}
}<file_sep>using HonglornBL.Models.Entities;
namespace HonglornBL
{
class DisciplineContainer<T> where T : Discipline
{
internal T MaleSprint { get; set; }
internal T MaleJump { get; set; }
internal T MaleThrow { get; set; }
internal T MaleMiddleDistance { get; set; }
internal T FemaleSprint { get; set; }
internal T FemaleJump { get; set; }
internal T FemaleThrow { get; set; }
internal T FemaleMiddleDistance { get; set; }
}
}<file_sep>using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
namespace HonglornWPF.ViewModels
{
class EditPerformanceViewModel : ViewModel
{
public ObservableCollection<string> Courses { get; } = new ObservableCollection<string>();
public ObservableCollection<short> Years { get; } = new ObservableCollection<short>();
public ObservableCollection<StudentPerformance> StudentCompetitions { get; } = new ObservableCollection<StudentPerformance>();
public ICommand RefreshYears { get; }
short currentYear;
public short CurrentYear
{
get => currentYear;
set
{
SaveCompetition();
OnPropertyChanged(out currentYear, value);
string previouslySelectedCourse = CurrentCourse;
LoadCourseNames();
CurrentCourse = Courses.Contains(previouslySelectedCourse) ? previouslySelectedCourse : Courses.FirstOrDefault();
}
}
string currentCourse;
public string CurrentCourse
{
get => currentCourse;
set
{
SaveCompetition();
OnPropertyChanged(out currentCourse, value);
LoadStudentsCompetitionsTuples();
}
}
StudentPerformance currentStudentCompetition;
public StudentPerformance CurrentStudentCompetition
{
get => currentStudentCompetition;
set
{
SaveCompetition();
OnPropertyChanged(out currentStudentCompetition, value);
}
}
public EditPerformanceViewModel()
{
RefreshYears = new RelayCommand(RefreshYearsFromDb);
RefreshYearsFromDb();
}
void RefreshYearsFromDb()
{
short previouslySelectedYear = CurrentYear;
LoadYears();
CurrentYear = Years.Contains(previouslySelectedYear) ? previouslySelectedYear : Years.FirstOrDefault();
}
void LoadCourseNames() => ClearAndFill(Courses, Honglorn.ValidCourseNames(CurrentYear));
void LoadYears() => ClearAndFill(Years, Honglorn.YearsWithStudentData());
void LoadStudentsCompetitionsTuples()
{
ClearAndFill(StudentCompetitions, Honglorn.StudentPerformances(CurrentCourse, CurrentYear).Select(i => new StudentPerformance(i)));
}
void SaveCompetition()
{
if (currentStudentCompetition != null)
{
Honglorn.UpdateSingleStudentCompetition(currentStudentCompetition.StudentPKey, CurrentYear, currentStudentCompetition.Sprint, currentStudentCompetition.Jump, currentStudentCompetition.Throw, currentStudentCompetition.MiddleDistance);
}
}
}
}<file_sep>using System.Diagnostics;
using HonglornBL.Enums;
namespace HonglornAUT
{
[DebuggerDisplay("{Sex} ({Sprint}|{SprintScore}) ({Jump}|{JumpScore}) ({Throw}|{ThrowScore}) ({MiddleDistance}|{MiddleDistanceScore}) {Certificate}")]
class CompetitionStudent
{
internal string Course { get; }
internal string Forename { get; }
internal string Surname { get; }
internal Sex Sex { get; }
internal float? Sprint { get; }
internal float? Jump { get; }
internal float? Throw { get; }
internal float? MiddleDistance { get; }
internal ushort SprintScore { get; }
internal ushort JumpScore { get; }
internal ushort ThrowScore { get; }
internal ushort MiddleDistanceScore { get; }
internal ushort Rank { get; }
internal Certificate Certificate { get; }
internal CompetitionStudent(string course, string forename, string surname, Sex sex, float? sprint, float? jump, float? @throw, float? middleDistance, ushort sprintScore, ushort jumpScore, ushort throwScore, ushort middleDistanceScore, ushort rank, Certificate certificate)
{
Course = course;
Forename = forename;
Surname = surname;
Sex = sex;
Sprint = sprint;
Jump = jump;
Throw = @throw;
MiddleDistance = middleDistance;
SprintScore = sprintScore;
JumpScore = jumpScore;
ThrowScore = throwScore;
MiddleDistanceScore = middleDistanceScore;
Rank = rank;
Certificate = certificate;
}
}
}<file_sep>namespace HonglornWPF.Views
{
/// <summary>
/// Interaction logic for AssignDisciplinesView.xaml
/// </summary>
partial class AssignDisciplinesView
{
public AssignDisciplinesView()
{
InitializeComponent();
}
}
}<file_sep>using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using HonglornBL.Models.Entities;
namespace HonglornBL.Models.Framework
{
class HonglornDb : DbContext
{
public virtual DbSet<Competition> Competition { get; set; }
public virtual DbSet<CompetitionDiscipline> CompetitionDiscipline { get; set; }
public virtual DbSet<DisciplineCollection> DisciplineCollection { get; set; }
public virtual DbSet<Student> Student { get; set; }
public virtual DbSet<StudentCourseRel> StudentCourseRel { get; set; }
public virtual DbSet<TraditionalDiscipline> TraditionalDiscipline { get; set; }
public virtual DbSet<TraditionalReportMeta> TraditionalReportMeta { get; set; }
internal HonglornDb(DbConnection connection) : base(connection, true)
{
Database.SetInitializer(new HonglornDbInitializer<HonglornDb>());
}
protected sealed override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}<file_sep>using System;
namespace HonglornBL.Interfaces
{
public interface IDisciplineCollection
{
Guid? MaleSprintPKey { get; }
Guid? MaleJumpPKey { get; }
Guid? MaleThrowPKey { get; }
Guid? MaleMiddleDistancePKey { get; }
Guid? FemaleSprintPKey { get; }
Guid? FemaleJumpPKey { get; }
Guid? FemaleThrowPKey { get; }
Guid? FemaleMiddleDistancePKey { get; }
}
} | b52de4ef2e212496b30c3343d778d8e057f777dc | [
"Markdown",
"C#"
] | 77 | C# | Danghor/Honglorn | 82fa7243ef8251a08092271984d6ae25fc22f942 | 4e11947d0e29d2ff0bfceb7d221a7269c4433f96 |
refs/heads/master | <repo_name>yanivsu/heroloTestDeploy<file_sep>/src/components/weatherMainComp/weatherCard.js
import React from "react";
import Grid from "@material-ui/core/Grid";
import { makeStyles } from "@material-ui/core/styles";
import { Typography } from "@material-ui/core";
import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent";
import * as enums from "../../helpers/enums";
const useStyles = makeStyles((theme) => ({
root: {
margin: theme.spacing(3),
},
}));
export default function WeatherCard(props) {
const classes = useStyles();
return (
<Card className={classes.root}>
<CardContent>
<Grid container direction="column" alignItems="center">
<Typography variant="h5" component="h2">
{props.data.foreCastDay !== undefined
? props.data.foreCastDay
: props.data.cityName}
</Typography>
<Typography variant="body2" component="p">
<img
src={
enums.serverWeatherEnums.API_ICON_LINK +
props.data.iconNumber +
enums.serverWeatherEnums.SVG
}
style={{ width: "4.5em", height: "4.5em", margin: "2px" }}
alt="Weather Icon"
></img>
</Typography>
<Typography variant="h5" component="h2">
{props.data.tempatureMin}
{props.unitMode
? enums.weatherEnums.CEL
: enums.weatherEnums.FER} - {props.data.tempatureMax}
{props.unitMode ? enums.weatherEnums.CEL : enums.weatherEnums.FER}
</Typography>
</Grid>
</CardContent>
</Card>
);
}
<file_sep>/src/components/FavoriteComp/favoiteComp.js
import React from "react";
import { useSelector } from "react-redux";
import Grid from "@material-ui/core/Grid";
import { makeStyles } from "@material-ui/core/styles";
import { Typography } from "@material-ui/core";
import WeatherCard from "../weatherMainComp/weatherCard";
const useStyles = makeStyles((theme) => ({
title: {
fontFamily: "Titillium Web",
fontWeight: "bold",
},
}));
export default function Favorite(props) {
const classes = useStyles();
const selectorFavorite = useSelector((state) => state.faivorteCitiesReducer);
return (
<Grid
container
direction="column"
alignItems="center"
justifyContent="center"
>
<Typography variant="h3" className={classes.title}>
Favorite Cities
</Typography>
<Grid
direction="row"
container
alignItems="center"
justifyContent="center"
>
{selectorFavorite.faivorteCities.length > 0
? selectorFavorite.faivorteCities.map((city) => {
return <WeatherCard data={city} unitMode={props.unitMode} />;
})
: null}
</Grid>
</Grid>
);
}
<file_sep>/src/App.js
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Grid from "@material-ui/core/Grid";
import { makeStyles } from "@material-ui/core/styles";
import {
CircularProgress,
createTheme,
ThemeProvider,
} from "@material-ui/core";
import CssBaseline from "@material-ui/core/CssBaseline";
import Brightness3Icon from "@material-ui/icons/Brightness3";
import Brightness5Icon from "@material-ui/icons/Brightness5";
import { loadWeaterByCoords } from "./actions/defaultAction";
import Header from "./components/Header/headerComp";
import WeatherMain from "./components/weatherMainComp/weatherMain";
import WeatherCard from "./components/weatherMainComp/weatherCard";
import SerachCity from "./components/SearchComp/searchComp";
import Favorite from "./components/FavoriteComp/favoiteComp";
const useStyles = makeStyles((theme) => ({
root: { flexGrow: 1 },
header: {
padding: theme.spacing(2),
fontWeight: "Bold",
textAlign: "center",
color: "whitesmoke",
background: "#3f51b5",
},
searchCity: {
padding: theme.spacing(2),
},
mainWeather: {
padding: theme.spacing(10),
},
darkIcon: {
margin: theme.spacing(2, 2, 2, 2),
},
}));
function App() {
const classes = useStyles();
const [darkMode, setDarkMode] = useState(false);
const dispatcher = useDispatch();
const weatherSelector = useSelector((state) => state.weatherReducer);
const theme = React.useMemo(
() =>
createTheme({
palette: {
type: darkMode ? "dark" : "light",
},
}),
[darkMode]
);
theme.typography.h4 = {
fontSize: "0rem",
"@media (min-width:600px)": {
fontSize: "5rem",
},
};
theme.typography.h5 = {
fontSize: "1.0rem",
fontFamily: "Segoe UI",
"@media (min-width:600px)": {
fontSize: "1.8rem",
},
};
theme.typography.h3 = {
fontSize: "1.0rem",
"@media (min-width:600px)": {
fontSize: "1.8rem",
},
};
theme.typography.h2 = {
fontSize: "2rem",
fontFamily: "Segoe UI",
"@media (min-width:600px)": {
fontSize: "5rem",
},
};
useEffect(() => {
navigator.geolocation.getCurrentPosition(
(result) => {
dispatcher(
loadWeaterByCoords(result.coords.latitude, result.coords.longitude)
);
},
(err) => {
console.error(err);
},
{ timeout: 8000 }
);
}, []);
const handleDarkMode = () => {
setDarkMode(!darkMode);
};
return (
<ThemeProvider theme={theme}>
<CssBaseline>
<Router exact path="/heroloTestDeploy">
<Header />
{darkMode ? (
<Brightness5Icon
className={classes.darkIcon}
onClick={handleDarkMode}
/>
) : (
<Brightness3Icon
className={classes.darkIcon}
onClick={handleDarkMode}
/>
)}
<Switch>
{weatherSelector.isLoading ? (
<CircularProgress />
) : (
<Route exact path="/heroloTestDeploy">
<Grid
container
alignItems="center"
justifyContent="center"
className={classes.searchCity}
>
<SerachCity />
</Grid>
<Grid container className={classes.mainWeather}>
<WeatherMain
data={weatherSelector.weatherForecast[0]}
cityName={weatherSelector.cityName}
unitMode={weatherSelector.tempFunction}
/>
<Grid
container
justifyContent="space-around"
alignItems="center"
>
{weatherSelector.weatherForecast.map((day) => {
return (
<WeatherCard
data={day}
unitMode={weatherSelector.tempFunction}
/>
);
})}
</Grid>
</Grid>
</Route>
)}
<Route exact path="/favorites">
<Favorite unitMode={weatherSelector.tempFunction} />
</Route>
</Switch>
</Router>
</CssBaseline>
</ThemeProvider>
);
}
export default App;
<file_sep>/src/reducers/weatherReducer.js
import produce from "immer";
import * as enums from "../helpers/enums";
const INITIAL_STATE = {
isLoading: true,
cityName: "",
cityCode: "",
tempFunction: true, // true -- Cel , false -- F
weatherForecast: [
{
tempatureMin: "",
tempatureMax: "",
date: "",
iconNumber: 0,
iconPharse: "",
cityCode: "",
},
],
};
const weatherReducer = (state = INITIAL_STATE, action) =>
produce(state, (draft) => {
switch (action.type) {
case enums.weatherEnums.WEATHER_FETCH_DATA: {
draft.isLoading = false;
draft.cityCode = action.payload.cityCode;
draft.cityName = action.payload.cityName;
let fiveDaysForecast = [];
action.payload.data.DailyForecasts.forEach((day) => {
let date = new Date(day.EpochDate * 1000);
var options = { weekday: "short" };
let tempDay = new Intl.DateTimeFormat("en-US", options).format(date);
let oneDayForecaste = {
tempatureMin: Math.floor(parseInt(day.Temperature.Minimum.Value)),
tempatureMax: Math.floor(parseInt(day.Temperature.Maximum.Value)),
date: day.Date,
foreCastDay: tempDay,
iconNumber: day.Day.Icon,
iconPharse: day.Day.IconPhrase,
cityCode: action.payload.cityCode,
};
if (!draft.tempFunction) {
oneDayForecaste.tempatureMin =
oneDayForecaste.tempatureMin * (9 / 5) + 32;
oneDayForecaste.tempatureMax =
oneDayForecaste.tempatureMax * (9 / 5) + 32;
}
fiveDaysForecast.push(oneDayForecaste);
});
draft.weatherForecast = fiveDaysForecast;
return draft;
}
case enums.weatherEnums.CHANGE_C_OR_F: {
if (!action.payload) {
draft.tempFunction = false;
draft.weatherForecast.forEach((day, index) => {
draft.weatherForecast[index].tempatureMin = Math.floor(
parseInt(day.tempatureMin * (9 / 5) + 32)
);
draft.weatherForecast[index].tempatureMax = Math.floor(
parseInt(day.tempatureMax * (9 / 5) + 32)
);
});
return draft;
} else if (action.payload) {
draft.tempFunction = true;
draft.weatherForecast.forEach((day, index) => {
draft.weatherForecast[index].tempatureMin = Math.floor(
parseInt((day.tempatureMin - 32) * (5 / 9))
);
draft.weatherForecast[index].tempatureMax = Math.floor(
parseInt((day.tempatureMax - 32) * (5 / 9))
);
});
return draft;
}
return draft;
}
default:
return draft;
}
});
export default weatherReducer;
<file_sep>/src/components/SearchComp/searchComp.js
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import {
loadCitiesByName,
loadWeaterByCode,
} from "../../actions/defaultAction";
export default function SerachCity(props) {
const [searchCity, setSearchCity] = useState("");
const [selectedCity, setSelectedCity] = useState("");
const citiesListSelector = useSelector((state) => state.searchCityReducer);
const loading =
searchCity !== "" && citiesListSelector.citiesOptions.length === 0;
const dispatcher = useDispatch();
useEffect(() => {
dispatcher(loadCitiesByName(searchCity));
}, [searchCity]);
useEffect(() => {
dispatcher(loadWeaterByCode(selectedCity.code, selectedCity.cityName));
}, [selectedCity]);
return (
<Autocomplete
getOptionSelected={(option, value) => {
if (option.cityName === value.cityName) {
setSelectedCity(option);
}
}}
loading={loading}
options={citiesListSelector.citiesOptions}
getOptionLabel={(option) => {
if (option !== undefined) {
return `${option.cityName}, ${option.countryName}`;
} else {
return;
}
}}
style={{ width: 300 }}
renderInput={(params) => (
<TextField
placeholder="Search City..."
onChange={(event) => {
let str = event.target.value;
str = str.charAt(0).toUpperCase() + str.slice(1);
setSearchCity(str);
}}
{...params}
variant="outlined"
/>
)}
/>
);
}
<file_sep>/src/reducers/rootReducer.js
import { combineReducers } from "redux";
import weatherReducer from "./weatherReducer";
import searchCityReducer from "./searchCityReducer";
import faivorteCitiesReducer from "./favoriteCitiesReducer";
const rootReducer = combineReducers({
weatherReducer,
searchCityReducer,
faivorteCitiesReducer,
});
export default rootReducer;
<file_sep>/src/helpers/enums.js
export const serverWeatherEnums = {
API_5DAYS_FORECAST:
"https://dataservice.accuweather.com/forecasts/v1/daily/5day/",
API_SEARCH_CITY_BY_NAME:
"https://dataservice.accuweather.com/locations/v1/cities/autocomplete?",
API_GET_CITY_CODE_BY_COORDS:
"https://dataservice.accuweather.com/locations/v1/cities/geoposition/search?",
API_QUERY: "&q=",
API_ICON_LINK: "https://vortex.accuweather.com/adc2010/images/slate/icons/",
APIKEY: "<KEY>",
TEMPERATURE: "&metric=true", // Celsuis
HAIFA_KEY: "213181",
QUESTION_MARK: "?",
HAIFA: "Haifa",
SVG: ".svg",
COMMA: ",",
};
export const weatherEnums = {
WEATHER_FETCH_DATA: "WEATHER_FETCH_DATA",
AUTOCOMPLETE_CITIES_LIST: "AUTOCOMPLETE_CITIES_LIST",
ADD_FAVORITE_CITY: "ADD_FAVORITE_CITY",
CHANGE_C_OR_F: "CHANGE_C_OR_F",
CEL: "°C",
FER: "°F",
};
export const mainEnums = {
ADD_TO_FAV: "❤️ Add to Favorites",
};
<file_sep>/src/actions/defaultAction.js
import { getApi } from "../helpers/apiUtils";
import * as enums from "../helpers/enums";
//----------------- Async Action functions ----------//
export function loadWeaterByCode(cityCode, cityName) {
return function (dispatch) {
return getApi(
enums.serverWeatherEnums.API_5DAYS_FORECAST +
cityCode +
enums.serverWeatherEnums.QUESTION_MARK +
enums.serverWeatherEnums.APIKEY +
enums.serverWeatherEnums.TEMPERATURE
)
.then(({ data }) => {
dispatch({
type: enums.weatherEnums.WEATHER_FETCH_DATA,
payload: { data, cityCode, cityName },
});
})
.catch((error) => console.log("loadData Error no data", error.message));
};
}
export function loadCitiesByName(cityName) {
return function (dispatch) {
return getApi(
enums.serverWeatherEnums.API_SEARCH_CITY_BY_NAME +
enums.serverWeatherEnums.APIKEY +
enums.serverWeatherEnums.API_QUERY +
cityName
)
.then(({ data }) => {
dispatch({
type: enums.weatherEnums.AUTOCOMPLETE_CITIES_LIST,
payload: data,
});
})
.catch((error) => console.log("loadData Error no data", error.message));
};
}
export function loadWeaterByCoords(lat, long) {
return function (dispatch) {
return getApi(
enums.serverWeatherEnums.API_GET_CITY_CODE_BY_COORDS +
enums.serverWeatherEnums.APIKEY +
enums.serverWeatherEnums.API_QUERY +
lat +
enums.serverWeatherEnums.COMMA +
long
)
.then(({ data }) => {
// Get city Code from data
let cityCode = data.Key;
let cityName = data.LocalizedName;
dispatch(loadWeaterByCode(cityCode, cityName));
})
.catch((error) => console.log("loadData Error no data", error.message));
};
}
export function addCityToFavorite(cityDetails) {
return { type: enums.weatherEnums.ADD_FAVORITE_CITY, payload: cityDetails };
}
export function changeToTempStatus(bit) {
return { type: enums.weatherEnums.CHANGE_C_OR_F, payload: bit };
}
<file_sep>/src/reducers/favoriteCitiesReducer.js
import produce from "immer";
import * as enums from "../helpers/enums";
const INITIAL_STATE = {
isLoading: true,
faivorteCities: [],
tempFunction: true, // 1 -- Cel , 0 -- F
};
const faivorteCitiesReducer = (state = INITIAL_STATE, action) =>
produce(state, (draft) => {
switch (action.type) {
case enums.weatherEnums.ADD_FAVORITE_CITY: {
draft.isLoading = false;
// Check if the city is already exist in fav cities:
let index = draft.faivorteCities.findIndex((value) => {
if (value.cityCode === action.payload.data.cityCode) {
return true;
}
});
if (index === -1) {
let newCity = {
cityName: action.payload.cityName,
cityCode: action.payload.data.cityCode,
tempatureMin: action.payload.data.tempatureMin,
tempatureMax: action.payload.data.tempatureMax,
date: action.payload.data.date,
dayName: action.payload.data.foreCastDay,
iconNumber: action.payload.data.iconNumber,
iconPharse: action.payload.data.iconPharse,
};
draft.faivorteCities.push(newCity);
}
return draft;
}
case enums.weatherEnums.CHANGE_C_OR_F: {
if (!action.payload) {
draft.tempFunction = false;
draft.faivorteCities.forEach((city, index) => {
draft.faivorteCities[index].tempatureMin = Math.floor(
parseInt(city.tempatureMin * (9 / 5) + 32)
);
draft.faivorteCities[index].tempatureMax = Math.floor(
parseInt(city.tempatureMax * (9 / 5) + 32)
);
});
return draft;
} else if (action.payload) {
draft.tempFunction = true;
draft.faivorteCities.forEach((city, index) => {
draft.faivorteCities[index].tempatureMin = Math.floor(
parseInt((city.tempatureMin - 32) * (5 / 9))
);
draft.faivorteCities[index].tempatureMax = Math.floor(
parseInt((city.tempatureMax - 32) * (5 / 9))
);
});
return draft;
}
}
default:
return draft;
}
});
export default faivorteCitiesReducer;
<file_sep>/src/helpers/apiUtils.js
import axios from "axios";
export async function getApi(api, obj = {}) {
// Load async data.
try {
return await axios.get(api, obj);
} catch (error) {
// console.error(error);
if (error.response) {
// Request made and server responded
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log("Error", error.message);
}
}
}
<file_sep>/src/reducers/searchCityReducer.js
import produce from "immer";
import * as enums from "../helpers/enums";
const INITIAL_STATE = {
isLoading: true,
citiesOptions: [],
};
const searchCityReducer = (state = INITIAL_STATE, action) =>
produce(state, (draft) => {
switch (action.type) {
case enums.weatherEnums.AUTOCOMPLETE_CITIES_LIST: {
if (Array.isArray(action.payload)) {
let options = [];
action.payload.forEach((city) => {
let newCity = {
countryName: city.Country.LocalizedName,
cityName: city.LocalizedName,
code: city.Key,
};
options.push(newCity);
});
draft.citiesOptions = options;
draft.isLoading = false;
} else {
draft.citiesOptions.length = 0;
}
return draft;
}
case enums.weatherEnums.CHANGE_C_OR_F: {
if (draft.citiesOptions.length > 0) {
}
}
default:
return draft;
}
});
export default searchCityReducer;
| 187db8ffcd4ebcf0069d76189df315709375e13d | [
"JavaScript"
] | 11 | JavaScript | yanivsu/heroloTestDeploy | 489cb133de38cccc4b360b23c77f25da4fc5e447 | c17b57eada95c5d21f0e142df50a04f219c770c4 |
refs/heads/master | <repo_name>vincedenbesten/madlibs-php<file_sep>/pages/onkunderesult.php
<?php
$kunnen = $_POST['kunnen'];
$persoon = $_POST['persoon'];
$getal = $_POST['getal'];
$vakantie = $_POST['vakantie'];
$beste = $_POST['beste'];
$slechtste = $_POST['slechtste'];
$overkomen = $_POST['overkomen'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Mad Libs</title>
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Black+Ops+One" />
</head>
<body>
<header>
<h1>Mad Libs</h1>
</header>
<nav>
<a href="../index.php">Er heerst paniek...</a>
<a href="onkunde.php">onkunde</a>
</nav>
<main>
<h2>Onkunde</h2>
<p>Er zijn veel mensen die niet kunnen <?=$kunnen?>. Neem nou <?=$persoon?>, zelfs met de hulp van een <?=$vakantie?> of zelfs <?=$getal?> kan <?=$persoon?> niet <?=$kunnen?>. Dat heeft niet te maken met een gebrek aan <?=$beste?>, maar met een teveel aan <?=$slechtste?>. Te veel <?=$slechtste?> leidt tot <?=$overkomen?> en dat is niet goed als je wilt <?=$kunnen?>. Helaas voor <?=$persoon?>.</p>
</main>
<footer>Footer</footer>
</body>
</html>
<file_sep>/pages/paniek.php
<?php
$huisdier = $_POST['huisdier'];
$persoon = $_POST['persoon'];
$wonen = $_POST['wonen'];
$vervelen = $_POST['vervelen'];
$speelgoed = $_POST['speelgoed'];
$docent = $_POST['docent'];
$kopen = $_POST['kopen'];
$hobby = $_POST['hobby'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Mad Libs</title>
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Black+Ops+One" />
</head>
<body>
<header>
<h1>Mad Libs</h1>
</header>
<nav>
<a href="../index.php">Er heerst paniek...</a>
<a href="onkunde.php">onkunde</a>
</nav>
<main>
<h2>Er heerst paniek...</h2>
<p>Er heerst paniek in het koninkrijk <?php echo $wonen ?>. Koning <?php echo $docent ?> is ten einde raad en als koning <?php echo $docent ?> ten einde raad is, dan roept hij zijn ten-einde-raadsheer <?php echo $persoon ?>.</p>
<p>"<?php echo $persoon ?>! Het is een ramp! Het is een schande!"</p>
<p>"Sire, Majesteit, Uwe Luidruchtigheid, wat is er aan de hand?"</p>
<p>"Mijn <?php echo $huisdier ?> is verdwenen! Zo maar, zonder waarscchuwing. En Ik had net <?php echo $speelgoed ?> voor hem gekocht!"</p>
<p>"Majesteit, uw <?php echo $huisdier ?> komt vast vanzelf weer terug?"</p>
<p>"Ja da's leuk en aardig, maar hoe moet ik in de tussentijd <?php echo $hobby ?> leren?"</p>
<p>"Maar Sire, daar kunt u toch uw <?php echo $kopen ?> voor gebruiken."</p>
<p>"<?php echo $docent ?>, je hebt helemaal gelijk! Wat zou ik doen als ik jouw niet had."</p>
<p>"<?php echo $vervelen ?>, Sire."</p>
</main>
<footer>Footer</footer>
</body>
</html>
| 1bc418322a9ccc298cd3d367fe22d5981e07040b | [
"PHP"
] | 2 | PHP | vincedenbesten/madlibs-php | 6c2048e38247dba6634812c6af54f016ba38c68e | b16d56494e610bd28a9802204b38d15e007b08f5 |
refs/heads/master | <file_sep>import React, { Component } from "react";
import Button from "../../components/UI/Button/Button";
import Spinner from "../../components/UI/Spinner/Spinner";
import "./ContactData.css";
import axios from "../../axios";
import Input from "../../components/UI/Input/Input";
import ImageUploader from "react-images-upload";
class ContactData extends Component {
state = {
formData: {
name: {
elementType: "input",
elementConfig: {
type: "text",
placeholder: "Imie",
},
value: "",
validation: {
required: true,
minLength: 3,
maxLength: 12,
},
valid: false,
},
surname: {
elementType: "input",
elementConfig: {
type: "text",
placeholder: "Nazwisko",
},
value: "",
validation: {
required: true,
minLength: 3,
maxLength: 12,
},
valid: false,
},
email: {
elementType: "input",
elementConfig: {
type: "email",
placeholder: "<NAME>",
},
value: "",
validation: {
required: true,
},
valid: false,
},
identificationNumber: {
elementType: "input",
elementConfig: {
type: "text",
placeholder: "Pesel lub NIP",
},
value: "",
validation: {
required: true,
},
valid: false,
},
personType: {
elementType: "select",
elementConfig: {
options: [
{ value: "osoba", displayValue: "osoba" },
{ value: "firma", displayValue: "firma" },
],
},
value: "",
validation: {},
valid: true,
},
},
formIsValid: false,
loading: false,
picture: [],
error: false,
author: "<NAME>"
};
onDrop = (picture) => {
this.setState({ picture: picture });
};
checkValidity(value, rules) {
let isValid = true;
if (rules.required) {
isValid = value.trim() !== "" && isValid;
}
if (rules.minLength) {
isValid = value.length >= rules.minLength && isValid;
}
if (rules.maxLength) {
isValid = value.length <= rules.maxLength && isValid;
}
return isValid;
}
formHandler = (event) => {
event.preventDefault();
this.setState({ loading: true });
const formData = {};
for (let formElementIdentifier in this.state.formData) {
formData[formElementIdentifier] = this.state.formData[
formElementIdentifier
].value;
}
const personData = {
formData: formData,
author: this.state.author,
};
axios
.post("/Contractor/save", personData)
.then((response) => {
this.setState({ loading: false });
})
.catch((error) => {
this.setState({ error: true, loading: false });
});
};
inputChangedHandler = (event, inputIdentifier) => {
const updatedPersonData = {
...this.state.formData,
};
const updatedFormElement = {
...updatedPersonData[inputIdentifier],
};
updatedFormElement.value = event.target.value;
updatedFormElement.valid = this.checkValidity(
updatedFormElement.value,
updatedFormElement.validation
);
updatedPersonData[inputIdentifier] = updatedFormElement;
let formIsValid = true;
for (let inputIdentifier in updatedPersonData) {
formIsValid = updatedPersonData[inputIdentifier].valid && formIsValid;
}
this.setState({ formData: updatedPersonData, formIsValid: formIsValid });
};
render() {
let messageToUser = (
<p className="errorMessage">
Nie znaleziono metody zapisu, przepraszamy :(
</p>
);
const formElementsArray = [];
for (let key in this.state.formData) {
formElementsArray.push({
id: key,
config: this.state.formData[key],
});
}
let form = (
<form onSubmit={this.formHandler}>
{formElementsArray.map((formElement) => (
<Input
key={formElement.id}
elementType={formElement.config.elementType}
elementConfig={formElement.config.elementConfig}
value={formElement.config.value}
changed={(event) => this.inputChangedHandler(event, formElement.id)}
/>
))}
<Button disabled={!this.state.formIsValid}>Wyślij</Button>
</form>
);
if (this.state.loading) {
form = <Spinner />;
}
return (
<div className="ContactData">
{this.state.error ? messageToUser : ""}
<h4>Proszę wprowadź swoje dane kontaktowe</h4>
<small className="smallText">
Upewnij się że wypełniłeś wszystko żeby przycisk zadziała
</small>
<ImageUploader
withIcon={true}
onChange={this.onDrop}
maxFileSize={5242880}
/>
{form}
</div>
);
}
}
export default ContactData;
| e92838b542dd8066a642647f7efc36a08706ecda | [
"JavaScript"
] | 1 | JavaScript | nbenlin/simple-react-form | e4dde772a370d2c73528d37d3613c7eec9018314 | 532fc8da610a116615c9d56469e0fe417c9bcc22 |
refs/heads/master | <file_sep>var arch = 0;
deb = 0;
devuan = 0;
fedora = 0;
handy = 0;
puppy = 0;
gentoo = 0;
lfs = 0;
ubuntu = 0;
voidlinux = 0;
windows = 0;
macos = 0;
var distros = []; // Un tableau qui permettra de sortir la meilleure distribution
// Opérations sur les variables, afin de déterminer la distribution à utiliser
document.getElementById('btn-infosis').onclick = function() { // Si l'utilisateur se sent à l'aise avec l'informatique, on incrémente ces variables
arch = ++arch;
deb = ++deb;
devuan = ++devuan;
fedora = ++fedora;
gentoo = ++gentoo;
lfs = ++lfs;
};
document.getElementById('btn-infomid').onclick = function() {
ubuntu = ++ubuntu;
fedora = ++fedora;
deb = ++deb;
puppy = ++puppy;
}
document.getElementById('btn-infosid').onclick = function() { // Au contraire, si l'informatique est une horreur, on incrémente ces variables
handy = ++handy;
puppy = ++puppy;
ubuntu = ++ubuntu;
fedora = ++fedora;
};
document.getElementById('btn-ootbs').onclick = function() { // Si l'utilisateur veut pas se prendre la tête, on incrémente ces variables
deb = ++deb;
devuan = ++devuan;
fedora = ++fedora;
ubuntu = ++ubuntu;
handy = ++handy;
puppy = ++puppy;
};
document.getElementById('btn-ootbd').onclick = function() { // Au contraire, si l'utilisateur aime bien configurer, on incrémente Arch/Gentoo/LFS
arch = ++arch;
gentoo = ++gentoo;
lfs = ++lfs;
};
document.getElementById('btn-windows').onclick = function() { // Si l'utilisateur veut une interface Windows-like, Windows gagne un point, on met macOS à 0
windows = 1;
macos = 0;
};
document.getElementById('btn-macos').onclick = function() { // L'inverse de l'autre fonction
macos = 1;
windows = 0;
};
document.getElementById('btn-olds').onclick = function() { // Si l'ordi est récent on va mettre des distros récentes ou avec GNOME/KDE par défaut
fedora = ++fedora;
ubuntu = ++ubuntu;
arch = ++arch;
gentoo = ++gentoo;
lfs = ++lfs;
deb = ++deb;
devuan = ++devuan;
handy = ++handy;
};
document.getElementById('btn-oldd').onclick = function() { // Si l'ordi n'est pas récent, on va préférer des versions légères (on enlève Gentoo et LFS parce que ça met sa vie sur des machines peu récentes)
arch = ++arch;
handy = ++handy;
puppy = ++puppy;
deb = ++deb;
devuan = ++devuan;
};
document.getElementById('btn-volds').onclick = function() { // Sur de très vieilles machines (tout ce qui n'est pas x86_64), on ne met que des distros x86
deb = ++deb;
ubuntu = ++ubuntu; // Avec Lubuntu c'est possible à la limite
puppy = ++puppy;
};
document.getElementById('btn-voldd').onclick = function() { // Entre 2006 et 2011
handy = ++handy;
puppy = ++puppy;
deb = ++deb;
devuan = ++devuan;
arch = ++arch;
ubuntu = ++ubuntu; // Xubuntu ?
fedora = ++fedora; // Fedora MATE/LXDE/XFCE ?
// On aurait pu mettre Gentoo, mais faut avoir la foi pour compiler dessus
};
document.getElementById('btn-rollings').onclick = function() { // Si l'utilisateur veut de la rolling release
arch = ++arch;
gentoo = ++gentoo;
lfs = ++lfs; // Si on met un gestionnaire de paquets ça passe
};
document.getElementById('btn-rollingd').onclick = function() {
handy = ++handy;
puppy = ++puppy;
deb = ++deb;
devuan = ++devuan;
ubuntu = ++ubuntu;
fedora = ++fedora;
lfs = ++lfs; // Si tu mets pas de gestionnaire de paquets ou que la recompilation ça fait chier, ça fait une LFS très stable
};
document.getElementById('btn-rollingdd').onclick = function() {
deb = deb+2; // Debian Jessie ou Wheezy sont effectivement très stables, Stretch le sera dans un an (quand les versions seront dépassées)
};
document.getElementById('btn-systemds').onclick = function() {
devuan = devuan+4; // 4 points de plus pour bien favoriser les distros non-systemd à la fin
voidlinux = voidlinux+4;
gentoo = ++gentoo+4;
lfs = lfs+4;
puppy = ++puppy; // Puppy Linux est surtout fait pour de l'USB donc juste 1 point
};
document.getElementById('btn-systemmid').onclick = function() {
devuan = 0; // Puisque l'utilisateur veut systemd, on va pas lui proposer un non-systemd
voidlinux = 0;
gentoo = ++gentoo; // Gentoo propose une version systemd
lfs = ++lfs; // Linux From Scratch propose une version systemd
ubuntu = ++ubuntu;
fedora = ++fedora;
arch = ++arch;
deb = ++deb;
handy = ++handy;
};
document.getElementById('btn-systemdd').onclick = function() {
devuan = ++devuan;
voidlinux = ++voidlinux;
gentoo = ++gentoo;
lfs = ++lfs;
ubuntu = ++ubuntu;
fedora = ++fedora;
arch = ++arch;
deb = ++deb;
handy = ++handy;
puppy = ++puppy;
};
document.getElementById('btn-inssis').onclick = function() {
ubuntu = ++ubuntu;
handy = ++handy;
puppy = ++puppy;
deb = ++deb;
devuan = ++devuan;
fedora = ++fedora;
showResult();
};
document.getElementById('btn-inssid').onclick = function() {
arch = ++arch;
gentoo = ++gentoo;
lfs = ++lfs;
showResult();
};
function showResult() { // Merci à @Sp3r4z pour cette fonction super utile !
// Pour masquer les conseils de chiffrement selon distrib
$("#archdisk").hide();
$("#gendisk").hide();
// Classement des distributions
distros.push(
{distro: 'Arch Linux',score: arch},
{distro: 'Gentoo',score: gentoo},
{distro: 'Linux From Scratch',score: lfs},
{distro: 'Fedora',score: fedora},
{distro: 'Debian',score: deb},
{distro: 'HandyLinux',score: handy},
{distro: 'Ubuntu',score: ubuntu},
{distro: 'Puppy Linux',score: puppy},
{distro: 'Devuan', score: devuan},
{distro: 'Void Linux', score: voidlinux}
);
distros.sort(function(a, b) { // On classe les distros en fonction de leur score
return b.score - a.score;
});
console.log(distros[0].distro);
$('#results').text(distros[0].distro); // On affiche le nom de la distro dans le h3
$('#scoreresult').text(distros[0].score); // Avec le score obtenu
$('#moui').text(distros[1].distro); // La seconde distribution voit son nom s'afficher
$('#mouiresult').text(distros[1].score); // Avec son score
$('#bof').text(distros[2].distro); // La troisième distribution
$('#bofresult').text(distros[2].score); // Avec son score
switch(distros[0].distro) { // On propose le lien vers le site officiel, ainsi que le texte sur le chiffrement en fonction de la distro
case 'Arch Linux': $("#lien").attr("href", "https://archlinux.org"); $("#archdisk").show(); break;
case 'Debian': $("#lien").attr("href", "https://debian.org"); $("#gendisk").show(); break;
case 'Linux From Scratch': $("#lien").attr("href", "http://linuxfromscratch.org"); break;
case 'Fedora': $("#lien").attr("href", "https://getfedora.org"); $("#gendisk").show(); break;
case 'HandyLinux': $("#lien").attr("href", "https://handylinux.org/"); break;
case 'Puppy Linux': $("#lien").attr("href", "http://puppylinux.com/"); break;
case 'Gentoo': $("#lien").attr("href", "https://gentoo.org"); break;
case 'Ubuntu': $("#lien").attr("href", "https://ubuntu.com"); $("#gendisk").show(); break;
case 'Void Linux': $("#lien").attr("href", "https://voidlinux.eu"); $("#gendisk").show(); break;
case 'Devuan': $("#lien").attr("href", "https://devuan.org"); $("#gendisk").show(); break;
};
$("#resultat").text(distros[0].distro);
if (windows != 0) { // On affiche le texte prévu pour l'interface Windows-like (et on désactive l'interface macOS)
$('#windowschosen').show();
$('#macoschosen').hide();
}
if (macos != 0) { // Et inversement
$('#macoschosen').show();
$('#windowschosen').hide();
}
};
document.getElementById('btn-restart').onclick = function() { // En appuyant sur le bouton "Recommencer", on remet les variables à zéro
arch = 0;
deb = 0;
lfs = 0;
fedora = 0;
handy = 0;
puppy = 0;
gentoo = 0;
ubuntu = 0;
windows = 0;
macos = 0;
distros = [];
};
| f7613b0d988d1354a574f4a255538d5075d6fa7b | [
"JavaScript"
] | 1 | JavaScript | TheKinrar/ChooseYourDistro | d6f0f863147060a11ea5628d2e78854d78b1cf66 | 9bc5b17e6fbc53fff8471226bb270eb3f5e0ad83 |
refs/heads/master | <file_sep>package com.hkbea.odinfw.ui;
import com.hkbea.odinfw.domain.FwMenu;
import com.hkbea.odinfw.domain.FwMenuExample;
import com.hkbea.odinfw.repositories.FwMenuMapper;
import com.vaadin.data.TreeData;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.ui.Tree;
import com.vaadin.ui.UI;
import java.util.List;
public class MenuTree extends Tree<FwMenu> {
public MenuTree() {
List<FwMenu> rootMenuList = addSubMenus(null); // add root menus
for (FwMenu rootMenu : rootMenuList) {
addSubMenus(rootMenu);
}
this.addItemClickListener(event -> {
FwMenu item = event.getItem();
if ("1".equals(item.getLeaf())) {
if (null != item.getFormName()) {
UI.getCurrent().getNavigator().navigateTo(item.getFormName());
}
} else {
addSubMenus(item);
}
});
}
private List<FwMenu> addSubMenus(FwMenu menu) {
List<FwMenu> subMenuList = findSubMenus(menu);
TreeData<FwMenu> treeData = this.getTreeData();
for (FwMenu subMenu : subMenuList) {
if (treeData.contains(subMenu)) {
continue;
}
treeData.addItem(menu, subMenu);
}
this.setItemIconGenerator(item -> {
if (!"1".equals(item.getLeaf())) {
return VaadinIcons.MENU;
}
return VaadinIcons.ANGLE_RIGHT;
});
this.getDataProvider().refreshAll();
this.expand(menu);
return subMenuList;
}
/**
* @param menu
* @return
*/
private List<FwMenu> findSubMenus(FwMenu menu) {
FwMenuMapper fwMenuMapper = UiUtils.getUI().getApplicationContext().getBean(FwMenuMapper.class);
FwMenuExample fme = new FwMenuExample();
String parentId;
if (null == menu) {
parentId = "0";
} else {
parentId = menu.getId();
}
fme.createCriteria().andParentIdEqualTo(parentId);
return fwMenuMapper.selectByExample(fme);
}
}
<file_sep># odinfw
## Usage
### Create a war file
```
gradlew clean bootWar
```
### Create an executable war file
```
gradlew clean bootWar
```
### Create an executable jar file
```
gradlew clean bootJar
```
### Start the demo app
After the app started, visit http://localhost:8080/odinfw
```
gradlew clean bootRun
```
### Generate MyBatis Mappers
```
gradlew clean genMyBatis
```
## FAQ
##### Q: Why does the Odin framework not base on the latest version of Vaadin, i.e. Vaadin 10+
##### A: Vaadin 10+ is lack of useful components, See [Components in Vaadin 10](https://vaadin.com/docs/v10/flow/migration/5-components.html)
<file_sep>package com.hkbea.odinfw.ui.forms;
import com.hkbea.odinfw.ui.MenuTree;
import com.hkbea.odinfw.ui.UiUtils;
import com.vaadin.navigator.View;
import com.vaadin.server.Page;
import com.vaadin.server.Sizeable;
import com.vaadin.server.VaadinSession;
import com.vaadin.shared.ui.MarginInfo;
import com.vaadin.ui.Component;
import com.vaadin.ui.HorizontalSplitPanel;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import javax.annotation.PostConstruct;
public abstract class BaseForm extends VerticalLayout implements View {
private static final String ATTR_MENU_TREE_PANEL = "__menuTreePanel";
@PostConstruct
protected void init() {
HorizontalSplitPanel body = createBody();
this.addComponent(body);
this.setSizeFull();
this.setExpandRatio(body, 1);
this.setMargin(new MarginInfo(true, false));
this.setHeight("100%");
}
private HorizontalSplitPanel createBody() {
HorizontalSplitPanel horizontalSplitPanel = new HorizontalSplitPanel();
Page currentPage = UI.getCurrent().getPage();
int width = currentPage.getBrowserWindowWidth();
int height = currentPage.getBrowserWindowHeight();
horizontalSplitPanel.setSplitPosition(Math.min(width, height) * 0.39f, Sizeable.Unit.PIXELS, false);
horizontalSplitPanel.setFirstComponent(getOrCreateMenuTree());
horizontalSplitPanel.setSecondComponent(getContentComponent());
return horizontalSplitPanel;
}
private MenuTree getOrCreateMenuTree() {
MenuTree menuTree = (MenuTree) VaadinSession.getCurrent().getAttribute(ATTR_MENU_TREE_PANEL);
if (null == menuTree) {
menuTree = createMenuTreePanel();
VaadinSession.getCurrent().setAttribute(ATTR_MENU_TREE_PANEL, menuTree);
}
return menuTree;
}
private MenuTree createMenuTreePanel() {
MenuTree menuTree = new MenuTree();
menuTree.setHeight("100%");
return menuTree;
}
protected String i18n(String code, String... args) {
return UiUtils.i18n(code, args);
}
protected abstract Component getContentComponent();
}
<file_sep>package com.hkbea.odinfw.addons.paginator;
import java.io.Serializable;
public interface PaginationChangeListener extends Serializable {
void changed(PaginationResource event);
}
<file_sep>rootProject.name = 'odinfw'
<file_sep>package com.hkbea.odinfw.ui.forms;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.ui.Component;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Label;
@SpringView(name="TodoForm")
public class TodoForm extends BaseForm {
@Override
protected Component getContentComponent() {
FormLayout formLayout = new FormLayout();
formLayout.addComponent(new Label("TODO"));
return formLayout;
}
}
<file_sep>package com.hkbea.odinfw.ui;
import com.hkbea.odinfw.addons.paginator.Paginator;
import com.vaadin.ui.Grid;
import com.vaadin.ui.VerticalLayout;
public class PaginableGridLayout<T> extends VerticalLayout {
private Grid<T> grid;
private Paginator paginator;
public PaginableGridLayout(Grid<T> grid, Paginator paginator) {
this.grid = grid;
this.paginator = paginator;
grid.setWidth("100%");
this.addComponent(grid);
this.addComponent(paginator);
}
}
<file_sep>package com.hkbea.odinfw.ui;
import com.hkbea.app.ui.forms.LoginForm;
import com.vaadin.server.Responsive;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinSession;
import com.vaadin.shared.ui.ContentMode;
import com.vaadin.shared.ui.MarginInfo;
import com.vaadin.spring.annotation.SpringUI;
import com.vaadin.spring.navigator.SpringNavigator;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.NativeSelect;
import com.vaadin.ui.Panel;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.context.support.ResourceBundleMessageSource;
import java.util.Arrays;
import java.util.Locale;
import java.util.Optional;
@SpringUI
public class OdinUI extends UI implements ApplicationContextAware {
private static final String ZW = "中文";
private static final String EN = "English";
private static final Locale LOCALE_ZH_CN = new Locale("zh", "CN");
private static final Locale LOCALE_EN_US = new Locale("en", "US");
@Autowired
private SpringNavigator navigator;
@Autowired
private ResourceBundleMessageSource resourceBundleMessageSource;
@Autowired
private ApplicationEventPublisher publisher;
private ApplicationContext applicationContext;
@Override
protected void init(VaadinRequest request) {
Responsive.makeResponsive(this);
this.getPage().setTitle(i18n("app.title"));
Panel contentPanel = createContentPanel();
VerticalLayout mainLayout = new VerticalLayout(createHeader(), contentPanel, createFooter());
mainLayout.setSizeFull();
mainLayout.setExpandRatio(contentPanel, 1);
mainLayout.setMargin(new MarginInfo(true, false));
mainLayout.setHeight("100%");
this.setContent(mainLayout);
navigator.init(this, contentPanel);
// navigator.setErrorView(InaccessibleErrorView.class);
}
private Panel createContentPanel() {
Panel contentPanel = new ContentPanel();
return contentPanel;
}
@EventListener
public void onLoginEvent(LoginForm.LoginEvent event) {
navigator.navigateTo("MainForm");
}
private HorizontalLayout createHeader() {
HorizontalLayout titleBar = new HorizontalLayout();
titleBar.setWidth("100%");
Label title = new Label("<strong style='font-size: 25px;'>" + i18n("app.title") + "</strong>", ContentMode.HTML);
titleBar.addComponent(title);
titleBar.setExpandRatio(title, 1.0f); // Expand
NativeSelect languageSelect = createLanguageSelect();
// languageSelect.setSizeUndefined(); // Take minimum space
titleBar.addComponent(languageSelect);
return titleBar;
}
private HorizontalLayout createFooter() {
HorizontalLayout footer = new HorizontalLayout();
footer.setWidth("100%");
Label copyrightLabel = new Label(i18n("app.copyright", "2012"), ContentMode.HTML);
copyrightLabel.setWidth(null);
footer.addComponent(copyrightLabel);
footer.setComponentAlignment(copyrightLabel, Alignment.MIDDLE_CENTER);
footer.setExpandRatio(copyrightLabel, 1.0f); // Expand
return footer;
}
private NativeSelect createLanguageSelect() {
NativeSelect<String> languageSelect = new NativeSelect<>(i18n("select.language"), Arrays.asList(EN, ZW));
languageSelect.setWidth("105px");
languageSelect.setEmptySelectionAllowed(false);
if (LOCALE_ZH_CN.equals(VaadinSession.getCurrent().getLocale())) {
languageSelect.setSelectedItem(ZW);
} else {
languageSelect.setSelectedItem(EN);
}
languageSelect.addSelectionListener(event -> {
Optional<String> item = event.getSelectedItem();
VaadinSession session = VaadinSession.getCurrent();
if (ZW.equals(item.get())) {
session.setLocale(LOCALE_ZH_CN);
} else {
session.setLocale(LOCALE_EN_US);
}
UI.getCurrent().getPage().reload();
});
return languageSelect;
}
public String i18n(String code, String... args) {
Locale locale = VaadinSession.getCurrent().getLocale();
return resourceBundleMessageSource.getMessage(code, args, locale);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public ApplicationContext getApplicationContext() {
return this.applicationContext;
}
}
<file_sep>DROP TABLE IF EXISTS USER_DAT;
CREATE TABLE USER_DAT (
ID VARCHAR(200),
NAME VARCHAR(200),
PASSWORD VARCHAR(200),
PRIMARY KEY (ID)
);
DROP TABLE IF EXISTS FW_MENU;
CREATE TABLE FW_MENU (
ID VARCHAR(200),
TEXT VARCHAR(200),
LEAF VARCHAR(200),
PARENT_ID VARCHAR(200),
FORM_NAME VARCHAR(200),
PRIMARY KEY (ID)
);
<file_sep>app.copyright=Copyright@{0} \u7248\u6743\u7531\u4E1C\u4E9A\u94F6\u884C(\u4E2D\u56FD)\u6709\u9650\u516C\u53F8\u62E5\u6709
app.title=Odin\u6846\u67B6\u6F14\u793A
paginator.items.per.page=\u6BCF\u9875\u6761\u6570
select.language=\u9009\u62E9\u8BED\u8A00
text.email=\u7535\u5B50\u90AE\u7BB1
text.id=ID
text.inputfields=\u8F93\u5165\u57DF
text.login=\u767B\u5F55
text.name=\u59D3\u540D
text.password=\<PASSWORD>
text.query=\u67E5\u8BE2<file_sep>package com.hkbea.app.ui.forms;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.navigator.View;
import com.vaadin.shared.ui.MarginInfo;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.ui.Button;
import com.vaadin.ui.Component;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Panel;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import javax.annotation.PostConstruct;
@SpringView(name="")
public class LoginForm extends Panel implements View {
@Autowired
public ApplicationEventPublisher publisher;
@PostConstruct
private void init() {
FormLayout formLayout = new FormLayout();
TextField idTF = new TextField("ID");
idTF.setIcon(VaadinIcons.USER);
idTF.setRequiredIndicatorVisible(true);
formLayout.addComponent(idTF);
PasswordField passwordTF = new PasswordField("<PASSWORD>");
passwordTF.setIcon(VaadinIcons.PASSWORD);
passwordTF.setRequiredIndicatorVisible(true);
formLayout.addComponent(passwordTF);
Button loginBtn = new Button("Login");
loginBtn.addClickListener(event -> {
publisher.publishEvent(new LoginEvent(this));
});
formLayout.addComponent(loginBtn);
HorizontalLayout horizontalLayout = new HorizontalLayout();
horizontalLayout.addComponent(formLayout);
this.setSizeFull();
this.setWidth("100%");
this.setHeight("100%");
// this.setComponentAlignment(formLayout, Alignment.MIDDLE_CENTER);
horizontalLayout.setExpandRatio(formLayout, 1);
horizontalLayout.setMargin(new MarginInfo(true, false, true, false));
this.setContent(horizontalLayout);
}
public static class LoginEvent extends ApplicationEvent {
public LoginEvent(Component source) {
super(source);
}
}
}
<file_sep>package com.hkbea.odinfw.domain;
import java.util.ArrayList;
import java.util.List;
public class FwMenuExample {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table fw_menu
*
* @mbg.generated
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table fw_menu
*
* @mbg.generated
*/
protected boolean distinct;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table fw_menu
*
* @mbg.generated
*/
protected List<Criteria> oredCriteria;
private Integer limit;
private Integer offset;
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table fw_menu
*
* @mbg.generated
*/
public FwMenuExample() {
oredCriteria = new ArrayList<Criteria>();
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table fw_menu
*
* @mbg.generated
*/
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table fw_menu
*
* @mbg.generated
*/
public String getOrderByClause() {
return orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table fw_menu
*
* @mbg.generated
*/
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table fw_menu
*
* @mbg.generated
*/
public boolean isDistinct() {
return distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table fw_menu
*
* @mbg.generated
*/
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table fw_menu
*
* @mbg.generated
*/
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table fw_menu
*
* @mbg.generated
*/
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table fw_menu
*
* @mbg.generated
*/
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table fw_menu
*
* @mbg.generated
*/
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table fw_menu
*
* @mbg.generated
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
public void setLimit(Integer limit) {
this.limit = limit;
}
public Integer getLimit() {
return limit;
}
public void setOffset(Integer offset) {
this.offset = offset;
}
public Integer getOffset() {
return offset;
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table fw_menu
*
* @mbg.generated
*/
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(String value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(String value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(String value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(String value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(String value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(String value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdLike(String value) {
addCriterion("id like", value, "id");
return (Criteria) this;
}
public Criteria andIdNotLike(String value) {
addCriterion("id not like", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<String> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<String> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(String value1, String value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(String value1, String value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andTextIsNull() {
addCriterion("text is null");
return (Criteria) this;
}
public Criteria andTextIsNotNull() {
addCriterion("text is not null");
return (Criteria) this;
}
public Criteria andTextEqualTo(String value) {
addCriterion("text =", value, "text");
return (Criteria) this;
}
public Criteria andTextNotEqualTo(String value) {
addCriterion("text <>", value, "text");
return (Criteria) this;
}
public Criteria andTextGreaterThan(String value) {
addCriterion("text >", value, "text");
return (Criteria) this;
}
public Criteria andTextGreaterThanOrEqualTo(String value) {
addCriterion("text >=", value, "text");
return (Criteria) this;
}
public Criteria andTextLessThan(String value) {
addCriterion("text <", value, "text");
return (Criteria) this;
}
public Criteria andTextLessThanOrEqualTo(String value) {
addCriterion("text <=", value, "text");
return (Criteria) this;
}
public Criteria andTextLike(String value) {
addCriterion("text like", value, "text");
return (Criteria) this;
}
public Criteria andTextNotLike(String value) {
addCriterion("text not like", value, "text");
return (Criteria) this;
}
public Criteria andTextIn(List<String> values) {
addCriterion("text in", values, "text");
return (Criteria) this;
}
public Criteria andTextNotIn(List<String> values) {
addCriterion("text not in", values, "text");
return (Criteria) this;
}
public Criteria andTextBetween(String value1, String value2) {
addCriterion("text between", value1, value2, "text");
return (Criteria) this;
}
public Criteria andTextNotBetween(String value1, String value2) {
addCriterion("text not between", value1, value2, "text");
return (Criteria) this;
}
public Criteria andLeafIsNull() {
addCriterion("leaf is null");
return (Criteria) this;
}
public Criteria andLeafIsNotNull() {
addCriterion("leaf is not null");
return (Criteria) this;
}
public Criteria andLeafEqualTo(String value) {
addCriterion("leaf =", value, "leaf");
return (Criteria) this;
}
public Criteria andLeafNotEqualTo(String value) {
addCriterion("leaf <>", value, "leaf");
return (Criteria) this;
}
public Criteria andLeafGreaterThan(String value) {
addCriterion("leaf >", value, "leaf");
return (Criteria) this;
}
public Criteria andLeafGreaterThanOrEqualTo(String value) {
addCriterion("leaf >=", value, "leaf");
return (Criteria) this;
}
public Criteria andLeafLessThan(String value) {
addCriterion("leaf <", value, "leaf");
return (Criteria) this;
}
public Criteria andLeafLessThanOrEqualTo(String value) {
addCriterion("leaf <=", value, "leaf");
return (Criteria) this;
}
public Criteria andLeafLike(String value) {
addCriterion("leaf like", value, "leaf");
return (Criteria) this;
}
public Criteria andLeafNotLike(String value) {
addCriterion("leaf not like", value, "leaf");
return (Criteria) this;
}
public Criteria andLeafIn(List<String> values) {
addCriterion("leaf in", values, "leaf");
return (Criteria) this;
}
public Criteria andLeafNotIn(List<String> values) {
addCriterion("leaf not in", values, "leaf");
return (Criteria) this;
}
public Criteria andLeafBetween(String value1, String value2) {
addCriterion("leaf between", value1, value2, "leaf");
return (Criteria) this;
}
public Criteria andLeafNotBetween(String value1, String value2) {
addCriterion("leaf not between", value1, value2, "leaf");
return (Criteria) this;
}
public Criteria andParentIdIsNull() {
addCriterion("parent_id is null");
return (Criteria) this;
}
public Criteria andParentIdIsNotNull() {
addCriterion("parent_id is not null");
return (Criteria) this;
}
public Criteria andParentIdEqualTo(String value) {
addCriterion("parent_id =", value, "parentId");
return (Criteria) this;
}
public Criteria andParentIdNotEqualTo(String value) {
addCriterion("parent_id <>", value, "parentId");
return (Criteria) this;
}
public Criteria andParentIdGreaterThan(String value) {
addCriterion("parent_id >", value, "parentId");
return (Criteria) this;
}
public Criteria andParentIdGreaterThanOrEqualTo(String value) {
addCriterion("parent_id >=", value, "parentId");
return (Criteria) this;
}
public Criteria andParentIdLessThan(String value) {
addCriterion("parent_id <", value, "parentId");
return (Criteria) this;
}
public Criteria andParentIdLessThanOrEqualTo(String value) {
addCriterion("parent_id <=", value, "parentId");
return (Criteria) this;
}
public Criteria andParentIdLike(String value) {
addCriterion("parent_id like", value, "parentId");
return (Criteria) this;
}
public Criteria andParentIdNotLike(String value) {
addCriterion("parent_id not like", value, "parentId");
return (Criteria) this;
}
public Criteria andParentIdIn(List<String> values) {
addCriterion("parent_id in", values, "parentId");
return (Criteria) this;
}
public Criteria andParentIdNotIn(List<String> values) {
addCriterion("parent_id not in", values, "parentId");
return (Criteria) this;
}
public Criteria andParentIdBetween(String value1, String value2) {
addCriterion("parent_id between", value1, value2, "parentId");
return (Criteria) this;
}
public Criteria andParentIdNotBetween(String value1, String value2) {
addCriterion("parent_id not between", value1, value2, "parentId");
return (Criteria) this;
}
public Criteria andFormNameIsNull() {
addCriterion("form_name is null");
return (Criteria) this;
}
public Criteria andFormNameIsNotNull() {
addCriterion("form_name is not null");
return (Criteria) this;
}
public Criteria andFormNameEqualTo(String value) {
addCriterion("form_name =", value, "formName");
return (Criteria) this;
}
public Criteria andFormNameNotEqualTo(String value) {
addCriterion("form_name <>", value, "formName");
return (Criteria) this;
}
public Criteria andFormNameGreaterThan(String value) {
addCriterion("form_name >", value, "formName");
return (Criteria) this;
}
public Criteria andFormNameGreaterThanOrEqualTo(String value) {
addCriterion("form_name >=", value, "formName");
return (Criteria) this;
}
public Criteria andFormNameLessThan(String value) {
addCriterion("form_name <", value, "formName");
return (Criteria) this;
}
public Criteria andFormNameLessThanOrEqualTo(String value) {
addCriterion("form_name <=", value, "formName");
return (Criteria) this;
}
public Criteria andFormNameLike(String value) {
addCriterion("form_name like", value, "formName");
return (Criteria) this;
}
public Criteria andFormNameNotLike(String value) {
addCriterion("form_name not like", value, "formName");
return (Criteria) this;
}
public Criteria andFormNameIn(List<String> values) {
addCriterion("form_name in", values, "formName");
return (Criteria) this;
}
public Criteria andFormNameNotIn(List<String> values) {
addCriterion("form_name not in", values, "formName");
return (Criteria) this;
}
public Criteria andFormNameBetween(String value1, String value2) {
addCriterion("form_name between", value1, value2, "formName");
return (Criteria) this;
}
public Criteria andFormNameNotBetween(String value1, String value2) {
addCriterion("form_name not between", value1, value2, "formName");
return (Criteria) this;
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table fw_menu
*
* @mbg.generated do_not_delete_during_merge
*/
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table fw_menu
*
* @mbg.generated
*/
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
<file_sep>package com.hkbea.odinfw.ui;
import com.vaadin.ui.UI;
/**
* Utilities for handling UI
*/
public class UiUtils {
public static OdinUI getUI() {
return (OdinUI) UI.getCurrent();
}
public static String i18n(String code, String... args) {
return getUI().i18n(code, args);
}
private UiUtils() {}
}
<file_sep>plugins {
id 'war'
id "org.springframework.boot" version "2.0.3.RELEASE"
id "io.spring.dependency-management" version "1.0.5.RELEASE"
id "com.github.ben-manes.versions" version "0.20.0"
}
group 'com.hkbea'
version '1.0-SNAPSHOT'
allprojects {
apply plugin: 'java'
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
compileJava.options.encoding = 'UTF-8'
repositories {
maven { url 'http://maven.aliyun.com/nexus/content/groups/public' }
mavenCentral()
maven { url 'http://vaadin.com/nexus/content/repositories/vaadin-addons/' }
}
}
ext {
vaadinVersion = '8.4.4'
springBootVersion = '2.0.3.RELEASE'
vaadinSpringBootStarterVersion = '3.0.1'
mybatisStarterVersion = '1.3.2'
druidStarterVersion = '1.1.10'
h2Version = '1.4.197'
junitVersion = '4.12'
mybatisGeneratorVersion = '1.3.6'
}
dependencies {
compile "com.vaadin:vaadin-spring-boot-starter:$vaadinSpringBootStarterVersion"
compile "org.springframework.boot:spring-boot-starter-actuator:$springBootVersion"
compile "org.mybatis.spring.boot:mybatis-spring-boot-starter:$mybatisStarterVersion"
compile "com.alibaba:druid-spring-boot-starter:$druidStarterVersion"
runtime "com.h2database:h2:$h2Version"
providedRuntime "org.springframework.boot:spring-boot-starter-tomcat:$springBootVersion"
testCompile "junit:junit:$junitVersion"
testCompile "org.springframework.boot:spring-boot-starter-test:$springBootVersion"
compile "org.mybatis.generator:mybatis-generator-core:$mybatisGeneratorVersion"
runtime "org.springframework.boot:spring-boot-devtools:$springBootVersion"
}
dependencyManagement {
imports {
mavenBom "com.vaadin:vaadin-bom:$vaadinVersion"
}
}
task genMyBatis(type: JavaExec) {
classpath = sourceSets.main.runtimeClasspath
main = 'com.hkbea.odinfw.generators.MyBatisGenerator'
}
wrapper {
gradleVersion = '4.8.1'
}
<file_sep>INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('dan2', 'Daniel', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('pau2', 'Paul', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('joh3', 'John', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('ali3', 'Alice', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('pet2', 'Peter', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('joc5', 'Jochen', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('gra5', 'Grace', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('sam6', 'Sam', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por1', 'Portia1', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por2', 'Portia2', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por3', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por4', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por5', 'Portia5', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por6', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por7', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por8', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por9', 'Portia9', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por10', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por11', 'Portia11', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por12', 'Portia12', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por13', '<PASSWORD>3', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por14', 'Portia14', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por15', '<PASSWORD>5', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por16', '<PASSWORD>6', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por17', '<PASSWORD>17', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por18', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por19', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por20', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por21', '<PASSWORD>1', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por22', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por23', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por24', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por25', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por26', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por27', '<PASSWORD>27', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por28', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por29', 'Portia29', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por30', 'Portia30', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por31', '<PASSWORD>1', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por32', '<PASSWORD>2', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por33', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>4', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por35', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por36', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por37', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por38', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por39', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>0', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>1', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por42', '<PASSWORD>2', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por43', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>4', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por45', '<PASSWORD>5', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por46', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por47', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por48', '<PASSWORD>48', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por49', 'Portia49', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por50', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por51', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por52', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por53', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por54', '<PASSWORD>4', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por55', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>6', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por57', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por58', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>9', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por60', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por61', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por62', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por63', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por64', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por65', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por66', 'Portia66', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por67', 'Portia67', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por68', '<PASSWORD>8', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por69', 'Portia69', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por72', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por73', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>4', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>5', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por76', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por78', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por79', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por80', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por81', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por82', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por83', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por84', 'Portia84', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por85', 'Portia85', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>7', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>8', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>0', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por91', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por94', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por97', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('<PASSWORD>', '<PASSWORD>', '******');
INSERT INTO USER_DAT (ID, NAME, PASSWORD) VALUES ('por100', '<PASSWORD>', '******');
INSERT INTO FW_MENU(ID , TEXT, LEAF, PARENT_ID, FORM_NAME) VALUES ('2', 'System Administration', '0', '0', NULL);
INSERT INTO FW_MENU(ID , TEXT, LEAF, PARENT_ID, FORM_NAME) VALUES ('3', 'Development Utilities', '0', '0', NULL);
INSERT INTO FW_MENU(ID , TEXT, LEAF, PARENT_ID, FORM_NAME) VALUES ('21', 'Manage Users', '1', '2', 'UserQueryForm');
INSERT INTO FW_MENU(ID , TEXT, LEAF, PARENT_ID, FORM_NAME) VALUES ('22', 'Manage Roles', '1', '2', 'TodoForm');
INSERT INTO FW_MENU(ID , TEXT, LEAF, PARENT_ID, FORM_NAME) VALUES ('31', 'H2 Console', '1', '3', 'H2ConsoleForm');
INSERT INTO FW_MENU(ID , TEXT, LEAF, PARENT_ID, FORM_NAME) VALUES ('32', 'Druid Monitor', '1', '3', 'DruidMonitorForm');
INSERT INTO FW_MENU(ID , TEXT, LEAF, PARENT_ID, FORM_NAME) VALUES ('33', 'MyBatis Generator', '1', '3', 'MyBatisGeneratorForm');
COMMIT;
<file_sep>app.copyright=Copyright \u00A9{0} The Bank of East Asia (China) Limited
app.title=Odin Framework Demo
paginator.items.per.page=Items per page
select.language=Select language
text.email=Email
text.id=ID
text.inputfields=Input Fields
text.login=Login
text.name=Name
text.password=<PASSWORD>
text.query=Query | 7ff2d240e533613bad412f90346dfb2ebbf03be5 | [
"SQL",
"Markdown",
"INI",
"Gradle",
"Java"
] | 16 | Java | danielsun1106/odinfw | 7aa052ec7cf4cedb19adce03e1e5b0203144e1ed | e55dd87f9a92b00743daf29cc5757f3485f4565a |
refs/heads/master | <file_sep>#
# Setting workspace
#
setwd("/home/lucas/git/inkitt-challenge/")
#
# Required libraries intallation
#
install.packages("devtools")
devtools::install_github("bmschmidt/wordVectors")
#
# Loading require libraries
#
library(wordVectors)
library(magrittr)
#
# Loading required sources
#
source("./task_03.black.list.r")
source("./task_03.countries.r")
#
# Loading word2vector
# This data is enabled at
# https://drive.google.com/uc?id=0B7XkCwpI5KDYNlNUTTlSS21pQmM&export=download
# It has 3.5GiB uncrompressed. Please, download this file to run this code.
#
vector = read.binary.vectors("./data/GoogleNews-vectors-negative300.bin", nrows = 200000)
stories <- read.csv('./data/stories.csv', sep=',', header=T)
#
# Removing invalid stories
#
stories <- stories[stories$title != "Untitled",]
#
# Getting possible countries
#
res <- apply(stories, 1, function(row) {
#
# Formmating text
#
teaser <- row['teaser']
teaser <- unlist(strsplit(gsub(' +', ' ', teaser), ' '))
teaser <- teaser[grep("^[A-Z]",teaser)]
teaser <- unlist(lapply(teaser, function(x) ifelse(!tolower(x) %in% black.list, x, NA)))
teaser <- teaser[!is.na(teaser)]
#
# Calculating words similarity
#
result = data.frame(country=c(), similarity=c())
#
# For each word calculate similarity using word2vector
#
for (word in teaser) {
f <- paste("~", "\"", word, "\"+", sep="")
f <- as.formula(paste(f, "\"countries\"", sep=""))
closest <- (vector %>% closest_to(f))
index <- which(closest$word[1:20] %in% as.character(COUNTRIES$name))
result <- rbind(result, data.frame(country=closest$word[index], similarity=closest$similarity[index]))
}
#
# Returning results
#
list(as.character(row[3]), result[order(-result$similarity),])
})
#
# Printing results
#
for (r in res) {
writeLines("\n============================================")
writeLines(r[[1]])
writeLines("")
print(r[[2]])
}<file_sep>import pandas as pd
#
# Importing data
#
visit = pd.read_csv('data/visits.csv')
read = pd.read_csv('data/reading.csv')
story = pd.read_csv('data/stories.csv')
#
# Converting objects to datetime
#
read['tracking_time'] = pd.to_datetime(read['tracking_time'])
read['created_at'] = pd.to_datetime(read['created_at'])
# Write the same query in Python and possibly with Pandas or Numpy;
# or write it in R if you feel more comfortable.
#
# Write an SQL query that sums up reading for horror readers by day:
# Task 1.1 - How much did they read?
result = read.merge(story.rename(columns={'id':'story_id'}), on='story_id', how='inner')
horror_filter = (result['category_one'].str.lower() == 'horror') | (result['category_two'].str.lower() == 'horror')
result = result[horror_filter]
result = result.groupby([result['tracking_time'].dt.date])
print(result.count()['visitor_id'])
# Write the same query in Python and possibly with Pandas or Numpy;
# or write it in R if you feel more comfortable.
#
# Write an SQL query that sums up reading for horror readers by day:
# Task 1.2 - How many readers are there?
print(result.nunique()['visitor_id'])
# Write the same query in Python and possibly with Pandas or Numpy;
# or write it in R if you feel more comfortable.
#
# Write an SQL query that sums up reading for horror readers by day:
# Task 1.3 - What country are the readers from?
#
# WARNING! Maybe there is an inconsistence into Visit or Read tables. Data into
# Read.visitorId or Visit.visitorId columns do not match each other.
# Changing Read.visitorId by Read.visitId generated the expected output.
#
result = read.merge(story.rename(columns={'id':'story_id'}), on='story_id', how='inner')
result = result.merge(visit.rename(columns={'visitor_id': 'visit_id'}), on='visit_id', how='inner')
result = result[horror_filter]
result = result.groupby([result['tracking_time'].dt.date]).apply(lambda x : set(x.country))
print(result)
<file_sep>--
-- Creating structure and importing data
--
DROP DATABASE IF EXISTS INKITT_CHALLENGE;
CREATE DATABASE INKITT_CHALLENGE;
USE INKITT_CHALLENGE;
CREATE TABLE `Read` (
isAppEvent ENUM('True', 'False') NULL,
visitorId CHAR(36) NULL,
id CHAR(36) NULL,
visitId CHAR(36) NULL,
trackingTime DATETIME NULL,
createdTime DATETIME NULL,
storyId INT NULL,
userId INT NULL
);
CREATE TABLE `Visit` (
visitorId CHAR(36) NULL,
userId CHAR(36) NULL,
country VARCHAR(100) NULL,
timezone VARCHAR(100) NULL,
locationAccuracy INT
);
CREATE TABLE `Story` (
id INT NULL,
userId INT NULL,
teaser TEXT NULL,
title VARCHAR(150) NULL,
cover VARCHAR(100) NULL,
categoryOne VARCHAR(50) NULL,
categoryTwo VARCHAR(50) NULL
);
LOAD DATA LOCAL INFILE "/home/lucas/git/inkitt-challenge/data/stories.csv"
INTO TABLE Story
COLUMNS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;
LOAD DATA LOCAL INFILE "/home/lucas/git/inkitt-challenge/data/visits.csv"
INTO TABLE Visit
COLUMNS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;
LOAD DATA LOCAL INFILE "/home/lucas/git/inkitt-challenge/data/reading.csv"
INTO TABLE `Read`
COLUMNS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;
-- Write an SQL query that sums up reading for horror readers by day:
-- Task 1.1 - How much did they read?
--
SELECT DATE(trackingTime) AS readDate, COUNT(*) AS readCount
FROM `Read` AS R INNER JOIN `Story` AS S ON(S.id = R.storyId)
WHERE LOWER(S.categoryOne) = 'horror' OR LOWER(S.categoryTwo) = 'horror'
GROUP BY readDate;
-- Write an SQL query that sums up reading for horror readers by day:
-- Task 1.2 - How many readers are there?
--
SELECT DATE(trackingTime) AS readDate, COUNT(DISTINCT R.visitorId) AS readersCount
FROM `Read` AS R INNER JOIN `Story` AS S ON(S.id = R.storyId)
WHERE LOWER(S.categoryOne) = 'horror' OR LOWER(S.categoryTwo) = 'horror'
GROUP BY readDate;
-- Write an SQL query that sums up reading for horror readers by day:
-- Task 1.3 - What country are the readers from?
--
-- WARNING! Maybe there is an inconsistence into Visit or Read tables. Data into
-- Read.visitorId or Visit.visitorId columns do not match each other.
-- Changing Read.visitorId by Read.visitId generated the expected output.
SELECT DATE(trackingTime) AS readDate,
GROUP_CONCAT(DISTINCT V.country) AS countries,
COUNT(DISTINCT V.country) AS countryCount
FROM `Visit` AS V INNER JOIN
`Read` AS R ON(V.visitorId = R.visitId) INNER JOIN
`Story` AS S ON(S.id = R.storyId)
WHERE LOWER(S.categoryOne) = 'horror' OR LOWER(S.categoryTwo) = 'horror'
GROUP BY readDate;
<file_sep># Inkitt Challenge Solutions
#### Task #1: Write an SQL query that sums up reading for horror readers by day.
- 1.1 How much did they read?
- 1.2 How many readers are there?
- 1.3 What country are the readers from?
The solution for each question is available in the file
[task_01.sql](https://github.com/lucasvenez/inkitt-challenge/blob/master/task_01.sql).
The code was prepared for the MySQL Database Management System.
I noticed maybe there is an inconsistency into `Visit` or `Read` tables.
Data into `Read.visitorId` or `Visit.visitorId` columns do not match each other.
Changing `Read.visitorId` by `Read.visitId` generated the expected output.
#### Task #2: Write the same query in Python and possibly with Pandas or Numpy.
All solutions for this task are avaiable at [`task_02.py`](https://github.com/lucasvenez/inkitt-challenge/blob/master/task_02.py).
I used `pandas` in all solution steps.
#### Task #3: The Stories table contains a field called `Teaser`. How would you extract geographic location from this?
The solution for this task are avaiable at [`task_03.r`](https://github.com/lucasvenez/inkitt-challenge/blob/master/task_03.r).
For this task I imported the countries names and acronyms available [here](http://www.nationsonline.org/oneworld/country_code_list.htm)
using a Javascript code available [here](https://github.com/lucasvenez/inkitt-challenge/blob/master/task_03.countries.export.js). `getCountriesNames` function output was embeeded into the R file
[`task_03.countries.r`](https://github.com/lucasvenez/inkitt-challenge/blob/master/task_03.countries.r).
I employed the [`Word2Vector`](https://github.com/bmschmidt/wordVectors) in order to estimate the distance between teaser nouns and
country names. Results show a set of country names with its semilarity score to the teaser.
This approach limits geographic location to countries.
**Warning**: for executing the script [`task_03.r`](https://github.com/lucasvenez/inkitt-challenge/blob/master/task_03.r), it is required
to download the `Word2Vect` file available [here](https://drive.google.com/uc?id=0B7XkCwpI5KDYNlNUTTlSS21pQmM&export=download).
<file_sep>/**
*
*/
var getCountriesName = function() {
let result = ["", ""]
let countries = []
let acronyms = []
/*
* Getting countries list at http://www.nationsonline.org/oneworld/country_code_list.htm
*/
$("td.abs").each(function() {
countries.push($(this).text());
acronyms.push($(this).next().text());
})
for (let i = 0; i < countries.length; i++) {
/*
* Formmating as vector to insert into an R file.
* Formmating names as used into Word2Vector.
*/
let country = countries[i].trim()
let acronym = acronyms[i].trim()
elements = [",", " (", "of"]
for (let e in elements)
if (country.indexOf(elements[e]) > -1)
country = country.split(elements[e])[0]
result[0] += "'" + country.trim().replace(/ +|-|\'/g, "_") + "',\n"
result[1] += "'" + acronym + "',\n"
}
for (let i = 0; i < 2; i++)
result[i] = result[i].substr(0, result[i].length - 2)
return result
}<file_sep>black.list <- c('aboard', 'about', 'above', 'across', 'after', 'against', 'along', 'amid',
'among', 'anti', 'around', 'as', 'at', 'before', 'behind', 'below', 'beneath',
'beside', 'besides', 'between', 'beyond', 'but', 'by', 'concerning', 'considering',
'despite', 'down', 'during', 'except', 'excepting', 'excluding',
'following', 'for', 'from', 'in', 'inside', 'into', 'like',
'minus', 'near', 'of', 'off', 'on', 'onto', 'opposite', 'outside', 'and', 'when', 'their',
'over', 'past', 'per', 'plus', 'regarding', 'round', 'save', 'since', 'his', 'which',
'than', 'through', 'to', 'toward', 'towards', 'under', 'underneath', 'unlike', 'were', 'was',
'until', 'up', 'upon', 'versus', 'via', 'with', 'within', 'without', 'the', 'he', 'is', 'are',
'she', 'it', 'they', 'we', 'our', 'you', 'your', 'your', 'mine', 'i', 'a', 'in', 'on', 'can')
| bc1ca66c4d2042001d7f940ad95b6cbab3d2fec1 | [
"SQL",
"Markdown",
"JavaScript",
"Python",
"R"
] | 6 | R | lucasvenez/inkitt-challenge | 1e27514b8e32521eaf93b38abe29820ca8c6089d | c54d0f9f5683ab87ded078dfd165ee3446cbb7ef |
refs/heads/master | <file_sep>import requests
from bs4 import BeautifulSoup
from string import ascii_lowercase
handedness = {"Right": "R", "Left": "L", "Both": "S"}
root_url = "http://www.baseball-reference.com"
team_abbrev = {
"San Francisco Giants": "SFG",
"Los Angeles Dodgers": "LAD",
"Colorado Rockies": "COL",
"San Diego Padres": "SDP",
"Arizona Diamondbacks": "ARI",
"Chicago Cubs": "CHC",
"Milwaukee Brewers": "MIL",
"St. Louis Cardinals": "STL",
"Cincinnati Reds": "CIN",
"Pittsburgh Pirates": "PIT",
"Atlanta Braves": "ATL",
"Washington Nationals": "WAS",
"Miami Marlins": "MIA",
"New York Mets": "NYM",
"Philadelphia Phillies": "PHI",
"Los Angeles Angels of Anaheim": "LAA",
"Oakland Athletics": "OAK",
"Texas Rangers": "TEX",
"Seattle Mariners": "SEA",
"Houston Astros": "HOU",
"Chicago White Sox": "CHW",
"Cleveland Indians": "CLE",
"Kansas City Royals": "KCR",
"Detroit Tigers": "DET",
"Minnesota Twins": "MIN",
"New York Yankees": "NYY",
"Boston Red Sox": "BOS",
"Tampa Bay Rays": "TBR",
"Toronto Blue Jays": "TOR",
"Baltimore Orioles": "BAL"
}
for c in ascii_lowercase:
index_page = requests.get(root_url + "/players/" + c)
soup = BeautifulSoup(index_page.content, "html.parser")
active_player_links = soup.select("#div_players_ > p > b > a")
for player_link in active_player_links:
player_page = requests.get(root_url + player_link['href'])
player_soup = BeautifulSoup(player_page.content, "html.parser")
player_meta = player_soup.select("#meta div[itemtype='http://schema.org/Person']")[0]
name = player_meta.h1.string
bats = handedness[player_meta.find_all("strong", string="Bats: ")[0].next_sibling.split()[0]]
throws = handedness[player_meta.find_all("strong", string="Throws: ")[0].next_sibling.split()[0]]
dob = player_meta.select("span[data-birth]")[0]["data-birth"]
team_name = player_meta.find_all("strong", string="Team:")
organization = team_abbrev[team_name[0].find_next_siblings("a")[0].string] if team_name else "n/a"
player_data = {
"name": name,
"organization": organization,
"batting_hand": bats,
"throwing_hand": throws,
"birthday": dob,
"disabled": False,
"options": 0,
"salary": 0
}
r = requests.post('http://127.0.0.1:5000/api/players', json = player_data)
<file_sep>'use strict';
exports.up = (knex, Promise) => {
return knex.schema.createTable('players', t => {
t.increments('id').notNullable().primary();
t.text('name').notNullable();
t.text('organization').references('mlb_teams.id');
t.enu('current_level', ['MiLB', 'MLB']);
t.enu('batting_hand', ['R', 'L', 'S']);
t.enu('throwing_hand', ['R', 'L', 'S']);
t.date('birthday');
t.boolean('disabled').notNullable();
t.integer('options').notNullable();
t.integer('salary').notNullable();
});
};
exports.down = (knex, Promise) => {
return knex.schema.dropTable('players');
};
<file_sep>'use strict';
exports.up = (knex, Promise) => {
return knex.schema.createTable('teams', t => {
t.text('id').notNullable().primary();
t.text('name').notNullable();
t.jsonb('roster').notNullable();
t.integer('faab').notNullable();
t.integer('draft_cash').notNullable();
});
};
exports.down = (knex, Promise) => {
return knex.schema.dropTable('teams');
};
<file_sep>import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
Vue.use(VueRouter);
new Vue(App).$mount('#app');
<file_sep>'use strict';
const Hapi = require('hapi');
const mongojs = require('mongojs');
const path = require('path');
const bookshelf = require('./bookshelf')
const server = new Hapi.Server();
server.connection({
port: 5000
});
const plugins = [
require('inert'),
require('./routes/player_routes.js'),
require('./routes/team_routes.js')
];
if (process.env.NODE_ENV !== 'production') {
const WebpackConfig = require('./config/webpack.config.js');
const HapiWebpackDevMiddleware = require('hapi-webpack-dev-middleware');
const HapiWebpackHotMiddleware = require('hapi-webpack-hot-middleware');
server.register([
{
register: HapiWebpackDevMiddleware,
options: {
config: WebpackConfig,
options: {
noInfo: true,
publicPath: WebpackConfig.output.publicPath,
stats: {
colors: true
}
}
}
}, {
register: HapiWebpackHotMiddleware
}
], err => {
if (err) {
throw err;
}
});
}
server.register(plugins, err => {
if (err) {
throw err;
}
server.route({
method: 'GET',
path: '/{file*}',
handler: {
directory: {
path: './public/',
index: true
}
}
});
server.ext('onPostHandler', (request, reply) => {
const response = request.response;
if (response.isBoom && response.output.statusCode === 404) {
return reply.file('./public/index.html');
}
return reply.continue();
});
server.start(err => {
if (err) {
throw err;
}
console.log('Server running at:', server.info.uri);
});
});
<file_sep>'use strict';
exports.up = (knex, Promise) => {
return knex.schema.createTable('users', t => {
t.text('email').notNullable().primary();
t.text('password_hash').notNullable();
t.text('team_id').references('id').inTable('teams').notNullable();
});
};
exports.down = (knex, Promise) => {
return knex.schema.dropTable('users');
};
<file_sep>'use strict';
exports.seed = (knex, Promise) => {
return knex('mlb_teams').del()
.then(() => {
return knex('mlb_teams').insert([
{id: 'SFG', city: 'San Francisco', name: 'Giants'},
{id: 'LAD', city: 'Los Angeles', name: 'Dodgers'},
{id: 'SDP', city: 'San Diego', name: 'Padres'},
{id: 'COL', city: 'Colorado', name: 'Rockies'},
{id: 'ARI', city: 'Arizona', name: 'Diamondbacks'},
{id: 'CHC', city: 'Chicago', name: 'Cubs'},
{id: 'STL', city: 'St. Louis', name: 'Cardinals'},
{id: 'MIL', city: 'Milwaukee', name: 'Brewers'},
{id: 'CIN', city: 'Cincinnati', name: 'Reds'},
{id: 'PIT', city: 'Pittsburgh', name: 'Pirates'},
{id: 'ATL', city: 'Atlanta', name: 'Braves'},
{id: 'NYM', city: 'New York', name: 'Mets'},
{id: 'WAS', city: 'Washington', name: 'Nationals'},
{id: 'MIA', city: 'Miami', name: 'Marlins'},
{id: 'PHI', city: 'Philadelphia', name: 'Phillies'},
{id: 'OAK', city: 'Oakland', name: 'Athletics'},
{id: 'SEA', city: 'Seattle', name: 'Mariners'},
{id: 'TEX', city: 'Texas', name: 'Rangers'},
{id: 'HOU', city: 'Houston', name: 'Astros'},
{id: 'LAA', city: 'Los Angeles', name: 'Angels of Anaheim'},
{id: 'CHW', city: 'Chicago', name: '<NAME>'},
{id: 'CLE', city: 'Cleveland', name: 'Indians'},
{id: 'KCR', city: 'Kansas City', name: 'Royals'},
{id: 'DET', city: 'Detroit', name: 'Tigers'},
{id: 'MIN', city: 'Minnesota', name: 'Twins'},
{id: 'NYY', city: 'New York', name: 'Yankees'},
{id: 'BOS', city: 'Boston', name: '<NAME>'},
{id: 'TBR', city: 'Tampa Bay', name: 'Rays'},
{id: 'BAL', city: 'Baltimore', name: 'Orioles'},
{id: 'TOR', city: 'Toronto', name: '<NAME>'},
{id: 'n/a', city: '', name: ''}
]);
});
};
<file_sep>'use strict';
exports.up = function(knex, Promise) {
return knex.schema.table('players', t => {
t.text('contract');
});
};
exports.down = function(knex, Promise) {
return knex.schema.table('players', t => {
t.dropColumn('contract');
})
};
<file_sep>'use strict'
const bookshelf = require('../bookshelf');
const MLB_Team = require('./mlb_team')
module.exports = bookshelf.Model.extend({
tableName: 'players',
organization: () => {
return this.belongsTo(MLB_Team);
}
});
<file_sep>'use strict'
const bookshelf = require('../bookshelf');
module.exports = bookshelf.Model.extend({
tableName: 'teams'
});
| d813f820127d0997528dbf1ee3fa25b9c02db352 | [
"JavaScript",
"Python"
] | 10 | Python | pverheecke/the-league | 27045d783a523dd6f2a74cdecb67424bb753638a | d22933e432d1837aa285c85f0e564bd4a9501c6a |
refs/heads/master | <file_sep>import { Component, OnInit } from '@angular/core';
import { FirebaseService } from 'src/app/Services/firebase.service';
@Component({
selector: 'mini-og',
templateUrl: './mini-og.component.html',
styleUrls: ['./mini-og.component.css']
})
export class MiniOGComponent implements OnInit {
trays;
constructor(private fb: FirebaseService) { }
ngOnInit() {
this.fb.getMiniTrays().subscribe( trayData => {
this.trays = trayData;
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { FirebaseService } from 'src/app/Services/firebase.service';
import { ActivatedRoute } from '@angular/router';
@Component({
// tslint:disable-next-line: component-selector
selector: 'original-og',
templateUrl: './original-og.component.html',
styleUrls: ['./original-og.component.css']
})
export class OriginalOGComponent implements OnInit {
trays;
constructor(private fb: FirebaseService, private route: ActivatedRoute) { }
ngOnInit() {
this.route.data.subscribe((data: {trays: any}) => {
this.trays = data.trays;
});
}
}
<file_sep>import { Component, OnInit, AfterViewChecked } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ITray } from 'src/app/data/tray';
import { PaymentService } from 'src/app/Services/payment.service';
import { FirebaseService } from 'src/app/Services/firebase.service';
declare var paypal;
@Component({
// tslint:disable-next-line: component-selector
selector: 'tray-detail',
templateUrl: './tray-detail.component.html',
styleUrls: ['./tray-detail.component.css']
})
export class TrayDetailComponent implements OnInit {
tray;
priceLabel = ' Price';
constructor(private route: ActivatedRoute, private payment: PaymentService, private fb: FirebaseService) {}
ngOnInit() {
this.route.data.subscribe((data: {tray: ITray}) => {
this.tray = data.tray;
});
this.payment.setPaymentAmount(this.tray.price);
}
/*ngAfterViewChecked(): void {
if (!this.payment.addScript) {
this.payment.addPayPalScript().then(() => {
paypal.Button.render(this.payment.payPalConfig, '#PayPalCheckoutButton');
this.payment.payPalLoad = false;
});
}
}*/
purchaseTray(tray) {
this.fb.purchaseTray(tray.price);
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {ReactiveFormsModule, FormsModule} from '@angular/forms';
// Custom Imports
import { AngularFontAwesomeModule } from 'angular-font-awesome';
import { SlickModule } from 'ngx-slick';
import { MDBBootstrapModule } from 'angular-bootstrap-md';
import { NavbarComponent } from './components/navbar/navbar.component';
import { OriginalOGComponent } from './components/original-og/original-og.component';
import { MiniOGComponent } from './components/mini-og/mini-og.component';
import { AshtraysComponent } from './components/ashtrays/ashtrays.component';
import { CustomComponent } from './components/custom/custom.component';
import { ContactComponent } from './components/contact/contact.component';
import { HomeComponent } from './components/home/home.component';
import { CarouselComponent } from './components/carousel/carousel.component';
import { ImageLinksComponent } from './components/image-links/image-links.component';
import { TrayDetailComponent } from './components/tray-detail/tray-detail.component';
import { ProductThumbnailComponent } from './components/product-thumbnail/product-thumbnail.component';
import { FirebaseModule } from './firebase/firebase.module';
import { OneOffComponent } from './components/oneOff/oneOff.component';
import { SendemailComponent } from './components/sendemail/sendemail.component';
import { HttpClientModule } from '@angular/common/http';
import { TrayDetailResolverService } from './Services/tray-detail-resolver.service';
import { TrayListResolverService } from './Services/tray-list-resolver.service';
import { PaymentSuccessComponent } from './components/payment-success/payment-success.component';
@NgModule({
declarations: [
AppComponent,
NavbarComponent,
OriginalOGComponent,
MiniOGComponent,
AshtraysComponent,
CustomComponent,
ContactComponent,
HomeComponent,
CarouselComponent,
ImageLinksComponent,
TrayDetailComponent,
ProductThumbnailComponent,
OneOffComponent,
SendemailComponent,
PaymentSuccessComponent
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule,
FormsModule,
AngularFontAwesomeModule,
FirebaseModule,
HttpClientModule,
MDBBootstrapModule.forRoot(),
SlickModule.forRoot()
],
providers: [
TrayDetailResolverService,
TrayListResolverService
],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
import { FirebaseService } from 'src/app/Services/firebase.service';
@Component({
selector: 'ashtrays',
templateUrl: './ashtrays.component.html',
styleUrls: ['./ashtrays.component.css']
})
export class AshtraysComponent implements OnInit {
trays;
constructor(private fb: FirebaseService) { }
ngOnInit() {
this.fb.getAshtrays().subscribe( trayData => {
this.trays = trayData;
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { FirebaseService } from 'src/app/Services/firebase.service';
import { Router } from '@angular/router';
@Component({
// tslint:disable-next-line: component-selector
selector: 'custom',
templateUrl: './custom.component.html',
styleUrls: ['./custom.component.css']
})
export class CustomComponent implements OnInit {
trays;
constructor(private fb: FirebaseService, private router: Router) { }
ngOnInit() {
this.fb.getCustomTrays().subscribe( trayData => {
this.trays = trayData;
});
}
requestCustomTray() {
this.router.navigate(['/CustomContact']);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { FirebaseService } from 'src/app/Services/firebase.service';
@Component({
// tslint:disable-next-line: component-selector
selector: 'one-off',
templateUrl: './oneOff.component.html',
styleUrls: ['./oneOff.component.css']
})
export class OneOffComponent implements OnInit {
trays;
constructor(private fb: FirebaseService) { }
ngOnInit() {
this.fb.getOneOffs().subscribe( trayData => {
this.trays = trayData;
});
}
}
<file_sep>import { Injectable } from '@angular/core';
import { FirebaseService } from './firebase.service';
import { RouterStateSnapshot, Resolve, ActivatedRouteSnapshot, Router } from '@angular/router';
import { Observable, EMPTY, of } from 'rxjs';
import { mergeMap, take } from 'rxjs/operators';
import { ITray } from '../data/tray';
@Injectable({
providedIn: 'root'
})
export class TrayDetailResolverService implements Resolve<ITray> {
constructor(private fb: FirebaseService, private router: Router) { }
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<ITray> | Observable<never> {
const urlName = route.paramMap.get('name');
const nameArray = urlName.split('-', 2);
const name = nameArray[1];
const category = nameArray[0];
switch (category) {
case 'Original': {
return this.fb.getOriginalTray(name).pipe(take(1), mergeMap( t => {
if (t) {
return of (t[0].payload.doc.data());
} else {
return EMPTY;
}
})
);
break;
}
case 'Mini': {
return this.fb.getMiniTray(name).pipe(take(1), mergeMap( t => {
if (t) {
return of (t[0].payload.doc.data());
} else {
return EMPTY;
}
})
);
break;
}
case 'Custom': {
return this.fb.getCustomTray(name).pipe(take(1), mergeMap( t => {
if (t) {
return of (t[0].payload.doc.data());
} else {
return EMPTY;
}
})
);
break;
}
case 'Ashtray': {
return this.fb.getAshtray(name).pipe(take(1), mergeMap( t => {
if (t) {
return of (t[0].payload.doc.data());
} else {
return EMPTY;
}
})
);
break;
}
case '1OFF': {
return this.fb.getOneOff(name).pipe(take(1), mergeMap( t => {
if (t) {
return of (t[0].payload.doc.data());
} else {
return EMPTY;
}
})
);
break;
}
}
}
}
<file_sep>import { Injectable } from '@angular/core';
import { FirebaseService } from './firebase.service';
import { RouterStateSnapshot, Resolve, ActivatedRouteSnapshot, Router } from '@angular/router';
import { Observable, EMPTY, of } from 'rxjs';
import { mergeMap, take } from 'rxjs/operators';
import { ITray } from '../data/tray';
@Injectable({
providedIn: 'root'
})
export class TrayListResolverService {
constructor(private fb: FirebaseService, private router: Router) { }
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Observable<never> {
const urlName = route.url.toString();
switch (urlName) {
case 'OriginalOG': {
return this.fb.getOriginalTrays().pipe(take(1), mergeMap( t => {
if (t) {
return of (t);
} else {
return EMPTY;
}
})
);
break;
}
case 'MiniOG': {
return this.fb.getMiniTrays().pipe(take(1), mergeMap( t => {
if (t) {
return of (t);
} else {
return EMPTY;
}
})
);
break;
}
case 'CustomOG': {
return this.fb.getCustomTrays().pipe(take(1), mergeMap( t => {
if (t) {
return of (t);
} else {
return EMPTY;
}
})
);
break;
}
case 'OGAshtrays': {
return this.fb.getAshtrays().pipe(take(1), mergeMap( t => {
if (t) {
return of (t);
} else {
return EMPTY;
}
})
);
break;
}
case '1OFF': {
return this.fb.getOneOffs().pipe(take(1), mergeMap( t => {
if (t) {
return of (t);
} else {
return EMPTY;
}
})
);
break;
}
}
}
}
<file_sep>export const environment = {
production: true,
firebase: {
apiKey: "<KEY>",
authDomain: "oglarry.firebaseapp.com",
databaseURL: "https://oglarry.firebaseio.com",
projectId: "oglarry",
storageBucket: "oglarry.appspot.com",
messagingSenderId: "1098093410298",
appId: "1:1098093410298:web:9f1516a234e175c3"
}
};
<file_sep>import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { FormBuilder, Validators } from '@angular/forms';
import { FirebaseService } from 'src/app/Services/firebase.service';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'})
};
@Component({
// tslint:disable-next-line: component-selector
selector: 'sendemail',
templateUrl: './sendemail.component.html',
styleUrls: ['./sendemail.component.scss']
})
export class SendemailComponent implements OnInit {
contactForm;
constructor(private fbs: FirebaseService, private fb: FormBuilder, private router: Router) { }
ngOnInit() {
this.createForm();
}
sendEmail() {
this.fbs.sendMail(this.contactForm);
}
createForm() {
this.contactForm = this.fb.group({
name: ['', [Validators.required]],
email: ['', [Validators.required, Validators.email]],
subject: ['', [Validators.required]],
text: ['', [Validators.required]]
});
}
canDeactivate(): Observable<boolean> | boolean {
if (!this.contactForm.dirty) {
return true;
}
const confirm = window.confirm('Are you sure you want to leave?');
return confirm;
}
cancel() {
this.router.navigate(['/OGLarryDesigns']);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { FileUpload } from 'src/app/data/FileUpload';
import { FirebaseService } from 'src/app/Services/firebase.service';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
@Component({
// tslint:disable-next-line: component-selector
selector: 'contact',
templateUrl: './contact.component.html',
styleUrls: ['./contact.component.css']
})
export class ContactComponent implements OnInit {
// Form Variables
contactForm;
isTextChecked = false;
isLogoChecked = false;
woodTypes = [];
// File Upload
selectedFiles: FileList;
currentFileUpload: FileUpload;
progress: { percentage: number } = { percentage: 0 };
constructor(private fb: FormBuilder, private firebase: FirebaseService, private router: Router) { }
ngOnInit() {
this.contactForm = this.fb.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
phone: [''],
woodType: [''],
trayTextRequested: [false],
trayText: [''],
trayLogoRequested: [false],
trayLogo: [''],
submissionDate: [new Date(Date.now())]
});
this.firebase.getWoodTypes().subscribe( woodData => {
this.woodTypes = woodData[0].woodTypes;
});
}
selectFile(event) {
const file = event.target.files.item(0);
if (file.type.match('image.*')) {
this.selectedFiles = event.target.files;
} else {
alert('invalid format!');
}
}
upload() {
const file = this.selectedFiles.item(0);
this.selectedFiles = undefined;
this.currentFileUpload = new FileUpload(file);
this.firebase.pushFileToStorage(this.currentFileUpload, this.progress);
}
onSubmit(contactDetails) {
contactDetails.trayLogoRequested = this.isLogoChecked;
contactDetails.trayTextRequested = this.isTextChecked;
if (this.isLogoChecked && this.firebase.logoURL) {
contactDetails.trayLogo = this.firebase.logoURL;
}
this.firebase.addCustomTrayRequest(contactDetails);
}
canDeactivate(): Observable<boolean> | boolean {
if (!this.contactForm.dirty) {
return true;
}
const confirm = window.confirm('Are you sure you want to leave?');
return confirm;
}
cancel() {
this.router.navigate(['/OGLarryDesigns']);
}
}
<file_sep>import { Injectable } from '@angular/core';
import {
AngularFirestoreCollection,
AngularFirestoreDocument,
AngularFirestore
} from '@angular/fire/firestore';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs';
import { ITray } from '../data/tray';
import { AngularFireDatabase } from '@angular/fire/database';
import 'firebase/storage';
import { FileUpload } from '../data/FileUpload';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class FirebaseService {
// Navigation Info
navigationLinksCollection: AngularFirestoreCollection<string>;
navigationLinks: Observable<string[]>;
// Company Info
companyInfoCollection: AngularFirestoreCollection<string>;
companyInfo: Observable<string[]>;
// Original Trays
originalTraysCollection: AngularFirestoreCollection<ITray>;
originalTrays: Observable<ITray[]>;
originalTray: Observable<ITray[]>;
originalTrayDoc: AngularFirestoreDocument<ITray>;
// Mini Trays
miniTraysCollection: AngularFirestoreCollection<ITray>;
miniTrays: Observable<ITray[]>;
miniTray: Observable<ITray[]>;
miniTrayDoc: Observable<ITray[]>;
// Ashtrays
ashtraysCollection: AngularFirestoreCollection<ITray>;
ashtrays: Observable<ITray[]>;
ashtray: Observable<ITray[]>;
ashtrayDoc: Observable<ITray[]>;
// Custom Trays
customTraysCollection: AngularFirestoreCollection<ITray>;
customTrays: Observable<ITray[]>;
customTray: Observable<ITray[]>;
customTrayDoc: Observable<ITray[]>;
// 1Offs
oneOffsCollection: AngularFirestoreCollection<ITray>;
oneOffs: Observable<ITray[]>;
oneOff: Observable<ITray[]>;
oneOffDoc: Observable<ITray[]>;
// Wood Types
woodTypesCollection: AngularFirestoreCollection<any>;
woodTypes: Observable<any>;
// Image Links
imageLinksCollection: AngularFirestoreCollection<any>;
imageLinks: Observable<any>;
// PayPal
payPalCollection: AngularFirestoreCollection<any>;
payPal: Observable<any>;
// File Uploads
private basePath = '/CustomLogoRequests';
public logoURL;
snapshot: any;
constructor(private afs: AngularFirestore, private db: AngularFireDatabase, private http: HttpClient) {}
// Navigation Info
getNavigationInfo() {
this.navigationLinksCollection = this.afs.collection('NavigationLinks');
this.navigationLinks = this.navigationLinksCollection.valueChanges();
return this.navigationLinks;
}
// Company Info
getCompanyInfo() {
this.companyInfoCollection = this.afs.collection('CompanyInfo');
this.companyInfo = this.companyInfoCollection.valueChanges();
return this.companyInfo;
}
// Original Trays
getOriginalTrays() {
this.originalTraysCollection = this.afs.collection('OGOriginals');
this.originalTrays = this.originalTraysCollection.valueChanges();
return this.originalTrays;
}
getOriginalTray(trayName) {
this.originalTraysCollection = this.afs.collection('OGOriginals', ref => {
return ref.where('name', '==', trayName);
});
return this.originalTraysCollection.snapshotChanges();
}
// Mini Trays
getMiniTrays() {
this.miniTraysCollection = this.afs.collection('OGOMinis');
this.miniTrays = this.miniTraysCollection.valueChanges();
return this.miniTrays;
}
getMiniTray(trayName) {
this.miniTraysCollection = this.afs.collection('OGOMinis', ref => {
return ref.where('name', '==', trayName);
});
return this.miniTraysCollection.snapshotChanges();
}
// Ashtrays
getAshtrays() {
this.ashtraysCollection = this.afs.collection('OGAshtrays');
this.ashtrays = this.ashtraysCollection.valueChanges();
return this.ashtrays;
}
getAshtray(trayName) {
this.ashtraysCollection = this.afs.collection('OGAshtrays', ref => {
return ref.where('name', '==', trayName);
});
return this.ashtraysCollection.snapshotChanges();
}
// Custom Trays
getCustomTrays() {
this.customTraysCollection = this.afs.collection('OGCustom');
this.customTrays = this.customTraysCollection.valueChanges();
return this.customTrays;
}
getCustomTray(trayName) {
this.customTraysCollection = this.afs.collection('OGCustom', ref => {
return ref.where('name', '==', trayName);
});
return this.customTraysCollection.snapshotChanges();
}
addCustomTrayRequest(requestDetails) {
this.afs
.collection('CustomRequests')
.add(requestDetails)
.then(docRef => {
console.log('Document written');
})
.catch(error => {
console.error('Error adding document: ', error);
});
}
// 1Offs
getOneOffs() {
this.oneOffsCollection = this.afs.collection('OneOffs');
this.oneOffs = this.oneOffsCollection.valueChanges();
return this.oneOffs;
}
getOneOff(trayName) {
this.oneOffsCollection = this.afs.collection('OneOffs', ref => {
return ref.where('name', '==', trayName);
});
return this.oneOffsCollection.snapshotChanges();
}
// Wood Types
getWoodTypes() {
this.woodTypesCollection = this.afs.collection('WoodTypes');
this.woodTypes = this.woodTypesCollection.valueChanges();
return this.woodTypes;
}
// Image Links
getImageLinks() {
this.imageLinksCollection = this.afs.collection('ImageLinks');
this.imageLinks = this.imageLinksCollection.valueChanges();
return this.imageLinks;
}
// PayPal
getPayPalConfigs() {
this.payPalCollection = this.afs.collection('PayPal');
this.payPal = this.payPalCollection.valueChanges();
return this.payPal;
}
// File Upload
pushFileToStorage(fileUpload: FileUpload, progress: { percentage: number }) {
const storageRef = firebase.storage().ref();
const uploadTask = storageRef
.child(`${this.basePath}/${fileUpload.file.name}`)
.put(fileUpload.file);
uploadTask.on(
firebase.storage.TaskEvent.STATE_CHANGED,
snapshot => {
// in progress
const snap = snapshot as firebase.storage.UploadTaskSnapshot;
progress.percentage = Math.round(
(snap.bytesTransferred / snap.totalBytes) * 100
);
},
error => {
// fail
console.log(error);
},
() => {
// success
uploadTask.snapshot.ref.getDownloadURL().then(url => {
fileUpload.url = url;
this.logoURL = fileUpload.url;
});
fileUpload.name = fileUpload.file.name;
this.saveFileData(fileUpload);
}
);
}
private saveFileData(fileUpload: FileUpload) {
this.db.list(`${this.basePath}/`).push(fileUpload);
}
// Emailer
sendMail(emailInput) {
const url = 'https://us-central1-oglarry.cloudfunctions.net/httpEmail';
const emailParams = new HttpParams();
const emailHeaders = new HttpHeaders();
emailHeaders.append('Content-Type', 'application/json');
emailHeaders.append('Access-Control-Allow-Origin', '*');
emailParams.set('to', '<EMAIL>');
emailParams.set('from', emailInput.value.email);
emailParams.set('subject', emailInput.value.subject);
emailParams.set('text', emailInput.value.text);
emailParams.set('html', `
<html>
<p>${emailInput.value.text}</p>
</html>`);
const body = {
to: '<EMAIL>',
from: emailInput.value.email, /** replace '<EMAIL>' with a working email address, I simply sent an email to myself. */
subject: emailInput.value.subject,
text: emailInput.value.text,
html: `
<html>
<p>${emailInput.value.text}</p>
</html>`
};
return this.http.post(url, body, {
headers: emailHeaders,
params: emailParams
})
.toPromise()
.then(res => {
console.log('sent');
})
.catch(err => {
console.log(err);
});
}
// Emailer
purchaseTray(inputPrice) {
const url = 'https://us-central1-oglarry.cloudfunctions.net/pay';
const payParams = new HttpParams();
const payHeaders = new HttpHeaders();
payHeaders.append('Content-Type', 'application/json');
payHeaders.append('Access-Control-Allow-Origin', '*');
payHeaders.set('price', '5');
const body = {
uid: 1,
price: inputPrice
};
return this.http.post(url, body, {
headers: payHeaders,
params: payParams
}).subscribe( res => {
console.log(res);
document.location.href = res.toString();
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { FirebaseService } from 'src/app/Services/firebase.service';
@Component({
// tslint:disable-next-line: component-selector
selector: 'navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
size = '2x';
navigationLinks;
constructor(private fb: FirebaseService) { }
ngOnInit() {
this.fb.getNavigationInfo().subscribe( links => {
this.navigationLinks = links[0];
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'carousel',
templateUrl: './carousel.component.html',
styleUrls: ['./carousel.component.css']
})
export class CarouselComponent implements OnInit {
slideConfig = {"slidesToShow": 1, "slidesToScroll": 1};
slides = [
{img: "../../assets/imgs/tray3.jpg"},
{img: "../../assets/imgs/tray3.jpg"},
{img: "../../assets/imgs/tray3.jpg"},
{img: "../../assets/imgs/tray3.jpg"},
];
constructor() { }
ngOnInit() {
}
}
<file_sep>export interface ITray {
dimensions: string;
fullDescription: string;
img: string;
name: string;
price: number;
shortDescription: string;
woodType: string;
}
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { OriginalOGComponent } from './components/original-og/original-og.component';
import { MiniOGComponent } from './components/mini-og/mini-og.component';
import { AshtraysComponent } from './components/ashtrays/ashtrays.component';
import { CustomComponent } from './components/custom/custom.component';
import { ContactComponent } from './components/contact/contact.component';
import { HomeComponent } from './components/home/home.component';
import { TrayDetailComponent } from './components/tray-detail/tray-detail.component';
import { OneOffComponent } from './components/oneOff/oneOff.component';
import { SendemailComponent } from './components/sendemail/sendemail.component';
import { CanDeactivateGuard } from './can-deactivate.guard';
import { TrayDetailResolverService } from './Services/tray-detail-resolver.service';
import { TrayListResolverService } from './Services/tray-list-resolver.service';
import { PaymentSuccessComponent } from './components/payment-success/payment-success.component';
const routes: Routes = [
{path: 'OGLarryDesigns', component: HomeComponent},
{path: 'OriginalOG', component: OriginalOGComponent, resolve: {trays: TrayListResolverService}},
{path: 'MiniOG', component: MiniOGComponent, resolve: {trays: TrayListResolverService}},
{path: 'OGAshtrays', component: AshtraysComponent, resolve: {trays: TrayListResolverService}},
{path: 'CustomOG', component: CustomComponent, resolve: {trays: TrayListResolverService}},
{path: 'CustomContact', component: ContactComponent, pathMatch: 'full', canDeactivate: [CanDeactivateGuard]},
{path: 'ContactOGLarry', component: SendemailComponent, pathMatch: 'full', canDeactivate: [CanDeactivateGuard]},
{path: '1OFF', component: OneOffComponent, resolve: {trays: TrayListResolverService}},
{path: 'TrayDetail/:name', component: TrayDetailComponent, resolve: {tray: TrayDetailResolverService}},
{path: 'PaymentConfirmation', component: PaymentSuccessComponent},
{path: '', redirectTo: '/OGLarryDesigns', pathMatch: 'full'}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>import { TestBed } from '@angular/core/testing';
import { TrayListResolverService } from './tray-list-resolver.service';
describe('TrayListResolverService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: TrayListResolverService = TestBed.get(TrayListResolverService);
expect(service).toBeTruthy();
});
});
<file_sep>const functions = require('firebase-functions');
const paypal = require('paypal-rest-sdk');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// Mailers
const cors = require('cors')({
origin: ['http://localhost:4200'], /** replace with the url of your development environment that serves your angular app. */
methods: ['POST', 'OPTIONS'],
allowedHeaders: ['Content-Type'],
preflightContinue: false,
optionsSuccessStatus: 204
});
const SENDGRID_API_KEY = functions.config().sendgrid.key
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(SENDGRID_API_KEY);
exports.httpEmail = functions.https.onRequest((req, res) => {
cors(req, res, () => {
return Promise.resolve()
.then(() => {
if (req.method !== 'POST') {
const error = new Error('Only POST requests are accepted');
error.code = 405;
throw error;
}
const message = {
to: req.body.to,
from: req.body.from,
subject: req.body.subject,
text: req.body.text,
html: req.body.html
};
return sgMail.send(message);
})
.then((response) => {
if (response.body) {
res.send(response.body);
} else {
res.end();
}
})
.catch((err) => {
console.error(err);
return Promise.reject(err);
});
});
});
exports.firestoreEmail = functions.firestore
.document('CustomRequests/{docID}')
.onCreate((snap, context) => {
const item = snap.data();
const db = admin.firestore();
const msg = {
to: '<EMAIL>',
from: '<EMAIL>',
subject: 'New Custom Tray Request',
html: `<h2> OGLarry, you have a new custom tray request.</h2>
<div>To view it go to <a href="https://console.firebase.google.com/project/oglarry/overview">OGLarry Console</a></div>
<div>From there, go to 'Database' -> 'CustomRequests' -> Navigate to the latest one.</div>
`
};
return sgMail.send(msg);
});
// PayPal
//console.log('client secret ' + functions.config().paypal.sandbox_client_secret);
//console.log('client id ' + functions.config().paypal.sandbox_client_id);
const clientID = functions.config().paypal.sandbox_client_id;
const secret1 = functions.config().paypal.client_secret1;
const secret2 = functions.config().paypal.client_secret2;
const secret3 = functions.config().paypal.client_secret3;
let clientSecret = `${secret1}-${secret2}-${secret3}`;
let paylPalConfig = {
mode: 'sandbox', // sandbox or live
client_id: clientID, // run: firebase functions:config:set paypal.client_id="yourPaypalClientID"
client_secret: clientSecret
};
paypal.configure(paylPalConfig);
exports.pay = functions.https.onRequest((req, res) => {
// 1.Set up a payment information object, Build PayPal payment request
cors(req, res, () => {
const payReq = JSON.stringify({
intent: 'sale',
payer: {
payment_method: 'paypal'
},
redirect_urls: {
return_url: `https://us-central1-oglarry.cloudfunctions.net/process`,
cancel_url: `http://localhost:4200/OGLarryDesigns`
},
transactions: [{
amount: {
total: req.body.price,
currency: 'CAD'
},
// This is the payment transaction description. Maximum length: 127
description: req.body.uid, // req.body.id
// reference_id string .Optional. The merchant-provided ID for the purchase unit. Maximum length: 256.
// reference_id: req.body.uid,
custom: req.body.uid,
// soft_descriptor: req.body.uid
// "invoice_number": req.body.uid,A
}]
});
// 2.Initialize the payment and redirect the user.
paypal.payment.create(payReq, (error, payment) => {
const links = {};
if (error) {
console.error(error);
res.status('500').end();
} else {
// Capture HATEOAS links
payment.links.forEach((linkObj) => {
links[linkObj.rel] = {
href: linkObj.href,
method: linkObj.method
};
});
// If redirect url present, redirect user
if (links.hasOwnProperty('approval_url')) {
// REDIRECT USER TO links['approval_url'].href
console.info(links.approval_url.href);
// res.json({"approval_url":links.approval_url.href});
res.status(200).send(JSON.stringify(links.approval_url.href));
} else {
console.error('no redirect URI present');
res.status('500').end();
}
}
});
});
});
// 3.Complete the payment. Use the payer and payment IDs provided in the query string following the redirect.
exports.process = functions.https.onRequest(async (req, res) => {
const paymentId = req.query.paymentId;
const payerId = {
payer_id: req.query.PayerID
};
const r = await paypal.payment.execute(paymentId, payerId, (error, payment) => {
if (error) {
console.error(error);
res.redirect(`http://localhost:4200/OGLarryDesigns`); // replace with your url page error
} else {
if (payment.state === 'approved') {
console.info('payment completed successfully, description: ', payment.transactions[0].description);
// console.info('req.custom: : ', payment.transactions[0].custom);
// set paid status to True in RealTime Database
console.log('success');
res.redirect(`http://localhost:4200/PaymentConfirmation`); // replace with your url, page success
} else {
console.warn('payment.state: not approved ?');
// replace debug url
// res.redirect(`https://console.firebase.google.com/project/${process.env.GCLOUD_PROJECT}/functions/logs?search=&severity=DEBUG`);
}
}
});
});
<file_sep>import { Component, OnInit } from '@angular/core';
import { FirebaseService } from 'src/app/Services/firebase.service';
@Component({
// tslint:disable-next-line: component-selector
selector: 'image-links',
templateUrl: './image-links.component.html',
styleUrls: ['./image-links.component.css']
})
export class ImageLinksComponent implements OnInit {
imageLinks;
constructor(private fb: FirebaseService) { }
ngOnInit() {
this.fb.getImageLinks().subscribe( links => {
this.imageLinks = links[0].ImageLinks;
});
}
}
<file_sep>import { Injectable} from '@angular/core';
import { Router } from '@angular/router';
import { FirebaseService } from './firebase.service';
@Injectable({
providedIn: 'root'
})
export class PaymentService {
addScript = false;
payPalLoad = true;
finalAmount;
payPalConfig = {
env: 'sandbox',
client: {
sandbox: '<KEY>
production: '<KEY>'
},
style: {
size: 'responsive',
color: 'gold',
shape: 'pill',
label: 'checkout',
tagline: 'false',
width: '100%'
},
commit: true,
payment: (data, actions) => {
return actions.payment.create({
payment: {
transactions: [
{ amount: {total: this.finalAmount, currency: 'CAD'}}
]
}
});
},
onAuthorize: (data, actions) => {
return actions.payment.execute().then((payment) => {
this.router.navigate(['/OGLarryDesigns']);
});
},
onCancel: (data, actions) => {
this.router.navigate(['/OGLarryDesigns']);
}
};
constructor(private router: Router, private fb: FirebaseService) {
}
setPaymentAmount(price) {
this.finalAmount = price;
}
addPayPalScript() {
this.addScript = true;
return new Promise((resolve, reject) => {
const scriptTagElement = document.createElement('script');
scriptTagElement.src = 'https://paypalobjects.com/api/checkout.js';
scriptTagElement.onload = resolve;
document.body.appendChild(scriptTagElement);
});
}
}
<file_sep>import { Component, OnInit, Input } from '@angular/core';
import { Router } from '@angular/router';
@Component({
// tslint:disable-next-line: component-selector
selector: 'product-thumbnail',
templateUrl: './product-thumbnail.component.html',
styleUrls: ['./product-thumbnail.component.css']
})
export class ProductThumbnailComponent implements OnInit {
@Input() tray;
constructor(private router: Router) { }
ngOnInit() {
}
goToDetailPage() {
this.router.navigate(['/TrayDetail', `${this.tray.category}-${this.tray.name}`]);
}
}
| c33b3a07db631c3832afb026819617ca30930a60 | [
"JavaScript",
"TypeScript"
] | 22 | TypeScript | Mark128/OGLarry | 14f2ae78ede59606deb1d891da953351c8d59bdc | c00e156c3409c80c52135e24a985eb68af4e93db |
refs/heads/main | <repo_name>karlkar/iOS_VirtualTourist<file_sep>/VirtualTourist/View Controllers/PhotoAlbumViewController.swift
import UIKit
import MapKit
import CoreData
class PhotoAlbumViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var pin: Pin!
var dataController: DataController!
private var allImagesDownloaded = false
var photos = [Photo]()
private let reuseIdentifier = "PhotoAlbumCellView"
private let flickrApiHelper = FlickrApiHelper()
@IBOutlet weak var mapViewOutlet: MKMapView!
@IBOutlet weak var collectionViewOutlet: UICollectionView!
@IBOutlet weak var labelOutlet: UILabel!
@IBOutlet weak var buttonOutlet: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.isHidden = false
collectionViewOutlet.delegate = self
collectionViewOutlet.dataSource = self
displayImagesLoadingLayout()
startLoadingImages()
setupMapView()
}
private func startLoadingImages() {
if pin.photoPageCount < 0 {
fetchImagesFromNetwork()
} else {
fetchImagesFromStore()
}
}
private func fetchImagesFromStore() {
allImagesDownloaded = false
let request = Photo.fetchRequest()
request.predicate = NSPredicate(format: "pin == %@", pin)
if let result = try? dataController.viewContext.fetch(request) {
photos = result
collectionViewOutlet.reloadData()
displayImagesLoadedLayout()
allImagesDownloaded = true
}
}
private func fetchImagesFromNetwork(page: Int = 0) {
allImagesDownloaded = false
flickrApiHelper.searchPhotos(latitude: pin.latitude, longitude: pin.longitude, page: page, resultHandler: { success, data in
if success {
self.handlePhotoListAcquired(response: data!)
}
})
}
private func handlePhotoListAcquired(response: FlickrSearchResponse) {
pin.photoPageCount = response.pageCount
for flickrPhoto in response.photos {
let photo = flickrPhoto.toPhoto(dataController: dataController, parentPin: pin)
photos.append(photo)
fetchImageData(photo: photo, flickrPhoto: flickrPhoto)
}
collectionViewOutlet.reloadData()
try? dataController.viewContext.save()
displayImagesLoadedLayout()
}
private func fetchImageData(photo: Photo, flickrPhoto: FlickrPhoto) {
flickrApiHelper.getImage(flickrPhoto: flickrPhoto, resultHandler: { success, data in
if success {
photo.image = data
try? self.dataController.viewContext.save()
self.collectionViewOutlet.reloadData()
self.allImagesDownloaded = self.photos.allSatisfy { $0.image != nil }
}
})
}
private func displayNoImageLayout() {
collectionViewOutlet.isHidden = true
labelOutlet.isHidden = false
buttonOutlet.isEnabled = false
labelOutlet.text = "No Images... :("
}
private func displayImagesLoadingLayout() {
collectionViewOutlet.isHidden = false
labelOutlet.isHidden = false
buttonOutlet.isEnabled = true
labelOutlet.text = "Loading..."
}
private func displayImagesLoadedLayout() {
collectionViewOutlet.isHidden = false
labelOutlet.isHidden = true
buttonOutlet.isEnabled = true
}
private func setupMapView() {
mapViewOutlet.centerCoordinate.latitude = pin.latitude
mapViewOutlet.centerCoordinate.longitude = pin.longitude
mapViewOutlet.region.span = MKCoordinateSpan(latitudeDelta: 0.03, longitudeDelta: 0.03)
let pointAnnotation = MKPointAnnotation()
pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: pin.latitude, longitude: pin.longitude)
mapViewOutlet.addAnnotation(pointAnnotation)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photos.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PhotoAlbumCellView
if photos[indexPath.row].image == nil {
cell.imageOutlet.image = UIImage(systemName: "slowmo")
} else {
cell.imageOutlet.image = UIImage(data: photos[indexPath.row].image!)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if allImagesDownloaded {
removePhoto(indexPath: indexPath)
}
}
private func removePhoto(indexPath: IndexPath) {
removePhotoFromStore(indexPath: indexPath)
removePhotoFromView(indexPath: indexPath)
}
private func removePhotoFromStore(indexPath: IndexPath) {
let photoToBeDeleted = photos[indexPath.row]
dataController.viewContext.delete(photoToBeDeleted)
try? dataController.viewContext.save()
}
private func removePhotoFromView(indexPath: IndexPath) {
photos.remove(at: indexPath.row)
collectionViewOutlet.deleteItems(at: [indexPath])
}
@IBAction func newCollectionButtonAction(_ sender: Any) {
displayImagesLoadingLayout()
clearPhotosInStore()
clearPhotosInView()
let upperBoundary = min(Int(pin.photoPageCount), 4000/FlickrApiHelper.PER_PAGE_COUNT)
let randomPage = Int.random(in: 1...upperBoundary)
fetchImagesFromNetwork(page: randomPage)
}
private func clearPhotosInStore() {
photos.forEach { dataController.viewContext.delete($0) }
}
private func clearPhotosInView() {
photos = []
collectionViewOutlet.reloadData()
}
}
extension FlickrPhoto {
func toPhoto(dataController: DataController, parentPin: Pin) -> Photo {
let photo = Photo(context: dataController.viewContext)
photo.identifier = self.id
photo.secret = self.secret
photo.server = Int32(self.server)
photo.image = nil
photo.pin = parentPin
return photo
}
}
<file_sep>/VirtualTourist/Views/PhotoAlbumCellView.swift
import UIKit
class PhotoAlbumCellView: UICollectionViewCell {
@IBOutlet weak var imageOutlet: UIImageView!
}
<file_sep>/VirtualTourist/model/FlickrSearchResponse.swift
import Foundation
struct FlickrSearchResponse {
let totalCount: Int
let pageCount: Int64
let photos: [FlickrPhoto]
}
<file_sep>/VirtualTourist/FlickrApiHelper.swift
import Foundation
class FlickrApiHelper {
static let PER_PAGE_COUNT = 50
private let baseUrl = "https://www.flickr.com/services/rest/?method="
private let apiKey = "<KEY>"
private let per_page = "per_page=\(PER_PAGE_COUNT)"
private let formatJson = "format=json&nojsoncallback=1"
private func doOnMainThread<T>(success: Bool, data: T?, resultHandler: @escaping (Bool, T?) -> ()) {
DispatchQueue.main.async {
resultHandler(success, data)
}
}
func searchPhotos(latitude: Double, longitude: Double, page: Int, resultHandler: @escaping (Bool, FlickrSearchResponse?) -> ()) {
let urlString = "\(baseUrl)flickr.photos.search&api_key=\(apiKey)&lat=\(latitude)&lon=\(longitude)&\(formatJson)&\(per_page)&page=\(page)"
let url = URL(string: urlString)!
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
print("ERROR: [searchPhotos] error != nil")
self.doOnMainThread(success: false, data: nil, resultHandler: resultHandler)
return
}
guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else {
print("ERROR: [searchPhotos] Your request returned a status code other than 2xx!")
self.doOnMainThread(success: false, data: nil, resultHandler: resultHandler)
return
}
// print("SUCCESS: [searchPhotos] data = \(String(data: data!, encoding: .utf8)!)")
let parsedResult: [String:AnyObject]!
do {
parsedResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
} catch {
print("Could not parse the data as JSON: '\(data!)'")
self.doOnMainThread(success: false, data: nil, resultHandler: resultHandler)
return
}
guard let parsedCheckedResult = parsedResult else {
print("Parsing failed")
self.doOnMainThread(success: false, data: nil, resultHandler: resultHandler)
return
}
let flickrSearchResponse = self.parseJson(json: parsedCheckedResult)
print("SUCCESS: [searchPhotos] response = \(flickrSearchResponse)")
self.doOnMainThread(success: true, data: flickrSearchResponse, resultHandler: resultHandler)
}
task.resume()
}
private func parseJson(json: [String: AnyObject]) -> FlickrSearchResponse {
let totalCount = json["photos"]!["total"] as! Int
let pageCount = json["photos"]!["pages"] as! Int64
let photoArray = (json["photos"]!["photo"] as! NSArray)
.map { $0 as! NSDictionary }
.map { FlickrPhoto(id: $0["id"] as! String, secret: $0["secret"] as! String, server: $0["farm"] as! Int) }
return FlickrSearchResponse(totalCount: totalCount, pageCount: pageCount, photos: photoArray)
}
func getImage(flickrPhoto: FlickrPhoto, resultHandler: @escaping (Bool, Data?) -> ()) {
let imageUrlString = "https://live.staticflickr.com/\(flickrPhoto.server)/\(flickrPhoto.id)_\(flickrPhoto.secret)_w.jpg"
let imageURL = URL(string: imageUrlString)
DispatchQueue.global(qos: .userInitiated).async {
if let imageData = try? Data(contentsOf: imageURL!) {
self.doOnMainThread(success: true, data: imageData, resultHandler: resultHandler)
}
}
}
}
<file_sep>/VirtualTourist/Views/CustomPointAnnotation.swift
import Foundation
import MapKit
class CustomPointAnnotation : MKPointAnnotation {
var tag: Pin!
}
<file_sep>/VirtualTourist/DataController.swift
import Foundation
import CoreData
class DataController {
let persistenceContainer: NSPersistentContainer
var viewContext: NSManagedObjectContext {
return persistenceContainer.viewContext
}
init(modelName: String) {
persistenceContainer = NSPersistentContainer(name: modelName)
}
func load(completion: (() -> Void)? = nil) {
persistenceContainer.loadPersistentStores { storeDescription, error in
guard error == nil else {
fatalError(error!.localizedDescription)
}
completion?()
}
}
}
<file_sep>/VirtualTourist/View Controllers/MapViewController.swift
import UIKit
import MapKit
import CoreData
class MapViewController: UIViewController, MKMapViewDelegate {
private let mapStateStore = MapStateStore()
var dataController: DataController!
@IBOutlet weak var mapViewOutlet: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
setupInitialPosition()
setupLongPressRecognizer()
loadStoredPinData()
mapViewOutlet.delegate = self
}
private func setupInitialPosition() {
if let mapState = mapStateStore.getStoredState() {
let region = MKCoordinateRegion(center: mapState.location, span: mapState.zoomLevel)
mapViewOutlet.setRegion(region, animated: true)
}
}
private func setupLongPressRecognizer() {
let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(onLongPress(recognizer:)))
mapViewOutlet.addGestureRecognizer(longGesture)
}
@objc func onLongPress(recognizer: UIGestureRecognizer) {
if recognizer.state != .began{
return
}
let touchCoordinate = getTouchCoordinates(mapView: mapViewOutlet, recognizer: recognizer)
let pin = addPinToDataStore(coordinate: touchCoordinate)
addPinToMap(mapView: mapViewOutlet, pin: pin, coordinate: touchCoordinate)
}
private func getTouchCoordinates(mapView: MKMapView, recognizer: UIGestureRecognizer) -> CLLocationCoordinate2D {
let touchPoint = recognizer.location(in: mapView)
let pointOnMap = mapView.convert(touchPoint, toCoordinateFrom: mapView)
let touchLocation = CLLocation(latitude: pointOnMap.latitude, longitude: pointOnMap.longitude)
return touchLocation.coordinate
}
private func addPinToMap(mapView: MKMapView, pin: Pin, coordinate: CLLocationCoordinate2D) {
let pointAnnotation = CustomPointAnnotation()
pointAnnotation.coordinate = coordinate
pointAnnotation.tag = pin
mapView.addAnnotation(pointAnnotation)
// Hack to deselect added pin
mapView.setCenter(mapView.centerCoordinate, animated: false)
}
private func addPinToDataStore(coordinate: CLLocationCoordinate2D) -> Pin {
let pin = Pin(context: dataController.viewContext)
pin.latitude = coordinate.latitude
pin.longitude = coordinate.longitude
pin.photoPageCount = -1
try? dataController.viewContext.save()
return pin
}
private func loadStoredPinData() {
let fetchRequest: NSFetchRequest<Pin> = Pin.fetchRequest()
if let result = try? dataController.viewContext.fetch(fetchRequest) {
result.reduce(into: [Pin: CLLocationCoordinate2D]()) {
$0[$1] = CLLocationCoordinate2D(latitude: $1.latitude, longitude: $1.longitude)
}.forEach { addPinToMap(mapView: mapViewOutlet, pin: $0, coordinate: $1) }
}
}
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
storeCurrentMapState()
}
private func storeCurrentMapState() {
let currentLocation = mapViewOutlet.centerCoordinate
let currentZoom = mapViewOutlet.region.span
mapStateStore.updateState(state: MapState(location: currentLocation, zoomLevel: currentZoom))
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if let vc = storyboard?.instantiateViewController(withIdentifier: "PhotoAlbumViewController") as? PhotoAlbumViewController {
vc.pin = (view.annotation as! CustomPointAnnotation).tag
vc.dataController = dataController
navigationController?.pushViewController(vc, animated: true)
}
self.mapViewOutlet.selectedAnnotations.forEach({ mapViewOutlet.deselectAnnotation($0, animated: false) })
}
}
<file_sep>/VirtualTourist/model/FlickrPhoto.swift
import Foundation
struct FlickrPhoto {
let id: String
let secret: String
let server: Int
}
<file_sep>/VirtualTourist/MapStateStore.swift
import Foundation
import CoreLocation
import MapKit
class MapStateStore {
private static let PREF_START_LAT = "PREF_START_LAT"
private static let PREF_START_LNG = "PREF_START_LNG"
private static let PREF_START_ZOOM_LAT = "PREF_START_ZOOM_LAT"
private static let PREF_START_ZOOM_LNG = "PREF_START_ZOOM_LNG"
func getStoredState() -> MapState? {
let startLat = UserDefaults.standard.double(forKey: MapStateStore.PREF_START_LAT)
let startLng = UserDefaults.standard.double(forKey: MapStateStore.PREF_START_LNG)
let startZoomLat = UserDefaults.standard.double(forKey: MapStateStore.PREF_START_ZOOM_LAT)
let startZoomLng = UserDefaults.standard.double(forKey: MapStateStore.PREF_START_ZOOM_LNG)
if (startLat == 0 && startLng == 0) || (startZoomLat == 0 && startZoomLng == 0) {
return nil
} else {
let location = CLLocationCoordinate2D(latitude: startLat, longitude: startLng)
let zoom = MKCoordinateSpan(latitudeDelta: startZoomLat, longitudeDelta: startZoomLng)
return MapState(location: location, zoomLevel: zoom)
}
}
func updateState(state: MapState) {
storeLocation(state)
storeZoom(state)
}
private func storeLocation(_ state: MapState) {
UserDefaults.standard.set(state.location.latitude, forKey: MapStateStore.PREF_START_LAT)
UserDefaults.standard.set(state.location.longitude, forKey: MapStateStore.PREF_START_LNG)
}
private func storeZoom(_ state: MapState) {
UserDefaults.standard.set(state.zoomLevel.latitudeDelta, forKey: MapStateStore.PREF_START_ZOOM_LAT)
UserDefaults.standard.set(state.zoomLevel.longitudeDelta, forKey: MapStateStore.PREF_START_ZOOM_LNG)
}
}
<file_sep>/VirtualTourist/model/MapState.swift
import MapKit
struct MapState {
let location: CLLocationCoordinate2D
let zoomLevel: MKCoordinateSpan
}
| 0ab6541bc976047355bcd327eeb22bd0df5b2d5e | [
"Swift"
] | 10 | Swift | karlkar/iOS_VirtualTourist | 8636b9583595f820fcf5f535c33e4e652045bc46 | fbf99a4de5397e1e0eb39fc6c51d53bf375a4782 |
refs/heads/master | <repo_name>ChaoSpiritZ/OOP-27-Homework<file_sep>/OOP 27 Homework/OOP 27 Homework/Garage.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OOP_27_Homework
{
public class Garage : IGarage
{
private List<Car> _cars;
private List<string> _carTypes;
public Garage(List<string> carTypes)
{
_cars = new List<Car>();
_carTypes = carTypes;
}
public void AddCar(Car car)
{
if(car is null)
{
throw new CarNullException($"failed adding car: the car sent is null [{car}]");
}
if (_cars.Contains(car))
{
throw new CarAlreadyHereException($"failed adding car: car [{car}] is already in the garage");
}
if(car.TotalLost)
{
throw new WeDoNotFixTotalLostException($"failed adding car: car [{car}] is beyond repair, we do not deal with those");
}
if (!_carTypes.Contains(car.Brand))
{
throw new WrongGarageException($"failed adding car: this garage doesn't fix cars with brand [{car.Brand}]");
}
if (!car.NeedsRepair)
{
throw new RepairMismatchException($"failed adding car: car [{car}] doesn't need repair");
}
_cars.Add(car);
}
public void TakeOutCar(Car car)
{
if(car is null)
{
throw new CarNullException($"failed taking out car: the car sent is null [{car}]");
}
if (!_cars.Contains(car))
{
throw new CarNotInGarageException($"failed taking out car: car [{car}] is was not found in the garage");
}
if (car.NeedsRepair)
{
throw new CarNotReadyException($"failed taking out car: car [{car}] still needs to be repaired");
}
_cars.Remove(car);
}
public void FixCar(Car car)
{
if(car is null)
{
throw new CarNullException($"failed fixing car: the car sent is null [{car}]");
}
if (!_cars.Contains(car))
{
throw new CarNotInGarageException($"failed fixing car: car [{car}] is was not found in the garage");
}
if (!car.NeedsRepair)
{
throw new RepairMismatchException($"failed fixing car: car [{car}] is already fixed");
}
car.NeedsRepair = false;
}
}
}
<file_sep>/OOP 27 Homework/OOP 27 Test/GarageTest.cs
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OOP_27_Homework;
namespace OOP_27_Test
{
[TestClass]
public class GarageTest
{
[TestMethod]
[ExpectedException(typeof(CarAlreadyHereException))]
public void AddCarMethodAlreadyHere()
{
Car car1 = new Car("mazda", false, true);
Garage myGarage = new Garage(new List<string>() { "mazda" });
myGarage.AddCar(car1);
myGarage.AddCar(car1);
}
[TestMethod]
[ExpectedException(typeof(WeDoNotFixTotalLostException))]
public void AddCarMethodTotalLost()
{
Car car1 = new Car("mazda", true, true);
Garage myGarage = new Garage(new List<string>() { "mazda" });
myGarage.AddCar(car1);
}
[TestMethod]
[ExpectedException(typeof(WrongGarageException))]
public void AddCarMethodWrongGarage()
{
Car car1 = new Car("toyota", false, true);
Garage myGarage = new Garage(new List<string>() { "mazda" });
myGarage.AddCar(car1);
}
[TestMethod]
[ExpectedException(typeof(CarNullException))]
public void AddCarMethodCarNull()
{
Car car1 = null;
Garage myGarage = new Garage(new List<string>() { "mazda" });
myGarage.AddCar(car1);
}
[TestMethod]
[ExpectedException(typeof(RepairMismatchException))]
public void AddCarMethodRepairMismatch()
{
Car car1 = new Car("mazda", false, false);
Garage myGarage = new Garage(new List<string>() { "mazda" });
myGarage.AddCar(car1);
}
[TestMethod]
public void AddCarMethod()
{
Car car1 = new Car("mazda", false, true);
Garage myGarage = new Garage(new List<string>() { "mazda" });
myGarage.AddCar(car1);
}
//-------------------------------------------------------------------------
[TestMethod]
[ExpectedException(typeof(CarNullException))]
public void TakeOutCarMethodCarNull()
{
Garage myGarage = new Garage(new List<string>() { "mazda" });
myGarage.TakeOutCar(null);
}
[TestMethod]
[ExpectedException(typeof(CarNotInGarageException))]
public void TakeOutCarMethodCarNotInGarage()
{
Car car1 = new Car("mazda", false, true);
Garage myGarage = new Garage(new List<string>() { "mazda" });
myGarage.TakeOutCar(car1);
}
[TestMethod]
[ExpectedException(typeof(CarNotReadyException))]
public void TakeOutCarMethodCarNotReady()
{
Car car1 = new Car("mazda", false, true);
Garage myGarage = new Garage(new List<string>() { "mazda" });
myGarage.AddCar(car1);
myGarage.TakeOutCar(car1);
}
[TestMethod]
public void TakeOutCarMethod()
{
Car car1 = new Car("mazda", false, true);
Garage myGarage = new Garage(new List<string>() { "mazda" });
myGarage.AddCar(car1);
myGarage.FixCar(car1);
myGarage.TakeOutCar(car1);
Assert.AreEqual(false, car1.NeedsRepair);
}
//--------------------------------------------------------------------------------
[TestMethod]
[ExpectedException(typeof(CarNullException))]
public void FixCarMethodCarNull()
{
Garage myGarage = new Garage(new List<string>() { "mazda" });
myGarage.FixCar(null);
}
[TestMethod]
[ExpectedException(typeof(CarNotInGarageException))]
public void FixCarMethodCarNotInGarage()
{
Car car1 = new Car("mazda", false, true);
Garage myGarage = new Garage(new List<string>() { "mazda" });
myGarage.FixCar(car1);
}
[TestMethod]
[ExpectedException(typeof(RepairMismatchException))]
public void FixCarMethodRepairMismatch()
{
Car car1 = new Car("mazda", false, true);
Garage myGarage = new Garage(new List<string>() { "mazda" });
myGarage.AddCar(car1);
myGarage.FixCar(car1);
myGarage.FixCar(car1);
}
[TestMethod]
public void FixCarMethod()
{
Car car1 = new Car("mazda", false, true);
Garage myGarage = new Garage(new List<string>() { "mazda" });
myGarage.AddCar(car1);
myGarage.FixCar(car1);
Assert.AreEqual(false, car1.NeedsRepair);
}
}
}
<file_sep>/OOP 27 Homework/OOP 27 Test/CarTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OOP_27_Homework;
namespace OOP_27_Test
{
[TestClass]
public class CarTest
{
[TestMethod]
[ExpectedException(typeof(RepairMismatchException))]
public void CarConstructor()
{
Car car = new Car("toyota", true, false);
}
}
}
| 3b8cfec4bc0dae279613f29466227cc5ca69a394 | [
"C#"
] | 3 | C# | ChaoSpiritZ/OOP-27-Homework | 6eb10bbdfd8e3e1426ecaf48abeed6e5ab282fe7 | 0481cfb455fb95c7e0fcd52892ccd03daf74f57a |
refs/heads/master | <repo_name>Patrick1993G/SecuringApps<file_sep>/ShoppingCart.Application/Services/StudentAssignmentsService.cs
using AutoMapper;
using AutoMapper.QueryableExtensions;
using ShoppingCart.Application.Interfaces;
using ShoppingCart.Application.ViewModels;
using ShoppingCart.Domain.Interfaces;
using ShoppingCart.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ShoppingCart.Application.Services
{
public class StudentAssignmentsService : IStudentAssignmentsService
{
private IMapper _mapper;
private IStudentAssignmentsRepository _studentAssignmentsRepo;
public StudentAssignmentsService(IStudentAssignmentsRepository studentAssignmentsRepository, IMapper mapper)
{
_mapper = mapper;
_studentAssignmentsRepo = studentAssignmentsRepository;
}
public Guid AddStudentAssignment(StudentAssignmentViewModel s)
{
var studentAssignment = _mapper.Map<StudentAssignment>(s);
_studentAssignmentsRepo.AddStudentAssignment(studentAssignment);
return studentAssignment.Id;
}
public StudentAssignmentViewModel GetStudentAssignment(Guid id)
{
var assignment = _studentAssignmentsRepo.GetStudentAssignment(id);
var assignmentModel = _mapper.Map<StudentAssignmentViewModel>(assignment);
return assignmentModel;
}
public IQueryable<StudentAssignmentViewModel> GetStudentAssignmentById(Guid id)
{
var assignments = _studentAssignmentsRepo.GetStudentAssignments().Where(s => s.Student.Id == id).ProjectTo<StudentAssignmentViewModel>(_mapper.ConfigurationProvider); ;
return assignments;
}
public IQueryable<StudentAssignmentViewModel> GetStudentAssignments()
{
var assignments = _studentAssignmentsRepo.GetStudentAssignments().ProjectTo<StudentAssignmentViewModel>(_mapper.ConfigurationProvider);
return assignments;
}
public bool SubmitAssignment(string filePath,string signiture,string publicKey, String privateKey, byte[] Key, byte[] Iv, Guid id)
{
_studentAssignmentsRepo.SubmitAssignment(filePath, signiture, publicKey, privateKey, Key, Iv, id);
return true;
}
}
}
<file_sep>/ShoppingCart.Application/Services/AssignmentsService.cs
using AutoMapper;
using AutoMapper.QueryableExtensions;
using ShoppingCart.Application.Interfaces;
using ShoppingCart.Application.ViewModels;
using ShoppingCart.Domain.Interfaces;
using ShoppingCart.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ShoppingCart.Application.Services
{
public class AssignmentsService : IAssignmentsService
{
private IMapper _mapper;
private IAssignmentsRepository _assignmentsRepo;
public AssignmentsService(IAssignmentsRepository assignmentsRepository, IMapper mapper)
{
_mapper = mapper;
_assignmentsRepo = assignmentsRepository;
}
public Guid AddAssignment(AssignmentViewModel model)
{
var assignment = _mapper.Map<Assignment>(model);
_assignmentsRepo.AddAssignment(assignment);
return assignment.Id;
}
public AssignmentViewModel GetAssignment(Guid id)
{
var assignment = _assignmentsRepo.GetAssignment(id);
var assignmentModel = _mapper.Map<AssignmentViewModel>(assignment);
return assignmentModel;
}
public IQueryable<AssignmentViewModel> GetAssignments()
{
var assignments = _assignmentsRepo.GetAssignments().ProjectTo<AssignmentViewModel>(_mapper.ConfigurationProvider);
return assignments;
}
public IQueryable<AssignmentViewModel> GetAssignmentsByTeacherId(Guid id)
{
var assignments = _assignmentsRepo.GetAssignments().Where(t => t.Teacher.Id == id).ProjectTo<AssignmentViewModel>(_mapper.ConfigurationProvider);
return assignments;
}
}
}
<file_sep>/SecuringApps_WebApplication/Controllers/CommentsController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using ShoppingCart.Application.Interfaces;
using ShoppingCart.Application.ViewModels;
using System;
using WebApplication.ActionFilters;
namespace WebApplication.Controllers
{
public class CommentsController : Controller
{
const string SessionKeyName = "_Id";
private readonly IAssignmentsService _assignmentsService;
private readonly IStudentAssignmentsService _studentAssignmentsService;
private readonly ITeachersService _teachersService;
private readonly IStudentsService _studentsService;
private readonly ICommentsService _commentsService;
private readonly ILogger<CommentsController> _logger;
public CommentsController(ILogger<CommentsController> logger,IAssignmentsService assignmentsService, ITeachersService teachersService,
IStudentsService studentsService, IStudentAssignmentsService studentAssignmentsService, ICommentsService commentsService)
{
_assignmentsService = assignmentsService;
_studentAssignmentsService = studentAssignmentsService;
_teachersService = teachersService;
_studentsService = studentsService;
_commentsService = commentsService;
_logger = logger;
}
// GET: CommentsController
[ActionFilter]
public ActionResult Index( String id)
{
byte[] encoded = Convert.FromBase64String(id);
Guid decId = new Guid(System.Text.Encoding.UTF8.GetString(encoded));
_logger.LogInformation($"User {User.Identity.Name} viewed comment for assignment id= {decId}! at date {DateTime.Now} with ip address {HttpContext.Connection.RemoteIpAddress}");
return View(_commentsService.GetCommentsByAssignmentId(decId));
}
// GET: CommentsController/Create
public ActionResult Create()
{
return View();
}
// POST: CommentsController/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CommentViewModel model)
{
try
{
model.Timestamp = DateTime.Now;
bool isTeacher = User.IsInRole("Teacher");
if (isTeacher)
{
var person = _teachersService.getTeacherByEmail(User.Identity.Name);
model.Teacher = person;
}
else
{
var person = _studentsService.GetStudentByEmail(User.Identity.Name);
model.Student = person;
}
model.StudentAssignment = _studentAssignmentsService.GetStudentAssignment(new Guid(HttpContext.Session.GetString(SessionKeyName)));
_commentsService.AddComment(model);
_logger.LogInformation($"User {User.Identity.Name} created a comment for assignment {model.StudentAssignment.Id}! at date {DateTime.Now} with ip address {HttpContext.Connection.RemoteIpAddress}");
var encoded = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(HttpContext.Session.GetString(SessionKeyName)));
return RedirectToAction("Index",new { id= encoded});
}
catch
{
TempData["error"] = ("Error occured Oooopppsss! We will look into it!");
_logger.LogError($"User {User.Identity.Name} tried to create a comment on assignment {model.StudentAssignment.Id}! at date {DateTime.Now} with ip address {HttpContext.Connection.RemoteIpAddress}");
return RedirectToAction("Error", "Home");
}
}
}
}
<file_sep>/ShoppingCart.Application/ViewModels/AssignmentViewModel.cs
using ShoppingCart.Domain.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace ShoppingCart.Application.ViewModels
{
public class AssignmentViewModel
{
public Guid Id { get; set; }
[Required(ErrorMessage = "Please input the title of the assignment")]
public string Title { get; set; }
[Required(ErrorMessage = "Please input a description describing the assignment")]
public string Description { get; set; }
[Required(ErrorMessage = "Please input the date published")]
public string PublishedDate { get; set; }
[Required(ErrorMessage = "Please input the deadline date")]
public string Deadline { get; set; }
[Required(ErrorMessage = "Please input a Teacher")]
public TeacherViewModel Teacher { get; set; }
}
}
<file_sep>/SecuringApps_WebApplication/Areas/Identity/Pages/Account/Register.cshtml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using SecuringApps_WebApplication.Data;
namespace SecuringApps_WebApplication.Areas.Identity.Pages.Account
{
public class RegisterModel : PageModel
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly UserManager<ApplicationUser> _userManager;
private readonly ILogger<RegisterModel> _logger;
private readonly IEmailSender _emailSender;
public RegisterModel(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
ILogger<RegisterModel> logger,
IEmailSender emailSender)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
_emailSender = emailSender;
}
public string ReturnUrl { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public async Task OnGetAsync(string returnUrl = null)
{
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
}
}
}
<file_sep>/SecuringApps_WebApplication/Areas/Identity/Pages/Account/StudentRegister.cshtml.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using PasswordGenerator;
using SecuringApps_WebApplication.Data;
using ShoppingCart.Application.Interfaces;
using ShoppingCart.Application.ViewModels;
namespace SecuringApps_WebApplication.Areas.Identity.Pages.Account
{
public class StudentRegisterModel : PageModel
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly UserManager<ApplicationUser> _userManager;
private readonly ILogger<StudentRegisterModel> _logger;
private readonly IEmailSender _emailSender;
private readonly ITeachersService _teacherService;
private readonly IStudentsService _studentService;
public StudentRegisterModel(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
ILogger<StudentRegisterModel> logger,
IEmailSender emailSender,
ITeachersService teachersService,
IStudentsService studentsService)
{
_teacherService = teachersService;
_studentService = studentsService;
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
_emailSender = emailSender;
}
[BindProperty]
public InputModel Input { get; set; }
public string ReturnUrl { get; set; }
public class InputModel
{
[Required]
[DataType(DataType.Text)]
[Display(Name = "Name")]
public string Name { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "LastName")]
public string LastName { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
public string Password { get; set; }
[Required]
public string Address { get; set; }
}
public async Task OnGetAsync(string returnUrl = null)
{
ReturnUrl = returnUrl;
}
public static void SendEmail(string server, int port, string emailTo,string _subject,string _message)
{
string to = emailTo;
string from = "<EMAIL>";
string subject = _subject;
string body = _message;
// SMTP Client
SmtpClient smtpClient = new SmtpClient(server, port);
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential(from, "123awsx?");
// Mail Message
MailMessage message = new MailMessage(from, to, subject, body);
// Send Mail
smtpClient.Send(message);
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email,EmailConfirmed = true };
var pwd = new Password();
var passResult = pwd.Next();
Input.Password = <PASSWORD>;
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
//add a role
var roleResult = await _userManager.AddToRoleAsync(user, "Student");
if (!roleResult.Succeeded)
{
ModelState.AddModelError("",
"Error while allocating role!");
}
_logger.LogInformation("User created a new account with password.");
//add student to student's table
StudentViewModel student = new StudentViewModel();
TeacherViewModel teacher = _teacherService.getTeacherByEmail(User.Identity.Name);
student.Id = Guid.Parse(user.Id);
student.Email = Input.Email;
student.FirstName = Input.Name;
student.LastName = Input.LastName;
student.Password = <PASSWORD>;
student.Teacher = teacher;
//add to db
_studentService.AddStudent(student);
//send details to student
string message = "Your email = "+ Input.Email + " and password= "+Input.Password;
SendEmail("smtp.live.com", 587, student.Email, "Student account details", message);
_logger.LogInformation($"User {User.Identity.Name} with ip address { HttpContext.Connection.RemoteIpAddress}" +
$"Created Student account for {Input.Email} at {DateTime.Now}");
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
return Page();
}
}
}
<file_sep>/ShoppingCart.Application/Interfaces/IStudentAssignmentsService.cs
using ShoppingCart.Application.ViewModels;
using ShoppingCart.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ShoppingCart.Application.Interfaces
{
public interface IStudentAssignmentsService
{
Guid AddStudentAssignment(StudentAssignmentViewModel s);
StudentAssignmentViewModel GetStudentAssignment(Guid id);
IQueryable<StudentAssignmentViewModel> GetStudentAssignments();
bool SubmitAssignment(string filePath,string signiture, string publicKey , string privateKey, byte[] key, byte[] iv, Guid id);
IQueryable<StudentAssignmentViewModel> GetStudentAssignmentById(Guid id);
}
}
<file_sep>/ShoppingCart.Application/Services/CommentsService.cs
using AutoMapper;
using AutoMapper.QueryableExtensions;
using ShoppingCart.Application.Interfaces;
using ShoppingCart.Application.ViewModels;
using ShoppingCart.Domain.Interfaces;
using ShoppingCart.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ShoppingCart.Application.Services
{
public class CommentsService : ICommentsService
{
private IMapper _mapper;
private ICommentsRepository _commentsRepo;
public CommentsService(ICommentsRepository commentsRepository, IMapper mapper)
{
_mapper = mapper;
_commentsRepo = commentsRepository;
}
public void AddComment(CommentViewModel model)
{
var comment = _mapper.Map<Comment>(model);
_commentsRepo.AddComment(comment);
}
public CommentViewModel GetComment(Guid id)
{
var comment = _commentsRepo.GetComment(id);
var commentModel = _mapper.Map<CommentViewModel>(comment);
return commentModel;
}
public IQueryable<CommentViewModel> GetComments()
{
var comments = _commentsRepo.GetComments().ProjectTo<CommentViewModel>(_mapper.ConfigurationProvider);
return comments;
}
public IQueryable<CommentViewModel> GetCommentsByAssignmentId(Guid id)
{
var comments = _commentsRepo.GetComments().Where(a => a.StudentAssignment.Id == id).ProjectTo<CommentViewModel>(_mapper.ConfigurationProvider);
return comments;
}
}
}
<file_sep>/SecuringApps_WebApplication/Controllers/AssignmentsController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using ShoppingCart.Application.Interfaces;
using ShoppingCart.Application.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Encodings;
using System.Threading.Tasks;
namespace SecuringApps_WebApplication.Controllers
{
public class AssignmentsController : Controller
{
private readonly IAssignmentsService _assignmentsService;
private readonly IStudentAssignmentsService _studentAssignmentsService;
private readonly ITeachersService _teachersService;
private readonly IStudentsService _studentsService;
private readonly ILogger<AssignmentsController> _logger;
public AssignmentsController(ILogger<AssignmentsController> logger, IAssignmentsService assignmentsService, ITeachersService teachersService, IStudentsService studentsService, IStudentAssignmentsService studentAssignmentsService)
{
_assignmentsService = assignmentsService;
_studentAssignmentsService = studentAssignmentsService;
_teachersService = teachersService;
_studentsService = studentsService;
_logger = logger;
}
// GET: AssignmentsController
[Authorize(Roles = "Teacher")]
public ActionResult Index()
{
var teacher = _teachersService.getTeacherByEmail(User.Identity.Name);
var assignments = _assignmentsService.GetAssignmentsByTeacherId(teacher.Id);
_logger.LogInformation($"User {User.Identity.Name} viewed Teacher {teacher.Email} assignments! at date {DateTime.Now} with ip address {HttpContext.Connection.RemoteIpAddress}");
return View(assignments);
}
// GET: AssignmentsController/Details/5
[Authorize(Roles = "Teacher")]
public ActionResult Details(String id)
{
byte[] encoded = Convert.FromBase64String(id);
Guid decId = new Guid(Encoding.UTF8.GetString(encoded));
var assignment = _assignmentsService.GetAssignment(decId);
_logger.LogInformation($"User {User.Identity.Name} viewed details for assignment id= {assignment.Id}! at date {DateTime.Now} with ip address {HttpContext.Connection.RemoteIpAddress}");
return View(assignment);
}
// GET: AssignmentsController/Create
[Authorize(Roles = "Teacher")]
public ActionResult Create()
{
return View();
}
// POST: AssignmentsController/Create
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Teacher")]
public ActionResult Create(AssignmentViewModel model)
{
try
{
model.Teacher = _teachersService.getTeacherByEmail(User.Identity.Name);
model.Deadline = DateTime.Parse(model.Deadline).ToString("dd/MM/yyyy");
var students = _studentsService.GetStudentsByTeacherId(model.Teacher.Id);
//adding date validation
if (DateTime.Now.Date < DateTime.Parse(model.Deadline).Date)
{
model.PublishedDate = DateTime.Today.ToString("dd/MM/yyyy");
Guid assignmentId = _assignmentsService.AddAssignment(model);
AssignmentViewModel assignment = _assignmentsService.GetAssignment(assignmentId);
//add assignment to the teacher's students
AllocateAssignmentsToStudents(students, assignment);
TempData["feedback"] = "Assignment was added successfully";
_logger.LogInformation($"User {User.Identity.Name} added assignment id= {assignment.Id}! at date {DateTime.Now} with ip address {HttpContext.Connection.RemoteIpAddress}");
}
else
{
TempData["warning"] = "Deadline needs to be after Published Date !";
_logger.LogInformation($"User {User.Identity.Name} attempted to add assignment! at date {DateTime.Now} with ip address {HttpContext.Connection.RemoteIpAddress}");
}
return RedirectToAction(nameof(Index));
}
catch (Exception e)
{
TempData["error"] = ("Error occured Oooopppsss! We will look into it!");
_logger.LogError($"User {User.Identity.Name} attempted to add assignment!! at date {DateTime.Now} with ip address {HttpContext.Connection.RemoteIpAddress} encountered error = {e.Message}");
return RedirectToAction("Error", "Home");
}
}
private void AllocateAssignmentsToStudents(IQueryable<StudentViewModel> students, AssignmentViewModel assignment)
{
IList<StudentViewModel> studentsList = students.ToList();
foreach (var student in studentsList)
{
StudentAssignmentViewModel studentAssignmentViewModel = new StudentAssignmentViewModel();
studentAssignmentViewModel.Assignment = assignment;
studentAssignmentViewModel.File = null;
studentAssignmentViewModel.Student = student;
if (_studentAssignmentsService.AddStudentAssignment(studentAssignmentViewModel) == null)
{
TempData["warning"] = "Assignment was not assigned to the student!";
_logger.LogInformation($"User {User.Identity.Name} attempted to assign assignment to student {student.Id}! at date {DateTime.Now} with ip address {HttpContext.Connection.RemoteIpAddress}");
}
else
{
_logger.LogInformation($"User {User.Identity.Name} assigned assignment to student {student.Id} successfully! at date {DateTime.Now} with ip address {HttpContext.Connection.RemoteIpAddress}");
}
}
}
}
}
<file_sep>/ShoppingCart.Application/ViewModels/CommentViewModel.cs
using ShoppingCart.Domain.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace ShoppingCart.Application.ViewModels
{
public class CommentViewModel
{
public Guid Id { get; set; }
[Required(ErrorMessage = "Please input a comment")]
public string Content { get; set; }
[Required(ErrorMessage = "Please input the timeStamp")]
public DateTime Timestamp { get; set; }
public TeacherViewModel Teacher { get; set; }
public StudentViewModel Student { get; set; }
[Required(ErrorMessage = "Please input a StudentAssignment")]
public StudentAssignmentViewModel StudentAssignment { get; set; }
}
}
<file_sep>/SecuringApps_WebApplication/ActionFilters/ActionFilter.cs
using Castle.Core.Logging;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using ShoppingCart.Application.Interfaces;
using System;
using System.Diagnostics;
namespace WebApplication.ActionFilters
{
public class ActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
try
{
ValidateStudentView(context);
}
catch (Exception example)
{
context.Result = new BadRequestObjectResult("Bad Request = "+example.Message);
}
}
private static void ValidateStudentView(ActionExecutingContext ctxt)
{
byte[] encodedId = Convert.FromBase64String(ctxt.ActionArguments["id"].ToString());
var decodedId = new Guid(System.Text.Encoding.UTF8.GetString(encodedId));
var currentLoggedUser = ctxt.HttpContext.User.Identity.Name;
IStudentAssignmentsService studentsService = (IStudentAssignmentsService)ctxt.HttpContext.RequestServices.GetService(typeof(IStudentAssignmentsService));
var studentAssignment = studentsService.GetStudentAssignment(decodedId);
if (studentAssignment.Student.Email == currentLoggedUser || studentAssignment.Student.Teacher.Email == currentLoggedUser)
{
//log to file
}
else
{ // Log to file
ctxt.Result = new UnauthorizedObjectResult("Access Denied");
}
}
}
}
<file_sep>/ShoppingCart.Application/Services/StudentsService.cs
using AutoMapper;
using AutoMapper.QueryableExtensions;
using ShoppingCart.Application.Interfaces;
using ShoppingCart.Application.ViewModels;
using ShoppingCart.Domain.Interfaces;
using ShoppingCart.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ShoppingCart.Application.Services
{
public class StudentsService : IStudentsService
{
private IMapper _mapper;
private IStudentsRepository _studentsRepo;
public StudentsService(IStudentsRepository studentsRepository, IMapper mapper)
{
_mapper = mapper;
_studentsRepo = studentsRepository;
}
public Guid AddStudent(StudentViewModel s)
{
var student = _mapper.Map<Student>(s);
_studentsRepo.AddStudent(student);
return student.Id;
}
public IQueryable<StudentViewModel> GetStudents()
{
var students = _studentsRepo.GetStudents().ProjectTo<StudentViewModel>(_mapper.ConfigurationProvider);
return students;
}
public IQueryable<StudentViewModel> GetStudentsByTeacherId(Guid id)
{
return _studentsRepo.GetStudentsByTeacher(id).ProjectTo<StudentViewModel>(_mapper.ConfigurationProvider);
}
public StudentViewModel GetStudentByEmail(string email)
{
return _mapper.Map<StudentViewModel>(_studentsRepo.GetStudentByEmail(email));
}
}
}
<file_sep>/ShoppingCart.Application/ViewModels/StudentAssignmentViewModel.cs
using ShoppingCart.Domain.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace ShoppingCart.Application.ViewModels
{
public class StudentAssignmentViewModel
{
public Guid Id { get; set; }
public string File { get; set; }
[Required(ErrorMessage = "Please input the submitted status")]
public bool Submitted { get; set; }
[Required(ErrorMessage = "Please input the student")]
public StudentViewModel Student { get; set; }
[Required(ErrorMessage = "Please input the Assignment")]
public AssignmentViewModel Assignment { get; set; }
public string Signiture { get; set; }
public string PublicKey { get; set; }
public string PrivateKey { get; set; }
public byte[] Key { get; set; }
public byte[] Iv { get; set; }
}
}
<file_sep>/ShoppingCart.Application/ViewModels/TeacherViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace ShoppingCart.Application.ViewModels
{
public class TeacherViewModel
{
public Guid Id { get; set; }
[Required(ErrorMessage = "Please input the email")]
public string Email { get; set; }
[Required(ErrorMessage = "Please input the first name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please input the last name")]
public string LastName { get; set; }
}
}
<file_sep>/SecuringApps_WebApplication/Controllers/StudentsAssignmentsController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ShoppingCart.Application.Interfaces;
using ShoppingCart.Application.ViewModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using Cryptography_SWD62B;
using WebApplication.ActionFilters;
using Microsoft.Extensions.Logging;
namespace WebApplication.Controllers
{
public class StudentsAssignmentsController : Controller
{
const string SessionKeyName = "_Id";
private readonly IAssignmentsService _assignmentsService;
private readonly IStudentAssignmentsService _studentAssignmentsService;
private readonly ITeachersService _teachersService;
private readonly IStudentsService _studentsService;
private IWebHostEnvironment _environment;
private readonly ILogger<StudentsAssignmentsController> _logger;
public StudentsAssignmentsController(ILogger<StudentsAssignmentsController> logger, IAssignmentsService assignmentsService, ITeachersService teachersService, IStudentsService studentsService, IStudentAssignmentsService studentAssignmentsService, IWebHostEnvironment environment)
{
_assignmentsService = assignmentsService;
_studentAssignmentsService = studentAssignmentsService;
_teachersService = teachersService;
_environment = environment;
_studentsService = studentsService;
_logger = logger;
}
[Authorize(Roles = "Student,Teacher")]
public ActionResult Index()
{
string email = User.Identity.Name;
var student = _studentsService.GetStudentByEmail(email);
var assignments = _studentAssignmentsService.GetStudentAssignmentById(student.Id);
_logger.LogInformation($"User {User.Identity.Name} viewed Student {student.Email} assignment! at date {DateTime.Now} with ip address {HttpContext.Connection.RemoteIpAddress}");
return View(assignments);
}
[Authorize(Roles = "Student,Teacher")]
[ActionFilter]
public ActionResult Details(String id)
{
byte[] encoded = Convert.FromBase64String(id);
Guid decId = new Guid(System.Text.Encoding.UTF8.GetString(encoded));
HttpContext.Session.SetString(SessionKeyName, decId.ToString());
var assignment = _studentAssignmentsService.GetStudentAssignment(decId);
_logger.LogInformation($"This User {User.Identity.Name} viewed Student assignment! at date {DateTime.Now} with ip address {HttpContext.Connection.RemoteIpAddress}");
return View(assignment);
}
[Authorize(Roles = "Student,Teacher")]
public ActionResult Submit(String id)
{
byte[] encoded = Convert.FromBase64String(id);
Guid decId = new Guid(System.Text.Encoding.UTF8.GetString(encoded));
return View(_studentAssignmentsService.GetStudentAssignment(decId));
}
private bool checkPdf(Stream stream, String path)
{
bool isValid = true;
IList<StudentAssignmentViewModel> files = _studentAssignmentsService.GetStudentAssignments().Where(f => f.File != path).ToList();
foreach (StudentAssignmentViewModel fileName in files)
{
if (fileName.File != null)
{
var filePath = _environment.ContentRootPath + fileName.File;
byte[] fileLocalBytes = System.IO.File.ReadAllBytes(filePath);
byte[] decryptedKey = CryptographicHelpers.AsymmetricDecrypt(fileName.Key, fileName.PrivateKey);
byte[] decryptedIv = CryptographicHelpers.AsymmetricDecrypt(fileName.Iv, fileName.PrivateKey);
Tuple<byte[], byte[]> decryptedKeys = new Tuple<byte[], byte[]>(decryptedKey, decryptedIv);
byte[] decryptedFile = CryptographicHelpers.SymmetricDecrypt(fileLocalBytes, decryptedKeys);
stream.Position = 0;
int len = decryptedFile.Length;
int counter = 0;
foreach (var b in decryptedFile)
{
if (stream.Length >= stream.Position)
{
if (Byte.Parse(stream.ReadByte().ToString()) == b)
{
counter++;
}
else
{
break;
}
}
if (counter == stream.Length)
{
isValid = !isValid;
}
}
}
}
return isValid;
}
[Authorize(Roles = "Student,Teacher")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Submit(StudentAssignmentViewModel data, IFormFile file)
{
var assignment = _studentAssignmentsService.GetStudentAssignment(data.Id);
var studentAssignment = assignment.Assignment;
try
{
string newFilenameWithAbsolutePath = "";
DateTime deadline = DateTime.Parse(studentAssignment.Deadline);
DateTime now = DateTime.Now.Date;
if (deadline.Date < now)
{
TempData["warning"] = "Assignment was not submitted Deadline date was exceeded !";
_logger.LogInformation($"This User {User.Identity.Name} tried to submit after the deadline was exceeded! at date {DateTime.Now} with ip address {HttpContext.Connection.RemoteIpAddress}");
}
else
{
bool isValid = false;
if (file != null)
{
string extension = System.IO.Path.GetExtension(file.FileName);
if (extension != ".pdf")
{
TempData["warning"] = "Assignment needs to be .pdf !";
}
else
{
if (file.Length > 0)
{
using (var stream = file.OpenReadStream())
{
stream.Position = 0;
//check if it is a genuine pdf
int byte1 = stream.ReadByte();
int byte2 = stream.ReadByte();
//check for pdf
if (byte1 == 37 && byte2 == 80)
{
//get all the submitted files from the db
isValid = true;
}
else
{
TempData["warning"] = "Assignment needs to be .pdf !";
return View();
}
stream.Position = 0;
}
if (isValid)
{
string newFilename = Guid.NewGuid() + extension;
newFilenameWithAbsolutePath = _environment.ContentRootPath + @"\Assignments\" + newFilename;
using (var stream = System.IO.File.Create(newFilenameWithAbsolutePath))
{
//generate keys
var keyPair = CryptographicHelpers.GenerateAsymmetricKeys();
var publicKey = keyPair.Item1;
var privateKey = keyPair.Item2;
data.PublicKey = publicKey;
data.PrivateKey = privateKey;
file.CopyTo(stream);
stream.Position = 0;
//sign the document
string signiture = SignDocument(stream, privateKey);
Tuple<byte[], byte[], byte[]> hybridEncryption = HybridEncrypt(file, publicKey);
data.Signiture = signiture;
data.Key = hybridEncryption.Item2;
data.Iv = hybridEncryption.Item3;
stream.Position = 0;
stream.Write(hybridEncryption.Item1);
stream.Position = 0;
}
data.File = @"\Assignments\" + newFilename;
}
}
}
}
if (isValid)
{
_studentAssignmentsService.SubmitAssignment(data.File, data.Signiture,data.PublicKey, data.PrivateKey, data.Key, data.Iv, data.Id);
TempData["feedback"] = "Assignment was submitted successfully";
}
}
}
catch (Exception e)
{
TempData["warning"] = "Assignment was not submitted !" + e.Message;
_logger.LogError($"Error occurred while trying to submit assignment User {User.Identity.Name} tried to submit assignment at {DateTime.Now} with ip address {HttpContext.Connection.RemoteIpAddress} error message = {e.Message}");
TempData["error"] = ("Error occured Oooopppsss! We will look into it!");
return RedirectToAction("Error", "Home");
}
return View(assignment);
}
private static string SignDocument(FileStream stream, string privateKey)
{
RSA rsa = RSA.Create();
MemoryStream ms = new MemoryStream();
stream.CopyTo(ms);
Byte[] objectArr = ms.ToArray();
string signiture = CryptographicHelpers.CreateSigniture(objectArr, rsa, privateKey);
return signiture;
}
private static Tuple<byte[], byte[], byte[]> HybridEncrypt(IFormFile file, string publicKey)
{
//encrypt file
//stage 1
//encrypt using symetric key on file
MemoryStream fileMs = new MemoryStream();
file.CopyTo(fileMs);
Byte[] fileByte = fileMs.ToArray();
//generate the keys
Tuple<byte[], byte[]> _keyIVPair = CryptographicHelpers.GenerateKeys();
byte[] k = _keyIVPair.Item1;
byte[] iv = _keyIVPair.Item2;
Byte[] encryptedFile = CryptographicHelpers.SymmetricEncrypt(fileByte, _keyIVPair);
//stage 2
//encrypt using asymetric key on signiture and key
byte[] encryptedKey = CryptographicHelpers.AsymetricEncrypt(k, publicKey);
byte[] encryptedIv = CryptographicHelpers.AsymetricEncrypt(iv, publicKey);
return new Tuple<byte[], byte[], byte[]>(encryptedFile, encryptedKey , encryptedIv);
}
[Authorize(Roles = "Student,Teacher")]
[ActionFilter]
public ActionResult Download(String id)
{
byte[] encoded = Convert.FromBase64String(id);
Guid decId = new Guid(System.Text.Encoding.UTF8.GetString(encoded));
//get assignment by id
var assignment = _studentAssignmentsService.GetStudentAssignment(decId);
string path = assignment.File;
string fileName = assignment.Assignment.Title + "/" + assignment.Student.FirstName + " " + assignment.Student.LastName;
var filePath = _environment.ContentRootPath + path;
byte[] fileLocalBytes = System.IO.File.ReadAllBytes(filePath);
//decrypt File
byte[] decryptedKey = CryptographicHelpers.AsymmetricDecrypt(assignment.Key, assignment.PrivateKey);
byte[] decryptedIv = CryptographicHelpers.AsymmetricDecrypt(assignment.Iv, assignment.PrivateKey);
Tuple <byte[], byte[]> decryptedKeys = new Tuple<byte[], byte[]>(decryptedKey, decryptedIv);
byte[] decryptedFile = CryptographicHelpers.SymmetricDecrypt(fileLocalBytes, decryptedKeys);
Stream localFile = new System.IO.MemoryStream(decryptedFile);
using (localFile)
{
RSA rsa = RSA.Create();
//decrypt Signiture
var publicKey = assignment.PublicKey;
bool isValid = CryptographicHelpers.VerifySigniture(decryptedFile,assignment.Signiture, rsa, publicKey);
isValid = checkPdf(localFile, path);
if (!isValid)
{
TempData["warning"] = "Assignment is already uploaded !";
_logger.LogInformation($" User {User.Identity.Name} tried to download an already uploaded assignment! at {DateTime.Now} with ip address {HttpContext.Connection.RemoteIpAddress}");
}
else
{
var ctnt = new System.IO.MemoryStream(decryptedFile);
var type = "application/pdf";
var file = $"{fileName}.pdf";
var fileDownloaded = File(ctnt, type, file);
_logger.LogInformation($" User {User.Identity.Name} downloaded sucessfully the assignment! at {DateTime.Now} with ip address {HttpContext.Connection.RemoteIpAddress}");
return fileDownloaded;
}
}
return RedirectToAction("Details", new { id = id.ToString() });
}
[Authorize(Roles = "Teacher")]
public ActionResult GetAllSubmittedAssignments()
{
_logger.LogInformation($" User {User.Identity.Name} viewed the submitted assignments! at {DateTime.Now} with ip address {HttpContext.Connection.RemoteIpAddress}");
return View(_studentAssignmentsService.GetStudentAssignments());
}
}
}
<file_sep>/ShoppingCart.Application/Interfaces/IStudentsService.cs
using ShoppingCart.Application.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ShoppingCart.Application.Interfaces
{
public interface IStudentsService
{
IQueryable<StudentViewModel> GetStudents();
IQueryable<StudentViewModel> GetStudentsByTeacherId(Guid id);
Guid AddStudent(StudentViewModel s);
StudentViewModel GetStudentByEmail(string email);
}
}
<file_sep>/ShoppingCart.Domain/Interfaces/IStudentAssignmentsRepository.cs
using ShoppingCart.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ShoppingCart.Domain.Interfaces
{
public interface IStudentAssignmentsRepository
{
StudentAssignment GetStudentAssignment(Guid id);
IQueryable<StudentAssignment> GetStudentAssignments();
Guid AddStudentAssignment(StudentAssignment c);
bool SubmitAssignment(String filePath,String signiture,String publicKey,String privateKey, byte[] Key, byte[] Iv, Guid id);
}
}
<file_sep>/ShoppingCart.Application/Services/TeachersService.cs
using AutoMapper;
using AutoMapper.QueryableExtensions;
using ShoppingCart.Application.Interfaces;
using ShoppingCart.Application.ViewModels;
using ShoppingCart.Domain.Interfaces;
using ShoppingCart.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ShoppingCart.Application.Services
{
public class TeachersService : ITeachersService
{
private IMapper _mapper;
private ITeachersRepository _teachersRepo;
public TeachersService(ITeachersRepository teachersRepository, IMapper mapper)
{
_mapper = mapper;
_teachersRepo = teachersRepository;
}
public Guid AddTeacher(TeacherViewModel t)
{
var teacher = _mapper.Map<Teacher>(t);
_teachersRepo.AddTeacher(teacher);
return teacher.Id;
}
public TeacherViewModel getTeacherByEmail(string email)
{
return _mapper.Map<TeacherViewModel>(_teachersRepo.GetTeacherByEmail(email));
}
public IQueryable<TeacherViewModel> GetTeachers()
{
var teachers = _teachersRepo.GetTeachers().ProjectTo<TeacherViewModel>(_mapper.ConfigurationProvider);
return teachers;
}
}
}
<file_sep>/ShoppingCart.Data/Repositories/StudentAssignmentsRepository.cs
using ShoppingCart.Data.Context;
using ShoppingCart.Domain.Interfaces;
using ShoppingCart.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ShoppingCart.Data.Repositories
{
public class StudentAssignmentsRepository : IStudentAssignmentsRepository
{
ShoppingCartDbContext _context;
public StudentAssignmentsRepository(ShoppingCartDbContext context)
{
_context = context;
}
public Guid AddStudentAssignment(StudentAssignment s)
{
s.Assignment = null;
s.Student = null;
_context.StudentAssignments.Add(s);
_context.SaveChanges();
return s.Id;
}
public StudentAssignment GetStudentAssignment(Guid id)
{
return _context.StudentAssignments.SingleOrDefault(s => s.Id == id);
}
public IQueryable<StudentAssignment> GetStudentAssignments()
{
return _context.StudentAssignments;
}
public bool SubmitAssignment(string filePath,string signiture,string publicKey, String privateKey, byte[] Key, byte[] Iv, Guid id)
{
var assignment = GetStudentAssignment(id);
assignment.Iv = Iv;
assignment.Key = Key;
assignment.PrivateKey = privateKey;
assignment.Signiture = signiture;
assignment.PublicKey = publicKey;
assignment.File = filePath;
assignment.Submitted = !assignment.Submitted;
_context.StudentAssignments.Update(assignment);
_context.SaveChanges();
return assignment.Submitted;
}
}
}
| e972101acc53dbb0f739884a5446d847298bcac0 | [
"C#"
] | 19 | C# | Patrick1993G/SecuringApps | 0fb33082a0dbd0ff56e81f28e2e810294b39ad45 | 84e13b763b343e15de9599dde3e84fc36d95c0a6 |
refs/heads/master | <file_sep>#include "ControlsMenu.h"
#include <SimpleAudioEngine.h>
Scene * ControlsMenu::createScene()
{
Scene* scene = ControlsMenu::create();
return scene;
}
bool ControlsMenu::init()
{
if (!Scene::init())
return false;
director = Director::getInstance();
//Setting the default animation rate for the director
director->setAnimationInterval(1.0f / 60.0f);
initUI();
initAnimations();
initMouseListener();
initControllerListener();
initMusic();
scheduleUpdate();
return true;
}
void ControlsMenu::initUI()
{
//set controls list image
controlsList = Sprite::create("Backgrounds/controlsListTest.png");
controlsList->setAnchorPoint(Vec2(0, 0));
controlsList->setPosition(0, 0);
this->addChild(controlsList, 7);
//set our sprite labels
backText = Sprite::create("Text/backTest.png");
backText->setPosition(200, 100);
this->addChild(backText, 10);
//set rects for label hover/click
backRect.setRect(backText->getPositionX() - 200, backText->getPositionY() - 100, 400, 200);
}
void ControlsMenu::initAnimations()
{
}
void ControlsMenu::initMusic()
{
auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
audio->resumeBackgroundMusic();
}
void ControlsMenu::initMouseListener()
{
//Init the mouse listener
mouseListener = EventListenerMouse::create();
//On Mouse Down
mouseListener->onMouseDown = CC_CALLBACK_1(ControlsMenu::mouseDownCallback, this);
//On Mouse Up
mouseListener->onMouseUp = CC_CALLBACK_1(ControlsMenu::mouseUpCallback, this);
//On Mouse Move
mouseListener->onMouseMove = CC_CALLBACK_1(ControlsMenu::mouseMoveCallback, this);
//On Mouse Scroll
mouseListener->onMouseScroll = CC_CALLBACK_1(ControlsMenu::mouseScrollCallback, this);
//Add the mouse listener to the dispatcher
_eventDispatcher->addEventListenerWithSceneGraphPriority(mouseListener, this);
}
void ControlsMenu::initControllerListener()
{
controllerListener = EventListenerController::create();
//set up callbacks
controllerListener->onKeyDown = CC_CALLBACK_3(ControlsMenu::buttonPressCallback, this);
controllerListener->onConnected = [](cocos2d::Controller* controller, cocos2d::Event* evt) {};
//add the controller listener to the dispatcher
_eventDispatcher->addEventListenerWithSceneGraphPriority(controllerListener, this);
}
void ControlsMenu::update(float dt)
{
if (backRect.containsPoint(cursorPos))
backText->setScale(1.2f);
else
backText->setScale(1.0f);
}
//--- Callbacks ---//
void ControlsMenu::mouseDownCallback(Event* event)
{
//Cast the event as a mouse event
EventMouse* mouseEvent = dynamic_cast<EventMouse*>(event);
auto mouseButton = mouseEvent->getMouseButton();
//Get the position of the mouse button press
auto mouseClickPosition = mouseEvent->getLocationInView();
if (mouseButton == cocos2d::EventMouse::MouseButton::BUTTON_LEFT)
{
//go back to previous scene
if (backRect.containsPoint(cursorPos))
{
director->popScene();
}
}
if (mouseButton == cocos2d::EventMouse::MouseButton::BUTTON_RIGHT)
{
}
}
void ControlsMenu::mouseUpCallback(Event* event)
{
}
void ControlsMenu::mouseMoveCallback(Event* event)
{
EventMouse* mouseEvent = dynamic_cast<EventMouse*>(event);
cursorPos = mouseEvent->getLocationInView();
cursorPos.y += 1080;
}
void ControlsMenu::mouseScrollCallback(Event* event)
{
}
void ControlsMenu::buttonPressCallback(Controller * controller, int keyCode, Event * event)
{
if (keyCode == ControllerInput::A || keyCode == ControllerInput::B || keyCode == ControllerInput::Back)
director->popScene();
}
<file_sep>#pragma once
#ifndef INPUTHANDLER_H
#define INPUTHANDLER_H
#include "cocos2d.h"
using namespace cocos2d;
enum InputState
{
Idle,
Pressed,
Released,
Held
};
#define NUM_MOUSE_BUTTONS (int)cocos2d::EventMouse::MouseButton::BUTTON_8 + 2
#define NUM_KEY_CODES (int)cocos2d::EventKeyboard::KeyCode::KEY_PLAY + 1
typedef cocos2d::EventKeyboard::KeyCode KeyCode;
typedef cocos2d::EventMouse::MouseButton MouseButton;
class InputHandler
{
protected:
//--- Constructor ---//
InputHandler(); //Singleton pattern
public:
//--- Destructor ---/
~InputHandler();
//--- Getters ---//
//Mouse
Vec2 getMousePosition() const;
bool getMouseButtonPress(MouseButton button) const;
bool getMouseButtonRelease(MouseButton button) const;
bool getMouseButton(MouseButton button) const;
float getMouseScroll() const;
//Keyboard
bool getKeyPress(KeyCode key) const;
bool getKeyRelease(KeyCode key) const;
bool getKey(KeyCode key) const;
//--- Methods ---//
void initInputs(); //This HAS to be called ONCE. If not, no inputs will ever be read
void updateInputs(); //This HAS to be called EVERY FRAME. If not, the inputs won't be synced to the current frame
//--- Singleton Instance ---//
static InputHandler* getInstance(); //Singleton
private:
//--- Private Data ---//
//Mouse
Vec2 mousePosition;
InputState mouseStates[NUM_MOUSE_BUTTONS]; //States for all of the mouse buttons in cocos2D. +2 since unset is a button as well and is defaulted to -1
//Keyboard
InputState keyboardStates[NUM_KEY_CODES]; //States for all of the keycodes in cocos2D
//--- Singleton Instance ---//
static InputHandler* inst; //Singleton pattern
};
#define INPUTS InputHandler::getInstance()
#endif<file_sep>#pragma once
#ifndef DYINGSTATE_H
#define DYINGSTATE_H
#include "HeroStateBase.h"
class DyingState : public HeroStateBase
{
public:
DyingState();
~DyingState();
void onEnter();
void onExit();
void handleInput(InputType input);
void update(float dt);
};
#endif<file_sep>#include "GrapplingState.h"
#include "Grapple.h"
#include "HeroStateManager.h"
#include "Hero.h"
GrapplingState::GrapplingState()
{
}
GrapplingState::~GrapplingState()
{
}
void GrapplingState::onEnter()
{
HeroStateManager::currentState = this;
Hero::hero->lookState = Grapple::grapple->lookDirectionOnShoot;
if (Hero::hero->lookState == Hero::LookDirection::lookingLeft) //hero should be facing left
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("grapple_left_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::RepeatForever::create(action->clone()));
}
else //hero should be facing right
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("grapple_right_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::RepeatForever::create(action->clone()));
}
}
void GrapplingState::onExit()
{
if (Grapple::grapple->isHeroAtEndPoint)
HeroStateManager::holdingPlatform->onEnter();
else if (!Grapple::grapple->isActive)
HeroStateManager::falling->onEnter();
}
void GrapplingState::handleInput(InputType input)
{
}
void GrapplingState::update(float dt)
{
if (Grapple::grapple->isHeroAtEndPoint || !Grapple::grapple->isActive)
onExit();
}
<file_sep>#pragma once
#ifndef BOSSFIGHT1_H
#define BOSSFIGHT1_H
#include "cocos2d.h"
#include "Vect2.h"
#include "Hero.h"
#include "Platform.h"
#include "Grapple.h"
#include "HeroAttackManager.h"
#include "IceProjectile.h"
#include "HeroMovementBase.h"
#include "PlatformTile.h"
#include "GroundTile.h"
#include "XinputManager.h"
using namespace cocos2d;
class Boss; //forward declare
class Boss1Scene : public cocos2d::Scene
{
public:
CREATE_FUNC(Boss1Scene);
static Scene* createScene();
Boss* boss;
float transitionDelay;
bool isTransitioning;
virtual bool init();
void initUI();
void initGameObjects();
void initSprites();
void initListeners();
void initMouseListener();
void initKeyboardListener();
void initControllerListener();
void initMusic();
void update(float dt);
void spawnEnemies();
void updateObjects(float dt);
void updateEnemies(float dt);
void removeAllObjects();
//mouse callbacks
void mouseDownCallback(Event* event);
void mouseUpCallback(Event* event);
void mouseMoveCallback(Event* event);
void mouseScrollCallback(Event* event);
//keyboard callbacks
void keyDownCallback(EventKeyboard::KeyCode keycode, Event* event);
void keyUpCallback(EventKeyboard::KeyCode keycode, Event* event);
//controller callbacks
void buttonPressCallback(Controller* controller, int keyCode, Event* event);
void buttonReleaseCallback(Controller* controller, int keyCode, Event* event);
void axisEventCallback(Controller* controller, int keyCode, Event* event);
private:
Director* director;
EventListenerMouse* mouseListener;
EventListenerKeyboard* keyboardListener;
EventListenerController* controllerListener;
Vect2 mousePosition;
Sprite* background;
DrawNode* testHurtbox; //for testing hurtbox
DrawNode* testMeleeAttack; //for testing melee attack
};
#endif<file_sep>#include "HitBox.h"
HitBox::HitBox(const cocos2d::Vec2& position, const float& aHeight, const float& aWidth)
: height(aHeight), width(aWidth)
{
updateHitBox(position);
}
void HitBox::updateHitBox(const cocos2d::Vec2& newPosition)
{
//Update hit box
hitBox.setRect(newPosition.x - width / 2, newPosition.y - height / 2, width, height);
}
void HitBox::setNewSize(const float& newWidth, const float& newHeight)
{
width = newWidth;
height = newHeight;
}
<file_sep>#pragma once
#ifndef HERO_H
#define HERO_H
#include "GameObject.h"
#include "Animation.h"
//singleton hero class
class Hero : public GameObject
{
public:
const float JUMP_VELOCITY;
const float MAX_HORIZONTAL_VELOCITY;
const float MAX_VERTICAL_VELOCITY;
const float DRAG_VELOCITY;
static Hero* hero; //single hero instance
void createHero();
cocos2d::Sprite* arm;
float movespeedIncrease;
bool isAirborne;
float invincibilityTimer;
enum LookDirection
{
lookingRight,
lookingLeft
};
LookDirection lookState;
enum MoveDirection
{
idle,
movingRight,
movingLeft
};
MoveDirection moveState;
int health;
bool bypassSpeedCap;
void moveRight();
void moveLeft();
void jump();
void takeDamage(float sourcePositionX, const int& damageTaken = 1);
void reset();
void updateArmPosition();
void updatePositionBasedOnArm();
void checkAndResolveOutOfBounds();
void updatePhysics(float dt) override;
void updateHitboxes() override;
void updateCollisions();
void update(float dt);
private:
Hero();
};
#endif<file_sep>#pragma once
#ifndef ANIMATION_H
#define ANIMATION_H
#include "cocos2d.h"
using namespace cocos2d;
//#include "GameObject.h"
namespace marcos
{
class AnimationManager
{
public:
//Member function
static void init();
static cocos2d::Animate* getAnimation(const std::string& animationKey);
static cocos2d::Animate* getAnimationWithAnimationTime(const std::string& animationKey, const float &animationTime);
private:
static void addAnimation(const std::string fileName, const int a_NumFrames, const float a_Width, const float a_Height,
const std::string& keyName, const float a_Delay = 0.1f);
static void addAnimation(const std::string fileName, const int a_RowFrames, const int a_rows, const float a_Width, const float a_Height,
const std::string& keyName, const float a_Delay = 0.1f);
static void addAnimation(Animation* animationToAdd, const std::string& animationKey);
//Private animation init functions
static void initBossStateAnimation();
static void initBossAttackParticleAnimation();
};
}
#endif<file_sep>#pragma once
#ifndef CONTROLLERINPUT_H
#define CONTROLLERINPUT_H
//I had to make this class because cocos controller key processing SUCKS and controller keycodes being passed around are way different from their enums
class ControllerInput
{
public:
enum Buttons
{
A,
B,
X,
Y,
LeftBumper,
RightBumper,
Back,
Start,
LeftAnalogPress,
RightAnalogPress,
DPadUp,
DPadRight,
DPadDown,
DPadLeft,
A_Release,
B_Release,
X_Release,
Y_Release,
LeftBumper_Release,
RightBumper_Release,
Back_Release,
Start_Release,
LeftAnalog_Release,
RightAnalog_Release,
DPadUp_Release,
DPadDown_Release,
DPadLeft_Release
};
enum Axis
{
leftStickX,
leftStickY,
rightStickX,
rightStickY,
leftTrigger,
rightTrigger
};
static bool isLeftTriggerReset;
static bool isRightTriggerReset;
static bool isLeftStickReset;
static bool isLeftStickIdle;
static bool isControllerUsed;
};
#endif<file_sep>#pragma once
#include "Boss/Ability States/FirstBossState.h"
class ExplosiveBullet4FirstBoss: public FirstBossState
{
public:
//Constructors and Destructor
ExplosiveBullet4FirstBoss(Boss *boss);
};
<file_sep>#include "ExplosiveBullet.h"
#include "Boss/General/Boss.h"
ExplosiveBullet4FirstBoss::ExplosiveBullet4FirstBoss(Boss* boss)
:FirstBossState(boss)
{
//Get the animations ready
const auto startingAnimation = cocos2d::Animate::create
(
cocos2d::AnimationCache::getInstance()->getAnimation("boss_explosive_tell_PRE_animation_key")
);
const auto finishingAnimation = cocos2d::Animate::create
(
cocos2d::AnimationCache::getInstance()->getAnimation("boss_explosive_tell_POST_animation_key")
);
//Play the animation
bossPointer->getSprite()->runAction
(
cocos2d::Sequence::create
(
cocos2d::Repeat::create(startingAnimation, 1),
cocos2d::CallFunc::create([&] {bossPointer->shootExplosiveBullet(); }),
cocos2d::DelayTime::create(0.5),
cocos2d::Repeat::create(finishingAnimation, 1),
cocos2d::CallFunc::create([&] {changeToIdleState(); }),
nullptr
)
);
}
<file_sep>#include "GroundTile.h"
#include "GameObject.h"
#include "Vect2.h"
#include <iostream>
std::vector<GroundTile*> GroundTile::groundTileList = std::vector<GroundTile*>();
GroundTile::GroundTile(cocos2d::Vec2 position, float tileSize)
: TileBase(position, tileSize),
ignoreLeftCollision(false),
ignoreRightCollision(false),
ignoreBottomCollision(false),
ignoreTopCollision(false)
{
type = TileType::ground;
hitBox.setRect(position.x, position.y, tileSize, tileSize - 15); //set the rect of platforms to exclude the top few pixels
groundTileList.push_back(this);
}
bool GroundTile::checkAndResolveCollision(GameObject * otherObject)
{
//first see if there is any collision in the first place
if (!this->checkGeneralCollision(otherObject))
return false;
//there is collision. time to resolve it
else
{
Vect2 overlap;
bool ignoreX = false;
bool ignoreY = false;
//get overlap on x
float leftSideOverlap = abs(otherObject->moveBox.getMaxX() - this->hitBox.getMinX());
float rightSideOverlap = abs(otherObject->moveBox.getMinX() - this->hitBox.getMaxX());
overlap.x = std::min(leftSideOverlap, rightSideOverlap);
//check for ignoring collision on x
if ((otherObject->moveBox.getMidX() > this->hitBox.getMidX() && ignoreRightCollision) || (otherObject->moveBox.getMidX() < this->hitBox.getMidX() && ignoreLeftCollision))
ignoreX = true;
//get overlap on y
float bottomOverlap = abs(otherObject->moveBox.getMaxY() - this->hitBox.getMinY());
float topOverlap = abs(otherObject->moveBox.getMinY() - this->hitBox.getMaxY());
overlap.y = std::min(bottomOverlap, topOverlap);
//check for ignoring collision on y
if ((otherObject->moveBox.getMidY() > this->hitBox.getMidY() && ignoreTopCollision) || (otherObject->moveBox.getMidY() < this->hitBox.getMidY() && ignoreBottomCollision))
ignoreY = true;
if (overlap.y < overlap.x && !ignoreY) //overlap on y is more shallow, so we want to push the y back or if the object is at the top of the tile
{
if (bottomOverlap < topOverlap) //bottom is the shallow collision side
{
otherObject->sprite->setPositionY(otherObject->getPosition().y - overlap.y);
otherObject->velocity.y = 0; //reset velocity after collision
}
else if (otherObject->velocity.y <= 0) //top side is the shallow collision side
{
otherObject->sprite->setPositionY(this->hitBox.getMaxY() + (otherObject->moveBox.size.height / 2));
otherObject->velocity.y = 0; //reset velocity after collision
}
}
else if (!ignoreX) //overlap on x is more shallow, so we want to push the x back
{
if (leftSideOverlap < rightSideOverlap) //left is the shallow collision side
otherObject->sprite->setPositionX(this->hitBox.getMinX() - (otherObject->moveBox.size.width / 2) - 1);
else //right side is the shallow collision side
otherObject->sprite->setPositionX(this->hitBox.getMaxX() + (otherObject->moveBox.size.width / 2));
//otherObject->sprite->setPositionX(otherObject->lastFramePosition.x); //push the object back to its x position last frame
otherObject->velocity.x = 0; //reset velocity after collision
}
return true; //because a collision happened (and we resolved it)
}
}
<file_sep>#pragma once
#include "HeroMovementBase.h"
class HeroMoveLeft : public HeroMovementBase
{
public:
HeroMoveLeft();
void init();
void update(float dt);
};<file_sep>#pragma once
#ifndef HEROATTACKMANAGER_H
#define HEROATTACKMANAGER_H
#include "EmptyAttack.h"
#include "MeleeFireAttack.h"
#include "ProjectileIceAttack.h"
enum HeroAttackTypes
{
emptyA,
meleeFireA,
projectileIceA
};
class HeroAttackManager
{
public:
static EmptyAttack* empty;
static MeleeFireAttack* meleeFire;
static ProjectileIceAttack* projectileIce;
static HeroAttackBase* currentAttack;
static void setCurrentAttack(HeroAttackTypes attackType, cocos2d::Scene* scene);
static void update(float dt);
};
#endif<file_sep>#include "GrappleJumpState.h"
#include "Grapple.h"
#include "Hero.h"
#include "HeroStateManager.h"
GrappleJumpState::GrappleJumpState()
{
}
GrappleJumpState::~GrappleJumpState()
{
}
void GrappleJumpState::onEnter()
{
HeroStateManager::currentState = this;
Grapple::grapple->unLatch();
Hero::hero->jump();
HeroStateManager::currentState = this;
if (Hero::hero->lookState == Hero::LookDirection::lookingLeft)
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("grapple_jump_left_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::Repeat::create(action->clone(), 1));
}
else //looking right
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("grapple_jump_right_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::Repeat::create(action->clone(), 1));
}
}
void GrappleJumpState::onExit()
{
if (Hero::hero->velocity.y < 0)
HeroStateManager::falling->onEnter();
else if (Hero::hero->velocity.y == 0)
HeroStateManager::idle->onEnter();
}
void GrappleJumpState::handleInput(InputType input)
{
switch (input)
{
}
}
void GrappleJumpState::update(float dt)
{
if (Hero::hero->moveState == Hero::MoveDirection::movingLeft)
Hero::hero->moveLeft();
else if (Hero::hero->moveState == Hero::MoveDirection::movingRight)
Hero::hero->moveRight();
if (Hero::hero->velocity.y <= 0)
onExit();
}
<file_sep>#pragma once
#ifndef MAINMENU_H
#define MAINMENU_H
#include "cocos2d.h";
#include "ControllerInput.h"
using namespace cocos2d;
class MainMenu : public cocos2d::Scene
{
public:
enum MenuOptions
{
nothing,
start,
controls,
exit
};
CREATE_FUNC(MainMenu);
static Scene* createScene();
bool init();
void initUI();
void initAnimations();
void initMusic();
void initMouseListener();
void initControllerListener();
void moveToNextMenuItem();
void moveToPreviousMenuItem();
void update(float dt);
void transitionScene();
//Callbacks
void mouseDownCallback(Event* event);
void mouseUpCallback(Event* event);
void mouseMoveCallback(Event* event);
void mouseScrollCallback(Event* event);
//controller callbacks
void buttonPressCallback(Controller* controller, int keyCode, Event* event);
void buttonReleaseCallback(Controller* controller, int keyCode, Event* event);
void axisEventCallback(Controller* controller, int keyCode, Event* event);
private:
MenuOptions currentSelection;
Director* director;
EventListenerMouse* mouseListener;
EventListenerController* controllerListener;
Vec2 cursorPos;
Sprite* Logo;
Sprite* startText;
Sprite* controlsText;
Sprite* exitText;
Rect startRect;
Rect controlsRect;
Rect exitRect;
bool isTransitioning;
};
#endif<file_sep>#include "Tutorial.h"
#include "Boss1Scene.h"
#include "PrettyPictureScene.h"
#include <iostream>
#include "HeroStateManager.h"
#include "PauseMenu.h"
#include "HelpBubble.h"
#include "ControllerInput.h"
#include "SpikeTile.h"
#include "DeathScreen.h"
#include "Hud.h"
#include <SimpleAudioEngine.h>
cocos2d::Scene* Tutorial::createScene()
{
Scene* scene = Tutorial::create();
return scene;
}
bool Tutorial::init()
{
if (!Scene::init())
return false;
ControllerInput::isControllerUsed = false;
isTransitioning = false;
srand(time(NULL)); //seed rng
director = Director::getInstance();
//Setting the default animation rate for the director
director->setAnimationInterval(1.0f / 60.0f);
initUI();
initGameObjects();
initSprites();
initListeners();
initMusic();
//Init music
auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
audio->playBackgroundMusic("wonderPlace.wav");
scheduleUpdate();
return true;
}
//initializes the user interface
void Tutorial::initUI()
{
//initialize help bubbles
HelpBubble* jumpHint = new HelpBubble("HintBubbles/jumpHint.png", cocos2d::Vec2(300, 300), 200, 500);
jumpHint->sprite->setScale(1.2);
this->addChild(jumpHint->sprite, 18);
HelpBubble* holdJumpHint = new HelpBubble("HintBubbles/holdJumpHint.png", cocos2d::Vec2(2125, 450), 1950, 2300);
holdJumpHint->sprite->setScale(1.2);
this->addChild(holdJumpHint->sprite, 18);
HelpBubble* grapplingHint = new HelpBubble("HintBubbles/grapplingHint.png", cocos2d::Vec2(3900, 375), 3690, 4050);
grapplingHint->sprite->setScale(1.2);
this->addChild(grapplingHint->sprite, 18);
HelpBubble* attackHint = new HelpBubble("HintBubbles/attackHint.png", cocos2d::Vec2(4650, 740), 4400, 4800);
attackHint->sprite->setScale(1.2);
this->addChild(attackHint->sprite, 18);
HelpBubble* dropHint = new HelpBubble("HintBubbles/dropHint.png", cocos2d::Vec2(5975, 875), 5600, 6200);
dropHint->sprite->setScale(1.2);
this->addChild(dropHint->sprite, 18);
}
void Tutorial::initGameObjects()
{
//set bounds for the scene
GameObject::MAX_X = 15000.0f;
GameObject::MAX_Y = 1080.0f;
}
void Tutorial::initSprites()
{
Vec2 origin = Director::sharedDirector()->getVisibleOrigin(); //origin point
Size size = Director::sharedDirector()->getVisibleSize(); //screen size
Vec2 center = Vec2(size.width / 2 + origin.x, size.height / 2 + origin.y); //center point
fieldWidth = 13888; //x boundary for camera
fieldHeight = size.height - 40; //y boundary for camera
Texture2D::TexParams params;
params.minFilter = GL_NEAREST;
params.magFilter = GL_NEAREST;
params.wrapS = GL_REPEAT;
params.wrapT = GL_REPEAT;
//add background layers
backgroundL1 = Sprite::create("Backgrounds/tutBackground_L1.png");
backgroundL1->setAnchorPoint(Vec2(0.0f, 0.0f));
backgroundL1->getTexture()->setTexParameters(params);
backgroundL1->setTextureRect(cocos2d::Rect(0, 0, fieldWidth, fieldHeight));
backgroundL2 = Sprite::create("Backgrounds/tutBackground_L2.png");
backgroundL2->setAnchorPoint(Vec2(0.0f, 0.0f));
backgroundL2->getTexture()->setTexParameters(params);
backgroundL2->setTextureRect(cocos2d::Rect(0, 0, fieldWidth, fieldHeight));
backgroundL3 = Sprite::create("Backgrounds/tutBackground_L3.png");
backgroundL3->setAnchorPoint(Vec2(0.0f, 0.0f));
backgroundL3->getTexture()->setTexParameters(params);
backgroundL3->setTextureRect(cocos2d::Rect(0, 0, fieldWidth, fieldHeight));
backgroundL4 = Sprite::create("Backgrounds/tutBackground_L4.png");
backgroundL4->setAnchorPoint(Vec2(0.0f, 0.0f));
backgroundL4->getTexture()->setTexParameters(params);
backgroundL4->setTextureRect(cocos2d::Rect(0, 0, fieldWidth, fieldHeight));
backgroundL5 = Sprite::create("Backgrounds/tutBackground_L5.png");
backgroundL5->setAnchorPoint(Vec2(0.0f, 0.0f));
backgroundL5->getTexture()->setTexParameters(params);
backgroundL5->setTextureRect(cocos2d::Rect(0, 0, fieldWidth, fieldHeight));
backgroundL6 = Sprite::create("Backgrounds/tutBackground_L6.png");
backgroundL6->setAnchorPoint(Vec2(0.0f, 0.0f));
backgroundL6->getTexture()->setTexParameters(params);
backgroundL6->setTextureRect(cocos2d::Rect(0, 0, fieldWidth, fieldHeight));
backgroundL7 = Sprite::create("Backgrounds/tutBackground_L7.png");
backgroundL7->setAnchorPoint(Vec2(0.0f, 0.0f));
backgroundL7->getTexture()->setTexParameters(params);
backgroundL7->setTextureRect(cocos2d::Rect(0, 0, fieldWidth, fieldHeight));
backgroundL8 = Sprite::create("Backgrounds/tutBackground_L8.png");
backgroundL8->setAnchorPoint(Vec2(0.0f, 0.0f));
backgroundL8->getTexture()->setTexParameters(params);
backgroundL8->setTextureRect(cocos2d::Rect(0, 0, fieldWidth, fieldHeight));
backgroundL9 = Sprite::create("Backgrounds/tutBackground_L9.png");
backgroundL9->setAnchorPoint(Vec2(0.0f, 0.0f));
backgroundL9->getTexture()->setTexParameters(params);
backgroundL9->setTextureRect(cocos2d::Rect(0, 0, fieldWidth, fieldHeight));
backgroundL10 = Sprite::create("Backgrounds/tutBackground_L10.png");
backgroundL10->setAnchorPoint(Vec2(0.0f, 0.0f));
backgroundL10->getTexture()->setTexParameters(params);
backgroundL10->setTextureRect(cocos2d::Rect(0, 0, fieldWidth, fieldHeight));
foregroundL1 = Sprite::create("Backgrounds/foreground1.png");
foregroundL1->setAnchorPoint(Vec2(0.0f, 0.0f));
foregroundL1->getTexture()->setTexParameters(params);
foregroundL1->setTextureRect(cocos2d::Rect(0, -464, fieldWidth, 2048));
foregroundL2 = Sprite::create("Backgrounds/foreground2.png");
foregroundL2->setAnchorPoint(Vec2(0.0f, 0.0f));
foregroundL2->getTexture()->setTexParameters(params);
foregroundL2->setTextureRect(cocos2d::Rect(0, -464, fieldWidth, 2048));
//create parallax node for background layers
ParallaxNode* backGroundParallax = ParallaxNode::create();
ParallaxNode* foregroundParallax = ParallaxNode::create();
//add background layers to the parallax node with various scrolling speeds, push them all up a bit by using the offset
backGroundParallax->addChild(backgroundL1, -20, Vec2(0.05, 0.05), Vec2(0, 100));
backGroundParallax->addChild(backgroundL2, -19, Vec2(0.1, 0.1), Vec2(0, 100));
backGroundParallax->addChild(backgroundL3, -18, Vec2(0.14, 0.14), Vec2(0, 100));
backGroundParallax->addChild(backgroundL4, -17, Vec2(0.32, 0.32), Vec2(0, 100));
backGroundParallax->addChild(backgroundL5, -16, Vec2(0.41, 0.41), Vec2(0, 100));
backGroundParallax->addChild(backgroundL6, -15, Vec2(0.54, 0.54), Vec2(0, 100));
backGroundParallax->addChild(backgroundL7, -14, Vec2(0.71, 0.71), Vec2(0, 100));
backGroundParallax->addChild(backgroundL8, -13, Vec2(0.85, 0.85), Vec2(0, 100));
backGroundParallax->addChild(backgroundL9, -12, Vec2(0.91, 0.91), Vec2(0, 100));
backGroundParallax->addChild(backgroundL10, -12, Vec2(0.91, 0.91), Vec2(0, 100));
foregroundParallax->addChild(foregroundL1, 91, Vec2(1.3, 1.3), Vec2(0, 00)); //foreground 1
foregroundParallax->addChild(foregroundL2, 90, Vec2(1.1, 1.1), Vec2(0, 00)); //foreground 2
this->addChild(backGroundParallax, -5);
this->addChild(foregroundParallax, 90);
//delete any existing tiles before we import our map
TileBase::deleteAllTiles();
//get the tilemap in
cocos2d::TMXTiledMap* testTileMap = TMXTiledMap::create("Tilemaps/Final.tmx"); //ayy it works
addChild(testTileMap, 1);
cocos2d::TMXLayer* groundLayer = testTileMap->getLayer("Ground");
cocos2d::TMXLayer* platformLayer = testTileMap->getLayer("platforms");
cocos2d::TMXLayer* spikeLayer = testTileMap->getLayer("spikes");
unsigned int tileMapWidth = testTileMap->getMapSize().width; //map width
unsigned int tileMapHeight = testTileMap->getMapSize().height; //map height
for (unsigned int x = 0; x < tileMapWidth; x++) //width of map grid
{
for (unsigned int y = 0; y < tileMapHeight; y++) //height of map grid
{
//check for ground tile
cocos2d::Sprite* currentTile = groundLayer->getTileAt(Vec2(x, y));
if (currentTile != NULL)
{
GroundTile* newGroundTile = new GroundTile(currentTile->getPosition(), 64);
//set collision flags if there are adjacent ground tiles
//we have to do our own x and y validation because cocos sucks and crashes otherwise
if (x != 0)
{
if (groundLayer->getTileAt(Vec2(x - 1, y)) != NULL)
newGroundTile->ignoreLeftCollision = true;
}
if (x != tileMapWidth - 1)
{
if (groundLayer->getTileAt(Vec2(x + 1, y)) != NULL)
newGroundTile->ignoreRightCollision = true;
}
if (y != 0)
{
if (groundLayer->getTileAt(Vec2(x, y - 1)) != NULL)
newGroundTile->ignoreTopCollision = true;
}
if (y != tileMapHeight - 1)
{
if (groundLayer->getTileAt(Vec2(x, y + 1)) != NULL)
newGroundTile->ignoreBottomCollision = true;
}
}
//check for platform tile
currentTile = platformLayer->getTileAt(Vec2(x, y));
if (currentTile != NULL)
PlatformTile* newPlatformTile = new PlatformTile(currentTile->getPosition(), 64);
//check for spike tile
currentTile = spikeLayer->getTileAt(Vec2(x, y));
if (currentTile != NULL)
SpikeTile* newSpikeTile = new SpikeTile(currentTile->getPosition(), 64);
}
}
//add hero (singleton class)
Hero::hero->sprite = Sprite::create("Sprites/shooting_test.png");
this->addChild(Hero::hero->sprite, 20);
Hero::hero->sprite->setPosition(Vec2(20, 200));
Hero::hero->lookState = Hero::LookDirection::lookingRight;
HeroStateManager::idle->onEnter();
//use a follow camera with strict dimensions for horizontal scrolling
this->runAction(Follow::create(Hero::hero->sprite, Rect(0, 50, fieldWidth, fieldHeight)));
Hero::hero->arm = cocos2d::Sprite::create("Sprites/armV2.png");
Hero::hero->arm->setVisible(0); //make arm invisible to begin with
Hero::hero->arm->setAnchorPoint(Vec2(0.5f, 0.0f));
this->addChild(Hero::hero->arm, 21); //add hero arm
//add grapple sprite
//add repeating pattern to grapple sprite
Grapple::grapple->sprite = Sprite::create("Sprites/grapple.png");
Grapple::grapple->sprite->getTexture()->setTexParameters(params);
Grapple::grapple->sprite->setVisible(0);
Grapple::grapple->sprite->setAnchorPoint(Vec2(0.5, 0));
this->addChild(Grapple::grapple->sprite, 5);
//grapple tip sprite
Grapple::grapple->tip = Sprite::create("Sprites/grappleTip.png");
//Grapple::grapple->tip->setAnchorPoint(Vec2(0.5, 0));
this->addChild(Grapple::grapple->tip, 7);
//grapple destination indicator
Grapple::grapple->indicator = Sprite::create("Sprites/grappleIndicator.png");
Grapple::grapple->indicator->setVisible(0);
this->addChild(Grapple::grapple->indicator, 6);
}
void Tutorial::initListeners()
{
//Init the mouse listener
initMouseListener();
//Init the keyboard listener
initKeyboardListener();
//init controller listener
initControllerListener();
}
void Tutorial::initMouseListener()
{
//Init the mouse listener
mouseListener = EventListenerMouse::create();
//On Mouse Down
mouseListener->onMouseDown = CC_CALLBACK_1(Tutorial::mouseDownCallback, this);
//On Mouse Up
mouseListener->onMouseUp = CC_CALLBACK_1(Tutorial::mouseUpCallback, this);
//On Mouse Move
mouseListener->onMouseMove = CC_CALLBACK_1(Tutorial::mouseMoveCallback, this);
//On Mouse Scroll
mouseListener->onMouseScroll = CC_CALLBACK_1(Tutorial::mouseScrollCallback, this);
//Add the mouse listener to the dispatcher
_eventDispatcher->addEventListenerWithSceneGraphPriority(mouseListener, this);
}
void Tutorial::initKeyboardListener()
{
//Create the keyboard listener
keyboardListener = EventListenerKeyboard::create();
//Setting up callbacks
keyboardListener->onKeyPressed = CC_CALLBACK_2(Tutorial::keyDownCallback, this);
keyboardListener->onKeyReleased = CC_CALLBACK_2(Tutorial::keyUpCallback, this);
//add the keyboard listener to the dispatcher
_eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardListener, this);
}
void Tutorial::initControllerListener()
{
controllerListener = EventListenerController::create();
//set up callbacks
controllerListener->onKeyDown = CC_CALLBACK_3(Tutorial::buttonPressCallback, this);
controllerListener->onKeyUp = CC_CALLBACK_3(Tutorial::buttonReleaseCallback, this);
controllerListener->onAxisEvent = CC_CALLBACK_3(Tutorial::axisEventCallback, this);
controllerListener->onConnected = [](cocos2d::Controller* controller, cocos2d::Event* evt) {};
//add the controller listener to the dispatcher
_eventDispatcher->addEventListenerWithSceneGraphPriority(controllerListener, this);
}
void Tutorial::initMusic()
{
auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
audio->resumeBackgroundMusic();
}
//UPDATE
void Tutorial::update(float dt)
{
if (!isTransitioning)
{
Grapple::grapple->update(dt, this); //update grapple
Hero::hero->update(dt); //update our hero
spawnEnemies(); //spawn enemies if needed
updateObjects(dt); //update objects
updateEnemies(dt); //update enemies
//check if we should move to the next scene
if (Hero::hero->moveBox.getMaxX() >= 13888)
{
Hero::hero->reset();
Hero::hero->lookState = Hero::LookDirection::lookingRight; //make sure they're looking right (over the clif)
HelpBubble::deleteAllInstances();
director->replaceScene(TransitionFade::create(1.5f, PrettyPictureScene::createScene(), Color3B(0, 0, 0)));
isTransitioning = true;
}
else if (Hero::hero->health == 0) //check for ded
{
Hero::hero->reset(); //reset hero
HelpBubble::deleteAllInstances();
director->replaceScene(TransitionFade::create(2.0f, DeathScreen::createScene(), Color3B(0, 0, 0)));
isTransitioning = true;
}
}
else //we are transitioning
{
//move hero down to the nearest block so they arent floating
Hero::hero->velocity.y = -400;
Hero::hero->updatePhysics(dt);
unsigned int tileListSize = TileBase::tileList.size();
for (unsigned int i = 0; i < tileListSize; i++)
{
if (TileBase::tileList[i]->checkAndResolveCollision(Hero::hero))
HeroStateManager::idle->onEnter();
}
}
}
void Tutorial::spawnEnemies()
{
//spawns all enemies to keep a certain amount of each in the map
}
void Tutorial::updateObjects(float dt)
{
//update all platforms
unsigned int numPlatforms = Platform::platformList.size();
for (unsigned int i = 0; i < numPlatforms; i++)
Platform::platformList[i]->update();
//update all ice projectiles
for (unsigned int i = 0; i < IceProjectile::iceProjectileList.size(); i++)
IceProjectile::iceProjectileList[i]->update(dt);
//update all help bubbles
unsigned int numHelpBubbles = HelpBubble::helpBubbleList.size();
for (unsigned int i = 0; i < numHelpBubbles; i++)
HelpBubble::helpBubbleList[i]->update(dt);
//update UI
for (unsigned int i = 0; i < HudObject::HudList.size(); i++)
{
HudObject::HudList[i]->update(dt);
}
}
void Tutorial::updateEnemies(float dt)
{
}
//removes all game objects from the world
void Tutorial::removeAllObjects()
{
}
//--- Callbacks ---//
void Tutorial::mouseDownCallback(Event* event)
{
//Cast the event as a mouse event
EventMouse* mouseEvent = dynamic_cast<EventMouse*>(event);
auto mouseButton = mouseEvent->getMouseButton();
if (mouseButton == cocos2d::EventMouse::MouseButton::BUTTON_LEFT)
{
HeroAttackManager::setCurrentAttack(HeroAttackTypes::meleeFireA, nullptr); //can pass a nullptr because we dont need to add anything to the scene for melee attacks
}
if (mouseButton == cocos2d::EventMouse::MouseButton::BUTTON_RIGHT)
{
//Get the position of the mouse button press
auto mouseClickPosition = mouseEvent->getLocationInView();
mouseClickPosition.y += 1080;
auto mouseGameViewPosition = mouseClickPosition;
mouseGameViewPosition.y += 45;
//calculate proper x position for grapple
if (Hero::hero->getPosition().x > (fieldWidth - (1920 / 2)))
{
mouseGameViewPosition.x -= 1920 / 2; //update if screen size changes
mouseGameViewPosition.x += (fieldWidth - (1920 / 2));
}
else if (Hero::hero->getPosition().x > 1920/2)
{
//do some simple math to convert mouse click position on screen to in-game world position
mouseGameViewPosition.x -= 1920 / 2; //update if screen size changes
mouseGameViewPosition.x += Hero::hero->sprite->getPosition().x;
}
Grapple::grapple->shoot(Vect2(mouseGameViewPosition)); //shoot the grapple
}
}
void Tutorial::mouseUpCallback(Event* event)
{
}
void Tutorial::mouseMoveCallback(Event* event)
{
}
void Tutorial::mouseScrollCallback(Event* event)
{
}
void Tutorial::keyDownCallback(EventKeyboard::KeyCode keyCode, Event* event)
{
switch (keyCode)
{
case EventKeyboard::KeyCode::KEY_A:
HeroStateManager::currentState->handleInput(InputType::p_a);
Hero::hero->lookState = Hero::LookDirection::lookingLeft;
Hero::hero->moveState = Hero::MoveDirection::movingLeft;
break;
case EventKeyboard::KeyCode::KEY_D:
HeroStateManager::currentState->handleInput(InputType::p_d);
Hero::hero->lookState = Hero::LookDirection::lookingRight;
Hero::hero->moveState = Hero::MoveDirection::movingRight;
break;
case EventKeyboard::KeyCode::KEY_W:
HeroAttackBase::isWKeyHeld = true;
break;
case EventKeyboard::KeyCode::KEY_S:
HeroStateManager::currentState->handleInput(InputType::p_s);
//HeroAttackBase::isSKeyHeld = true;
break;
case EventKeyboard::KeyCode::KEY_SPACE:
HeroStateManager::currentState->handleInput(InputType::p_space);
break;
case EventKeyboard::KeyCode::KEY_E:
//HeroAttackManager::setCurrentAttack(HeroAttackTypes::projectileIceA, this);
break;
case EventKeyboard::KeyCode::KEY_ESCAPE:
director->pushScene(PauseMenu::createScene());
}
}
void Tutorial::keyUpCallback(EventKeyboard::KeyCode keyCode, Event* event)
{
switch (keyCode)
{
case EventKeyboard::KeyCode::KEY_A:
//make sure the hero is moving in this direction before we decide if they are now idle
if (Hero::hero->moveState == Hero::MoveDirection::movingLeft)
Hero::hero->moveState = Hero::MoveDirection::idle;
break;
case EventKeyboard::KeyCode::KEY_D:
//make sure the hero is moving in this direction before we decide if they are now idle
if (Hero::hero->moveState == Hero::MoveDirection::movingRight)
Hero::hero->moveState = Hero::MoveDirection::idle;
break;
case EventKeyboard::KeyCode::KEY_W:
HeroAttackBase::isWKeyHeld = false;
break;
case EventKeyboard::KeyCode::KEY_SPACE:
HeroStateManager::currentState->handleInput(InputType::r_space);
break;
}
}
void Tutorial::buttonPressCallback(Controller * controller, int keyCode, Event * event)
{
switch (keyCode)
{
case ControllerInput::A:
HeroStateManager::currentState->handleInput(InputType::p_space);
break;
case ControllerInput::Start:
director->pushScene(PauseMenu::createScene());
break;
}
}
void Tutorial::buttonReleaseCallback(Controller * controller, int keyCode, Event * event)
{
switch (keyCode)
{
case ControllerInput::A:
HeroStateManager::currentState->handleInput(InputType::r_space);
break;
}
}
void Tutorial::axisEventCallback(Controller * controller, int keyCode, Event * event)
{
switch (keyCode)
{
//x axis of the left stick
case ControllerInput::leftStickX:
//moving to the left
if (controller->getKeyStatus(keyCode).value <= -1)
{
ControllerInput::isLeftStickIdle = false;
ControllerInput::isControllerUsed = true; //controller has been used this playthrough
HeroStateManager::currentState->handleInput(InputType::p_a);
Hero::hero->lookState = Hero::LookDirection::lookingLeft;
Hero::hero->moveState = Hero::MoveDirection::movingLeft;
}
//moving to the right
else if (controller->getKeyStatus(keyCode).value >= 1)
{
ControllerInput::isLeftStickIdle = false;
ControllerInput::isControllerUsed = true; //controller has been used this playthrough
HeroStateManager::currentState->handleInput(InputType::p_d);
Hero::hero->lookState = Hero::LookDirection::lookingRight;
Hero::hero->moveState = Hero::MoveDirection::movingRight;
}
else if (!ControllerInput::isLeftStickIdle) //not moving AND left stick isn't at rest
{
Hero::hero->moveState = Hero::MoveDirection::idle;
ControllerInput::isLeftStickIdle = true;
}
break;
//y axis of the left stick
case ControllerInput::leftStickY:
if (controller->getKeyStatus(keyCode).value >= 1)
HeroAttackBase::isWKeyHeld = true;
else
{
HeroAttackBase::isWKeyHeld = false;
if (controller->getKeyStatus(keyCode).value <= -1)
HeroStateManager::currentState->handleInput(InputType::p_s);
}
break;
case ControllerInput::leftTrigger:
//check for attack
if (controller->getKeyStatus(keyCode).value >= 1 && ControllerInput::isLeftTriggerReset)
{
ControllerInput::isLeftTriggerReset = false;
HeroAttackManager::setCurrentAttack(HeroAttackTypes::meleeFireA, nullptr); //can pass a nullptr because we dont need to add anything to the scene for melee attacks
}
else if (controller->getKeyStatus(keyCode).value <= -1)
ControllerInput::isLeftTriggerReset = true;
break;
case ControllerInput::rightTrigger:
if (controller->getKeyStatus(keyCode).value >= 1 && ControllerInput::isRightTriggerReset)
{
ControllerInput::isRightTriggerReset = false;
//use xinput stuff to get a more accurate reading on the stick input than cocos' controller support
XinputManager::instance->update();
XinputController* controller1 = XinputManager::instance->getController(0);
Stick sticks[2];
controller1->getSticks(sticks);
//calculate angle (in radians) using atan2 with the right stick's y and x values
float grappleAngle = atan2(sticks[RS].x, sticks[RS].y);
//check if right stick is at rest (account for reading being slightly off or controller not being perfectly calibrated)
if (sticks[RS].x < 0.3 && sticks[RS].x > -0.3 && sticks[RS].y <= 0.3f && sticks[RS].y > -0.3f)
{
//calculate angle (in radians) using atan2 with the right stick's y and x values
grappleAngle = atan2(0.0f, 0.0f);
}
Grapple::grapple->shoot(grappleAngle); //shoot grapple
}
else if (controller->getKeyStatus(keyCode).value <= -1)
ControllerInput::isRightTriggerReset = true;
break;
}
}<file_sep>#include "Hud.h"
#include "Hero.h"
std::vector<HudObject*> HudObject::HudList = std::vector<HudObject*>();
HudObject::~HudObject()
{
}
void HudObject::deleteAllInstances()
{
HudList.clear();
}
HudObject::HudObject(std::string filePath, cocos2d::Vec2 position)
{
//set up sprite
sprite = cocos2d::Sprite::create(filePath);
sprite->setPosition(position);
HudList.push_back(this); //add to list
}
void HudObject::update(float dt)
{
if (HudList.size() > 0)
{
if (Hero::hero->health < HudList.size())
{
HudList[Hero::hero->health]->sprite->setVisible(0);
HudList.erase(HudList.begin() + Hero::hero->health);
}
}
else if (Hero::hero->health <= 0)
{
HudList[0]->sprite->setVisible(0);
HudList.erase(HudList.begin());
}
}<file_sep>#include "Boss1Scene.h"
#include "PauseMenu.h"
#include <iostream>
#include "HeroStateManager.h"
#include "Boss/General/Boss.h"
#include "XinputManager.h"
#include "DeathScreen.h"
#include "VictoryScreen.h"
#include "Boss/Attacks/Projectiles.h"
#include "Hud.h"
#include <SimpleAudioEngine.h>
cocos2d::Scene* Boss1Scene::createScene()
{
Scene* scene = Boss1Scene::create();
return scene;
}
bool Boss1Scene::init()
{
if (!Scene::init())
return false;
transitionDelay = 3.0f;
isTransitioning = false;
srand(time(NULL)); //seed rng
director = Director::getInstance();
//Setting the default animation rate for the director
director->setAnimationInterval(1.0f / 60.0f);
initGameObjects();
initSprites();
initListeners();
initUI();
initMusic();
scheduleUpdate();
return true;
}
//initializes the user interface
void Boss1Scene::initUI()
{
HudObject::deleteAllInstances();
for (int i = 0; i < Hero::hero->health; i++)
{
HudObject* health = new HudObject("Sprites/PlayerHealth.png", cocos2d::Vec2(70 + (70 * i), 1000));
this->addChild(health->sprite, 100);
}
HudObject* BossHealthBar = new HudObject("Sprites/BossHealth.png", cocos2d::Vec2(1000, 1000));
this->addChild(BossHealthBar->sprite, 100);
}
void Boss1Scene::initGameObjects()
{
Hero::hero->moveState = Hero::MoveDirection::idle;
GameObject::MAX_X = 1856.0f;
GameObject::MAX_Y = 952.0f;
boss = new Boss(Hero::hero, this);
}
void Boss1Scene::initSprites()
{
//add background
background = Sprite::create("Backgrounds/bossBackground.png");
background->setAnchorPoint(Vec2(0.0f, 0.0f));
this->addChild(background, 1);
//delete any existing tiles before we import our map
TileBase::deleteAllTiles();
//get the tilemap in
cocos2d::TMXTiledMap* testTileMap = TMXTiledMap::create("Tilemaps/bossMap.tmx"); //ayy it works
addChild(testTileMap, 1);
cocos2d::TMXLayer* groundLayer = testTileMap->getLayer("tiles");
cocos2d::TMXLayer* platformLayer = testTileMap->getLayer("platforms");
cocos2d::TMXLayer* pillarLayer = testTileMap->getLayer("pillars");
unsigned int tileMapWidth = testTileMap->getMapSize().width; //map width
unsigned int tileMapHeight = testTileMap->getMapSize().height; //map height
for (unsigned int x = 0; x < tileMapWidth; x++) //width of map grid
{
for (unsigned int y = 0; y < tileMapHeight; y++) //height of map grid
{
cocos2d::Sprite* currentTile = groundLayer->getTileAt(Vec2(x, y));
if (currentTile != NULL)
{
GroundTile* newGroundTile = new GroundTile(currentTile->getPosition(), 64);
//set collision flags if there are adjacent ground tiles
//we have to do our own x and y validation because cocos sucks and crashes otherwise
if (x != 0)
{
if (groundLayer->getTileAt(Vec2(x - 1, y)) != NULL)
newGroundTile->ignoreLeftCollision = true;
}
if (x != tileMapWidth - 1)
{
if (groundLayer->getTileAt(Vec2(x + 1, y)) != NULL)
newGroundTile->ignoreRightCollision = true;
}
if (y != 0)
{
if (groundLayer->getTileAt(Vec2(x, y - 1)) != NULL)
newGroundTile->ignoreTopCollision = true;
}
if (y != tileMapHeight - 1)
{
if (groundLayer->getTileAt(Vec2(x, y + 1)) != NULL)
newGroundTile->ignoreBottomCollision = true;
}
}
currentTile = platformLayer->getTileAt(Vec2(x, y));
if (currentTile != NULL)
{
PlatformTile* newPlatformTile = new PlatformTile(currentTile->getPosition(), 64);
}
}
}
//add hero (singleton class)
Hero::hero->sprite = Sprite::create("Sprites/shooting_test.png");
this->addChild(Hero::hero->sprite, 20);
Hero::hero->sprite->setPosition(Vec2(1700, 200));
Hero::hero->lookState = Hero::LookDirection::lookingLeft; //make sure they're looking towards the boss
HeroStateManager::idle->onEnter();
Hero::hero->health = 5;
Hero::hero->arm = cocos2d::Sprite::create("Sprites/armV2.png");
Hero::hero->arm->setVisible(0); //make arm invisible to begin with
Hero::hero->arm->setAnchorPoint(Vec2(0.5f, 0.0f));
this->addChild(Hero::hero->arm, 21); //add hero arm
//add boss
this->addChild(boss->getSprite(), 17);
//add grapple sprite
//add repeating pattern to grapple sprite
Grapple::grapple->sprite = Sprite::create("Sprites/grapple.png");
Texture2D::TexParams params;
params.minFilter = GL_NEAREST;
params.magFilter = GL_NEAREST;
params.wrapS = GL_REPEAT;
params.wrapT = GL_REPEAT;
Grapple::grapple->sprite->getTexture()->setTexParameters(params);
Grapple::grapple->sprite->setVisible(0);
Grapple::grapple->sprite->setAnchorPoint(Vec2(0.5, 0));
this->addChild(Grapple::grapple->sprite, 5);
//grapple tip
Grapple::grapple->tip = Sprite::create("Sprites/grappleTip.png");
//Grapple::grapple->tip->setAnchorPoint(Vec2(0.5, 0));
this->addChild(Grapple::grapple->tip, 7);
//grapple destination indicator
Grapple::grapple->indicator = Sprite::create("Sprites/grappleIndicator.png");
Grapple::grapple->indicator->setVisible(0);
this->addChild(Grapple::grapple->indicator, 6);
}
void Boss1Scene::initListeners()
{
//Init the mouse listener
initMouseListener();
//Init the keyboard listener
initKeyboardListener();
//init controller listener
initControllerListener();
}
void Boss1Scene::initMouseListener()
{
//Init the mouse listener
mouseListener = EventListenerMouse::create();
//On Mouse Down
mouseListener->onMouseDown = CC_CALLBACK_1(Boss1Scene::mouseDownCallback, this);
//On Mouse Up
mouseListener->onMouseUp = CC_CALLBACK_1(Boss1Scene::mouseUpCallback, this);
//On Mouse Move
mouseListener->onMouseMove = CC_CALLBACK_1(Boss1Scene::mouseMoveCallback, this);
//On Mouse Scroll
mouseListener->onMouseScroll = CC_CALLBACK_1(Boss1Scene::mouseScrollCallback, this);
//Add the mouse listener to the dispatcher
_eventDispatcher->addEventListenerWithSceneGraphPriority(mouseListener, this);
}
void Boss1Scene::initKeyboardListener()
{
//Create the keyboard listener
keyboardListener = EventListenerKeyboard::create();
//Setting up callbacks
keyboardListener->onKeyPressed = CC_CALLBACK_2(Boss1Scene::keyDownCallback, this);
keyboardListener->onKeyReleased = CC_CALLBACK_2(Boss1Scene::keyUpCallback, this);
//Add the keyboard listener to the dispatcher
_eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardListener, this);
}
void Boss1Scene::initControllerListener()
{
controllerListener = EventListenerController::create();
//set up callbacks
controllerListener->onKeyDown = CC_CALLBACK_3(Boss1Scene::buttonPressCallback, this);
controllerListener->onKeyUp = CC_CALLBACK_3(Boss1Scene::buttonReleaseCallback, this);
controllerListener->onAxisEvent = CC_CALLBACK_3(Boss1Scene::axisEventCallback, this);
controllerListener->onConnected = [](cocos2d::Controller* controller, cocos2d::Event* evt) {};
//add the controller listener to the dispatcher
_eventDispatcher->addEventListenerWithSceneGraphPriority(controllerListener, this);
}
void Boss1Scene::initMusic()
{
auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
audio->playBackgroundMusic("Music/BossMusic.mp3",true);
}
//UPDATE
void Boss1Scene::update(float dt)
{
if (!isTransitioning)
{
Grapple::grapple->update(dt, this); //update grapple
Hero::hero->update(dt); //update our hero
if (Hero::hero->moveBox.getMinX() < 350.0f)
{
Hero::hero->sprite->setPositionX(350 + (Hero::hero->moveBox.size.width / 2.0f));
Hero::hero->velocity.x = 0.0f;
}
spawnEnemies(); //spawn enemies if needed
updateObjects(dt); //update objects
updateEnemies(dt); //update enemies
//hero death
if (Hero::hero->health <= 0)
{
if (transitionDelay == 3.0f)
{
Hero::hero->reset(); //reset hero
HeroStateManager::dying->onEnter();
}
transitionDelay -= dt;
if (transitionDelay <= 0.0f)
{
director->replaceScene(TransitionFade::create(2.0f, DeathScreen::createScene(), Color3B(0, 0, 0)));
isTransitioning = true;
}
}
}
}
void Boss1Scene::spawnEnemies()
{
//spawns all enemies to keep a certain amount of each in the map
}
void Boss1Scene::updateObjects(float dt)
{
//update all platforms
unsigned int numPlatforms = Platform::platformList.size();
for (unsigned int i = 0; i < numPlatforms; i++)
Platform::platformList[i]->update();
//update all ice projectiles
for (unsigned int i = 0; i < IceProjectile::iceProjectileList.size(); i++)
IceProjectile::iceProjectileList[i]->update(dt);
for (unsigned int i = 0; i < HudObject::HudList.size(); i++)
{
HudObject::HudList[i]->update(dt);
}
}
void Boss1Scene::updateEnemies(float dt)
{
//update boss
boss->update(dt);
//check for an attack hitting the boss
HeroAttackBase* currentAttack = HeroAttackManager::currentAttack;
for (auto i : boss->getHitBox())
{
if (currentAttack == HeroAttackManager::meleeFire && myHelper::isCollision(currentAttack->hitbox,i->hitBox))
{
currentAttack->disabled = true;
boss->takeDamage();
}
//check for collision on boss
if (Hero::hero->isHitboxCollision(i->hitBox))
{
Hero::hero->takeDamage(i->hitBox.getMidX());
}
}
//loop through each attack checking for collisions
for (auto i : boss->getLavaList())
{
if (Hero::hero->isHitboxCollision(i->getHitBox()))
{
if (i->getHitBox().size.height > 0 && i->getHitBox().size.width > 0)
{
if (i->getAttackType() == Boss1LavaAttack::BossAttack::Flamethrower)
Hero::hero->takeDamage(i->getHitBox().getMinX(), i->getDealingDamage());
else //not flamethrower attack
Hero::hero->takeDamage(i->getHitBox().getMidX(), i->getDealingDamage());
i->hitByHero();
}
}
}
}
//removes all game objects from the world
void Boss1Scene::removeAllObjects()
{
}
//--- Callbacks ---//
void Boss1Scene::mouseDownCallback(Event* event)
{
//Cast the event as a mouse event
EventMouse* mouseEvent = dynamic_cast<EventMouse*>(event);
auto mouseButton = mouseEvent->getMouseButton();
if (mouseButton == cocos2d::EventMouse::MouseButton::BUTTON_LEFT)
{
HeroAttackManager::setCurrentAttack(HeroAttackTypes::meleeFireA, nullptr); //can pass a nullptr because we dont need to add anything to the scene for melee attacks
}
if (mouseButton == cocos2d::EventMouse::MouseButton::BUTTON_RIGHT)
{
//Get the position of the mouse button press
auto mouseClickPosition = mouseEvent->getLocationInView();
mouseClickPosition.y += 1080;
auto mouseGameViewPosition = mouseClickPosition;
mouseGameViewPosition.y += 15;
Grapple::grapple->shoot(Vect2(mouseGameViewPosition)); //shoot the grapple
}
}
void Boss1Scene::mouseUpCallback(Event* event)
{
}
void Boss1Scene::mouseMoveCallback(Event* event)
{
}
void Boss1Scene::mouseScrollCallback(Event* event)
{
}
void Boss1Scene::keyDownCallback(EventKeyboard::KeyCode keyCode, Event* event)
{
switch (keyCode)
{
case EventKeyboard::KeyCode::KEY_A:
HeroStateManager::currentState->handleInput(InputType::p_a);
Hero::hero->lookState = Hero::LookDirection::lookingLeft;
Hero::hero->moveState = Hero::MoveDirection::movingLeft;
break;
case EventKeyboard::KeyCode::KEY_D:
HeroStateManager::currentState->handleInput(InputType::p_d);
Hero::hero->lookState = Hero::LookDirection::lookingRight;
Hero::hero->moveState = Hero::MoveDirection::movingRight;
break;
case EventKeyboard::KeyCode::KEY_S:
HeroStateManager::currentState->handleInput(InputType::p_s);
//HeroAttackBase::isSKeyHeld = true;
break;
case EventKeyboard::KeyCode::KEY_W:
HeroAttackBase::isWKeyHeld = true;
break;
case EventKeyboard::KeyCode::KEY_SPACE:
HeroStateManager::currentState->handleInput(InputType::p_space);
break;
case EventKeyboard::KeyCode::KEY_E:
//HeroAttackManager::setCurrentAttack(HeroAttackTypes::projectileIceA, this);
break;
case EventKeyboard::KeyCode::KEY_ESCAPE:
director->pushScene(PauseMenu::createScene());
}
}
void Boss1Scene::keyUpCallback(EventKeyboard::KeyCode keyCode, Event* event)
{
switch (keyCode)
{
case EventKeyboard::KeyCode::KEY_A:
//make sure the hero is moving in this direction before we decide if they are now idle
if (Hero::hero->moveState == Hero::MoveDirection::movingLeft)
Hero::hero->moveState = Hero::MoveDirection::idle;
break;
case EventKeyboard::KeyCode::KEY_D:
//make sure the hero is moving in this direction before we decide if they are now idle
if (Hero::hero->moveState == Hero::MoveDirection::movingRight)
Hero::hero->moveState = Hero::MoveDirection::idle;
break;
case EventKeyboard::KeyCode::KEY_S:
HeroAttackBase::isSKeyHeld = false;
break;
case EventKeyboard::KeyCode::KEY_W:
HeroAttackBase::isWKeyHeld = false;
break;
case EventKeyboard::KeyCode::KEY_SPACE:
HeroStateManager::currentState->handleInput(InputType::r_space);
break;
}
}
void Boss1Scene::buttonPressCallback(Controller * controller, int keyCode, Event * event)
{
switch (keyCode)
{
case ControllerInput::A:
HeroStateManager::currentState->handleInput(InputType::p_space);
break;
case ControllerInput::Start:
director->pushScene(PauseMenu::createScene());
break;
}
}
void Boss1Scene::buttonReleaseCallback(Controller * controller, int keyCode, Event * event)
{
switch (keyCode)
{
case ControllerInput::A:
HeroStateManager::currentState->handleInput(InputType::r_space);
break;
}
}
void Boss1Scene::axisEventCallback(Controller * controller, int keyCode, Event * event)
{
switch (keyCode)
{
//x axis of the left stick
case ControllerInput::leftStickX:
//moving to the left
if (controller->getKeyStatus(keyCode).value <= -1)
{
ControllerInput::isLeftStickIdle = false;
ControllerInput::isControllerUsed = true; //controller has been used this playthrough
HeroStateManager::currentState->handleInput(InputType::p_a);
Hero::hero->lookState = Hero::LookDirection::lookingLeft;
Hero::hero->moveState = Hero::MoveDirection::movingLeft;
}
//moving to the right
else if (controller->getKeyStatus(keyCode).value >= 1)
{
ControllerInput::isLeftStickIdle = false;
ControllerInput::isControllerUsed = true; //controller has been used this playthrough
HeroStateManager::currentState->handleInput(InputType::p_d);
Hero::hero->lookState = Hero::LookDirection::lookingRight;
Hero::hero->moveState = Hero::MoveDirection::movingRight;
}
else if (!ControllerInput::isLeftStickIdle) //not moving AND left stick isn't at rest
{
Hero::hero->moveState = Hero::MoveDirection::idle;
ControllerInput::isLeftStickIdle = true;
}
break;
//y axis of the left stick
case ControllerInput::leftStickY:
if (controller->getKeyStatus(keyCode).value >= 1)
HeroAttackBase::isWKeyHeld = true;
else
{
HeroAttackBase::isWKeyHeld = false;
if (controller->getKeyStatus(keyCode).value <= -1)
HeroStateManager::currentState->handleInput(InputType::p_s);
}
break;
case ControllerInput::leftTrigger:
//check for attack
if (controller->getKeyStatus(keyCode).value >= 1 && ControllerInput::isLeftTriggerReset)
{
ControllerInput::isLeftTriggerReset = false;
HeroAttackManager::setCurrentAttack(HeroAttackTypes::meleeFireA, nullptr); //can pass a nullptr because we dont need to add anything to the scene for melee attacks
}
else if (controller->getKeyStatus(keyCode).value <= -1)
ControllerInput::isLeftTriggerReset = true;
break;
case ControllerInput::rightTrigger:
if (controller->getKeyStatus(keyCode).value >= 1 && ControllerInput::isRightTriggerReset)
{
ControllerInput::isRightTriggerReset = false;
//use xinput stuff to get a more accurate reading on the stick input than cocos' controller support
XinputManager::instance->update();
XinputController* controller1 = XinputManager::instance->getController(0);
Stick sticks[2];
controller1->getSticks(sticks);
//calculate angle (in radians) using atan2 with the right stick's y and x values
float grappleAngle = atan2(sticks[RS].x, sticks[RS].y);
//check if right stick is at rest (account for reading being slightly off or controller rest not being perfectly calibrated)
if (sticks[RS].x < 0.3 && sticks[RS].x > -0.3 && sticks[RS].y <= 0.3f && sticks[RS].y > -0.3f)
{
//calculate angle (in radians) using atan2 with the right stick's y and x values
grappleAngle = atan2(0.0f, 0.0f);
}
Grapple::grapple->shoot(grappleAngle); //shoot grapple
}
else if (controller->getKeyStatus(keyCode).value <= -1)
ControllerInput::isRightTriggerReset = true;
break;
}
}
<file_sep>#include "HeroMoveLeft.h"
#include "Hero.h"
HeroMoveLeft::HeroMoveLeft()
{
}
void HeroMoveLeft::init()
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("running_left_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->setFlippedX(1);
Hero::hero->sprite->runAction(cocos2d::RepeatForever::create(action->clone()));
}
void HeroMoveLeft::update(float dt)
{
Hero::hero->moveLeft();
}<file_sep>#pragma once
#include "cocos2d.h"
class HudObject
{
public:
HudObject(std::string filePath, cocos2d::Vec2 position);
~HudObject();
cocos2d::Sprite* sprite;
static std::vector<HudObject*> HudList;
static void deleteAllInstances();
void update(float dt);
};
<file_sep>#include "PauseMenu.h"
#include "Tutorial.h"
#include "Boss1Scene.h"
#include "ControlsMenu.h"
#include <SimpleAudioEngine.h>
Scene * PauseMenu::createScene()
{
Scene* scene = PauseMenu::create();
return scene;
}
bool PauseMenu::init()
{
if (!Scene::init())
return false;
currentSelection = MenuOptions::nothing;
director = Director::getInstance();
//Setting the default animation rate for the director
director->setAnimationInterval(1.0f / 60.0f);
initUI();
initAnimations();
//init listeners
initMouseListener();
initControllerListener();
initMusic();
auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
audio->resumeBackgroundMusic();
scheduleUpdate();
return true;
}
void PauseMenu::initUI()
{
//set our sprite labels
background = Sprite::create("Backgrounds/pause_menu.png");
background->setAnchorPoint(Vec2(0.0f, 0.0f));
this->addChild(background, 5);
resumeText = Sprite::create("Text/resumeTest.png");
resumeText->setPosition(1920 / 2, 700);
this->addChild(resumeText, 10);
controlsText = Sprite::create("Text/controlsTest.png");
controlsText->setPosition(1920 / 2, 500);
this->addChild(controlsText, 10);
exitText = Sprite::create("Text/exitTest.png");
exitText->setPosition(1920 / 2, 300);
this->addChild(exitText, 10);
//set rects for label hover/click
resumeRect.setRect(resumeText->getPositionX() - 300, resumeText->getPositionY() - 100, 600, 200);
controlsRect.setRect(controlsText->getPositionX() - 300, controlsText->getPositionY() - 100, 600, 200);
exitRect.setRect(exitText->getPositionX() - 300, exitText->getPositionY() - 100, 600, 200);
}
void PauseMenu::initAnimations()
{
}
void PauseMenu::initMusic()
{
auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
audio->resumeBackgroundMusic();
}
void PauseMenu::initMouseListener()
{
//Init the mouse listener
mouseListener = EventListenerMouse::create();
//On Mouse Down
mouseListener->onMouseDown = CC_CALLBACK_1(PauseMenu::mouseDownCallback, this);
//On Mouse Up
mouseListener->onMouseUp = CC_CALLBACK_1(PauseMenu::mouseUpCallback, this);
//On Mouse Move
mouseListener->onMouseMove = CC_CALLBACK_1(PauseMenu::mouseMoveCallback, this);
//On Mouse Scroll
mouseListener->onMouseScroll = CC_CALLBACK_1(PauseMenu::mouseScrollCallback, this);
//Add the mouse listener to the dispatcher
_eventDispatcher->addEventListenerWithSceneGraphPriority(mouseListener, this);
}
void PauseMenu::initControllerListener()
{
controllerListener = EventListenerController::create();
//set up callbacks
controllerListener->onKeyDown = CC_CALLBACK_3(PauseMenu ::buttonPressCallback, this);
controllerListener->onKeyUp = CC_CALLBACK_3(PauseMenu::buttonReleaseCallback, this);
controllerListener->onAxisEvent = CC_CALLBACK_3(PauseMenu::axisEventCallback, this);
controllerListener->onConnected = [](cocos2d::Controller* controller, cocos2d::Event* evt) {};
//add the controller listener to the dispatcher
_eventDispatcher->addEventListenerWithSceneGraphPriority(controllerListener, this);
}
//move to the next selection on the menu
void PauseMenu::moveToNextMenuItem()
{
switch (currentSelection)
{
case MenuOptions::nothing:
currentSelection = MenuOptions::resume;
break;
case MenuOptions::resume:
currentSelection = MenuOptions::controls;
break;
case MenuOptions::controls:
currentSelection = MenuOptions::exit;
break;
case MenuOptions::exit:
currentSelection = MenuOptions::resume;
break;
}
}
//move back one selection on the menu
void PauseMenu::moveToPreviousMenuItem()
{
switch (currentSelection)
{
case MenuOptions::nothing:
currentSelection = MenuOptions::resume;
break;
case MenuOptions::resume:
currentSelection = MenuOptions::exit;
break;
case MenuOptions::controls:
currentSelection = MenuOptions::resume;
break;
case MenuOptions::exit:
currentSelection = MenuOptions::controls;
break;
}
}
void PauseMenu::update(float dt)
{
if (resumeRect.containsPoint(cursorPos) || currentSelection == MenuOptions::resume)
resumeText->setScale(1.2f);
else
resumeText->setScale(1.0f);
if (controlsRect.containsPoint(cursorPos) || currentSelection == MenuOptions::controls)
controlsText->setScale(1.2f);
else
controlsText->setScale(1.0f);
if (exitRect.containsPoint(cursorPos) || currentSelection == MenuOptions::exit)
exitText->setScale(1.2f);
else
exitText->setScale(1.0f);
}
//--- Callbacks ---//
void PauseMenu::mouseDownCallback(Event* event)
{
//Cast the event as a mouse event
EventMouse* mouseEvent = dynamic_cast<EventMouse*>(event);
auto mouseButton = mouseEvent->getMouseButton();
//Get the position of the mouse button press
auto mouseClickPosition = mouseEvent->getLocationInView();
if (mouseButton == cocos2d::EventMouse::MouseButton::BUTTON_LEFT)
{
//resume game
if (resumeRect.containsPoint(cursorPos))
{
director->popScene();
}
//bring up controls menu
else if (controlsRect.containsPoint(cursorPos))
{
director->pushScene(ControlsMenu::createScene());
}
//exit game
else if (exitRect.containsPoint(cursorPos))
{
director->end();
}
}
if (mouseButton == cocos2d::EventMouse::MouseButton::BUTTON_RIGHT)
{
}
}
void PauseMenu::mouseUpCallback(Event* event)
{
}
void PauseMenu::mouseMoveCallback(Event* event)
{
EventMouse* mouseEvent = dynamic_cast<EventMouse*>(event);
cursorPos = mouseEvent->getLocationInView();
cursorPos.y += 1080;
}
void PauseMenu::mouseScrollCallback(Event* event)
{
}
void PauseMenu::buttonPressCallback(Controller * controller, int keyCode, Event * event)
{
switch (keyCode)
{
case ControllerInput::A:
//start game
if (currentSelection == MenuOptions::resume)
{
director->popScene();
}
//open controls menu
else if (currentSelection == MenuOptions::controls)
{
director->pushScene(ControlsMenu::createScene());
}
//exit game
else if (currentSelection == MenuOptions::exit)
{
director->end();
}
break;
case ControllerInput::B:
director->popScene();
break;
case ControllerInput::Back:
director->popScene();
break;
case ControllerInput::Start:
director->popScene();
break;
}
}
void PauseMenu::buttonReleaseCallback(Controller * controller, int keyCode, Event * event)
{
}
void PauseMenu::axisEventCallback(Controller * controller, int keyCode, Event * event)
{
switch (keyCode)
{
//y axis of the left stick
case ControllerInput::leftStickY:
if (controller->getKeyStatus(keyCode).value >= 1 && ControllerInput::isLeftStickReset)
{
moveToPreviousMenuItem();
ControllerInput::isLeftStickReset = false;
}
else if (controller->getKeyStatus(keyCode).value <= -1 && ControllerInput::isLeftStickReset)
{
moveToNextMenuItem();
ControllerInput::isLeftStickReset = false;
}
else if (controller->getKeyStatus(keyCode).value > -0.9 && controller->getKeyStatus(keyCode).value < 0.9)
ControllerInput::isLeftStickReset = true;
break;
}
}
<file_sep>#include "Platform.h"
std::vector<Platform*> Platform::platformList = std::vector<Platform*>();
Platform::Platform(Vect2 position) : GameObject(position, "Sprites/Platform2.png")
{
mass = 0;
updateHitboxes();
platformList.push_back(this);
}
//platforms have their own collision (since these are one-way platforms, you can go through the bottom but not the top)
bool Platform::checkOneWayCollision(GameObject* otherObject)
{
//check for general collision, then make sure only the bottom of the other object is colliding, then make sure the other object is moving down
if (this->isMovementCollision(otherObject) && otherObject->getBottomPos() >= this->getBottomPos() && otherObject->velocity.y <= 0)
return true;
return false;
}
void Platform::updateHitboxes()
{
moveBox.setRect(getLeftSidePos(), getBottomPos(), width, height);
hurtBox.setRect(getLeftSidePos(), getBottomPos(), width, height);
}
void Platform::update()
{
if (this->checkOneWayCollision(Hero::hero))
{
Hero::hero->sprite->setPositionY(this->getTopPos() + Hero::hero->height / 2);
Hero::hero->velocity.y = 0;
}
}
<file_sep>#pragma once
#ifndef RUNNINGSTATE_H
#define RUNNINGSTATE_H
#include "HeroStateBase.h"
class RunningState : public HeroStateBase
{
public:
RunningState();
~RunningState();
void onEnter();
void onExit();
void handleInput(InputType input);
void update(float dt);
};
#endif<file_sep>#include "Animation.h"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// //
// Animation Class //
// //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void marcos::AnimationManager::init()
{
//Hero Movement Animations
addAnimation("Sprites/idle_right.png", 20, 75, 135, "idle_right_animation_key");
addAnimation("Sprites/idle_left.png", 20, 75, 135, "idle_left_animation_key");
addAnimation("Sprites/running_right.png", 6, 105, 135, "running_right_animation_key");
addAnimation("Sprites/running_left.png", 6, 105, 135, "running_left_animation_key");
addAnimation("Sprites/jump_right.png", 15, 105, 135, "jumping_right_animation_key");
addAnimation("Sprites/jump_left.png", 15, 105, 135, "jumping_left_animation_key");
addAnimation("Sprites/falling_right.png", 14, 105, 135, "falling_right_animation_key");
addAnimation("Sprites/falling_left.png", 8, 105, 135, "falling_left_animation_key");
//Hero Attacking Animations
addAnimation("Sprites/melee_right.png", 4, 177, 138, "melee_right_animation_key");
addAnimation("Sprites/melee_left.png", 4, 177, 138, "melee_left_animation_key");
addAnimation("Sprites/melee_up_right.png", 4, 135, 260, "melee_up_right_animation_key");
addAnimation("Sprites/melee_up_left.png", 4, 135, 260, "melee_up_left_animation_key");
//Hero Grappling Animations
addAnimation("Sprites/grapple_right.png", 6, 105, 135, "grapple_right_animation_key");
addAnimation("Sprites/grapple_left.png", 6, 105, 135, "grapple_left_animation_key");
addAnimation("Sprites/shooting_grapple_right.png", 2, 120, 135, "shooting_grapple_right_animation_key");
addAnimation("Sprites/shooting_grapple_left.png", 2, 120, 135, "shooting_grapple_left_animation_key");
addAnimation("Sprites/grapple_jump_right.png", 5, 120, 135, "grapple_jump_right_animation_key");
addAnimation("Sprites/grapple_jump_left.png", 5, 120, 135, "grapple_jump_left_animation_key");
addAnimation("Sprites/grapple_hold_right.png", 1, 105, 195, "grapple_hold_right_animation_key");
addAnimation("Sprites/grapple_hold_left.png", 1, 105, 195, "grapple_hold_left_animation_key");
//Hero Death Animations
addAnimation("Sprites/death_left.png", 25, 168, 135, "hero_death_left_animation_key");
addAnimation("Sprites/death_right.png", 25, 168, 135, "hero_death_right_animation_key");
addAnimation("Backgrounds/mainMenu.png", 4, 7, 1920, 1080, "main_menu_animation_key");
//Boss State Animations
initBossStateAnimation();
//Boss attack projectile Animations
initBossAttackParticleAnimation();
}
/**
* @brief This function adds all the boss state to animation cache
*/
void marcos::AnimationManager::initBossStateAnimation()
{
const int bossHeight{ 1300 }, bossWidth{ 500 };
addAnimation("Sprites/boss_flamethrow_part1.png", 12, bossWidth, bossHeight, "boss_flame_tell_PRE_animation_key");
addAnimation("Sprites/boss_flamethrow_part2.png", 5, bossWidth, bossHeight, "boss_flame_tell_POST_animation_key");
addAnimation("Sprites/boss_projectile_attack_part1.png", 14, bossWidth, bossHeight, "boss_spit_tell_PRE_animation_key");
addAnimation("Sprites/Spit_attack_part2.png", 9, bossWidth, bossHeight, "boss_spit_tell_POST_animation_key");
addAnimation("Sprites/boss_explosive_attack_part1.png", 8, bossWidth, bossHeight, "boss_explosive_tell_PRE_animation_key");
addAnimation("Sprites/boss_explosive_attack_part2.png", 4, bossWidth, bossHeight, "boss_explosive_tell_POST_animation_key");
addAnimation("Sprites/boss_idle.png", 8, 5, bossWidth, bossHeight, "boss_idle_animation_key");
addAnimation("Sprites/BossDeathGame.png", 12, 4, bossWidth + 150, bossHeight, "boss_death_animation_key");
addAnimation("Sprites/boss_resting.png", 16, bossWidth, bossHeight, "boss_resting_animation_key");
}
/**
* @brief This function adds all the boss attack particles to animation cache
*/
void marcos::AnimationManager::initBossAttackParticleAnimation()
{
addAnimation("Sprites/exploding_fireball.png", 6, 60, 60, "boss_explosive_PRE_animation_key");
addAnimation("Sprites/exploding_fireballpart2.png", 17, 60, 60, "boss_explosive_MID_animation_key");
addAnimation("Sprites/exploding_fireballpart3.png", 8, 120, 120, "boss_explosive_POST_animation_key");
addAnimation("Sprites/flame_1.png", 2, 2, 1920, 500, "boss_flame_PRE_animation_key");
addAnimation("Sprites/flame_2.png", 4, 2, 1920, 500, "boss_flame_MID_animation_key");
addAnimation("Sprites/flame_3.png", 4, 2, 1920, 500, "boss_flame_POST_animation_key");
addAnimation("Sprites/fire_ball.png", 12, 70, 70, "boss_spit_animation_key");
}
//Animation setter, to store the animation frames in the animation cache to be called later
void marcos::AnimationManager::addAnimation(const std::string fileName, const int a_NumFrames, const float a_Width, const float a_Height, const std::string& keyName,
const float a_Delay)
{
cocos2d::Vector<cocos2d::SpriteFrame*> m_AnimFrames;
for (int i = 0; i < a_NumFrames; i++)
{
auto frame = cocos2d::SpriteFrame::create(fileName, cocos2d::Rect(a_Width * i, 3, a_Width, a_Height));
m_AnimFrames.pushBack(frame);
}
auto animation = cocos2d::Animation::createWithSpriteFrames(m_AnimFrames, a_Delay);
addAnimation(animation, keyName);
}
/**
* @brief This function set the animation from the file and add it onto the animation cache
*/
void marcos::AnimationManager::addAnimation(const std::string fileName, const int a_RowFrames, const int a_rows, const float a_Width, const float a_Height,
const std::string& keyName, const float a_Delay)
{
cocos2d::Vector<cocos2d::SpriteFrame*> m_AnimFrames;
for (int i = 0; i < a_rows; i++)
{
for (int j = 0; j < a_RowFrames && j < 8; j++)
{
auto frame = cocos2d::SpriteFrame::create(fileName, cocos2d::Rect(a_Width * j, a_Height * i, a_Width, a_Height));
m_AnimFrames.pushBack(frame);
}
}
auto animation = cocos2d::Animation::createWithSpriteFrames(m_AnimFrames, a_Delay);
addAnimation(animation, keyName);
}
/**
*
*/
void marcos::AnimationManager::addAnimation(Animation* animationToAdd, const std::string& animationKey)
{
AnimationCache::getInstance()->addAnimation(animationToAdd, animationKey);
}
/**
* This static function will create an animation based on the animation key
* @param animationKey The name of the key to create animation from
*
* @return Return the cocos2d::Animate pointer
*/
cocos2d::Animate* marcos::AnimationManager::getAnimation(const std::string& animationKey)
{
return Animate::create(AnimationCache::getInstance()->getAnimation(animationKey));
}
/**
* This function will create an animation based on the animation key
* and change the total animation time based on value
*
* @param animationKey The key string for animation
* @param animationTime The total animation time for the animation
*
* @return Return the cocos2d::Animate pointer
*/
cocos2d::Animate* marcos::AnimationManager::getAnimationWithAnimationTime(const std::string& animationKey,
const float& animationTime)
{
const float delay = animationTime/ AnimationCache::getInstance()->getAnimation(animationKey)->getFrames().size();
AnimationCache::getInstance()->getAnimation(animationKey)->setDelayPerUnit(delay);
return getAnimation(animationKey);
}
<file_sep>#include "FirstBossState.h"
#include "Boss/General/Boss.h"
#include "Boss/BossStates.h"
FirstBossState::FirstBossState(Boss *bossInstance)
:bossPointer(bossInstance)
{
}
void FirstBossState::update(const float& deltaTime)
{
}
/**
* @brief Change to idle state
*/
void FirstBossState::changeToIdleState() const
{
bossPointer->setHitboxIndex(Boss::idling);
bossPointer->setState(new Idling4FirstBoss(bossPointer));
}
/**
* @brief Change to death state
*/
void FirstBossState::changeToDeathState() const
{
bossPointer->setState(new DeathState(bossPointer));
}
/**
* @brief Change to flame split state
*/
void FirstBossState::changeToFlameSplit() const
{
bossPointer->setHitboxIndex(Boss::flameSplitter);
bossPointer->setState(new FlameSplit4FirstBoss(bossPointer));
}
/**
*@brief Change to flame thrower state
*/
void FirstBossState::changeToFlameThrower() const
{
bossPointer->setHitboxIndex(Boss::flamethrower);
bossPointer->setState(new FlameThrower4FirstBoss(bossPointer));
}
/**
* @brief Change to explosive bullet state
*/
void FirstBossState::changeToExplosiveBullet() const
{
bossPointer->setHitboxIndex(Boss::idling);
bossPointer->setState(new ExplosiveBullet4FirstBoss(bossPointer));
}
/**
* @brief Change to resting state
*/
void FirstBossState::changeToRestingState() const
{
bossPointer->setHitboxIndex(Boss::idling);
bossPointer->setState(new RestingState(bossPointer));
}
<file_sep>#include "HeroStateManager.h"
AttackingState* HeroStateManager::attacking = new AttackingState();
DyingState* HeroStateManager::dying = new DyingState();
FallingState* HeroStateManager::falling = new FallingState();
GrapplingState* HeroStateManager::grappling = new GrapplingState();
IdleState* HeroStateManager::idle = new IdleState();
JumpingState* HeroStateManager::jumping = new JumpingState();
RunningState* HeroStateManager::running = new RunningState();
GrappleJumpState* HeroStateManager::grappleJumping = new GrappleJumpState();
HoldingPlatformState* HeroStateManager::holdingPlatform = new HoldingPlatformState();
ShootingGrappleState* HeroStateManager::shootingGrapple = new ShootingGrappleState();
HeroStateBase* HeroStateManager::currentState = idle; //initialize to idle state
HeroStateManager::HeroStateManager()
{
}
HeroStateManager::~HeroStateManager()
{
}<file_sep>#pragma once
#ifndef GROUNDTILE_H
#define GROUNDTILE_H
#include "TileBase.h"
class GroundTile : public TileBase
{
public:
GroundTile(cocos2d::Vec2 position, float tileSize);
static std::vector<GroundTile*> groundTileList;
bool ignoreLeftCollision;
bool ignoreRightCollision;
bool ignoreBottomCollision;
bool ignoreTopCollision;
bool checkAndResolveCollision(GameObject* otherObject) override;
};
#endif<file_sep>#include "Boss/Attacks/FlameThrowerProjectile.h"
#include "Boss/General/Boss.h"
FlameThrower::FlameThrower(Boss *bossInstance)
: Boss1LavaAttack(bossInstance, "Sprites/flame_sprite.png")
{
//Set sprite
position.set(1000, 350);
sprite->setPosition(position);
bossPointer->getBossScene()->removeChild(sprite, false);
bossPointer->getBossScene()->addChild(sprite, 16);
attackType = BossAttack::Flamethrower;
//Get all animations
const auto startingAnimation = marcos::AnimationManager::getAnimationWithAnimationTime("boss_flame_PRE_animation_key",0.5);
const auto midAnimation = marcos::AnimationManager::getAnimationWithAnimationTime("boss_flame_MID_animation_key",1.5);
const auto finishingAnimation = marcos::AnimationManager::getAnimation("boss_flame_POST_animation_key");
//Run actions
sprite->runAction
(
cocos2d::Sequence::create
(
cocos2d::Repeat::create(startingAnimation, 1),
cocos2d::DelayTime::create(.1f),
cocos2d::CallFunc::create([&] {hitBox->setNewSize(1920, 230); }),
cocos2d::Repeat::create(midAnimation, 1),
cocos2d::CallFunc::create([&] {hitBox->setNewSize(0, 0); }),
cocos2d::Repeat::create(finishingAnimation,1),
cocos2d::CallFunc::create([&] {delete this; }),
nullptr
)
);
//Set hit box
hitBox = new HitBox(position, 0, 0);
}
FlameThrower::~FlameThrower()
{
bossPointer->removeFromLavaList(this);
}<file_sep>#include "JumpingState.h"
#include "Hero.h"
#include "HeroStateManager.h"
JumpingState::JumpingState()
{
}
JumpingState::~JumpingState()
{
}
void JumpingState::onEnter()
{
HeroStateManager::currentState = this;
if (Hero::hero->lookState == Hero::LookDirection::lookingLeft)
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("jumping_left_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::RepeatForever::create(action->clone()));
}
else
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("jumping_right_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::RepeatForever::create(action->clone()));
}
Hero::hero->jump();
}
void JumpingState::onExit()
{
if (Hero::hero->velocity.y < 0)
HeroStateManager::falling->onEnter();
else if (Hero::hero->velocity.y == 0)
HeroStateManager::idle->onEnter();
}
void JumpingState::handleInput(InputType input)
{
switch (input)
{
case InputType::r_space:
//variable jump height
Hero::hero->velocity.y /= 1.5;
break;
case InputType::p_a:
//if the hero is changing directions, call onEnter() again to play the proper animation
if (Hero::hero->lookState == Hero::LookDirection::lookingRight)
{
Hero::hero->lookState = Hero::LookDirection::lookingLeft;
HeroStateManager::falling->onEnter();
}
break;
case InputType::p_d:
//if the hero is changing directions, call onEnter() again to play the proper animation
if (Hero::hero->lookState == Hero::LookDirection::lookingLeft)
{
Hero::hero->lookState = Hero::LookDirection::lookingRight;
HeroStateManager::falling->onEnter();
}
}
}
void JumpingState::update(float dt)
{
if (Hero::hero->moveState == Hero::MoveDirection::movingLeft)
Hero::hero->moveLeft();
else if (Hero::hero->moveState == Hero::MoveDirection::movingRight)
Hero::hero->moveRight();
if (Hero::hero->velocity.y <= 0)
onExit();
}
<file_sep>#include "AttackingState.h"
#include "HeroAttackManager.h"
#include "HeroStateManager.h"
#include "Hero.h"
#include "Grapple.h"
AttackingState::AttackingState()
{
}
AttackingState::~AttackingState()
{
}
void AttackingState::onEnter()
{
HeroStateManager::currentState = this;
Hero::hero->sprite->stopAllActions();
}
void AttackingState::onExit()
{
//check which state to go to next from the top to the bottom of the hierarchy
if (Grapple::grapple->isActive)
HeroStateManager::grappling->onEnter();
else if (Hero::hero->velocity < 0)
HeroStateManager::falling->onEnter();
else if (Hero::hero->velocity > 0)
HeroStateManager::jumping->onEnter();
else if (Hero::hero->moveState != Hero::MoveDirection::idle)
HeroStateManager::running->onEnter();
else
HeroStateManager::idle->onEnter();
}
//handle any input that occurs in this state
void AttackingState::handleInput(InputType input)
{
switch (input)
{
case InputType::p_space:
Hero::hero->jump();
break;
case InputType::r_space:
//variable jump height
Hero::hero->velocity.y /= 1.5;
break;
}
}
void AttackingState::update(float dt)
{
if (Hero::hero->moveState == Hero::MoveDirection::movingLeft)
Hero::hero->moveLeft();
else if (Hero::hero->moveState == Hero::MoveDirection::movingRight)
Hero::hero->moveRight();
//if the attack ends, move onto another state
if (HeroAttackManager::currentAttack == HeroAttackManager::empty)
onExit();
}<file_sep>#pragma once
#include "Boss/Attacks/Boss1Attack.h"
class FlameThrower : public Boss1LavaAttack
{
public:
FlameThrower(Boss *bossInstance);
~FlameThrower();
private:
cocos2d::Vec2 startPoint;
};
<file_sep>#include "myHelper.h"
myHelper::myHelper()
{
}
myHelper::~myHelper()
{
}
//checks AABB rect collision
bool myHelper::isCollision(cocos2d::Rect rect1, cocos2d::Rect rect2)
{
//check x values to see if they arent touching
//assuming rects are named A and B:
//A_begin.x > B_end.x OR B_begin.x > A_end.x means there IS a gap on x
if (rect1.getMinX() >= rect2.getMaxX() || rect2.getMinX() >= rect1.getMaxX())
return false;
//check y values to see if they arent touching
//A_begin.y > B_end.y OR B_begin.y > A_end.y means there IS a gap on y
else if (rect1.getMinY() >= rect2.getMaxY() || rect2.getMinY() >= rect1.getMaxY())
return false;
//if neither, there's a collision
else
return true;
}
//p1 = first line start point
//p2 = first line end point
//p3 = second line start point
//p4 = second line end point
cocos2d::Vec2 myHelper::getLineLineIntersect(cocos2d::Vec2 p1, cocos2d::Vec2 p2, cocos2d::Vec2 p3, cocos2d::Vec2 p4)
{
float determinant = (p1.x - p2.x) * (p3.y - p4.y) - (p1.y - p2.y) * (p3.x - p4.x);
//if determinant is 0, they're parallel
if (determinant == 0)
return cocos2d::Vec2(0, 0);
//get the x and y of the intersect
float pre = p1.x * p2.y - p1.y * p2.x;
float post = p3.x * p4.y - p3.y * p4.x;
float x = (pre * (p3.x - p4.x) - (p1.x - p2.x) * post) / determinant;
float y = (pre * (p3.y - p4.y) - (p1.y - p2.y) * post) / determinant;
//check if the x and y coordinates are within both lines (add a small buffer to prevent rounding inaccuracies)
if ((x + 0.01) < std::min(p1.x, p2.x) || (x - 0.01) > std::max(p1.x, p2.x) || (x + 0.01) < std::min(p3.x, p4.x) || (x - 0.01) > std::max(p3.x, p4.x))
return cocos2d::Vec2(0, 0);
if ((y + 0.01) < std::min(p1.y, p2.y) || (y - 0.01) > std::max(p1.y, p2.y) || (y + 0.01) < std::min(p3.y, p4.y) || (y - 0.01) > std::max(p3.y, p4.y))
return cocos2d::Vec2(0, 0);
//return the point of intersection
cocos2d::Vec2 intersect = cocos2d::Vec2(x, y);
return intersect;
}
//gets a random number
int myHelper::getRandNum(int maxNum, int scaleNum, bool canBeNegative)
{
int randNum = (rand() % maxNum) + scaleNum;
//number can be a negative
if (canBeNegative)
{
//check randomly for either a 1 or 0 to determine if number should be negative or not
if (rand() % 2)
randNum *= -1;
}
return randNum;
}
<file_sep>#pragma once
//Foward declare
class Boss;
class FirstBossState
{
public:
//Constructors and Destructor
FirstBossState(Boss *bossInstance);
virtual ~FirstBossState() = default;
//Member functions
virtual void update(const float& deltaTime);
void changeToIdleState() const; //Idle state is allowed to change publicly
void changeToDeathState() const; //Dealth state is allowed to change publicly
protected:
Boss *bossPointer;
/*
* State changes functions. These can only
* be changes through inheritance
*/
void changeToFlameSplit() const;
void changeToFlameThrower() const;
void changeToExplosiveBullet() const;
void changeToRestingState() const;
};<file_sep>#pragma once
#include "HeroMovementBase.h"
class HeroMoveRight : public HeroMovementBase
{
public:
HeroMoveRight();
void init();
void update(float dt);
};<file_sep>#include "Grapple.h"
#include "PlatformTile.h"
#include "GroundTile.h"
#include "XinputManager.h"
#include "HeroStateManager.h"
Grapple* Grapple::grapple = 0;
const float Grapple::MOVE_SPEED = 800.0f;
const float Grapple::MAX_LENGTH = 500.0f;
Grapple::Grapple() :
isActive(false),
isLatched(false),
isHeroAtEndPoint(false),
lengthScale(0),
heroMoveScale(0),
latchDuration(0)
{
}
//initializes the grapple and creates a single object for the class (if one doesn't already exist)
void Grapple::initGrapple()
{
if (!grapple)
{
grapple = new Grapple;
//set up repeating pattern sprite
grapple->sprite = Sprite::create("Sprites/grapple.png");
Texture2D::TexParams params;
params.minFilter = GL_NEAREST;
params.magFilter = GL_NEAREST;
params.wrapS = GL_REPEAT;
params.wrapT = GL_REPEAT;
grapple->sprite->getTexture()->setTexParameters(params);
grapple->sprite->setVisible(0);
grapple->sprite->setAnchorPoint(Vec2(0.5f, 0.0f));
//set up tip sprite
grapple->tip = Sprite::create("Sprites/grappleTip.png");
grapple->tip->setVisible(0);
grapple->tip->setAnchorPoint(Vec2(0.f, 0.0f));
}
}
void Grapple::predictCollision()
{
if (ControllerInput::isControllerUsed)
{
//use xinput stuff to get a more accurate reading on the stick input than cocos' controller support
XinputManager::instance->update();
XinputController* controller1 = XinputManager::instance->getController(0);
Stick sticks[2];
controller1->getSticks(sticks);
//calculate angle (in radians) using atan2 with the right stick's y and x values
float grappleAngle = atan2(sticks[RS].x, sticks[RS].y);
//check if right stick is at rest (add a small buffer account for reading being slightly off or controller not being perfectly calibrated)
if (sticks[RS].x < 0.3 && sticks[RS].x > -0.3 && sticks[RS].y <= 0.3f && sticks[RS].y > -0.3f)
{
//calculate angle (in radians) using atan2 with the right stick's y and x values
grappleAngle = atan2(0.0f, 1.0f);
}
//calculate endpoint
Vect2 normalizedEndPoint(sin(grappleAngle), cos(grappleAngle));
endPoint = Vect2(Hero::hero->getPosition()) + (normalizedEndPoint * (MAX_LENGTH - 50)); //calculate endpoint by extending the normalized version
Vec2 heroPosition = Hero::hero->arm->getPosition();
//loop through each platform tile to check for intersects
unsigned int tileListSize = PlatformTile::platformTileList.size();
for (unsigned int i = 0; i < tileListSize; i++)
{
cocos2d::Vec2 platformStart = Vec2(PlatformTile::platformTileList[i]->hitBox.getMinX(), PlatformTile::platformTileList[i]->hitBox.getMidY());
cocos2d::Vec2 platformEnd = Vec2(PlatformTile::platformTileList[i]->hitBox.getMaxX(), PlatformTile::platformTileList[i]->hitBox.getMidY());
Vec2 intersectPoint = myHelper::getLineLineIntersect(
heroPosition,
Vec2(endPoint.x, endPoint.y),
platformStart,
platformEnd);
//there is an intersection
if (intersectPoint != Vec2(0, 0))
{
bool isCollisionAlongLine = false;
//we have to do collision checks now because there could be something inbetween
unsigned int numPlatforms = PlatformTile::platformTileList.size();
for (unsigned int j = 0; j < numPlatforms; j++)
{
//make sure we skip past the platform that's already been confirmed for collision
if (!(PlatformTile::platformTileList[j] == PlatformTile::platformTileList[i]))
{
cocos2d::Vec2 otherPlatformStart = Vec2(PlatformTile::platformTileList[j]->hitBox.getMinX(), PlatformTile::platformTileList[j]->hitBox.getMidY());
cocos2d::Vec2 otherPlatformEnd = Vec2(PlatformTile::platformTileList[j]->hitBox.getMaxX(), PlatformTile::platformTileList[j]->hitBox.getMidY());
Vec2 blockingPoint = myHelper::getLineLineIntersect(
heroPosition,
intersectPoint,
otherPlatformStart,
otherPlatformEnd);
//there is a platform blocking the grapple
if (blockingPoint != Vec2(0, 0))
{
isCollisionAlongLine = true;
break;
}
}
}
//no collision yet, lets go through the ground blocks
if (!isCollisionAlongLine)
{
GroundTile* currentTile;
unsigned int numGroundTiles = GroundTile::groundTileList.size();
for (unsigned int i = 0; i < numGroundTiles; i++)
{
currentTile = GroundTile::groundTileList[i];
//first lets check if the distance is out of range to quickly eliminate most blocks
if (Vect2::calculateDistance(heroPosition, Vect2(currentTile->hitBox.getMidX(), currentTile->hitBox.getMidY())) < (MAX_LENGTH + 100))
{
//this part is a bit tricky, to efficiently calculate collision blocking the grapple from hitting the platform,
//all we really need is 2 lines, one from the top left corner of the block to the bottom right, and one from the
//bottom left corner to the top right, and then check if the grapple passed either of the lines
//check top left to bottom right
cocos2d::Vec2 blockTopLeft = Vec2(currentTile->hitBox.getMinX(), currentTile->hitBox.getMaxY());
cocos2d::Vec2 blockBottomRight = Vec2(currentTile->hitBox.getMaxX(), currentTile->hitBox.getMinY());
Vec2 groundBlockPoint1 = myHelper::getLineLineIntersect(
heroPosition,
intersectPoint,
blockTopLeft,
blockBottomRight);
//check bottom left to top right
cocos2d::Vec2 blockBottomLeft = Vec2(currentTile->hitBox.getMinX(), currentTile->hitBox.getMinY());
cocos2d::Vec2 blockTopRight = Vec2(currentTile->hitBox.getMaxX(), currentTile->hitBox.getMaxY());
Vec2 groundBlockPoint2 = myHelper::getLineLineIntersect(
heroPosition,
intersectPoint,
blockBottomLeft,
blockTopRight);
//there is an intersection
if (groundBlockPoint1 != Vec2(0, 0) || groundBlockPoint2 != Vec2(0, 0))
{
isCollisionAlongLine = true;
break;
}
}
}
}
//if there isnt anything blocking the two intersections
if (!isCollisionAlongLine)
{
indicator->setPosition(intersectPoint);
indicator->setVisible(1);
endPoint = intersectPoint;
break; //break out of loop if we find a connection
}
}
else //there is no intersection with any platforms
indicator->setVisible(0);
}
}
}
//performs initial grapple shoot actions from a destination (mouse position)
void Grapple::shoot(Vect2 destination)
{
if (!isActive && HeroStateManager::currentState != HeroStateManager::dying)
{
//set all initial variables upon grapple being shot out
isActive = true;
initialPosClicked = destination;
initialPosClicked.y -= 13;
//determine look position after latching
if (Hero::hero->getPosition().x <= initialPosClicked.x)
{
Hero::hero->lookState = Hero::LookDirection::lookingRight;
Hero::hero->arm->setZOrder(Hero::hero->sprite->getZOrder() - 1);
}
else //heroLatchPos.x > latchPoint.x
{
Hero::hero->lookState = Hero::LookDirection::lookingLeft;
Hero::hero->arm->setZOrder(Hero::hero->sprite->getZOrder() + 1);
}
lookDirectionOnShoot = Hero::hero->lookState;
Hero::hero->updateArmPosition();
lastFrameGrappleTip = Hero::hero->arm->getPosition();
extendGrapple();
initialPosClicked = endPoint;
//make arm visible and rotate it
Hero::hero->arm->setVisible(1);
Hero::hero->arm->setRotation(theta * 180 / M_PI);
//make grapple sprite visible
sprite->setVisible(1);
grapple->tip->setVisible(1);
HeroStateManager::shootingGrapple->onEnter(); //put hero in grapple state
}
}
//performs initial grapple shoot actions from an angle (controller stick)
void Grapple::shoot(float a_theta)
{
if (!isActive && HeroStateManager::currentState != HeroStateManager::dying)
{
//set all initial variables upon grapple being shot out
theta = a_theta;
isActive = true;
lastFrameGrappleTip = Hero::hero->arm->getPosition();
//determine look position after latching
if (theta > 0)
{
Hero::hero->lookState = Hero::LookDirection::lookingRight;
Hero::hero->arm->setZOrder(Hero::hero->sprite->getZOrder() - 1);
}
else if (theta < 0)
{
Hero::hero->lookState = Hero::LookDirection::lookingLeft;
Hero::hero->arm->setZOrder(Hero::hero->sprite->getZOrder() + 1);
}
else if (theta == 0 && Hero::hero->lookState == Hero::LookDirection::lookingRight)
Hero::hero->arm->setZOrder(Hero::hero->sprite->getZOrder() - 1);
else if (theta == 0 && Hero::hero->lookState == Hero::LookDirection::lookingLeft)
Hero::hero->arm->setZOrder(Hero::hero->sprite->getZOrder() + 1);
lookDirectionOnShoot = Hero::hero->lookState;
initialPosClicked = endPoint;
//make arm visible and rotate it
Hero::hero->arm->setVisible(1);
Hero::hero->arm->setRotation(theta * 180 / M_PI);
//make grapple sprite visible
sprite->setVisible(1);
grapple->tip->setVisible(1);
HeroStateManager::shootingGrapple->onEnter(); //put hero in grapple state
}
}
//extends the grapple past the point the player aimed at
void Grapple::extendGrapple()
{
//find the angle at which the grapple is being shot at
Vect2 distance = initialPosClicked - Hero::hero->arm->getPosition(); //calculate distance vector between the grapple and the hero
theta = atan2(distance.x, distance.y); //perform atan2 (returns the angle in radians between the positive x axis (1, 0) and the point provided) on the distance
//get normalized new endpoint
Vect2 normalizedEndPoint(sin(theta), cos(theta));
endPoint = Vect2(Hero::hero->arm->getPosition()) + (normalizedEndPoint * MAX_LENGTH); //calculate new endpoint by extending the normalized version
}
//called when the grapple latches onto something
void Grapple::latch()
{
isLatched = true;
heroLatchPosition = Vect2(Hero::hero->arm->getPosition());
heroToLatchPointDistance = Vect2::calculateDistance(heroLatchPosition, latchPoint);
}
//grapple detaches and disappears, reset all values for the grapple
void Grapple::unLatch()
{
Hero::hero->arm->setVisible(0); //make arm invisible
sprite->setVisible(0);
grapple->tip->setVisible(0);
isActive = false;
isLatched = false;
isHeroAtEndPoint = false;
//grapple->clear();
lengthScale = 0;
heroMoveScale = 0;
latchDuration = 0;
}
//check for grapple hook max length or out of bounds
bool Grapple::isMaxLength()
{
Vect2 grappleLength = grappleTip - Vect2(Hero::hero->arm->getPosition());
if (grappleLength.getMagnitude() > MAX_LENGTH) //check max length
return true;
else if (grappleTip.x < 0 || grappleTip.x > GameObject::MAX_X || grappleTip.y < 0 || grappleTip.y > GameObject::MAX_Y) //check for out of bounds
return true;
return false;
}
//displays an indicator to the player if there is any point of collision with a platform along the direction currently aimed
void Grapple::performGrapplePrediction()
{
}
/*//checks collision between the grapple and a game object
bool Grapple::isCollidingWith(GameObject* otherObject)
{
if (grappleTip.x >= otherObject->getRightSidePos() || grappleTip.x <= otherObject->getLeftSidePos())
return false;
else if (grappleTip.y >= otherObject->getTopPos() || grappleTip.y <= otherObject->getBottomPos())
return false;
//if neither, there's a collision
else
return true;
}*/
bool Grapple::isCollidingWith(cocos2d::Rect otherObject)
{
if (grappleTip.x >= otherObject.getMaxX() || grappleTip.x <= otherObject.getMinX())
return false;
else if (grappleTip.y >= otherObject.getMaxY() || grappleTip.y <= otherObject.getMinY())
return false;
//if neither, there's a collision
else
return true;
}
/*//performs collision detection with a given point to check
bool Grapple::checkPointCollision(Vect2 pointToCheck, GameObject * otherObject)
{
if (pointToCheck.x >= otherObject->getRightSidePos() || pointToCheck.x <= otherObject->getLeftSidePos())
return false;
else if (pointToCheck.y >= otherObject->getTopPos() || pointToCheck.y <= otherObject->getBottomPos())
return false;
//if neither, there's a collision
else
return true;
}*/
bool Grapple::checkPointCollision(Vect2 pointToCheck, cocos2d::Rect otherObject)
{
if (pointToCheck.x >= otherObject.getMaxX() || pointToCheck.x <= otherObject.getMinX())
return false;
else if (pointToCheck.y >= otherObject.getMaxY() || pointToCheck.y <= otherObject.getMinY())
return false;
//if neither, there's a collision
else
return true;
}
/*//performs collision detection that checks for multiple points per frame
bool Grapple::checkTunnelingCollision(GameObject* otherObject)
{
Vect2 positionToCheck;
for (float positionScale = 0.25f; positionScale < 1.0f; positionScale += 0.25f)
{
positionToCheck = Vect2::lerp(lastFrameGrappleTip, grappleTip, positionScale); //lerp along the distance travelled last frame
if (checkPointCollision(positionToCheck, otherObject)) //check for collision at the determined position
{
latchPoint = positionToCheck;
grappleTip = latchPoint;
return true;
}
}
return false;
}*/
bool Grapple::checkTunnelingCollision(cocos2d::Rect otherObject)
{
Vect2 positionToCheck;
for (float positionScale = 0.25f; positionScale < 1.0f; positionScale += 0.25f)
{
positionToCheck = Vect2::lerp(lastFrameGrappleTip, grappleTip, positionScale); //lerp along the distance travelled last frame
if (checkPointCollision(positionToCheck, otherObject)) //check for collision at the determined position
{
latchPoint = positionToCheck;
grappleTip = latchPoint;
return true;
}
}
return false;
}
//goes through each tile looking for collision
bool Grapple::checkAllPlatformCollisions()
{
//loop through each platform tile to check for intersects
unsigned int tileListSize = PlatformTile::platformTileList.size();
for (unsigned int i = 0; i < tileListSize; i++)
{
cocos2d::Vec2 platformStart = Vec2(PlatformTile::platformTileList[i]->hitBox.getMinX(), PlatformTile::platformTileList[i]->hitBox.getMidY());
cocos2d::Vec2 platformEnd = Vec2(PlatformTile::platformTileList[i]->hitBox.getMaxX(), PlatformTile::platformTileList[i]->hitBox.getMidY());
Vec2 intersectPoint = myHelper::getLineLineIntersect(
Vec2(lastFrameGrappleTip.x, lastFrameGrappleTip.y),
Vec2(grappleTip.x, grappleTip.y),
platformStart,
platformEnd);
//there is an intersection
if (intersectPoint != Vec2(0, 0))
{
latchPoint = intersectPoint;
grappleTip = latchPoint;
return true;
}
}
return false; //no collision
}
void Grapple::update(float dt, Scene* scene)
{
if (isActive)
{
tip->setScale(1.2f);
//indicator->setVisible(0);
startPoint = Vect2(Hero::hero->arm->getPosition()); //have grapple start point move with the hero
if (isLatched)
{
heroMoveScale += 25 / heroToLatchPointDistance;
//check if the hero has reached the end of the grapple latch point
if (heroMoveScale >= 1.0f)
{
//hide grappling sprites
Hero::hero->arm->setVisible(0);
sprite->setVisible(0);
grapple->tip->setVisible(0);
indicator->setVisible(0);
isHeroAtEndPoint = true;
heroMoveScale = 1.0f;
latchDuration += dt;
}
//move the hero to the new position, determined by lerping along the grapple
Vect2 newHeroPosition = Vect2::lerp(heroLatchPosition, latchPoint, heroMoveScale);
Hero::hero->arm->setPosition(Vec2(newHeroPosition.x, newHeroPosition.y));
Hero::hero->updatePositionBasedOnArm();
Hero::hero->velocity.y = 0;
//check to see if the hero has been latched for beyond the max duration
if (latchDuration > 0.5f)
unLatch();
}
else
{
extendGrapple(); //recalculate endpoint, ensuring that the initial mouse clicked position is passed through
grappleTip = Vect2::lerp(startPoint, endPoint, lengthScale); //use lerp to increase the length of the grapple each frame until it reaches the end point
heroToDestinationDistance = Vect2::calculateDistance(startPoint, endPoint);
lengthScale += 35 / heroToDestinationDistance;
//check for collision on each platform
if (checkAllPlatformCollisions())
latch();
//check for collision on each ground tile
unsigned int numGroundTiles = GroundTile::groundTileList.size();
for (unsigned int i = 0; i < numGroundTiles; i++)
{
if (checkTunnelingCollision(GroundTile::groundTileList[i]->hitBox))
{
unLatch();
break;
}
}
//limit length scale factor to 1 (1 being the endpoint) or max length being reached
if (lengthScale > 1.0f || isMaxLength())
unLatch();
lastFrameGrappleTip = grappleTip;
}
if (isActive)
{
float grappleDistance = Vect2::calculateDistance(startPoint, grappleTip);
//show grapple sprite and rotate properly
sprite->setAnchorPoint(Vec2(0.5f, 0.0f));
sprite->setTextureRect(cocos2d::Rect(startPoint.x, startPoint.y, 4, grappleDistance));
sprite->setPosition(Vec2(startPoint.x, startPoint.y));
sprite->setRotation(theta * 180 / M_PI);
//show grapple tip sprite and rotate properly
tip->setPosition(Vec2(grappleTip.x, grappleTip.y));
tip->setRotation(theta * 180 / M_PI);
}
//rotate arm
Hero::hero->arm->setRotation(theta * 180 / M_PI);
}
else //grapple is inactive
predictCollision();
}
<file_sep>#include "Boss/Ability States/RestingState.h"
#include "Boss/General/Boss.h"
RestingState::RestingState(Boss* aBossInstance)
:FirstBossState(aBossInstance), onTime(5.f)
{
//Get animation
cocos2d::Animate* animation = marcos::AnimationManager::getAnimation("boss_resting_animation_key");
//Run action
bossPointer->getSprite()->runAction(cocos2d::RepeatForever::create(animation));
}
/**
* @brief Reduce the onTime for the state
* @param deltaTime The change of time from last frame to current frame
*/
void RestingState::update(const float& deltaTime)
{
onTime -= deltaTime;
if (onTime <= 0)
changeToIdleState();
}
<file_sep>#include "MeleeFireAttack.h"
#include "Hero.h"
#include "EmptyAttack.h"
#include "HeroAttackManager.h"
MeleeFireAttack::MeleeFireAttack()
{
attackTimer = 0.0f;
attackWindup = 0.2f;
attackDuration = 0.2f;
attackCooldown = 0.12f;
disabled = false;
}
//directional attacks (set attack hitbox based on direction)
void MeleeFireAttack::attackUp()
{
hitbox.setRect(
Hero::hero->hurtBox.getMinX() - 20,
Hero::hero->getBottomPos() + Hero::hero->height / 1.5,
Hero::hero->hurtBox.size.width + 40,
130);
}
void MeleeFireAttack::attackDown()
{
hitbox.setRect(
Hero::hero->hurtBox.getMinX() - 20,
Hero::hero->getBottomPos() + Hero::hero->height / 2.5,
Hero::hero->hurtBox.size.width + 40,
-130);
}
void MeleeFireAttack::attackLeft()
{
hitbox.setRect(
Hero::hero->hurtBox.getMaxX() - 130,
Hero::hero->getBottomPos() + Hero::hero->height / 2.5,
130,
50);
}
void MeleeFireAttack::attackRight()
{
hitbox.setRect(
Hero::hero->hurtBox.getMinX(),
Hero::hero->getBottomPos() + Hero::hero->height / 2.5,
130,
50);
}
//initialize the attack
void MeleeFireAttack::initAttack()
{
//aim upwards
if (HeroAttackBase::isWKeyHeld)
{
performAttack = &MeleeFireAttack::attackUp; //setting member function pointer
if (Hero::hero->lookState == Hero::LookDirection::lookingRight)
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("melee_up_right_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::CCRepeat::create(action->clone(), 1));
}
else
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("melee_up_left_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::CCRepeat::create(action->clone(), 1));
}
}
//aim downwards
else if (HeroAttackBase::isSKeyHeld)
performAttack = &MeleeFireAttack::attackDown;
//aim right
else if (Hero::hero->lookState == Hero::LookDirection::lookingRight)
{
performAttack = &MeleeFireAttack::attackRight;
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("melee_right_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::CCRepeat::create(action->clone(), 1));
}
//aim left
else if (Hero::hero->Hero::hero->lookState == Hero::LookDirection::lookingLeft)
{
performAttack = &MeleeFireAttack::attackLeft;
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("melee_left_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::CCRepeat::create(action->clone(), 1));
}
}
void MeleeFireAttack::update(float dt)
{
//before the attack hitbox should appear
if (attackTimer < attackWindup)
{
attackTimer += dt;
}
//during the attack duration
else if (attackTimer < attackDuration + attackWindup)
{
if (disabled)
hitbox = hitbox.ZERO; //deactivate hitbox
else //attack is not disabled
(this->*performAttack)(); //calling member function pointer
attackTimer += dt;
}
//after the attack is finished
else
{
attackTimer = 0.0f;
hitbox = hitbox.ZERO; //deactivate hitbox
disabled = false; //undisable if needed
HeroAttackManager::empty->attackCooldown = this->attackCooldown;
HeroAttackManager::setCurrentAttack(HeroAttackTypes::emptyA, nullptr);
}
}<file_sep>#include "FallingState.h"
#include "HeroStateManager.h"
#include "Hero.h"
#include "Grapple.h"
FallingState::FallingState()
{
}
FallingState::~FallingState()
{
}
void FallingState::onEnter()
{
HeroStateManager::currentState = this;
if (Hero::hero->lookState == Hero::LookDirection::lookingLeft)
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("falling_left_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::RepeatForever::create(action->clone()));
}
else
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("falling_right_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::RepeatForever::create(action->clone()));
}
}
void FallingState::onExit()
{
if (Hero::hero->moveState == Hero::MoveDirection::idle)
HeroStateManager::idle->onEnter();
else //moving
HeroStateManager::running->onEnter();
}
void FallingState::handleInput(InputType input)
{
switch (input)
{
case InputType::p_a:
//if the hero is changing directions, call onEnter() again to play the proper animation
if (Hero::hero->lookState == Hero::LookDirection::lookingRight)
{
Hero::hero->lookState = Hero::LookDirection::lookingLeft;
onEnter();
}
break;
case InputType::p_d:
//if the hero is changing directions, call onEnter() again to play the proper animation
if (Hero::hero->lookState == Hero::LookDirection::lookingLeft)
{
Hero::hero->lookState = Hero::LookDirection::lookingRight;
onEnter();
}
break;
case InputType::r_space:
//variable jump height
Hero::hero->velocity.y /= 1.5;
break;
}
}
void FallingState::update(float dt)
{
if (Hero::hero->moveState == Hero::MoveDirection::movingLeft)
Hero::hero->moveLeft();
else if (Hero::hero->moveState == Hero::MoveDirection::movingRight)
Hero::hero->moveRight();
if (Hero::hero->velocity.y == 0)
onExit();
}
<file_sep>#pragma once
#ifndef GRAPPLEJUMPSTATE_H
#define GRAPPLEJUMPSTATE_H
#include "HeroStateBase.h"
class GrappleJumpState : public HeroStateBase
{
public:
GrappleJumpState();
~GrappleJumpState();
void onEnter();
void onExit();
void handleInput(InputType input);
void update(float dt);
};
#endif<file_sep>#include "HeroMoveRight.h"
#include "Hero.h"
HeroMoveRight::HeroMoveRight()
{
}
void HeroMoveRight::init()
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("running_right_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->setFlippedX(0);
Hero::hero->sprite->runAction(cocos2d::RepeatForever::create(action->clone()));
}
void HeroMoveRight::update(float dt)
{
Hero::hero->moveRight();
}<file_sep>#include "HeroStateBase.h"<file_sep>#include "PrettyPictureScene.h"
#include "Boss1Scene.h"
#include <SimpleAudioEngine.h>
Scene * PrettyPictureScene::createScene()
{
Scene* scene = PrettyPictureScene::create();
return scene;
}
bool PrettyPictureScene::init()
{
if (!Scene::init())
return false;
director = Director::getInstance();
//Setting the default animation rate for the director
director->setAnimationInterval(1.0f / 60.0f);
image = Sprite::create("Backgrounds/cutscene.png");
image->setAnchorPoint(Vec2(0.0f, 0.0f));
image -> setPosition(Vec2(0.0f, 0.0f));
this->addChild(image);
timer = 0.0f;
isDone = false;
auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
audio->stopBackgroundMusic();
scheduleUpdate();
return true;
}
void PrettyPictureScene::update(float dt)
{
timer += dt;
if (timer > 10.0f && !isDone)
{
isDone = true;
director->replaceScene(TransitionFade::create(1.5f, Boss1Scene::createScene(), Color3B(0, 0, 0)));
}
}<file_sep>#pragma once
#ifndef MELEEFIREATTACK_H
#define MELEEFIREATTACK_H
#include "HeroAttackBase.h"
class MeleeFireAttack : public HeroAttackBase
{
public:
MeleeFireAttack();
void initAttack();
void attackUp();
void attackDown();
void attackLeft();
void attackRight();
void (MeleeFireAttack::*performAttack)(); //member function pointer.. syntax with these guys are weird
void update(float dt);
};
#endif<file_sep>#include "InputHandler.h"
//--- Static Variables ---//
InputHandler* InputHandler::inst = 0;
//--- Constructor and Destructor ---//
InputHandler::InputHandler()
{
}
InputHandler::~InputHandler()
{
//Delete the singleton instance
delete inst;
inst = nullptr;
}
//--- Setters and Getters ---//
//Mouse
Vec2 InputHandler::getMousePosition() const
{
//Return the position of the mouse cursor, from the BOTTOM LEFT! Flipped on the y-axis from the value that Cocos returns
return mousePosition;
}
bool InputHandler::getMouseButtonPress(MouseButton button) const
{
//If the mouse button requested is set to pressed, it was pressed this exact frame. +1 since the first mouse button is set to -1
return (mouseStates[(int)button + 1] == InputState::Pressed);
}
bool InputHandler::getMouseButtonRelease(MouseButton button) const
{
//If the mouse button requested is set to released, it was released this exact frame. +1 since the first mouse button is set to -1
return (mouseStates[(int)button + 1] == InputState::Released);
}
bool InputHandler::getMouseButton(MouseButton button) const
{
//If the mouse button requested is set to pressed OR set to held, it is currently down and so should return true
return (mouseStates[(int)button + 1] == InputState::Pressed || mouseStates[(int)button + 1] == InputState::Held);
}
float InputHandler::getMouseScroll() const
{
//TO DO: Implement mouse scroll capabilities
return 0.0f;
}
//Keyboard
bool InputHandler::getKeyPress(KeyCode key) const
{
//If the key requested is set to pressed, it was pressed this exact frame
return (keyboardStates[(int)key] == InputState::Pressed);
}
bool InputHandler::getKeyRelease(KeyCode key) const
{
//If the key requested is set to released, it was released this exact frame
return (keyboardStates[(int)key] == InputState::Released);
}
bool InputHandler::getKey(KeyCode key) const
{
//If the key requested is set to pressed OR set to held, it is currently down and so should return true
return (keyboardStates[(int)key] == InputState::Pressed || keyboardStates[(int)key] == InputState::Held);
}
//--- Methods ---//
void InputHandler::updateInputs()
{
//Loop through the mouse buttons and update their states. If they were pressed last frame, they are now held. If they were released last frame, they are now idle.
for (int i = 0; i < NUM_MOUSE_BUTTONS; i++)
{
if (mouseStates[i] == InputState::Idle)
continue;
if (mouseStates[i] == InputState::Pressed)
mouseStates[i] = InputState::Held;
else if (mouseStates[i] == InputState::Released)
mouseStates[i] = InputState::Idle;
}
//Loop through the keyboard buttons and update their states. If they were pressed last frame, they are now held. If they were released last frame, they are now idle.
for (int i = 0; i < NUM_KEY_CODES; i++)
{
if (keyboardStates[i] == InputState::Idle)
continue;
if (keyboardStates[i] == InputState::Pressed)
keyboardStates[i] = InputState::Held;
else if (keyboardStates[i] == InputState::Released)
keyboardStates[i] = InputState::Idle;
}
}
//--- Singleton Instance ---//
InputHandler* InputHandler::getInstance()
{
//Generate the singleton if it hasn't been created yet
if (!inst)
inst = new InputHandler();
//Return the singleton
return inst;
}
<file_sep>#pragma once
#ifndef GRAPPLE_H
#define GRAPPLE_H
#include "cocos2d.h"
#include "Vect2.h"
#include "Platform.h"
class Grapple
{
private:
Grapple();
public:
static Grapple* grapple;
void initGrapple();
static const float MOVE_SPEED;
static const float MAX_LENGTH;
Sprite* sprite;
Sprite* tip;
Sprite* indicator;
Hero::LookDirection lookDirectionOnShoot;
Vect2 initialPosClicked;
Vect2 startPoint;
Vect2 endPoint;
Vect2 grappleTip;
Vect2 lastFrameGrappleTip;
Vect2 latchPoint;
Vect2 heroLatchPosition;
float lengthScale;
float heroMoveScale;
float theta;
float latchDuration;
float heroToLatchPointDistance;
float heroToDestinationDistance;
Color4F grappleColour;
bool isActive;
bool isLatched;
bool isHeroAtEndPoint;
void predictCollision();
void shoot(Vect2 destination);
void shoot(float a_theta);
void extendGrapple();
void latch();
void unLatch();
bool isMaxLength();
void performGrapplePrediction();
bool isCollidingWith(cocos2d::Rect otherObject);
bool checkPointCollision(Vect2 pointToCheck, cocos2d::Rect otherObject);
bool checkTunnelingCollision(cocos2d::Rect otherObject);
bool checkAllPlatformCollisions();
void update(float dt, Scene* scene);
};
#endif<file_sep>#pragma once
#include <Windows.h>
#include <Xinput.h>
#include <cmath>
#pragma comment(lib,"Xinput.lib")
//Buttons used for the controllers
enum CONTROLLER_INPUT_BUTTONS
{
DPAD_UP = XINPUT_GAMEPAD_DPAD_UP,
DPAD_DOWN = XINPUT_GAMEPAD_DPAD_DOWN,
DPAD_LEFT = XINPUT_GAMEPAD_DPAD_LEFT,
DPAD_RIGHT = XINPUT_GAMEPAD_DPAD_RIGHT,
A = XINPUT_GAMEPAD_A,
B = XINPUT_GAMEPAD_B,
X = XINPUT_GAMEPAD_X,
Y = XINPUT_GAMEPAD_Y,
LB = XINPUT_GAMEPAD_LEFT_SHOULDER,
RB = XINPUT_GAMEPAD_RIGHT_SHOULDER,
THUMB_LEFT = XINPUT_GAMEPAD_LEFT_THUMB,
THUMB_RIGHT = XINPUT_GAMEPAD_RIGHT_THUMB,
SELECT = XINPUT_GAMEPAD_BACK,
START = XINPUT_GAMEPAD_START
};
enum STICK_NAMES
{
LS,
RS
};
enum TRIGGER_NAMES
{
LT,
RT
};
//The X & Y input of the controller given as a float value from -1 -> 1
struct Stick
{
float x, y;
};
//The left and right trigger values that are given as a float value from 0 -> 1
struct Triggers
{
float LT, RT;
};
class XinputController
{
public:
//...
void setControllerIndex(int index)
{
this->index = index;
}
void update()
{
if (index >= 0 && index < 4)
XInputGetState(index, &info);
}
void deadZoneSticks(float dz)
{
deadZoneStick = dz;
}
void deadZoneTriggers(float dz)
{
deadZoneTrigger = dz;
}
bool isButtonPressed(int button)
{
return button & info.Gamepad.wButtons;
}
bool isButtonReleased(int button)
{
return !isButtonPressed(button);
}
void getSticks(Stick sticks[2])
{
//left stick
float x = (float)info.Gamepad.sThumbLX / 32768;
float y = (float)info.Gamepad.sThumbLY / 32768;
if (sqrt(x*x + y*y) > deadZoneStick)
{
if (info.Gamepad.sThumbLX < 0)
sticks[0].x = (float)info.Gamepad.sThumbLX / 32768; //convert to a float from -1 -> 1
else
sticks[0].x = (float)info.Gamepad.sThumbLX / 32767; //convert to a float from -1 -> 1
if (info.Gamepad.sThumbLY < 0)
sticks[0].y = (float)info.Gamepad.sThumbLY / 32768; //convert to a float from -1 -> 1
else
sticks[0].y = (float)info.Gamepad.sThumbLY / 32767; //convert to a float from -1 -> 1
}
else
sticks[0] = { 0,0 };
//right stick
x = (float)info.Gamepad.sThumbRX / 32768;
y = (float)info.Gamepad.sThumbRY / 32768;
if (sqrt(x*x + y*y) > deadZoneStick)
{
if (info.Gamepad.sThumbRX < 0)
sticks[1].x = (float)info.Gamepad.sThumbRX / 32768; //convert to a float from -1 -> 1
else
sticks[1].x = (float)info.Gamepad.sThumbRX / 32767; //convert to a float from -1 -> 1
if (info.Gamepad.sThumbRY < 0)
sticks[1].y = (float)info.Gamepad.sThumbRY / 32768; //convert to a float from -1 -> 1
else
sticks[1].y = (float)info.Gamepad.sThumbRY / 32767; //convert to a float from -1 -> 1
}
else
sticks[1] = { 0,0 };
}
void getTriggers(Triggers &triggers)
{
float l = (float)info.Gamepad.bLeftTrigger / 255;
float r = (float)info.Gamepad.bRightTrigger / 255;
triggers = Triggers{ l<deadZoneTrigger ? 0 : l , r < deadZoneTrigger ? 0 : r};
}
private:
//...
int index = -1;
XINPUT_STATE info;
float deadZoneStick;
float deadZoneTrigger;
};
class XinputManager
{
public:
//...
bool create();
static XinputManager* instance;
static bool controllerConnected(int index);
static XinputController* getController(int index);
static void update();
private:
//...
XinputManager();
static XinputController controllers[4];
};<file_sep>#pragma once
#ifndef FALLINGSTATE_H
#define FALLINGSTATE_H
#include "HeroStateBase.h"
class FallingState : HeroStateBase
{
public:
FallingState();
~FallingState();
void onEnter();
void onExit();
void handleInput(InputType input);
void update(float dt);
};
#endif<file_sep>#pragma once
#include "Boss/Attacks/ExplosiveBulletProjectile.h"
#include "Boss/Attacks/FlameThrowerProjectile.h"
#include "Boss/Attacks/LavaBallProjectile.h"<file_sep>#include "Boss1Attack.h"
#include "Boss/General/Boss.h"
#include "Boss/General/HitBox.h"
Boss1LavaAttack::Boss1LavaAttack(Boss* bossInstance, const std::string& fileName)
: bossPointer(bossInstance), sprite(cocos2d::Sprite::create(fileName))
{
bossPointer->getBossScene()->addChild(sprite, 18);
}
Boss1LavaAttack::~Boss1LavaAttack()
{
delete hitBox;
bossPointer->getBossScene()->removeChild(sprite);
}
/**
* @brief This class update its data members
*/
void Boss1LavaAttack::update(const float& deltaT)
{
hitBox->updateHitBox(position);
}
/**
* @brief This function will resolve the attack object
* when it collides with hero
*/
void Boss1LavaAttack::hitByHero()
{
}
/**
* @brief This function will resolve the attack object
* when it collides with an environment object
*/
void Boss1LavaAttack::hitByEnvironment()
{
}
/**
* @brief Gets the hitbox for the attack
*
* @return Return cocos2d::Rect
*/
cocos2d::Rect Boss1LavaAttack::getHitBox() const
{
return hitBox->hitBox;
}
Boss1LavaAttack::BossAttack Boss1LavaAttack::getAttackType() const
{
return attackType;
}
int Boss1LavaAttack::getDealingDamage() const
{
return dealingDamage;
}
<file_sep>#pragma once
//Header Files
#include <2d/CCSprite.h>
#include "HitBox.h"
#include "Boss/Ability States/FirstBossState.h"
#include "Animation.h"
//Foward Declare Classes
class Hero;
class Boss1LavaAttack;
class Boss
{
enum HitboxIndex
{
idling, //Use this for idling, explosive bullet
flameSplitter,
flamethrower,
death
};
friend class FirstBossState;
//Private data members
int health;
FirstBossState *state;
cocos2d::Sprite *sprite;
std::vector<Boss1LavaAttack*> lavaList;
std::vector<std::vector<HitBox*>> hitBoxLists;
HitboxIndex hitboxIndex{ idling };
cocos2d::Scene *bossScene;
//Private functions
void initHitbox();
std::vector<HitBox*> initIdleHitbox() const;
std::vector<HitBox*> initFlameSplitHitbox() const;
std::vector<HitBox*> initFlameThrowerHitbox() const;
std::vector<HitBox*> initDeathHitbox() const;
void setHitboxIndex(HitboxIndex newIndex);
public:
Boss(Hero* heroInstance, cocos2d::Scene *sceneForBoss, float height = 581, float width = 325);
~Boss();
//Setters
void setState(FirstBossState *newState);
//Getters
int getHealth() const;
cocos2d::Sprite* getSprite() const;
std::vector<Boss1LavaAttack*> getLavaList() const;
cocos2d::Scene* getBossScene() const;
std::vector<HitBox*> getHitBox() const;
FirstBossState* getCurrentState() const;
//Member functions
void takeDamage();
void update(const float &deltaT);
//Attack functions
void spewLava();
void activateFlameThrower();
void shootExplosiveBullet();
//Utility functions
void removeFromLavaList(Boss1LavaAttack *attackToRemove);
void addAttack(Boss1LavaAttack* attackToAdd);
};<file_sep>#pragma once
#ifndef PRETTYPICTURESCENE_H
#define PRETTYPICTURESCENE_H
#include "cocos2d.h"
using namespace cocos2d;
class PrettyPictureScene : public cocos2d::Scene
{
public:
CREATE_FUNC(PrettyPictureScene);
static Scene* createScene();
bool init();
void update(float dt);
private:
Director* director;
Sprite* image;
bool isDone;
float timer;
};
#endif<file_sep>#pragma once
#ifndef INITIALLOADSCENE_H
#define INITIALLOADSCENE_H
#include "cocos2d.h"
using namespace cocos2d;
class InitialLoadScreen : public cocos2d::Scene
{
public:
CREATE_FUNC(InitialLoadScreen);
static Scene* createScene();
bool init();
void preloadAnimations();
void update(float dt);
private:
Director* director;
Sprite* image;
bool isDone;
float timer;
};
#endif<file_sep>#pragma once
#ifndef TILEBASE_H
#define TILEBASE_H
#include "cocos2d.h"
class GameObject; //forward declare
enum TileType
{
platform,
ground,
spike
};
//base class for a tile
class TileBase
{
public:
TileBase(cocos2d::Vec2 position, float tileSize);
static std::vector<TileBase*> tileList;
static void deleteAllTiles();
cocos2d::Rect hitBox;
TileType type;
bool checkGeneralCollision(GameObject* otherObject);
virtual bool checkAndResolveCollision(GameObject* otherObject) = 0;
};
#endif<file_sep>#include "ShootingGrappleState.h"
#include "Hero.h"
#include "Grapple.h"
#include "HeroStateManager.h"
ShootingGrappleState::ShootingGrappleState()
{
}
ShootingGrappleState::~ShootingGrappleState()
{
}
void ShootingGrappleState::onEnter()
{
if (HeroStateManager::currentState != HeroStateManager::dying)
{
HeroStateManager::currentState = this;
if (Hero::hero->lookState == Hero::LookDirection::lookingLeft)
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("shooting_grapple_left_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::Repeat::create(action->clone(), 1));
}
else
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("shooting_grapple_right_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::Repeat::create(action->clone(), 1));
}
}
}
void ShootingGrappleState::onExit()
{
//determine which state to transition into
if (Grapple::grapple->isActive)
HeroStateManager::grappling->onEnter();
else if (Hero::hero->velocity.y < 0)
HeroStateManager::falling->onEnter();
else if (Hero::hero->velocity.y > 0)
HeroStateManager::jumping->onEnter();
else if (Hero::hero->moveState != Hero::MoveDirection::idle)
HeroStateManager::running->onEnter();
else
HeroStateManager::idle->onEnter();
}
void ShootingGrappleState::handleInput(InputType input)
{
switch (input)
{
case InputType::p_space:
Hero::hero->jump();
break;
case InputType::r_space:
//variable jump height
Hero::hero->velocity.y /= 1.5;
break;
}
}
void ShootingGrappleState::update(float dt)
{
if (Hero::hero->moveState == Hero::MoveDirection::movingLeft)
Hero::hero->moveLeft();
else if (Hero::hero->moveState == Hero::MoveDirection::movingRight)
Hero::hero->moveRight();
if (Grapple::grapple->isLatched || !Grapple::grapple->isActive) //if the grapple latches onto something or becomes inactive (doesnt hit anything)
onExit();
}
<file_sep>#include "HoldingPlatformState.h"
#include "Hero.h"
#include "HeroStateManager.h"
#include "Grapple.h"
HoldingPlatformState::HoldingPlatformState()
{
}
HoldingPlatformState::~HoldingPlatformState()
{
}
void HoldingPlatformState::onEnter()
{
HeroStateManager::currentState = this;
if (Hero::hero->lookState == Hero::LookDirection::lookingLeft)
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("grapple_hold_left_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::RepeatForever::create(action->clone()));
}
else
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("grapple_hold_right_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::RepeatForever::create(action->clone()));
}
}
void HoldingPlatformState::onExit()
{
HeroStateManager::falling->onEnter();
}
void HoldingPlatformState::handleInput(InputType input)
{
switch (input)
{
case InputType::p_s: //let go of the platform and start falling down
Grapple::grapple->unLatch();
HeroStateManager::falling->onEnter();
break;
case InputType::p_space: //jump from the holding position
HeroStateManager::grappleJumping->onEnter();
break;
}
}
void HoldingPlatformState::update(float dt)
{
Hero::hero->velocity.y = 0;
if (!Grapple::grapple->isActive)
onExit();
}<file_sep>#include "EmptyAttack.h"
EmptyAttack::EmptyAttack() :
onCooldown(false)
{
hitbox = cocos2d::Rect::ZERO;
attackTimer = 0.0f;
attackCooldown = 0.0f;
}
void EmptyAttack::update(float dt)
{
attackTimer += dt;
if (attackTimer < attackCooldown)
onCooldown = true;
else
{
onCooldown = false;
attackTimer = 0.0f;
attackCooldown = 0.0f;
}
}<file_sep>#pragma once
#ifndef VECT2_H
#define VECT2_H
#include "cocos2d.h"
class Vect2
{
public:
float x;
float y;
Vect2();
Vect2(const float x, const float y);
Vect2(cocos2d::Vec2 vector);
Vect2 operator+(const Vect2 a) const;
Vect2 operator-(const Vect2 a) const;
Vect2 operator*(const Vect2 a) const;
Vect2 operator/(const Vect2 a) const;
Vect2 operator+=(const Vect2 a);
Vect2 operator-=(const Vect2 a);
Vect2 operator*=(const Vect2 a);
Vect2 operator/=(const Vect2 a);
Vect2 operator*(const float scalar) const;
Vect2 operator/(const float scalar) const;
Vect2 operator+(const float scalar) const;
Vect2 operator-(const float scalar) const;
Vect2 operator+=(const float scalar);
Vect2 operator-=(const float scalar);
Vect2 operator*=(const float scalar);
Vect2 operator/=(const float scalar);
friend bool operator> (const Vect2 vector, const float scalar);
friend bool operator< (const Vect2 vector, const float scalar);
friend bool operator> (const Vect2 lhs, const Vect2 rhs);
friend bool operator< (const Vect2 lhs, const Vect2 rhs);
friend Vect2 operator+(const float a, const Vect2 b);
friend Vect2 operator-(const float a, const Vect2 b);
Vect2 operator-() const;
const float & Vect2::operator[](int index) const;
float & Vect2::operator[](int index);
void set(float newX, float newY);
float getMagnitude();
float getMagnitudeSquared();
Vect2 getNormalized();
float dotProduct(const Vect2 rhs);
float crossProduct(const Vect2 rhs);
static float calculateDistance(const Vect2 vectA, const Vect2 vectB);
static float calculateDistanceSquared(const Vect2 vectA, const Vect2 vectB);
static Vect2 lerp(Vect2 vectA, Vect2 vectB, float scaleFactor);
};
#endif<file_sep>#pragma once
#ifndef ATTACKINGSTATE_H
#define ATTACKINGSTATE_H
#include "HeroStateBase.h"
class AttackingState : public HeroStateBase
{
public:
AttackingState();
~AttackingState();
void onEnter();
void onExit();
void handleInput(InputType input);
void update(float dt);
};
#endif<file_sep>#pragma once
#include "FirstBossState.h"
class FlameSplit4FirstBoss : public FirstBossState
{
public:
FlameSplit4FirstBoss(Boss *boss);
};<file_sep>#pragma once
#ifndef HEROSTATEBASE_H
#define HEROSTATEBASE_H
#include "InputType.h"
#include "cocos2d.h"
#include "ControllerInput.h"
class HeroStateBase
{
public:
virtual void onEnter() = 0;
virtual void onExit() = 0;
virtual void handleInput(InputType input) = 0;
virtual void update(float dt) = 0;
};
#endif<file_sep>#pragma once
//Header files
#include <math/Vec2.h>
#include <2d/CCSprite.h>
//Foward declare classes
class Boss;
class HitBox;
/**
* This class is the base class for all attacks for the boss.\n
* This class cannot be created by itself.
*/
class Boss1LavaAttack
{
public:
enum BossAttack
{
ExplosiveBullet,
Flamethrower,
LavaBall
};
virtual ~Boss1LavaAttack();
//Member functions
virtual void update(const float &deltaT);
virtual void hitByHero();
virtual void hitByEnvironment();
//Getters
cocos2d::Rect getHitBox() const;
BossAttack getAttackType() const;
int getDealingDamage() const;
protected:
//Protected Variables
Boss *bossPointer;
cocos2d::Vec2 position, velocity, acceleration;
cocos2d::Sprite *sprite;
HitBox *hitBox;
BossAttack attackType;
int dealingDamage{ 1 };
//Protected Constructor
Boss1LavaAttack(Boss *bossInstance, const std::string& fileName);
};
<file_sep>#pragma once
#ifndef INPUTTYPE_H
#define INPUTTYPE_H
/*
KEYBOARD INPUT FORMAT:
<'p'ress or 'r'elease>_<key name> ex. q_r = release q key
*/
enum InputType
{
//key press
p_1,
p_2,
p_3,
p_4,
p_5,
p_6,
p_7,
p_8,
p_9,
p_0,
p_q,
p_w,
p_e,
p_r,
p_t,
p_y,
p_u,
p_i,
p_o,
p_p,
p_a,
p_s,
p_d,
p_f,
p_g,
p_h,
p_j,
p_k,
p_l,
p_z,
p_x,
p_c,
p_v,
p_b,
p_n,
p_m,
p_esc,
p_shift,
p_tab,
p_ctrl,
p_space,
p_alt,
//key release
r_1,
r_2,
r_3,
r_4,
r_5,
r_6,
r_7,
r_8,
r_9,
r_0,
r_q,
r_w,
r_e,
r_r,
r_t,
r_y,
r_u,
r_i,
r_o,
r_p,
r_a,
r_s,
r_d,
r_f,
r_g,
r_h,
r_j,
r_k,
r_l,
r_z,
r_x,
r_c,
r_v,
r_b,
r_n,
r_m,
r_esc,
r_shift,
r_tab,
r_ctrl,
r_space,
r_alt,
//mouse press
leftclick_down,
rightclick_down,
//mouse release
leftclick_up,
rightclick_up,
//mouse scroll
scrollup,
scrolldown
};
#endif<file_sep>#include "DeathScreen.h"
#include "MainMenu.h"
#include "Tutorial.h"
#include "Boss1Scene.h"
#include <SimpleAudioEngine.h>
Scene * DeathScreen::createScene()
{
Scene* scene = DeathScreen::create();
return scene;
}
bool DeathScreen::init()
{
if (!Scene::init())
return false;
currentSelection = MenuOptions::nothing;
director = Director::getInstance();
//Setting the default animation rate for the director
director->setAnimationInterval(1.0f / 60.0f);
initUI();
initAnimations();
initMusic();
//init listeners
initMouseListener();
initControllerListener();
scheduleUpdate();
return true;
}
void DeathScreen::initUI()
{
//set background
background = Sprite::create("Backgrounds/deathScreen.png");
background->setAnchorPoint(Vec2(0.0f, 0.0f));
this->addChild(background, 1);
textOverlay = Sprite::create("Backgrounds/uLoseTest.png");
textOverlay->setAnchorPoint(Vec2(0.0f, 0.0f));
this->addChild(textOverlay, 2);
//set our sprite labels
tryAgainText = Sprite::create("Text/tryAgainTest.png");
tryAgainText->setPosition(1920 / 2, 600);
this->addChild(tryAgainText, 10);
mainMenuText = Sprite::create("Text/mainMenuTest.png");
mainMenuText->setPosition(1920 / 2, 400);
this->addChild(mainMenuText, 10);
exitText = Sprite::create("Text/exitTest2.png");
exitText->setPosition(1920 / 2, 200);
this->addChild(exitText, 10);
//set rects for label hover/click
tryAgainRect.setRect(tryAgainText->getPositionX() - 300, tryAgainText->getPositionY() - 100, 600, 200);
mainMenuRect.setRect(mainMenuText->getPositionX() - 300, mainMenuText->getPositionY() - 100, 600, 200);
exitRect.setRect(exitText->getPositionX() - 300, exitText->getPositionY() - 100, 600, 200);
}
void DeathScreen::initAnimations()
{
}
void DeathScreen::initMusic()
{
auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
audio->resumeBackgroundMusic();
}
void DeathScreen::initMouseListener()
{
//Init the mouse listener
mouseListener = EventListenerMouse::create();
//On Mouse Down
mouseListener->onMouseDown = CC_CALLBACK_1(DeathScreen::mouseDownCallback, this);
//On Mouse Up
mouseListener->onMouseUp = CC_CALLBACK_1(DeathScreen::mouseUpCallback, this);
//On Mouse Move
mouseListener->onMouseMove = CC_CALLBACK_1(DeathScreen::mouseMoveCallback, this);
//On Mouse Scroll
mouseListener->onMouseScroll = CC_CALLBACK_1(DeathScreen::mouseScrollCallback, this);
//Add the mouse listener to the dispatcher
_eventDispatcher->addEventListenerWithSceneGraphPriority(mouseListener, this);
}
void DeathScreen::initControllerListener()
{
controllerListener = EventListenerController::create();
//set up callbacks
controllerListener->onKeyDown = CC_CALLBACK_3(DeathScreen::buttonPressCallback, this);
controllerListener->onKeyUp = CC_CALLBACK_3(DeathScreen::buttonReleaseCallback, this);
controllerListener->onAxisEvent = CC_CALLBACK_3(DeathScreen::axisEventCallback, this);
controllerListener->onConnected = [](cocos2d::Controller* controller, cocos2d::Event* evt) {};
//add the controller listener to the dispatcher
_eventDispatcher->addEventListenerWithSceneGraphPriority(controllerListener, this);
}
//move to the next selection on the menu
void DeathScreen::moveToNextMenuItem()
{
switch (currentSelection)
{
case MenuOptions::nothing:
currentSelection = MenuOptions::tryAgain;
break;
case MenuOptions::tryAgain:
currentSelection = MenuOptions::mainMenu;
break;
case MenuOptions::mainMenu:
currentSelection = MenuOptions::exit;
break;
case MenuOptions::exit:
currentSelection = MenuOptions::tryAgain;
break;
}
}
//move back one selection on the menu
void DeathScreen::moveToPreviousMenuItem()
{
switch (currentSelection)
{
case MenuOptions::nothing:
currentSelection = MenuOptions::tryAgain;
break;
case MenuOptions::tryAgain:
currentSelection = MenuOptions::exit;
break;
case MenuOptions::mainMenu:
currentSelection = MenuOptions::tryAgain;
break;
case MenuOptions::exit:
currentSelection = MenuOptions::mainMenu;
break;
}
}
void DeathScreen::update(float dt)
{
if (!isTransitioning)
{
//check for mouse hover over menu items
if (tryAgainRect.containsPoint(cursorPos) || currentSelection == MenuOptions::tryAgain)
tryAgainText->setScale(1.2f);
else
tryAgainText->setScale(1.0f);
if (mainMenuRect.containsPoint(cursorPos) || currentSelection == MenuOptions::mainMenu)
mainMenuText->setScale(1.2f);
else
mainMenuText->setScale(1.0f);
if (exitRect.containsPoint(cursorPos) || currentSelection == MenuOptions::exit)
exitText->setScale(1.2f);
else
exitText->setScale(1.0f);
}
}
//--- Callbacks ---//
void DeathScreen::mouseDownCallback(Event* event)
{
//Cast the event as a mouse event
EventMouse* mouseEvent = dynamic_cast<EventMouse*>(event);
auto mouseButton = mouseEvent->getMouseButton();
//Get the position of the mouse button press
auto mouseClickPosition = mouseEvent->getLocationInView();
if (mouseButton == cocos2d::EventMouse::MouseButton::BUTTON_LEFT)
{
//start game
if (tryAgainRect.containsPoint(cursorPos))
{
director->replaceScene(TransitionFade::create(1.f, Boss1Scene::createScene(), Color3B(0, 0, 0)));
isTransitioning = true;
}
//open controls menu
else if (mainMenuRect.containsPoint(cursorPos))
{
director->replaceScene(TransitionFade::create(1.f, MainMenu::createScene(), Color3B(0, 0, 0)));
isTransitioning = true;
}
//exit game
else if (exitRect.containsPoint(cursorPos))
{
director->end();
}
}
if (mouseButton == cocos2d::EventMouse::MouseButton::BUTTON_RIGHT)
{
}
}
void DeathScreen::mouseUpCallback(Event* event)
{
}
void DeathScreen::mouseMoveCallback(Event* event)
{
EventMouse* mouseEvent = dynamic_cast<EventMouse*>(event);
cursorPos = mouseEvent->getLocationInView();
cursorPos.y += 1080;
}
void DeathScreen::mouseScrollCallback(Event* event)
{
}
void DeathScreen::buttonPressCallback(Controller * controller, int keyCode, Event * event)
{
switch (keyCode)
{
case ControllerInput::A:
case ControllerInput::Start:
//start game
if (currentSelection == MenuOptions::tryAgain)
{
director->replaceScene(TransitionFade::create(1.f, Boss1Scene::createScene(), Color3B(0, 0, 0)));
isTransitioning = true;
}
//open controls menu
else if (currentSelection == MenuOptions::mainMenu)
{
director->replaceScene(TransitionFade::create(1.f, MainMenu::createScene(), Color3B(0, 0, 0)));
isTransitioning = true;
}
//exit game
else if (currentSelection == MenuOptions::exit)
{
director->end();
}
break;
}
}
void DeathScreen::buttonReleaseCallback(Controller * controller, int keyCode, Event * event)
{
}
void DeathScreen::axisEventCallback(Controller * controller, int keyCode, Event * event)
{
switch (keyCode)
{
//y axis of the left stick
case ControllerInput::leftStickY:
if (controller->getKeyStatus(keyCode).value >= 1 && ControllerInput::isLeftStickReset)
{
moveToPreviousMenuItem();
ControllerInput::isLeftStickReset = false;
}
else if (controller->getKeyStatus(keyCode).value <= -1 && ControllerInput::isLeftStickReset)
{
moveToNextMenuItem();
ControllerInput::isLeftStickReset = false;
}
else if (controller->getKeyStatus(keyCode).value > -0.9 && controller->getKeyStatus(keyCode).value < 0.9)
ControllerInput::isLeftStickReset = true;
break;
}
}
<file_sep>#include "VictoryScreen.h"
#include "MainMenu.h"
#include <SimpleAudioEngine.h>
Scene * VictoryScreen::createScene()
{
Scene* scene = VictoryScreen::create();
return scene;
}
bool VictoryScreen::init()
{
if (!Scene::init())
return false;
currentSelection = MenuOptions::nothing;
director = Director::getInstance();
//Setting the default animation rate for the director
director->setAnimationInterval(1.0f / 60.0f);
initUI();
initAnimations();
//init listeners
initMouseListener();
initControllerListener();
initMusic();
scheduleUpdate();
return true;
}
void VictoryScreen::initUI()
{
//set background
background = Sprite::create("Backgrounds/winscreen.png");
background->setAnchorPoint(Vec2(0.0f, 0.0f));
this->addChild(background, 1);
textOverlay = Sprite::create("Backgrounds/uWinTest.png");
textOverlay->setAnchorPoint(Vec2(0.0f, 0.0f));
this->addChild(textOverlay, 2);
mainMenuText = Sprite::create("Text/mainMenuTest.png");
mainMenuText->setPosition(1920 / 2, 400);
this->addChild(mainMenuText, 10);
exitText = Sprite::create("Text/exitTest2.png");
exitText->setPosition(1920 / 2, 200);
this->addChild(exitText, 10);
//set rects for label hover/click
mainMenuRect.setRect(mainMenuText->getPositionX() - 300, mainMenuText->getPositionY() - 100, 600, 200);
exitRect.setRect(exitText->getPositionX() - 300, exitText->getPositionY() - 100, 600, 200);
}
void VictoryScreen::initAnimations()
{
}
void VictoryScreen::initMusic()
{
auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
audio->resumeBackgroundMusic();
}
void VictoryScreen::initMouseListener()
{
//Init the mouse listener
mouseListener = EventListenerMouse::create();
//On Mouse Down
mouseListener->onMouseDown = CC_CALLBACK_1(VictoryScreen::mouseDownCallback, this);
//On Mouse Up
mouseListener->onMouseUp = CC_CALLBACK_1(VictoryScreen::mouseUpCallback, this);
//On Mouse Move
mouseListener->onMouseMove = CC_CALLBACK_1(VictoryScreen::mouseMoveCallback, this);
//On Mouse Scroll
mouseListener->onMouseScroll = CC_CALLBACK_1(VictoryScreen::mouseScrollCallback, this);
//Add the mouse listener to the dispatcher
_eventDispatcher->addEventListenerWithSceneGraphPriority(mouseListener, this);
}
void VictoryScreen::initControllerListener()
{
controllerListener = EventListenerController::create();
//set up callbacks
controllerListener->onKeyDown = CC_CALLBACK_3(VictoryScreen::buttonPressCallback, this);
controllerListener->onKeyUp = CC_CALLBACK_3(VictoryScreen::buttonReleaseCallback, this);
controllerListener->onAxisEvent = CC_CALLBACK_3(VictoryScreen::axisEventCallback, this);
controllerListener->onConnected = [](cocos2d::Controller* controller, cocos2d::Event* evt) {};
//add the controller listener to the dispatcher
_eventDispatcher->addEventListenerWithSceneGraphPriority(controllerListener, this);
}
//move to the next selection on the menu
void VictoryScreen::moveToNextMenuItem()
{
switch (currentSelection)
{
case MenuOptions::nothing:
currentSelection = MenuOptions::mainMenu;
break;
case MenuOptions::mainMenu:
currentSelection = MenuOptions::exit;
break;
case MenuOptions::exit:
currentSelection = MenuOptions::mainMenu;
break;
}
}
//move back one selection on the menu
void VictoryScreen::moveToPreviousMenuItem()
{
switch (currentSelection)
{
case MenuOptions::nothing:
currentSelection = MenuOptions::mainMenu;
break;
case MenuOptions::mainMenu:
currentSelection = MenuOptions::exit;
break;
case MenuOptions::exit:
currentSelection = MenuOptions::mainMenu;
break;
}
}
void VictoryScreen::update(float dt)
{
if (!isTransitioning)
{
//check for mouse hover over menu items
if (mainMenuRect.containsPoint(cursorPos) || currentSelection == MenuOptions::mainMenu)
mainMenuText->setScale(1.2f);
else
mainMenuText->setScale(1.0f);
if (exitRect.containsPoint(cursorPos) || currentSelection == MenuOptions::exit)
exitText->setScale(1.2f);
else
exitText->setScale(1.0f);
}
}
//--- Callbacks ---//
void VictoryScreen::mouseDownCallback(Event* event)
{
//Cast the event as a mouse event
EventMouse* mouseEvent = dynamic_cast<EventMouse*>(event);
auto mouseButton = mouseEvent->getMouseButton();
//Get the position of the mouse button press
auto mouseClickPosition = mouseEvent->getLocationInView();
if (mouseButton == cocos2d::EventMouse::MouseButton::BUTTON_LEFT)
{
//open controls menu
if (mainMenuRect.containsPoint(cursorPos))
{
director->replaceScene(TransitionFade::create(1.f, MainMenu::createScene(), Color3B(0, 0, 0)));
isTransitioning = true;
}
//exit game
else if (exitRect.containsPoint(cursorPos))
{
director->end();
}
}
if (mouseButton == cocos2d::EventMouse::MouseButton::BUTTON_RIGHT)
{
}
}
void VictoryScreen::mouseUpCallback(Event* event)
{
}
void VictoryScreen::mouseMoveCallback(Event* event)
{
EventMouse* mouseEvent = dynamic_cast<EventMouse*>(event);
cursorPos = mouseEvent->getLocationInView();
cursorPos.y += 1080;
}
void VictoryScreen::mouseScrollCallback(Event* event)
{
}
void VictoryScreen::buttonPressCallback(Controller * controller, int keyCode, Event * event)
{
switch (keyCode)
{
case ControllerInput::A:
case ControllerInput::Start:
//start game
if (currentSelection == MenuOptions::mainMenu)
{
director->replaceScene(TransitionFade::create(1.f, MainMenu::createScene(), Color3B(0, 0, 0)));
isTransitioning = true;
}
//exit game
else if (currentSelection == MenuOptions::exit)
{
director->end();
}
break;
}
}
void VictoryScreen::buttonReleaseCallback(Controller * controller, int keyCode, Event * event)
{
}
void VictoryScreen::axisEventCallback(Controller * controller, int keyCode, Event * event)
{
switch (keyCode)
{
//y axis of the left stick
case ControllerInput::leftStickY:
if (controller->getKeyStatus(keyCode).value >= 1 && ControllerInput::isLeftStickReset)
{
moveToPreviousMenuItem();
ControllerInput::isLeftStickReset = false;
}
else if (controller->getKeyStatus(keyCode).value <= -1 && ControllerInput::isLeftStickReset)
{
moveToNextMenuItem();
ControllerInput::isLeftStickReset = false;
}
else if (controller->getKeyStatus(keyCode).value > -0.9 && controller->getKeyStatus(keyCode).value < 0.9)
ControllerInput::isLeftStickReset = true;
break;
}
}
<file_sep>#pragma once
#ifndef PROJECTILEICEATTACK_H
#define PROJECTILEICEATTACK_H
#include "HeroAttackBase.h"
class ProjectileIceAttack : public HeroAttackBase
{
public:
ProjectileIceAttack();
void initAttack(cocos2d::Scene* scene);
void update(float dt);
};
#endif<file_sep>#include "FlameSplit.h"
#include "Boss/General/Boss.h"
FlameSplit4FirstBoss::FlameSplit4FirstBoss(Boss *boss)
:FirstBossState(boss)
{
//Get the animation
const auto startingAction = marcos::AnimationManager::getAnimation("boss_spit_tell_PRE_animation_key");
const auto finishingAction = marcos::AnimationManager::getAnimation("boss_spit_tell_POST_animation_key");
//Run the actions
boss->getSprite()->runAction
(
cocos2d::Sequence::create
(
cocos2d::Repeat::create(startingAction, 1),
cocos2d::CallFunc::create([&] {bossPointer->spewLava(); }),
cocos2d::DelayTime::create(2),
cocos2d::Repeat::create(finishingAction, 1),
cocos2d::CallFunc::create([&] {changeToIdleState(); }),
nullptr
)
);
}
<file_sep>#include "IdleState.h"
#include "Hero.h"
#include "HeroStateManager.h"
IdleState::IdleState()
{
}
IdleState::~IdleState()
{
}
void IdleState::onEnter()
{
HeroStateManager::currentState = this;
if (Hero::hero->lookState == Hero::LookDirection::lookingLeft)
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("idle_left_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::Repeat::create(action->clone(),1));
}
else
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("idle_right_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::RepeatForever::create(action->clone()));
}
}
void IdleState::onExit()
{
if (Hero::hero->velocity.y < 0) //falling
HeroStateManager::falling->onEnter();
else //started moving
HeroStateManager::running->onEnter();
}
void IdleState::handleInput(InputType input)
{
switch (input)
{
case InputType::p_space:
HeroStateManager::jumping->onEnter();
break;
}
}
void IdleState::update(float dt)
{
if (Hero::hero->moveState != Hero::MoveDirection::idle || Hero::hero->velocity.y < 0)
onExit();
}<file_sep>#include "HeroAttackBase.h"
bool HeroAttackBase::isWKeyHeld = false;
bool HeroAttackBase::isSKeyHeld = false;<file_sep>#pragma once
#ifndef CONTROLSMENU_H
#define CONTROLSMENU_H
#include "cocos2d.h"
#include "ControllerInput.h"
using namespace cocos2d;
class ControlsMenu : public cocos2d::Scene
{
public:
CREATE_FUNC(ControlsMenu);
static Scene* createScene();
bool init();
void initUI();
void initAnimations();
void initMusic();
void initMouseListener();
void initControllerListener();
void update(float dt);
//Callbacks
void mouseDownCallback(Event* event);
void mouseUpCallback(Event* event);
void mouseMoveCallback(Event* event);
void mouseScrollCallback(Event* event);
//controller callbacks
void buttonPressCallback(Controller* controller, int keyCode, Event* event);
private:
Director* director;
EventListenerMouse* mouseListener;
EventListenerController* controllerListener;
Vec2 cursorPos;
Sprite* controlsList;
Sprite* backText;
Rect backRect;
};
#endif<file_sep>#include "HeroMovementBase.h"
#include "HeroIdle.h"
#include "HeroMoveLeft.h"
#include "HeroMoveRight.h"
HeroIdle* HeroMovementBase::idleState = new HeroIdle();
HeroMoveLeft* HeroMovementBase::moveLeftState = new HeroMoveLeft();
HeroMoveRight* HeroMovementBase::moveRightState = new HeroMoveRight();
HeroMovementBase* HeroMovementBase::currentState = HeroMovementBase::idleState; //initialize state to idle
void HeroMovementBase::setCurrentState(HeroMoveStates newState)
{
//check which movement type to set and call init function if applicable
switch (newState)
{
case idle:
currentState = idleState;
idleState->init();
break;
case moveLeft:
currentState = moveLeftState;
moveLeftState->init();
break;
case moveRight:
currentState = moveRightState;
moveRightState->init();
break;
}
}<file_sep>#include "ControllerInput.h"
bool ControllerInput::isLeftTriggerReset = true;
bool ControllerInput::isRightTriggerReset = true;
bool ControllerInput::isLeftStickReset = true;
bool ControllerInput::isLeftStickIdle = true;
bool ControllerInput::isControllerUsed = false;<file_sep>#include "FlameThrower.h"
#include "Boss/General/Boss.h"
FlameThrower4FirstBoss::FlameThrower4FirstBoss(Boss *boss)
: FirstBossState(boss)
{
//Get the animation
const auto startingAction = marcos::AnimationManager::getAnimation("boss_flame_tell_PRE_animation_key");
const auto finishingAction = marcos::AnimationManager::getAnimation("boss_flame_tell_POST_animation_key");
//Run the animation
boss->getSprite()->runAction
(
cocos2d::Sequence::create
(
cocos2d::Repeat::create(startingAction, 1),
cocos2d::CallFunc::create([&] {bossPointer->activateFlameThrower(); }),
cocos2d::DelayTime::create(2.5f),
cocos2d::Repeat::create(finishingAction, 1),
cocos2d::CallFunc::create([&] {changeToIdleState(); }),
nullptr
)
);
}
<file_sep>#include "BossIdleState.h"
#include "Boss/General/Boss.h"
//Static function initialize
int Idling4FirstBoss::numberOfCast = 0;
const int Idling4FirstBoss::maxNumberOfCastPerRound = 7;
Idling4FirstBoss::Idling4FirstBoss(Boss *boss)
: FirstBossState(boss), cooldownBeforeNextAbility{ 2.5f }
{
//Get the animation
const auto animationForIdling = marcos::AnimationManager::getAnimation("boss_idle_animation_key");
//Run the animation
boss->getSprite()->stopAllActions();
boss->getSprite()->runAction(cocos2d::RepeatForever::create(animationForIdling));
}
/**
* @brief Delete number of cast to 0
*/
Idling4FirstBoss::~Idling4FirstBoss()
{
}
/**
* @brief Updates the idling time. When the time reaches
* 0, the boss will perform an ability
*
* @param deltaT The change of time from last frame to current
* frame
*/
void Idling4FirstBoss::update(const float &deltaT)
{
cooldownBeforeNextAbility -= deltaT;
//Start shooting ability
if (cooldownBeforeNextAbility <= 0)
{
bossPointer->getSprite()->stopAllActions();
if (numberOfCast == maxNumberOfCastPerRound)
{
numberOfCast = 0;
changeToRestingState();
}
else
{
numberOfCast++;
chooseRandomAbility();
}
}
}
/**
* @brief Chooses a random ability to perform
*/
void Idling4FirstBoss::chooseRandomAbility()
{
const int randomNum = cocos2d::RandomHelper::random_int(1, 20);
if (randomNum >= 1 && randomNum <= 5)
changeToExplosiveBullet();
else if (randomNum >= 6 && randomNum <= 14)
changeToFlameSplit();
else
changeToFlameThrower();
}<file_sep>#pragma once
#include "FirstBossState.h"
class FlameThrower4FirstBoss : public FirstBossState
{
public:
FlameThrower4FirstBoss(Boss *boss);
};
<file_sep>#pragma once
#ifndef HEROSTATEMANAGER_H
#define HEROSTATEMANAGER_H
#include "AttackingState.h"
#include "DyingState.h"
#include "FallingState.h"
#include "GrapplingState.h"
#include "IdleState.h"
#include "JumpingState.h"
#include "RunningState.h"
#include "GrappleJumpState.h"
#include "HoldingPlatformState.h"
#include "ShootingGrappleState.h"
class HeroStateManager
{
public:
HeroStateManager();
~HeroStateManager();
static HeroStateBase* currentState;
static AttackingState* attacking;
static DyingState* dying;
static FallingState* falling;
static GrapplingState* grappling;
static IdleState* idle;
static JumpingState* jumping;
static RunningState* running;
static GrappleJumpState* grappleJumping;
static HoldingPlatformState* holdingPlatform;
static ShootingGrappleState* shootingGrapple;
};
#endif<file_sep>#pragma once
#include "HeroMovementBase.h"
class HeroIdle : public HeroMovementBase
{
public:
void init();
HeroIdle();
};<file_sep>#include "XinputManager.h"
XinputManager* XinputManager::instance = 0;
XinputController XinputManager::controllers[4];
bool XinputManager::create()
{
if (!instance)
{
instance = new XinputManager();
return true;
}
return false;
}
XinputManager::XinputManager()
{
for (int index = 0; index < 4; index++)
controllers[index].setControllerIndex(index);
}
bool XinputManager::controllerConnected(int index)
{
if (index < 0 || index >= 4)
return false;
XINPUT_STATE connected;
return XInputGetState(index, &connected) == ERROR_SUCCESS;
}
XinputController * XinputManager::getController(int index)
{
if (index >= 0 && index < 4)
return &controllers[index];
return nullptr;
}
void XinputManager::update()
{
for (int index = 0; index < 4; index++)
{
if (controllerConnected(index))
{
controllers[index].update();
}
}
}
<file_sep>#pragma once
#ifndef IDLESTATE_H
#define IDLESTATE_H
#include "HeroStateBase.h"
class IdleState : public HeroStateBase
{
public:
IdleState();
~IdleState();
void onEnter();
void onExit();
void handleInput(InputType input);
void update(float dt);
};
#endif<file_sep>#include "HeroIdle.h"
#include "Hero.h"
#include "cocos2d.h"
HeroIdle::HeroIdle()
{
}
void HeroIdle::init()
{
if (Hero::hero->sprite->isFlippedX())
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("idle_left_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::RepeatForever::create(action->clone()));
}
else
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("idle_right_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::RepeatForever::create(action->clone()));
}
}<file_sep>#include "InitialLoadScreen.h"
#include "MainMenu.h"
Scene * InitialLoadScreen::createScene()
{
Scene* scene = InitialLoadScreen::create();
return scene;
}
bool InitialLoadScreen::init()
{
if (!Scene::init())
return false;
director = Director::getInstance();
//Setting the default animation rate for the director
director->setAnimationInterval(1.0f / 60.0f);
image = Sprite::create("Backgrounds/bootScreen.png");
image->setAnchorPoint(Vec2(0.0f, 0.0f));
image->setPosition(Vec2(0.0f, 0.0f));
this->addChild(image, 1);
preloadAnimations();
timer = 0.0f;
isDone = false;
scheduleUpdate();
return true;
}
//preloads animations to reduce lag later on
void InitialLoadScreen::preloadAnimations()
{
//flamethrower attack
auto sprite = cocos2d::Sprite::create("Sprites/flame_sprite.png");
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("boss_explosive_tell_PRE_animation_key");
auto action = cocos2d::Animate::create(anim);
sprite->stopAllActions();
sprite->runAction(cocos2d::Repeat::create(action->clone(), 1));
sprite->setPosition(500, 500);
this->addChild(sprite, -20);
sprite = cocos2d::Sprite::create("Sprites/flame_sprite.png");
anim = cocos2d::AnimationCache::getInstance()->getAnimation("boss_idle_animation_key");
action = cocos2d::Animate::create(anim);
sprite->stopAllActions();
sprite->runAction(cocos2d::Repeat::create(action->clone(), 1));
sprite->setPosition(500, 500);
this->addChild(sprite, -20);
sprite = cocos2d::Sprite::create("Sprites/flame_sprite.png");
anim = cocos2d::AnimationCache::getInstance()->getAnimation("boss_explosive_tell_POST_animation_key");
action = cocos2d::Animate::create(anim);
sprite->stopAllActions();
sprite->runAction(cocos2d::Repeat::create(action->clone(), 1));
sprite->setPosition(500, 500);
this->addChild(sprite, -20);
sprite = cocos2d::Sprite::create("Sprites/flame_sprite.png");
anim = cocos2d::AnimationCache::getInstance()->getAnimation("boss_spit_tell_PRE_animation_key");
action = cocos2d::Animate::create(anim);
sprite->stopAllActions();
sprite->runAction(cocos2d::Repeat::create(action->clone(), 1));
sprite->setPosition(500, 500);
this->addChild(sprite, -20);
sprite = cocos2d::Sprite::create("Sprites/flame_sprite.png");
anim = cocos2d::AnimationCache::getInstance()->getAnimation("boss_spit_tell_POST_animation_key");
action = cocos2d::Animate::create(anim);
sprite->stopAllActions();
sprite->runAction(cocos2d::Repeat::create(action->clone(), 1));
sprite->setPosition(500, 500);
this->addChild(sprite, -20);
sprite = cocos2d::Sprite::create("Sprites/flame_sprite.png");
anim = cocos2d::AnimationCache::getInstance()->getAnimation("boss_flame_tell_PRE_animation_key");
action = cocos2d::Animate::create(anim);
sprite->stopAllActions();
sprite->runAction(cocos2d::Repeat::create(action->clone(), 1));
sprite->setPosition(500, 500);
this->addChild(sprite, -20);
sprite = cocos2d::Sprite::create("Sprites/flame_sprite.png");
anim = cocos2d::AnimationCache::getInstance()->getAnimation("boss_flame_tell_POST_animation_key");
action = cocos2d::Animate::create(anim);
sprite->stopAllActions();
sprite->runAction(cocos2d::Repeat::create(action->clone(), 1));
sprite->setPosition(500, 500);
this->addChild(sprite, -20);
sprite = cocos2d::Sprite::create("Sprites/flame_sprite.png");
anim = cocos2d::AnimationCache::getInstance()->getAnimation("boss_idle_animation_key");
action = cocos2d::Animate::create(anim);
sprite->stopAllActions();
sprite->runAction(cocos2d::Repeat::create(action->clone(), 1));
sprite->setPosition(500, 500);
this->addChild(sprite, -20);
sprite = cocos2d::Sprite::create("Sprites/flame_sprite.png");
anim = cocos2d::AnimationCache::getInstance()->getAnimation("boss_explosive_POST_animation_key");
action = cocos2d::Animate::create(anim);
sprite->stopAllActions();
sprite->runAction(cocos2d::Repeat::create(action->clone(), 1));
sprite->setPosition(500, 500);
this->addChild(sprite, -20);
sprite = cocos2d::Sprite::create("Sprites/flame_sprite.png");
anim = cocos2d::AnimationCache::getInstance()->getAnimation("boss_explosive_PRE_animation_key");
action = cocos2d::Animate::create(anim);
sprite->stopAllActions();
sprite->runAction(cocos2d::Repeat::create(action->clone(), 1));
sprite->setPosition(500, 500);
this->addChild(sprite, -20);
sprite = cocos2d::Sprite::create("Sprites/flame_sprite.png");
anim = cocos2d::AnimationCache::getInstance()->getAnimation("boss_flame_PRE_animation_key");
action = cocos2d::Animate::create(anim);
sprite->stopAllActions();
sprite->runAction(cocos2d::Repeat::create(action->clone(), 1));
sprite->setPosition(500, 500);
this->addChild(sprite, -20);
sprite = cocos2d::Sprite::create("Sprites/flame_sprite.png");
anim = cocos2d::AnimationCache::getInstance()->getAnimation("boss_flame_MID_animation_key");
action = cocos2d::Animate::create(anim);
sprite->stopAllActions();
sprite->runAction(cocos2d::Repeat::create(action->clone(), 1));
sprite->setPosition(500, 500);
this->addChild(sprite, -20);
sprite = cocos2d::Sprite::create("Sprites/flame_sprite.png");
anim = cocos2d::AnimationCache::getInstance()->getAnimation("boss_flame_POST_animation_key");
action = cocos2d::Animate::create(anim);
sprite->stopAllActions();
sprite->runAction(cocos2d::Repeat::create(action->clone(), 1));
sprite->setPosition(500, 500);
this->addChild(sprite, -20);
sprite = cocos2d::Sprite::create("Sprites/flame_sprite.png");
anim = cocos2d::AnimationCache::getInstance()->getAnimation("boss_spit_animation_key");
action = cocos2d::Animate::create(anim);
sprite->stopAllActions();
sprite->runAction(cocos2d::Repeat::create(action->clone(), 1));
sprite->setPosition(500, 500);
this->addChild(sprite, -20);
sprite = cocos2d::Sprite::create("Backgrounds/greyBackground.png");
anim = cocos2d::AnimationCache::getInstance()->getAnimation("main_menu_animation_key");
action = cocos2d::Animate::create(anim);
sprite->stopAllActions();
sprite->runAction(cocos2d::RepeatForever::create(action->clone()));
sprite->setAnchorPoint(Vec2(0, 0));
sprite->setPosition(0, 0);
this->addChild(sprite, -21);
sprite = cocos2d::Sprite::create("Backgrounds/greyBackground.png");
anim = cocos2d::AnimationCache::getInstance()->getAnimation("boss_death_animation_key");
action = cocos2d::Animate::create(anim);
sprite->stopAllActions();
sprite->runAction(cocos2d::RepeatForever::create(action->clone()));
sprite->setAnchorPoint(Vec2(0, 0));
sprite->setPosition(0, 0);
this->addChild(sprite, -21);
}
void InitialLoadScreen::update(float dt)
{
//if (timer == 0.0f)
//preloadAnimations();
timer += dt;
if (timer > 2.0f && !isDone)
{
isDone = true;
director->replaceScene(TransitionFade::create(1.5f, MainMenu::createScene(), Color3B(0, 0, 0)));
}
}<file_sep>#pragma once
#ifndef GAMEOBJECT_H
#define GAMEOBJECT_H
#include "cocos2d.h"
#include "Vect2.h"
#include "myHelper.h"
using namespace cocos2d;
class GameObject
{
public:
GameObject(Vect2 position, std::string spriteFilePath);
virtual ~GameObject();
static float MAX_X;
static float MAX_Y;
float width;
float height;
float theta;
float mass;
float gravityMultiplier;
Vect2 lastFramePosition;
Vect2 velocity;
Vect2 acceleration;
Vect2 force;
static const Vect2 GRAVITY;
Sprite* sprite;
cocos2d::Rect hurtBox;
cocos2d::Rect moveBox; //like a hitbox but for movement and shit
//get sprite position functions
Vect2 getPosition();
float getLeftSidePos();
float getRightSidePos();
float getBottomPos();
float getTopPos();
void destroySprite();
bool isMovementCollision(GameObject* otherObject);
bool isHitboxCollision(cocos2d::Rect otherHitbox);
virtual void updateHitboxes() = 0;
virtual void updatePhysics(float dt);
};
#endif<file_sep>#pragma once
#include "Boss/Ability States/FirstBossState.h"
class DeathState: public FirstBossState
{
public:
DeathState(Boss *bossInstance);
private:
void changeToVictoryScreen();
void removeAllElements();
};
<file_sep>#pragma once
#ifndef MYHELPER_H
#define MYHELPER_H
#include "cocos2d.h"
class myHelper
{
public:
myHelper();
virtual ~myHelper();
static bool isCollision(cocos2d::Rect rect1, cocos2d::Rect rect2);
static cocos2d::Vec2 getLineLineIntersect(cocos2d::Vec2 lineOneStart, cocos2d::Vec2 lineOneEnd, cocos2d::Vec2 lineTwoStart, cocos2d::Vec2 lineTwoEnd);
static int getRandNum(int maxNum, int scaleNum, bool canBeNegative = false);
};
#endif<file_sep>#include "MainMenu.h"
#include "Tutorial.h"
#include "ControlsMenu.h"
#include "SimpleAudioEngine.h"
#include "Boss1Scene.h"
Scene * MainMenu::createScene()
{
Scene* scene = MainMenu::create();
return scene;
}
bool MainMenu::init()
{
if (!Scene::init())
return false;
currentSelection = MenuOptions::nothing;
director = Director::getInstance();
//Setting the default animation rate for the director
director->setAnimationInterval(1.0f / 60.0f);
initUI();
initAnimations();
initMusic();
//init listeners
initMouseListener();
initControllerListener();
scheduleUpdate();
return true;
}
void MainMenu::initUI()
{
//set our sprite labels
Logo = Sprite::create("Backgrounds/Echoes_logo.png");
Logo->setPosition(Vec2(950, 900));
this->addChild(Logo, 10);
startText = Sprite::create("Text/start.png");
startText->setPosition(1920 / 2, 700);
this->addChild(startText, 10);
controlsText = Sprite::create("Text/controlsTest.png");
controlsText->setPosition(1920 / 2, 500);
this->addChild(controlsText, 10);
exitText = Sprite::create("Text/exitTest.png");
exitText->setPosition(1920 / 2, 300);
this->addChild(exitText, 10);
//set rects for label hover/click
startRect.setRect(startText->getPositionX() - 300, startText->getPositionY() - 100, 600, 200);
controlsRect.setRect(controlsText->getPositionX() - 300, controlsText->getPositionY() - 100, 600, 200);
exitRect.setRect(exitText->getPositionX() - 300, exitText->getPositionY() - 100, 600, 200);
}
void MainMenu::initAnimations()
{
auto sprite = cocos2d::Sprite::create("Backgrounds/greyBackground.png");
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("main_menu_animation_key");
auto action = cocos2d::Animate::create(anim);
sprite->stopAllActions();
sprite->runAction(cocos2d::RepeatForever::create(action->clone()));
sprite->setAnchorPoint(Vec2(0, 0));
sprite->setPosition(0, 0);
this->addChild(sprite, -5);
}
void MainMenu::initMusic()
{
auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
audio->playBackgroundMusic("Music/TutorialMusic.mp3", true);
}
void MainMenu::initMouseListener()
{
//Init the mouse listener
mouseListener = EventListenerMouse::create();
//On Mouse Down
mouseListener->onMouseDown = CC_CALLBACK_1(MainMenu::mouseDownCallback, this);
//On Mouse Up
mouseListener->onMouseUp = CC_CALLBACK_1(MainMenu::mouseUpCallback, this);
//On Mouse Move
mouseListener->onMouseMove = CC_CALLBACK_1(MainMenu::mouseMoveCallback, this);
//On Mouse Scroll
mouseListener->onMouseScroll = CC_CALLBACK_1(MainMenu::mouseScrollCallback, this);
//Add the mouse listener to the dispatcher
_eventDispatcher->addEventListenerWithSceneGraphPriority(mouseListener, this);
}
void MainMenu::initControllerListener()
{
controllerListener = EventListenerController::create();
//set up callbacks
controllerListener->onKeyDown = CC_CALLBACK_3(MainMenu::buttonPressCallback, this);
controllerListener->onKeyUp = CC_CALLBACK_3(MainMenu::buttonReleaseCallback, this);
controllerListener->onAxisEvent = CC_CALLBACK_3(MainMenu::axisEventCallback, this);
controllerListener->onConnected = [](cocos2d::Controller* controller, cocos2d::Event* evt) {};
//add the controller listener to the dispatcher
_eventDispatcher->addEventListenerWithSceneGraphPriority(controllerListener, this);
}
//move to the next selection on the menu
void MainMenu::moveToNextMenuItem()
{
switch (currentSelection)
{
case MenuOptions::nothing:
currentSelection = MenuOptions::start;
break;
case MenuOptions::start:
currentSelection = MenuOptions::controls;
break;
case MenuOptions::controls:
currentSelection = MenuOptions::exit;
break;
case MenuOptions::exit:
currentSelection = MenuOptions::start;
break;
}
}
//move back one selection on the menu
void MainMenu::moveToPreviousMenuItem()
{
switch (currentSelection)
{
case MenuOptions::nothing:
currentSelection = MenuOptions::start;
break;
case MenuOptions::start:
currentSelection = MenuOptions::exit;
break;
case MenuOptions::controls:
currentSelection = MenuOptions::start;
break;
case MenuOptions::exit:
currentSelection = MenuOptions::controls;
break;
}
}
void MainMenu::update(float dt)
{
if (!isTransitioning)
{
//check for mouse hover over menu items
if (startRect.containsPoint(cursorPos) || currentSelection == MenuOptions::start)
startText->setScale(1.2f);
else
startText->setScale(1.0f);
if (controlsRect.containsPoint(cursorPos) || currentSelection == MenuOptions::controls)
controlsText->setScale(1.2f);
else
controlsText->setScale(1.0f);
if (exitRect.containsPoint(cursorPos) || currentSelection == MenuOptions::exit)
exitText->setScale(1.2f);
else
exitText->setScale(1.0f);
}
}
//performs duties to transition to the next scene
void MainMenu::transitionScene()
{
this->removeAllChildrenWithCleanup(true);
director->replaceScene(TransitionFade::create(1.f, Tutorial::createScene(), Color3B(0, 0, 0)));
isTransitioning = true;
}
//--- Callbacks ---//
void MainMenu::mouseDownCallback(Event* event)
{
//Cast the event as a mouse event
EventMouse* mouseEvent = dynamic_cast<EventMouse*>(event);
auto mouseButton = mouseEvent->getMouseButton();
//Get the position of the mouse button press
auto mouseClickPosition = mouseEvent->getLocationInView();
if (mouseButton == cocos2d::EventMouse::MouseButton::BUTTON_LEFT)
{
//start game
if (startRect.containsPoint(cursorPos))
{
transitionScene();
}
//open controls menu
else if (controlsRect.containsPoint(cursorPos))
{
director->pushScene(ControlsMenu::createScene());
}
//exit game
else if (exitRect.containsPoint(cursorPos))
{
director->end();
}
}
if (mouseButton == cocos2d::EventMouse::MouseButton::BUTTON_RIGHT)
{
}
}
void MainMenu::mouseUpCallback(Event* event)
{
}
void MainMenu::mouseMoveCallback(Event* event)
{
EventMouse* mouseEvent = dynamic_cast<EventMouse*>(event);
cursorPos = mouseEvent->getLocationInView();
cursorPos.y += 1080;
}
void MainMenu::mouseScrollCallback(Event* event)
{
}
void MainMenu::buttonPressCallback(Controller * controller, int keyCode, Event * event)
{
switch (keyCode)
{
case ControllerInput::A:
//start game
if (currentSelection == MenuOptions::start)
{
transitionScene();
}
//open controls menu
else if (currentSelection == MenuOptions::controls)
{
director->pushScene(ControlsMenu::createScene());
}
//exit game
else if (currentSelection == MenuOptions::exit)
{
director->end();
}
break;
case ControllerInput::Start:
transitionScene();
break;
}
}
void MainMenu::buttonReleaseCallback(Controller * controller, int keyCode, Event * event)
{
}
void MainMenu::axisEventCallback(Controller * controller, int keyCode, Event * event)
{
switch (keyCode)
{
//y axis of the left stick
case ControllerInput::leftStickY:
if (controller->getKeyStatus(keyCode).value >= 1 && ControllerInput::isLeftStickReset)
{
moveToPreviousMenuItem();
ControllerInput::isLeftStickReset = false;
}
else if (controller->getKeyStatus(keyCode).value <= -1 && ControllerInput::isLeftStickReset)
{
moveToNextMenuItem();
ControllerInput::isLeftStickReset = false;
}
else if (controller->getKeyStatus(keyCode).value > -0.9 && controller->getKeyStatus(keyCode).value < 0.9)
ControllerInput::isLeftStickReset = true;
break;
}
}
<file_sep>#include "Hero.h"
#include "HeroAttackManager.h"
#include "HeroStateManager.h"
#include "TileBase.h"
#include "Grapple.h"
Hero* Hero::hero = 0;
Hero::Hero() : GameObject(Vect2(700, 150), "Sprites/shooting_test.png"),
JUMP_VELOCITY(610),
MAX_HORIZONTAL_VELOCITY(300),
MAX_VERTICAL_VELOCITY(850),
DRAG_VELOCITY(30),
movespeedIncrease(70),
invincibilityTimer(0),
health(5),
isAirborne(false),
bypassSpeedCap(false),
lookState(LookDirection::lookingRight),
moveState(MoveDirection::idle)
{
//initialize arm
arm = cocos2d::Sprite::create("Sprites/armV2.png");
mass = 5;
marcos::AnimationManager::init();
//auto anim = AnimationCache::getInstance()->getAnimation("idle_right_animation_key");
//auto action = Animate::create(anim);
//this->sprite->runAction(RepeatForever::create(action));
//TODO: its not gonna be like this later change it. //this triggers a breakpoint, read acess violation
hurtBox.setRect(getLeftSidePos() + width / 2.7f, getBottomPos() + height / 6.0f, width / 4.5f, height / 1.5f);
updateHitboxes();
}
void Hero::createHero()
{
if (!hero)
hero = new Hero;
}
void Hero::moveRight()
{
lookState = LookDirection::lookingRight;
//make sure hero isn't above max velocity
if (!(velocity.x > MAX_HORIZONTAL_VELOCITY || velocity.x < -MAX_HORIZONTAL_VELOCITY))
{
if (isAirborne)
velocity.x += movespeedIncrease * 0.7; //add some drag in the air
else
velocity.x += movespeedIncrease;
}
}
void Hero::moveLeft()
{
lookState = LookDirection::lookingLeft;
//make sure hero isn't above max velocity
if (!(velocity.x > MAX_HORIZONTAL_VELOCITY || velocity.x < -MAX_HORIZONTAL_VELOCITY))
{
if (isAirborne)
velocity.x -= movespeedIncrease * 0.7; //add some drag in the air
else
velocity.x -= movespeedIncrease;
}
}
//jump if not already airbourne
void Hero::jump()
{
if (!isAirborne)
velocity.y = JUMP_VELOCITY;
}
//hero takes damage from any source
void Hero::takeDamage(float sourcePositionX, const int& damageTaken)
{
if (damageTaken == 0)
return;
//make sure hero isn't already invulnerable or ded
if (invincibilityTimer <= 0 && HeroStateManager::currentState != HeroStateManager::dying)
{
health-= damageTaken;
invincibilityTimer = 0.99;
bypassSpeedCap = true;
//if we're not in any of the grappling states or dying, go into falling state
if (HeroStateManager::currentState != HeroStateManager::grappling &&
HeroStateManager::currentState != HeroStateManager::shootingGrapple &&
HeroStateManager::currentState != HeroStateManager::holdingPlatform)
{
HeroStateManager::falling->onEnter();
}
if (this->getPosition().x < sourcePositionX)
Hero::hero->velocity = Vect2(-600, 400);
else //hero position().x <= sourcePositionX
Hero::hero->velocity = Vect2(600, 400);
}
}
//resets hero after a death or victory
void Hero::reset()
{
invincibilityTimer = 0.0f;
velocity = Vect2(0, 0);
force = Vect2(0, 0);
moveState = MoveDirection::idle;
HeroStateManager::idle->onEnter();
Grapple::grapple->unLatch();
}
//updates the hero's arm position (only visible while grappling)
void Hero::updateArmPosition()
{
float armRightOffset = 23;
float armLeftOffset = 30;
float armYOffset = 25;
if (Grapple::grapple->lookDirectionOnShoot == LookDirection::lookingRight)
arm->setPosition(Vec2(this->getPosition().x - armRightOffset, this->getPosition().y + armYOffset)); //update arm position each frame
else //hero looking left
arm->setPosition(Vec2(this->getPosition().x + armLeftOffset, this->getPosition().y + armYOffset)); //update arm position each frame
}
void Hero::updatePositionBasedOnArm()
{
float armRightOffset = 23;
float armLeftOffset = 30;
float armYOffset = 25;
if (Grapple::grapple->lookDirectionOnShoot == LookDirection::lookingRight)
this->sprite->setPosition(Vec2(arm->getPosition().x + armRightOffset, arm->getPosition().y - armYOffset)); //update hero based on arm position when being pulled in
else //hero looking left
this->sprite->setPosition(Vec2(arm->getPosition().x - armLeftOffset, arm->getPosition().y - armYOffset)); //update hero based on arm position when being pulled in
}
//checks if the character is out of bounds and performs appropriate actions
void Hero::checkAndResolveOutOfBounds()
{
//check for out of bounds
//on x
if (this->moveBox.getMinX() < 0.0f)
{
sprite->setPositionX(this->moveBox.size.width / 2.0f);
velocity.x = 0.0f;
}
else if (this->moveBox.getMaxX() > MAX_X)
{
sprite->setPositionX(MAX_X - (this->moveBox.size.width / 2.0f) - 2);
velocity.x = 0.0f;
}
//on y
if (this->moveBox.getMinY() < 0.0f)
{
sprite->setPositionY(this->moveBox.size.height / 2.0f);
velocity.y = 0.0f;
}
else if (this->moveBox.getMaxY() > MAX_Y)
{
sprite->setPositionY(MAX_Y - (this->moveBox.size.height / 2.0f));
velocity.y = 0.0f;
}
}
void Hero::updatePhysics(float dt)
{
//check if airborne or not
if (velocity.y == 0)
isAirborne = false;
else
isAirborne = true;
HeroStateManager::currentState->update(dt);
//have hero fall faster than rise
if (velocity.y < 0)
gravityMultiplier = 1.7f;
else
gravityMultiplier = 1.0f;
this->GameObject::updatePhysics(dt); //call base class update
//no player input but hero is still moving
if (velocity.x > 0)
{
velocity.x -= DRAG_VELOCITY; //apply drag
}
else //velocity <= 0
{
velocity.x += DRAG_VELOCITY;
//if velocity goes from negative to positive after drag is applied, set it to 0 to prevent a slight "drift" to occur in later frames if no movement key is pressed
if (velocity.x > 0)
velocity.x = 0;
}
//check max velocity
if (!bypassSpeedCap)
{
//for x
if (velocity.x > MAX_HORIZONTAL_VELOCITY)
velocity.x = MAX_HORIZONTAL_VELOCITY;
else if (velocity.x < -MAX_HORIZONTAL_VELOCITY)
velocity.x = -MAX_HORIZONTAL_VELOCITY;
//for y
if (velocity.y > MAX_VERTICAL_VELOCITY)
velocity.y = MAX_VERTICAL_VELOCITY;
else if (velocity.y < -MAX_VERTICAL_VELOCITY)
velocity.y = -MAX_VERTICAL_VELOCITY;
}
//check for hero out of bounds
updateHitboxes();
checkAndResolveOutOfBounds();
}
void Hero::updateHitboxes()
{
moveBox.setRect(getLeftSidePos() + width / 5.0f, getBottomPos(), width / 1.6f, height);
hurtBox.setRect(getLeftSidePos() + width / 2.7f, getBottomPos() + height / 6.0f, width / 4.5f, height / 1.5f);
}
//updates any collisions dealing with the hero and other objects
void Hero::updateCollisions()
{
if (HeroStateManager::currentState != HeroStateManager::grappling)
{
unsigned int tileListSize = TileBase::tileList.size();
for (unsigned int i = 0; i < tileListSize; i++)
{
//check if it's a spike tile (deals damage)
if (TileBase::tileList[i]->checkAndResolveCollision(this) && TileBase::tileList[i]->type == TileType::spike)
{
this->takeDamage(TileBase::tileList[i]->hitBox.getMidX());
this->health++;
}
}
}
}
//updates all the things
void Hero::update(float dt)
{
this->updatePhysics(dt);
//check for invincibility
if (((int)(invincibilityTimer * 10)) % 2 == 1)
sprite->setVisible(0); //flicker the sprite
else
sprite->setVisible(1); //show the sprite again
//update invincibility timer
if (invincibilityTimer > 0)
{
invincibilityTimer -= dt;
if (invincibilityTimer < 0.8f)
bypassSpeedCap = false;
}
updateHitboxes();
updateCollisions();
HeroAttackManager::update(dt);
updateArmPosition();
//show grapple sprite and rotate properly
Grapple::grapple->startPoint = Vect2(arm->getPosition()); //have grapple start point move with the hero
float grappleDistance = Vect2::calculateDistance(Grapple::grapple->startPoint, Grapple::grapple->grappleTip);
Grapple::grapple->sprite->setTextureRect(cocos2d::Rect(Grapple::grapple->startPoint.x, Grapple::grapple->startPoint.y, 4, grappleDistance));
Grapple::grapple->sprite->setPosition(Vec2(Grapple::grapple->startPoint.x, Grapple::grapple->startPoint.y));
}<file_sep>#include "PlatformTile.h"
#include "Hero.h"
std::vector<PlatformTile*> PlatformTile::platformTileList = std::vector<PlatformTile*>();
PlatformTile::PlatformTile(cocos2d::Vec2 position, float tileSize)
: TileBase(position, tileSize)
{
hitBox.setRect(position.x, position.y + tileSize - 35, tileSize, 20); //set the rect of platforms to only be the highest few pixels (for collision purposes)
type = TileType::platform;
platformTileList.push_back(this);
}
bool PlatformTile::checkAndResolveCollision(GameObject * otherObject)
{
//check x values to see if they arent touching
//assuming objects are named A and B:
//A_begin.x > B_end.x OR B_begin.x > A_end.x means there IS a gap on x
if (this->hitBox.getMinX() >= otherObject->moveBox.getMaxX() || otherObject->moveBox.getMinX() >= this->hitBox.getMaxX())
return false;
//check y values to see if they arent touching
//A_begin.y > B_end.y OR B_begin.y > A_end.y means there IS a gap on y
else if (this->hitBox.getMinY() >= otherObject->moveBox.getMaxY() || otherObject->moveBox.getMinY() >= this->hitBox.getMaxY())
return false;
//make sure only the bottom of the other object is colliding, then make sure the other object is moving down
else if (otherObject->getBottomPos() >= this->hitBox.getMinY() && otherObject->velocity.y <= 0)
{
otherObject->sprite->setPositionY(this->hitBox.getMaxY() + Hero::hero->height / 2);
otherObject->velocity.y = 0;
return true;
}
else //no proper collision detected
return false;
}<file_sep>#pragma once
#ifndef ICEPROJECTILE_H
#define ICEPROJECTILE_H
#include "GameObject.h"
class IceProjectile : public GameObject
{
public:
IceProjectile();
IceProjectile(Vect2 startVelocity);
static const float SPEED;
static std::vector<IceProjectile*> iceProjectileList;
void removeAndDelete();
void checkAndResolveOutOfBounds();
void updateHitboxes() override;
void update(float dt);
};
#endif<file_sep>#pragma once
#include "cocos2d.h"
class HitBox
{
public:
//Public data member
cocos2d::Rect hitBox;
//Constructors and Destructor
HitBox(const cocos2d::Vec2& position, const float& aHeight, const float& aWidth);
//Member functions
void updateHitBox(const cocos2d::Vec2 &newPosition);
//Setters
void setNewSize(const float& newWidth, const float& newHeight);
private:
//Private data members
float height, width;
};<file_sep>#include "RunningState.h"
#include "Hero.h"
#include "HeroStateManager.h"
RunningState::RunningState()
{
}
RunningState::~RunningState()
{
}
void RunningState::onEnter()
{
HeroStateManager::currentState = this;
if (Hero::hero->lookState == Hero::LookDirection::lookingLeft)
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("running_left_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::RepeatForever::create(action->clone()));
}
else
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("running_right_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::RepeatForever::create(action->clone()));
}
}
void RunningState::onExit()
{
//check which state to go into next
if (Hero::hero->velocity.y < 0)
HeroStateManager::falling->onEnter();
else if (Hero::hero->velocity.y > 0)
HeroStateManager::jumping->onEnter();
else
HeroStateManager::idle->onEnter();
}
void RunningState::handleInput(InputType input)
{
switch (input)
{
case InputType::p_space:
HeroStateManager::jumping->onEnter();
break;
case InputType::p_a:
//if the hero is changing directions, call onEnter() again to play the proper animation
if (Hero::hero->lookState == Hero::LookDirection::lookingRight)
{
Hero::hero->lookState = Hero::LookDirection::lookingLeft;
onEnter();
}
break;
case InputType::p_d:
//if the hero is changing directions, call onEnter() again to play the proper animation
if (Hero::hero->lookState == Hero::LookDirection::lookingLeft)
{
Hero::hero->lookState = Hero::LookDirection::lookingRight;
onEnter();
}
break;
}
}
void RunningState::update(float dt)
{
switch (Hero::hero->moveState)
{
case Hero::MoveDirection::movingLeft:
Hero::hero->moveLeft();
break;
case Hero::MoveDirection::movingRight:
Hero::hero->moveRight();
break;
case Hero::MoveDirection::idle:
onExit();
break;
}
if (Hero::hero->velocity.y != 0)
onExit();
}<file_sep>#include "DyingState.h"
#include "HeroStateManager.h"
#include "Hero.h"
#include "Grapple.h"
DyingState::DyingState()
{
}
DyingState::~DyingState()
{
}
void DyingState::onEnter()
{
if (HeroStateManager::currentState != this)
{
HeroStateManager::currentState = this;
Hero::hero->sprite->stopAllActions();
if (Hero::hero->lookState == Hero::LookDirection::lookingLeft)
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("hero_death_left_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::Repeat::create(action->clone(), 1));
}
else //looking right
{
auto anim = cocos2d::AnimationCache::getInstance()->getAnimation("hero_death_right_animation_key");
auto action = cocos2d::Animate::create(anim);
Hero::hero->sprite->stopAllActions();
Hero::hero->sprite->runAction(cocos2d::Repeat::create(action->clone(), 1));
}
}
}
void DyingState::onExit()
{
}
void DyingState::handleInput(InputType input)
{
}
void DyingState::update(float dt)
{
Grapple::grapple->indicator->setVisible(0);
Hero::hero->force = Vect2(0.0f, 0.0f);
Hero::hero->velocity = Vect2(0.0f, -400.0f);
}
<file_sep>#include "SpikeTile.h"
std::vector<SpikeTile*> SpikeTile::spikeTileList = std::vector<SpikeTile*>();
SpikeTile::SpikeTile(cocos2d::Vec2 position, float tileSize)
: TileBase(position, tileSize)
{
hitBox.setRect(position.x, position.y, tileSize, tileSize);
spikeTileList.push_back(this);
}
bool SpikeTile::checkAndResolveCollision(GameObject * otherObject)
{
if (this->checkGeneralCollision(otherObject))
return true;
return false;
}<file_sep>#pragma once
#ifndef JUMPINGSTATE_H
#define JUMPINGSTATE_H
#include "HeroStateBase.h"
class JumpingState : public HeroStateBase
{
public:
JumpingState();
~JumpingState();
void onEnter();
void onExit();
void handleInput(InputType input);
void update(float dt);
};
#endif<file_sep>#include "IceProjectile.h"
#include "Hero.h"
#include <iostream>
const float IceProjectile::SPEED = 900;
std::vector<IceProjectile*> IceProjectile::iceProjectileList = std::vector<IceProjectile*>();
//default sets velocity to 0
IceProjectile::IceProjectile() : GameObject(Hero::hero->getPosition(), "Sprites/IceProjectileTest.png")
{
mass = 0;
velocity = Vect2(0, 0);
updateHitboxes();
iceProjectileList.push_back(this);
}
//create projectile with starting velocity
IceProjectile::IceProjectile(Vect2 startVelocity) : GameObject(Hero::hero->getPosition(), "Sprites/IceProjectileTest.png")
{
mass = 0;
velocity = startVelocity;
iceProjectileList.push_back(this);
}
void IceProjectile::removeAndDelete()
{
//remove the ice projectile
destroySprite();
iceProjectileList.erase(std::remove(iceProjectileList.begin(), iceProjectileList.end(), this), iceProjectileList.end()); //remove from vector list
}
//checks if the projectile is out of bounds and performs appropriate actions
void IceProjectile::checkAndResolveOutOfBounds()
{
//check for out of bounds
//on x
if (getLeftSidePos() < 0 || getRightSidePos() > MAX_X)
removeAndDelete();
//on y
else if (getBottomPos() < 0 || getTopPos() > MAX_Y)
removeAndDelete();
}
void IceProjectile::updateHitboxes()
{
moveBox.setRect(getLeftSidePos(), getBottomPos(), width, height);
hurtBox.setRect(getLeftSidePos(), getBottomPos(), width, height);
}
void IceProjectile::update(float dt)
{
//call base update
GameObject::updatePhysics(dt);
updateHitboxes();
checkAndResolveOutOfBounds();
}<file_sep>#pragma once
#ifndef SHOOTINGGRAPPLESTATE_H
#define SHOOTINGGRAPPLESTATE_H
#include "HeroStateBase.h"
class ShootingGrappleState : public HeroStateBase
{
public:
ShootingGrappleState();
~ShootingGrappleState();
void onEnter();
void onExit();
void handleInput(InputType input);
void update(float dt);
};
#endif<file_sep>#include "Vect2.h"
Vect2::Vect2()
{
x = 0.0f;
y = 0.0f;
}
Vect2::Vect2(const float x, const float y)
{
this->x = x;
this->y = y;
}
Vect2::Vect2(cocos2d::Vec2 vector)
{
x = vector.x;
y = vector.y;
}
Vect2 Vect2::operator+(const Vect2 a) const
{
Vect2 sum;
sum.x = x + a.x;
sum.y = y + a.y;
return sum;
}
Vect2 Vect2::operator-(const Vect2 a) const
{
Vect2 difference;
difference.x = x - a.x;
difference.y = y - a.y;
return difference;
}
Vect2 Vect2::operator*(const Vect2 a) const
{
Vect2 result;
result.x = x * a.x;
result.y = y * a.y;
return result;
}
Vect2 Vect2::operator/(const Vect2 a) const
{
Vect2 result;
result.x = x / a.x;
result.y = y / a.y;
return result;
}
bool operator>(const Vect2 vector, const float scalar)
{
if (vector.x > scalar && vector.y > scalar)
return true;
return false;
}
bool operator<(const Vect2 vector, const float scalar)
{
if (vector.x < scalar && vector.y < scalar)
return true;
return false;
}
bool operator>(const Vect2 lhs, const Vect2 rhs)
{
if (lhs.x > rhs.x && lhs.y > rhs.y)
return true;
return false;
}
bool operator<(const Vect2 lhs, const Vect2 rhs)
{
if (lhs.x < rhs.x && lhs.y < rhs.y)
return true;
return false;
}
Vect2 operator+(const float a, const Vect2 b)
{
Vect2 temp;
temp.x = a + b.x;
temp.y = a + b.y;
return temp;
}
Vect2 operator-(const float a, const Vect2 b)
{
Vect2 temp;
temp.x = a - b.x;
temp.y = a - b.y;
return temp;
}
Vect2 Vect2::operator-() const
{
Vect2 temp;
temp.x = 0 - this->x;
temp.y = 0 - this->y;
return temp;
}
Vect2 Vect2::operator+=(const Vect2 a)
{
*this = *this + a;
return *this;
}
Vect2 Vect2::operator-=(const Vect2 a)
{
*this = *this - a;
return *this;
}
Vect2 Vect2::operator*=(const Vect2 a)
{
*this = *this * a;
return *this;
}
Vect2 Vect2::operator/=(const Vect2 a)
{
*this = *this / a;
return *this;
}
Vect2 Vect2::operator*(const float scalar) const
{
Vect2 result;
result.x = x * scalar;
result.y = y * scalar;
return result;
}
Vect2 Vect2::operator/(const float scalar) const
{
Vect2 temp;
temp.x = x / scalar;
temp.y = y / scalar;
return temp;
}
// this is the addition operator to add a vector to a float
Vect2 Vect2::operator+(const float rhs) const
{
Vect2 result;
result.x = x + rhs;
result.y = y + rhs;
return result;
}
// this is the subtraction operator to add a vector to a float
Vect2 Vect2::operator-(const float rhs) const
{
Vect2 result;
result.x = x - rhs;
result.y = y - rhs;
return result;
}
Vect2 Vect2::operator+=(const float a)
{
*this = *this + a;
return *this;
}
Vect2 Vect2::operator-=(const float a)
{
*this = *this - a;
return *this;
}
Vect2 Vect2::operator*=(const float a)
{
*this = *this * a;
return *this;
}
Vect2 Vect2::operator/=(const float a)
{
*this = *this / a;
return *this;
}
const float & Vect2::operator[](int index) const
{
return (&x)[index];
}
float & Vect2::operator[](int index)
{
return (&x)[index];
}
void Vect2::set(float newX, float newY)
{
x = newX;
y = newY;
}
float Vect2::getMagnitude()
{
return sqrt((x * x) + (y * y));
}
float Vect2::getMagnitudeSquared()
{
return (x * x) + (y * y); //pythagorean theorum
}
Vect2 Vect2::getNormalized()
{
return Vect2(x,y) / Vect2(x,y).getMagnitude();
}
float Vect2::dotProduct(const Vect2 rhs)
{
return (x * rhs.x) + (y * rhs.y);
}
float Vect2::crossProduct(const Vect2 rhs)
{
return (x * rhs.y) - (y * rhs.x);
}
float Vect2::calculateDistance(const Vect2 vectA, const Vect2 vectB)
{
return sqrt(((vectA.x - vectB.x) * (vectA.x - vectB.x)) +
((vectA.y - vectB.y) * (vectA.y - vectB.y)));
}
float Vect2::calculateDistanceSquared(const Vect2 vectA, const Vect2 vectB)
{
return ((vectA.x - vectB.x) * (vectA.x - vectB.x)) +
((vectA.y - vectB.y) * (vectA.y - vectB.y));
}
//returns a point between two points with a given scale factor
Vect2 Vect2::lerp(Vect2 vectA, Vect2 vectB, float scaleFactor)
{
return (vectA * (1.0f - scaleFactor)) + (vectB * scaleFactor);
}<file_sep>#include "ProjectileIceAttack.h"
#include "HeroAttackManager.h"
#include "IceProjectile.h"
#include "Hero.h"
ProjectileIceAttack::ProjectileIceAttack()
{
attackTimer = 0.0f;
attackCooldown = 0.9f;
}
void ProjectileIceAttack::initAttack(cocos2d::Scene* scene)
{
IceProjectile* newProjectile = new IceProjectile();
//aim upwards
if (HeroAttackBase::isWKeyHeld)
newProjectile->velocity = Vect2(0, IceProjectile::SPEED);
//aim downwards
else if (HeroAttackBase::isSKeyHeld)
newProjectile->velocity = Vect2(0, -IceProjectile::SPEED);
//aim right
else if (Hero::hero->lookState == Hero::LookDirection::lookingRight)
newProjectile->velocity = Vect2(IceProjectile::SPEED, 0);
//aim left
else //(Hero::hero->Hero::hero->lookState == Hero::LookDirection::lookingLeft)
newProjectile->velocity = Vect2(-IceProjectile::SPEED, 0);
scene->addChild(newProjectile->sprite, 15);
}
void ProjectileIceAttack::update(float dt)
{
//during the attack cooldown
if (attackTimer < attackCooldown)
{
attackTimer += dt;
hitbox = hitbox.ZERO; //deactivate hitbox
}
else
{
attackTimer = 0.0f;
HeroAttackManager::setCurrentAttack(HeroAttackTypes::emptyA, nullptr);
}
}
<file_sep>#pragma once
#include "cocos2d.h"
//forward declare some classes for member variable
class HeroIdle;
class HeroMoveLeft;
class HeroMoveRight;
enum HeroMoveStates
{
idle,
moveLeft,
moveRight
};
class HeroMovementBase
{
public:
static HeroIdle* idleState;
static HeroMoveLeft* moveLeftState;
static HeroMoveRight* moveRightState;
static HeroMovementBase* currentState;
static void setCurrentState(HeroMoveStates newState);
virtual void init() {};
virtual void update(float dt) {};
};<file_sep>#pragma once
#ifndef HEROATTACKBASE_H
#define HEROATTACKBASE_H
#include "cocos2d.h"
class HeroAttackBase
{
public:
float attackTimer;
float attackWindup;
float attackDuration;
float attackCooldown;
bool disabled;
cocos2d::Rect hitbox;
static bool isWKeyHeld;
static bool isSKeyHeld;
virtual void initAttack() {};
virtual void update(float dt) {};
};
#endif<file_sep>#include "GameObject.h"
//set static const/variables
float GameObject::MAX_X = 1477.0f;
float GameObject::MAX_Y = 985.0f;
const Vect2 GameObject::GRAVITY = Vect2(0.0f, -250.0f); //set gravity
GameObject::GameObject(Vect2 position, std::string spriteFilePath) :
theta(0.0f),
mass(1.0f),
gravityMultiplier(1.0f)
{
//create sprite and set initial values
sprite = Sprite::create(spriteFilePath);
sprite->setPosition(Vec2(position.x, position.y));
width = sprite->getBoundingBox().size.width;
height = sprite->getBoundingBox().size.height;
//initially set hitboxes to the sprite's size, each game object can modify these in their own classes as necessary
moveBox.setRect(getLeftSidePos(), getBottomPos(), width, height);
hurtBox.setRect(getLeftSidePos(), getBottomPos(), width, height);
velocity.set(0.f, 0.f);
acceleration.set(0.f, 0.f);
force.set(0.f, 0.f);
}
GameObject::~GameObject()
{
sprite = NULL; //delete sprite
}
//gets poition of the sprite (middle)
Vect2 GameObject::getPosition()
{
return Vect2(sprite->getPosition());
}
//get the position (x or y) for the left, right, bottom and top edges of the sprite
float GameObject::getLeftSidePos()
{
return getPosition().x - width / 2;
}
float GameObject::getRightSidePos()
{
return getPosition().x + width / 2;
}
float GameObject::getBottomPos()
{
return getPosition().y - height / 2;
}
float GameObject::getTopPos()
{
return getPosition().y + height / 2;
}
//removes the sprite from the screen and deletes it
void GameObject::destroySprite()
{
sprite->runAction(RemoveSelf::create());
delete this;
}
//checks for collision on two AABB objects movement hitboxes
bool GameObject::isMovementCollision(GameObject* otherObject)
{
//check x values to see if they arent touching
//assuming sprites are named A and B:
//A_begin.x > B_end.x OR B_begin.x > A_end.x means there IS a gap on x
if (this->moveBox.getMinX() >= otherObject->moveBox.getMaxX() || otherObject->moveBox.getMinX() >= this->moveBox.getMaxX())
return false;
//check y values to see if they arent touching
//A_begin.y > B_end.y OR B_begin.y > A_end.y means there IS a gap on y
else if (this->moveBox.getMinY() >= otherObject->moveBox.getMaxY() || otherObject->moveBox.getMinY() >= this->moveBox.getMaxY())
return false;
//if neither, there's a collision
else
return true;
}
//checks for collision on the gameobject's hitbox
bool GameObject::isHitboxCollision(cocos2d::Rect otherHitbox)
{
//check x values to see if they arent touching
//assuming sprites are named A and B:
//A_begin.x > B_end.x OR B_begin.x > A_end.x means there IS a gap on x
if (this->hurtBox.getMinX() >= otherHitbox.getMaxX() || otherHitbox.getMinX() >= this->hurtBox.getMaxX())
return false;
//check y values to see if they arent touching
//A_begin.y > B_end.y OR B_begin.y > A_end.y means there IS a gap on y
else if (this->hurtBox.getMinY() >= otherHitbox.getMaxY() || otherHitbox.getMinY() >= this->hurtBox.getMaxY())
return false;
//if neither, there's a collision
else
return true;
}
//updates the object's physics properties
void GameObject::updatePhysics(float dt)
{
lastFramePosition = getPosition();
acceleration = force + (GRAVITY * gravityMultiplier * mass);
velocity += acceleration * dt; //update velocity
sprite->setPosition(sprite->getPosition() + Vec2(velocity.x, velocity.y) * dt); //update position
}<file_sep>#pragma once
#ifndef GRAPPLINGSTATE_H
#define GRAPPLINGSTATE_H
#include "HeroStateBase.h"
class GrapplingState : public HeroStateBase
{
public:
GrapplingState();
~GrapplingState();
void onEnter();
void onExit();
void handleInput(InputType input);
void update(float dt);
};
#endif<file_sep>#pragma once
#include "FirstBossState.h"
class Idling4FirstBoss : public FirstBossState
{
public:
//Constructor
Idling4FirstBoss(Boss *boss);
~Idling4FirstBoss();
//Member functions
void update(const float &deltaT) override;
private:
float cooldownBeforeNextAbility;
static int numberOfCast;
static const int maxNumberOfCastPerRound;
//Utility functions
void chooseRandomAbility();
};<file_sep>#pragma once
#include "Boss/Ability States/RestingState.h"
#include "Boss/Ability States/BossIdleState.h"
#include "Boss/Ability States/ExplosiveBullet.h"
#include "Boss/Ability States/FlameSplit.h"
#include "Boss/Ability States/FlameThrower.h"
#include "Boss/Ability States/DeathState.h"<file_sep>#pragma once
#ifndef HELPBUBBLE_H
#define HELPBUBBLE_H
#include "cocos2d.h"
class HelpBubble
{
public:
HelpBubble(std::string filePath, cocos2d::Vec2 position, float a_startThreshold, float a_endThreshold);
cocos2d::Sprite* sprite;
//start and end thresholds for displaying the help bubble
float startThreshold;
float endThreshold;
bool isFading;
static std::vector<HelpBubble*> helpBubbleList;
static void deleteAllInstances();
void update(float dt);
};
#endif<file_sep>#pragma once
#include "Boss/Attacks/Boss1Attack.h"
#include "Vect2.h"
/**
* @brief This attack will spawn when the explosive bullet get deleted and
* will suck the player in (if they are in range).\n
* This object can only be created through Explosive bullet class
*/
class ExplosiveArea : public Boss1LavaAttack
{
public:
//Constructors and Destructor
~ExplosiveArea();
//Member functions
void update(const float& deltaT) override;
private:
//Friend class
friend class ExplosiveBullet;
//Private constructor
explicit ExplosiveArea(const cocos2d::Vec2 &startPosition, Boss *bossInstance);
//Utility function
void addForceToHero();
Vect2 calculateDirectionToHero() const;
void resetHeroForce() const;
bool isHeroInRange() const;
float calculateDistanceSquare() const;
//Private data members
bool isExploding{false};
const float constantG;
};
/**
* @brief This attack will be shot from the boss's mouth to the player
* location.\n
* This object will be destroyed if it collides with the player or
* ground objects
*/
class ExplosiveBullet : public Boss1LavaAttack
{
public:
//Constructors and Destructor
explicit ExplosiveBullet(const cocos2d::Vec2 &heroLocation, Boss *bossInstance);
~ExplosiveBullet();
//Member functions
void update(const float& deltaT) override;
void hitByHero() override;
void hitByEnvironment() override;
private:
//Private members
bool isWaiting{ true };
static const float accelerationMultiplier, velocityMultiplier;
//Utility functions
void setUpPhysic(const cocos2d::Vec2& heroPos);
};<file_sep>#include "HelpBubble.h"
#include "Hero.h"
std::vector<HelpBubble*> HelpBubble::helpBubbleList = std::vector<HelpBubble*>();
HelpBubble::HelpBubble(std::string filePath, cocos2d::Vec2 position, float a_startThreshold, float a_endThreshold)
{
//set up sprite
sprite = Sprite::create(filePath);
sprite->setPosition(position);
sprite->setOpacity(0); //set opacity to 0 to allow fading in
//set thresholds
startThreshold = a_startThreshold;
endThreshold = a_endThreshold;
isFading = false;
helpBubbleList.push_back(this); //add to list
}
//clears all help bubbles from the list
void HelpBubble::deleteAllInstances()
{
helpBubbleList.clear();
}
//check hero's position to determine if we should doing any fading in/out
void HelpBubble::update(float dt)
{
float heroPosX = Hero::hero->getPosition().x;
//check if hero is in threshold range
if (heroPosX > startThreshold && heroPosX < endThreshold && !isFading)
{
sprite->runAction(cocos2d::FadeIn::create(1));
isFading = true;
}
//check if hero is out of threshold range and sprite is still visible
else if ((heroPosX < startThreshold && sprite->getOpacity()) || (heroPosX > endThreshold && sprite->getOpacity()))
{
sprite->runAction(cocos2d::FadeOut::create(1));
isFading = false;
}
}<file_sep>#pragma once
#ifndef PAUSEMENU_H
#define PAUSEMENU_H
#include "cocos2d.h"
#include "ControllerInput.h"
using namespace cocos2d;
class PauseMenu : public cocos2d::Scene
{
public:
enum MenuOptions
{
nothing,
resume,
controls,
exit
};
CREATE_FUNC(PauseMenu);
static Scene* createScene();
bool init();
void initUI();
void initAnimations();
void initMusic();
void initMouseListener();
void initControllerListener();
void moveToNextMenuItem();
void moveToPreviousMenuItem();
void update(float dt);
//Callbacks
void mouseDownCallback(Event* event);
void mouseUpCallback(Event* event);
void mouseMoveCallback(Event* event);
void mouseScrollCallback(Event* event);
//controller callbacks
void buttonPressCallback(Controller* controller, int keyCode, Event* event);
void buttonReleaseCallback(Controller* controller, int keyCode, Event* event);
void axisEventCallback(Controller* controller, int keyCode, Event* event);
private:
MenuOptions currentSelection;
Director* director;
EventListenerMouse* mouseListener;
EventListenerController* controllerListener;
Vec2 cursorPos;
Sprite* background;
Sprite* resumeText;
Sprite* controlsText;
Sprite* exitText;
Rect resumeRect;
Rect controlsRect;
Rect exitRect;
};
#endif<file_sep>#pragma once
#ifndef TUTORIAL_H
#define TUTORIAL_H
#include "cocos2d.h"
#include "Vect2.h"
#include "Hero.h"
#include "Platform.h"
#include "Grapple.h"
#include "HeroAttackManager.h"
#include "IceProjectile.h"
#include "HeroMovementBase.h"
#include "PlatformTile.h"
#include "GroundTile.h"
#include "XinputManager.h"
#include "SimpleAudioEngine.h"
using namespace cocos2d;
class Tutorial : public cocos2d::Scene
{
public:
CREATE_FUNC(Tutorial);
static Scene* createScene();
bool isTransitioning;
virtual bool init();
void initUI();
void initGameObjects();
void initSprites();
void initListeners();
void initMouseListener();
void initKeyboardListener();
void initControllerListener();
void initMusic();
void update(float dt);
void spawnEnemies();
void updateObjects(float dt);
void updateEnemies(float dt);
void removeAllObjects();
//mouse callbacks
void mouseDownCallback(Event* event);
void mouseUpCallback(Event* event);
void mouseMoveCallback(Event* event);
void mouseScrollCallback(Event* event);
//keyboard callbacks
void keyDownCallback(EventKeyboard::KeyCode keycode, Event* event);
void keyUpCallback(EventKeyboard::KeyCode keycode, Event* event);
//controller callbacks
void buttonPressCallback(Controller* controller, int keyCode, Event* event);
void buttonReleaseCallback(Controller* controller, int keyCode, Event* event);
void axisEventCallback(Controller* controller, int keyCode, Event* event);
private:
Director* director;
EventListenerMouse* mouseListener;
EventListenerKeyboard* keyboardListener;
EventListenerController* controllerListener;
Vect2 mousePosition;
float fieldWidth;
float fieldHeight;
Sprite* backgroundL1;
Sprite* backgroundL2;
Sprite* backgroundL3;
Sprite* backgroundL4;
Sprite* backgroundL5;
Sprite* backgroundL6;
Sprite* backgroundL7;
Sprite* backgroundL8;
Sprite* backgroundL9;
Sprite* backgroundL10;
Sprite* foregroundL1;
Sprite* foregroundL2;
DrawNode* testHurtbox; //for testing hurtbox
DrawNode* testMeleeAttack; //for testing melee attack
};
#endif<file_sep>#include "Boss.h"
#include "Hero.h"
#include "Boss/Ability States/BossIdleState.h"
#include "Boss/Attacks/Projectiles.h"
#include "VictoryScreen.h"
#include "GroundTile.h"
#include "Boss/Ability States/RestingState.h"
Boss::Boss(Hero* heroInstance, cocos2d::Scene* sceneForBoss, float height, float width)
: sprite(cocos2d::Sprite::create()), bossScene(sceneForBoss), health(30)
{
sprite->setPosition(230, 450);
initHitbox();
state = new RestingState(this);
}
Boss::~Boss()
{
delete state;
}
void Boss::setState(FirstBossState* newState)
{
if (state != nullptr)
delete state;
state = newState;
}
/**
* @brief Set the index for the hitbox base on the
* new state
* @param newIndex The new enum for the index
*/
void Boss::setHitboxIndex(HitboxIndex newIndex)
{
hitboxIndex = newIndex;
}
/**
* @brief Get the boss health
* @return Return int
*/
int Boss::getHealth() const
{
return health;
}
/**
* @brief Get the boss sprite
* @return Return the cocos2d::Sprite pointer
*/
cocos2d::Sprite* Boss::getSprite() const
{
return sprite;
}
/**
* @brief Get the vector of lavaList
* @return Return vector<Boss1LavaAttack*>
*/
std::vector<Boss1LavaAttack*> Boss::getLavaList() const
{
return lavaList;
}
/**
* @brief Return the scene that the boss is on
* @return Return cocos2d::Scene pointer
*/
cocos2d::Scene* Boss::getBossScene() const
{
return bossScene;
}
/**
* @brief Returns vector of hitboxes
* @return Return vector<Hitbox*>
*/
std::vector<HitBox*> Boss::getHitBox() const
{
return hitBoxLists[hitboxIndex];
}
/**
* @brief Reduce both health due to hero's attack
*/
void Boss::takeDamage()
{
sprite->setVisible(false); //flicker sprite upon taking damage
health--;
if (health == 0)
{
hitboxIndex = death;
state->changeToDeathState();
}
}
/**
* @brief Gets the boss's current state
* @return Return FirstBossState pointer
*/
FirstBossState* Boss::getCurrentState() const
{
return state;
}
/**
* @brief Updates the boss and all lava attacks from
* the boss
* @param deltaT The time changes from last frame to current frame
*/
void Boss::update(const float &deltaT)
{
state->update(deltaT);
for (auto attack : lavaList)
{
//Update the position of the attack
attack->update(deltaT);
//Check if the attack hits the ground tile
for (auto ground : GroundTile::groundTileList)
{
if (attack->getHitBox().intersectsRect(ground->hitBox))
{
attack->hitByEnvironment();
break;
}
}
}
//make sure sprite is visible
sprite->setVisible(true);
}
/**
* @brief Creates lava balls
*/
void Boss::spewLava()
{
for (size_t i = 1; i <= 5; i++)
{
lavaList.push_back(new LavaBall(i, this));
}
}
/**
* @brief Creates a flame thrower
*/
void Boss::activateFlameThrower()
{
lavaList.push_back(new FlameThrower(this));
}
/**
* @brief Creates an explosive bullet
*/
void Boss::shootExplosiveBullet()
{
lavaList.push_back(new ExplosiveBullet(Hero::hero->sprite->getPosition(), this));
}
/**
* @brief Remove a lava attack from the lavaList
* @param attackToRemove The attack to be removed
*/
void Boss::removeFromLavaList(Boss1LavaAttack* attackToRemove)
{
for (size_t i = 0; i < lavaList.size(); i++)
{
if (lavaList[i] == attackToRemove)
lavaList.erase(lavaList.begin() + i);
}
}
/**
* @brief Adds a lava attack to the lavaList
* @param attackToAdd The attack to be added to the list
*/
void Boss::addAttack(Boss1LavaAttack* attackToAdd)
{
lavaList.push_back(attackToAdd);
}
/**
* @brief Initialize all the hitboxes for all different states
*/
void Boss::initHitbox()
{
hitBoxLists.push_back(initIdleHitbox());
hitBoxLists.push_back(initFlameSplitHitbox());
hitBoxLists.push_back(initFlameThrowerHitbox());
hitBoxLists.push_back(initDeathHitbox());
}
/**
* @brief This function initialize hitboxes for idling.
* Explosive bullet state also share the same hitboxes
* @return Returns a Hitbox pointer vector
*/
std::vector<HitBox*> Boss::initIdleHitbox() const
{
std::vector<HitBox*> tempVector;
tempVector.push_back(new HitBox(Vec2(175, 845), 100, 350));
tempVector.push_back(new HitBox(Vec2(350, 790), 90, 100));
tempVector.push_back(new HitBox(Vec2(395, 575), 350, 75));
tempVector.push_back(new HitBox(Vec2(340, 300), 175, 100));
return tempVector;
}
/**
* @brief This function initialize hitboxes for flame split
* @return Returns a Hitbox pointer vector
*/
std::vector<HitBox*> Boss::initFlameSplitHitbox() const
{
std::vector<HitBox*> tempVector;
tempVector.push_back(new HitBox(Vec2(175, 875), 100, 350));
tempVector.push_back(new HitBox(Vec2(350, 820), 90, 100));
tempVector.push_back(new HitBox(Vec2(395, 605), 350, 75));
tempVector.push_back(new HitBox(Vec2(340, 210), 175, 100));
return tempVector;
}
/**
* @brief This function initialize hitboxes for flame thrower
* @return Returns a Hitbox pointer vector
*/
std::vector<HitBox*> Boss::initFlameThrowerHitbox() const
{
std::vector<HitBox*> tempVector;
tempVector.push_back(new HitBox(Vec2(175, 945), 100, 350));
tempVector.push_back(new HitBox(Vec2(350, 890), 90, 100));
tempVector.push_back(new HitBox(Vec2(395, 675), 350, 75));
tempVector.push_back(new HitBox(Vec2(340, 125), 175, 100));
return tempVector;
}
std::vector<HitBox*> Boss::initDeathHitbox() const
{
std::vector<HitBox*> tempVector;
return tempVector;
}
<file_sep>#pragma once
#ifndef PLATFORMTILE_H
#define PLATFORMTILE_H
#include "TileBase.h"
class PlatformTile : public TileBase
{
public:
PlatformTile(cocos2d::Vec2 position, float tileSize);
static std::vector<PlatformTile*> platformTileList;
bool checkAndResolveCollision(GameObject* otherObject) override;
};
#endif<file_sep>#pragma once
#include "Boss/Attacks/Boss1Attack.h"
class LavaBall : public Boss1LavaAttack
{
public:
LavaBall(int order, Boss *bossInstance);
~LavaBall();
//Functions
void update(const float &deltaT) override;
void hitByEnvironment() override;
void hitByHero() override;
private:
float waitingTime;
bool isWaiting{ true };
//Private member functions
void setUpPhysics();
};
<file_sep>#pragma once
#ifndef PLATFORM_H
#define PLATFORM_H
#include "Hero.h"
class Platform : public GameObject
{
public:
Platform(Vect2 position);
static std::vector<Platform*> platformList;
bool checkOneWayCollision(GameObject* otherObject);
void updateHitboxes() override;
void update();
};
#endif<file_sep>#pragma once
#ifndef EMPTYATTACK_H
#define EMPTYATTACK_H
#include "HeroAttackBase.h"
class EmptyAttack : public HeroAttackBase
{
public:
EmptyAttack();
bool onCooldown;
void update(float dt);
};
#endif<file_sep>#pragma once
#include "Boss/Ability States/FirstBossState.h"
/**
*
*/
class RestingState: public FirstBossState
{
float onTime{0};
public:
RestingState(Boss* aBossInstance);
void update(const float& deltaTime) override;
};<file_sep>#include "Boss/Ability States/DeathState.h"
#include <3d/CCAnimate3D.h>
#include "Animation.h"
#include "Boss/General/Boss.h"
#include "VictoryScreen.h"
#include "Hero.h"
DeathState::DeathState(Boss* bossInstance)
: FirstBossState(bossInstance)
{
Hero::hero->health = 100; //make sure hero doesnt die during transition
//Get animation
cocos2d::Animate* animation = marcos::AnimationManager::
getAnimation("boss_death_animation_key");
//Run action
bossPointer->getSprite()->stopAllActions();
bossPointer->getSprite()->runAction
(
cocos2d::Sequence::create
(
cocos2d::Repeat::create(animation, 1),
cocos2d::DelayTime::create(3),
cocos2d::CallFunc::create([&]{changeToVictoryScreen(); }),
nullptr
)
);
}
/**
* @brief Changes to victory scene when the boss finish
* doing death animation
*/
void DeathState::changeToVictoryScreen()
{
removeAllElements();
Hero::hero->reset(); //reset hero
cocos2d::Director::getInstance()->replaceScene
(
TransitionFade::create(2.0f, VictoryScreen::createScene(), Color3B(0, 0, 0))
);
}
void DeathState::removeAllElements()
{
auto lavaList = bossPointer->getLavaList();
for (auto i : lavaList) {
delete i;
}
bossPointer->getLavaList().clear();
}
<file_sep>#include "Boss/Attacks/ExplosiveBulletProjectile.h"
#include "Boss/General/Boss.h"
#include "Hero.h"
/**
* @brief Initialize data members for explosive area and set up sprite animation
*
* @param startPosition The position where the explosive bullet was destroyed
* @param bossInstance The current bossPointer
*/
ExplosiveArea::ExplosiveArea(const cocos2d::Vec2& startPosition, Boss* bossInstance)
: Boss1LavaAttack(bossInstance, "Sprites/spit_sprite.png"), constantG(7500)
{
//Set up the sprite's information
position = startPosition;
sprite->setPosition(position);
attackType = BossAttack::ExplosiveBullet;
//Set up hitbox
hitBox = new HitBox(position, 0, 0);
//Get the animation
const auto suckingAnimation = marcos::AnimationManager::getAnimationWithAnimationTime("boss_explosive_MID_animation_key",3);
const auto explodingAnimation = marcos::AnimationManager::getAnimation("boss_explosive_POST_animation_key");
//Run action
sprite->runAction
(
cocos2d::Sequence::create
(
cocos2d::Repeat::create(suckingAnimation, 1),
cocos2d::CallFunc::create([&] {isExploding = true; hitBox->setNewSize(120, 120); }),
cocos2d::Repeat::create(explodingAnimation, 1),
cocos2d::CallFunc::create([&] {delete this; }),
nullptr
)
);
}
/**
* @brief Run the destruction for explosive area object. This will
* also set the hero's position to 0
*/
ExplosiveArea::~ExplosiveArea()
{
resetHeroForce();
bossPointer->removeFromLavaList(this);
}
/**
* @brief This function updates the hitbox, as well as
* add force to the player
*/
void ExplosiveArea::update(const float& deltaT)
{
hitBox->updateHitBox(position);
if (!isExploding)
addForceToHero();
else
resetHeroForce();
}
/**
* @brief This function adds a force to the hero if they are in range
* and reset it to zero if they are not;
*/
void ExplosiveArea::addForceToHero()
{
//Apply force to hero if the hero position is in range
if (isHeroInRange())
Hero::hero->force = calculateDirectionToHero() * constantG;
else
resetHeroForce();
}
/**
* @brief This function calculate the direction from the hero
* to the center of the explosive area
*
* @return Returns Vect2 class
*/
Vect2 ExplosiveArea::calculateDirectionToHero() const
{
return Vect2(position.x - Hero::hero->getPosition().x, position.y - Hero::hero->getPosition().y).getNormalized();
}
/**
* @brief This function resets the hero's force if the explosive
* area has applied a force to the hero
*/
void ExplosiveArea::resetHeroForce() const
{
Hero::hero->force = Vect2(0, 0);
}
/**
* @brief This function checks if the hero is in the effective range
* @return True if hero is in range.\n False if hero is not in range
*/
bool ExplosiveArea::isHeroInRange() const
{
return Vec2(Hero::hero->getPosition().x - position.x, Hero::hero->getPosition().y - position.y).getLength()
< 200;
}
/**
* @brief Calculate distance square between the hero's position and the
* explosive area position
* @return Return distance square as float
*/
float ExplosiveArea::calculateDistanceSquare() const
{
return Vec2(Hero::hero->getPosition().x - position.x, Hero::hero->getPosition().y - position.y).getLength();
}
//Explosive Bullet static members
const float ExplosiveBullet::accelerationMultiplier = 2500;
const float ExplosiveBullet::velocityMultiplier = 1500;
/**
*@brief This initialize the data members and sprite action for the explosive bullet
*/
ExplosiveBullet::ExplosiveBullet(const cocos2d::Vec2& heroLocation, Boss* bossInstance)
: Boss1LavaAttack(bossInstance, "Sprites/spit_sprite.png")
{
//Set up the sprite
position.set(300, 300);
sprite->setPosition(position);
//Set up the animation
const auto animation = marcos::AnimationManager::getAnimation("boss_explosive_PRE_animation_key");
//Run actions
sprite->runAction
(
cocos2d::Sequence::create
(
cocos2d::Repeat::create(animation->clone(), 1),
cocos2d::CallFunc::create([&] {setUpPhysic(heroLocation); isWaiting = false; }),
nullptr
)
);
//Set up hit box
hitBox = new HitBox(position, 50, 50);
dealingDamage = 0;
}
ExplosiveBullet::~ExplosiveBullet()
{
bossPointer->removeFromLavaList(this);
bossPointer->addAttack(new ExplosiveArea(position, bossPointer));
}
/**
* @brief Updates the physics for the object
* @param deltaT The changes in time from the last frame to the
* current frame
*/
void ExplosiveBullet::update(const float& deltaT)
{
if (!isWaiting)
{
//physics update
setUpPhysic(Hero::hero->sprite->getPosition());
velocity += acceleration * deltaT;
position += velocity * deltaT;
////Update the sprite
sprite->setPosition(position);
hitBox->updateHitBox(position);
}
}
/**
* @brief This will delete the explosive bullet
*/
void ExplosiveBullet::hitByHero()
{
delete this;
}
/**
* @brief This will delete the explosive bullet
*/
void ExplosiveBullet::hitByEnvironment()
{
delete this;
}
/**
* @brief This will calculate all the initial physics
* components
* @param heroPos The hero location
*/
void ExplosiveBullet::setUpPhysic(const cocos2d::Vec2& heroPos)
{
const cocos2d::Vec2 tempVector = heroPos - position;
acceleration = tempVector.getNormalized() * accelerationMultiplier;
velocity = tempVector.getNormalized() * velocityMultiplier;
}
<file_sep>#include "TileBase.h"
#include "PlatformTile.h"
#include "GroundTile.h"
#include "SpikeTile.h"
#include "Hero.h"
std::vector<TileBase*> TileBase::tileList = std::vector<TileBase*>();
TileBase::TileBase(cocos2d::Vec2 position, float tileSize)
{
hitBox.setRect(position.x, position.y, tileSize, tileSize);
type = TileType::spike;
tileList.push_back(this);
}
//clears all tile vectors
void TileBase::deleteAllTiles()
{
tileList.clear();
PlatformTile::platformTileList.clear();
GroundTile::groundTileList.clear();
SpikeTile::spikeTileList.clear();
}
bool TileBase::checkGeneralCollision(GameObject * otherObject)
{
//check x values to see if they arent touching
//assuming objects are named A and B:
//A_begin.x > B_end.x OR B_begin.x > A_end.x means there IS a gap on x
if (this->hitBox.getMinX() >= otherObject->moveBox.getMaxX() || otherObject->moveBox.getMinX() >= this->hitBox.getMaxX())
return false;
//check y values to see if they arent touching
//A_begin.y > B_end.y OR B_begin.y > A_end.y means there IS a gap on y
else if (this->hitBox.getMinY() >= otherObject->moveBox.getMaxY() || otherObject->moveBox.getMinY() >= this->hitBox.getMaxY())
return false;
else //no gap means collision!
return true;
}
<file_sep>#pragma once
#include "TileBase.h"
class SpikeTile : public TileBase
{
public:
SpikeTile(cocos2d::Vec2 position, float tileSize);
static std::vector<SpikeTile*> spikeTileList;
bool checkAndResolveCollision(GameObject* otherObject) override;
};<file_sep>#include "HeroAttackManager.h"
#include "HeroStateManager.h"
EmptyAttack* HeroAttackManager::empty = new EmptyAttack();
MeleeFireAttack* HeroAttackManager::meleeFire = new MeleeFireAttack();
ProjectileIceAttack* HeroAttackManager::projectileIce = new ProjectileIceAttack();
HeroAttackBase* HeroAttackManager::currentAttack = HeroAttackManager::empty; //initialize current to empty
void HeroAttackManager::setCurrentAttack(HeroAttackTypes attackType, cocos2d::Scene* scene)
{
if (currentAttack == empty && !empty->onCooldown && HeroStateManager::currentState != HeroStateManager::dying) //make sure there isnt already an attack in progress
{
HeroStateManager::attacking->onEnter();
//check which attack type to set and call init function if applicable
switch (attackType)
{
case meleeFireA:
currentAttack = meleeFire;
meleeFire->initAttack();
break;
case projectileIceA:
currentAttack = projectileIce;
projectileIce->initAttack(scene);
break;
}
}
else if (attackType == emptyA) //or if the attack is not empty but now being set to empty
currentAttack = empty;
}
void HeroAttackManager::update(float dt)
{
currentAttack->update(dt);
}<file_sep>#include "Boss/Attacks/LavaBallProjectile.h"
#include "Boss/General/Boss.h"
#include "Hero.h"
LavaBall::LavaBall(int order, Boss *bossInstance)
: Boss1LavaAttack(bossInstance, "Sprites/spit_sprite.png")
{
attackType = BossAttack::LavaBall;
//Set Position for the lava ball
switch (order)
{
case 1:
waitingTime = 0.5;
position = cocos2d::Vec2(350, 525);
break;
case 2:
waitingTime = 1.1;
position = cocos2d::Vec2(350, 675);
break;
case 3:
waitingTime = 1.6;
position = cocos2d::Vec2(350, 375);
break;
case 4:
waitingTime = 2.2;
position = cocos2d::Vec2(350, 825);
break;
case 5:
waitingTime = 2.8;
position = cocos2d::Vec2(350, 225);
break;
default:
throw;
}
//Set physic variables
sprite->setPosition(position);
//Set sprite size
hitBox = new HitBox(position, 50.f, 50);
//Set up animation for sprite
const auto animation = marcos::AnimationManager::getAnimation("boss_spit_animation_key");
//Run the actions
sprite->runAction
(
cocos2d::Sequence::create
(
cocos2d::Repeat::create(animation->clone(), 1),
cocos2d::DelayTime::create(waitingTime),
cocos2d::CallFunc::create([&]{setUpPhysics();isWaiting = false;}),
nullptr
)
);
}
LavaBall::~LavaBall()
{
bossPointer->removeFromLavaList(this);
}
void LavaBall::update(const float& deltaT)
{
if (!isWaiting)
{
//setUpPhysics();
velocity += acceleration * deltaT;
position += velocity * deltaT;
sprite->setPosition(position);
hitBox->updateHitBox(position);
}
}
void LavaBall::hitByEnvironment()
{
delete this;
}
void LavaBall::hitByHero()
{
delete this;
}
void LavaBall::setUpPhysics()
{
const cocos2d::Vec2 tempVector = Hero::hero->sprite->getPosition() - position;
acceleration = tempVector.getNormalized() * 2000;
velocity = tempVector.getNormalized() * 750;
}
| 07518b924a59ca49da1e027b98ef3757fb1c1518 | [
"C",
"C++"
] | 120 | C++ | MatKostDev/EchosOfArem-GDW4-Game | 50117cade970ca5f0943b82177fd6877c50cdf0b | 5e5c26d646a25ff302c5fb46f11bd52181cc15fa |
refs/heads/master | <repo_name>kazuto1027/topview-sample1<file_sep>/sample.js
$(function() {
$(".fa-bars").click(function() {
// メニューバーを押したら処理開始//
$(".main__changemenu").fadeIn(1000);
$(".main__changemenu ul li").hide();
// 繰り返し処理
$(".main__changemenu ul li").each(function(i) {
// 遅延させてフェードイン
$(this).delay(500 * i).fadeIn(1000);
});
});
$(".main__changemenu").click(function() {
$(".main__changemenu").fadeOut(1000);
});
}); | f35e3df8443c155a4f57699d4aba96aa6ecdafa3 | [
"JavaScript"
] | 1 | JavaScript | kazuto1027/topview-sample1 | 633189f8f26260f32ca7f6399b2cc1e423bd2ed9 | ef7c6157e36aa19622ad4f06afe735582b74beff |
refs/heads/master | <repo_name>Zod-/ONIMods<file_sep>/README.md
# ONIMods
Mods and stuff
# Building the Mods
The projects assume ONI location and output to be at:
```
C:\Program Files (x86)\Steam\steamapps\common\OxygenNotIncluded
C:\Users\$(USERNAME)\Documents\Klei\OxygenNotIncluded\mods\Dev\$(ProjectName)\
```
<file_sep>/SolidFilterPokeshellFix/README.md
[Fixes this bug](https://forums.kleientertainment.com/klei-bug-tracker/oni/no-big-pokeshell-molt-choosable-r24180/)<file_sep>/SolidFilterPokeshellFix/Patches.cs
using Harmony;
using JetBrains.Annotations;
namespace ZodBain.SolidFilterPokeshellFix
{
[HarmonyPatch(typeof(TagNameComparer), nameof(TagNameComparer.Compare))]
public class TagNameComparerComparePatch
{
private static Tag _babbyCrabShell = new Tag("BabyCrabShell");
private static Tag _crabShell = new Tag("CrabShell");
public static bool FixActive;
[UsedImplicitly]
[HarmonyPostfix]
// ReSharper disable once InconsistentNaming
public static void Postfix(Tag x, Tag y, ref int __result)
{
if (!FixActive)
{
return;
}
//The real comparer uses the actual names which in both cases is "Pokeshell Molt"
if (x.Name == _crabShell.Name && y.Name == _babbyCrabShell.Name)
{
__result = -1;
}
else if (y.Name == _crabShell.Name && x.Name == _babbyCrabShell.Name)
{
__result = 1;
}
}
}
[HarmonyPatch(typeof(FilterSideScreen), "Configure")]
public class FilterSideScreenConfigurePatch
{
[UsedImplicitly]
[HarmonyPrefix]
public static void Prefix()
{
// Just to make sure we don't break anything else only enable this during the one method.
TagNameComparerComparePatch.FixActive = true;
}
[UsedImplicitly]
[HarmonyPostfix]
public static void Postfix()
{
TagNameComparerComparePatch.FixActive = false;
}
}
} | 7cdf9ea8b26a0fae2f482dde96ad262046ed7cec | [
"Markdown",
"C#"
] | 3 | Markdown | Zod-/ONIMods | 0d877978855138f2a9b38e9a10f045012c0f76b1 | 4f01fcb48392b78dc47a72c150c2579bbcdc10c8 |
refs/heads/master | <repo_name>m-r-tanha/samset<file_sep>/web/views.py
from typing import Dict, Any
from django.shortcuts import render
from .models import *
from django.views.decorators.csrf import csrf_exempt
#from Linkedin_Webscrapping import *
@csrf_exempt
#@require_POST
def UserInput(request):
if request.method == 'POST':
if request.POST.get( 'Email' ) and request.POST.get( 'Keyword' ):
post = UserInsert()
post.Email= request.POST.get( 'Email' )
post.Keyword = request.POST.get( 'Keyword' )
post.Location = request.POST.get( 'Location' )
post.CV = request.POST.get( 'CV' )
post.save()
return render( request, 'UserInput.html' )
else:
return render( request, 'UserInput.html' )
<file_sep>/README.md
# SAMSET-Django
<p> <h3> This is a startup project and I am going to run a Webscraping-NLP system to help someone who looks for a job. I have some Data Science innovative plans and I will use then in this project.
This project is in infancy part, but at the end, it will be appeared as a website, on this page I try to share and mention my challenges/solution/experience to up a site.
<h4>
<h2> Issue and solution when I am developing this Django site up
<h4>
- Access to the admin webpage: (http://127.0.0.1:8009/admin/)
- Create an account -->(python manage.py createsuperuser)
- Manage the next pages by adding them to admin.py

- When I want to import models to insert data to the data base (from models import *) this erros appear:
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
- solution:
set DJANGO_SETTINGS_MODULE=samset.settings
set DJANGO_SETTINGS_MODULE=settings
- As a matter of fact, the above commands didn't help me, and I found, I should run the (from models import *) in django shell
:pensive: " python manage.py shell"
<file_sep>/web/models.py
from django.db import models
# Create your models here.
from django.db.models import CharField
class WebInput( models.Model ):
JobDescription = models.TextField()
JobTitle = models.CharField( max_length=255 )
URL = models.CharField(max_length = 255)
class UserInsert( models.Model ):
Keyword = models.CharField( max_length=255 )
Location = models.CharField( max_length=255 )
Email=models.CharField( max_length=255 )
CV = models.TextField("")
<file_sep>/web/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.UserInput, name='UserInput'),
] | d4166a8507f678f470c6310d8dd1d05d2251721a | [
"Markdown",
"Python"
] | 4 | Python | m-r-tanha/samset | fe28db01b2b7d7c4564c583b16ddc7d10db914c5 | 896525d037d9987cac336aeffc102ccdda284ff5 |
refs/heads/main | <file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { NeighborhoodListComponent } from './neighborhood-list/neighborhood-list.component';
import { NeighborhoodFormComponent } from './neighborhood-form/neighborhood-form.component';
const routes: Routes = [
{ path: '', component: NeighborhoodListComponent },
{ path: 'new', component: NeighborhoodFormComponent },
{ path: ':id/edit', component: NeighborhoodFormComponent }
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class NeighborhoodsRoutingModule { }
<file_sep>/*
export class Neighborhood {
constructor(
public id?:number,
public name?:string
){}
}
FORMATO DO CURSO ANGULAR AVANÇADO
*/
//FORMATO DA MICHELE BRITO
export class Neighborhood {
id: number;
name: string;
}<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NeighborhoodsRoutingModule } from './neighborhoods-routing.module';
import { NeighborhoodListComponent } from './neighborhood-list/neighborhood-list.component';
import { NeighborhoodFormComponent } from './neighborhood-form/neighborhood-form.component';
@NgModule({
declarations: [NeighborhoodListComponent, NeighborhoodFormComponent],
imports: [
CommonModule,
NeighborhoodsRoutingModule
]
})
export class NeighborhoodsModule{}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Neighborhood } from '../../shared/neighborhood.model';
import { NeighborhoodService } from '../../shared/neighborhood.service';
@Component({
selector: 'app-neighborhood-list',
templateUrl: './neighborhood-list.component.html',
styleUrls: ['./neighborhood-list.component.css']
})
export class NeighborhoodListComponent implements OnInit {
//listaBairros: Neighborhood[];
neighborhoods: Neighborhood[] = [];
constructor(public neighborhoodService: NeighborhoodService) { }
ngOnInit(): void {
this.neighborhoodService.getAll().subscribe(
neighborhoods => this.neighborhoods = neighborhoods,
error => alert('Erro ao carregar a lista')
)
}
deleteNeighborhood(neighborhood) {
const mustDelete = confirm('Deseja reamente excluir este item? ');
if (mustDelete) {
this.neighborhoodService.delete(neighborhood.id).subscribe(
() => this.neighborhoods = this.neighborhoods.filter(element => element != neighborhood),
() => alert("Erro ao tentar excluir!")
)
}
}
/*
getAll(){
this.neighborhoodService.getAll().subscribe(data => {
this.listaBairros = data.content;
console.log(this.listaBairros);
});
}
*/
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpClientModule, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError, flatMap } from 'rxjs/operators';
import { Neighborhood } from './neighborhood.model';
import { NeighborhoodsModule } from '../neighborhoods/neighborhoods.module';
import { ResponsePageable } from './responsePageable';
@Injectable({
providedIn: 'root'
})
export class NeighborhoodService {
// Inicio - Micheli
//apiUrl = 'http://localhost:8080/neighborhoods'; //Alterado para funcionar com proxy, videio da Loiane em: https://www.youtube.com/watch?v=D9oFe6rHjpY
apiUrl = '/api/neighborhoods';
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
// Fim - Micheli
//private apiPath: string = "api/neighborhoods"
//constructor(private http: HttpClient) { } //ESTE ERA O CONTRUTOR ORIGINAL
constructor(private httpClient: HttpClient) { } //CONSTRUTOR <NAME>
/* TESTE
public getAll(): Observable<ResponsePageable> {
return this.httpClient.get<ResponsePageable>(this.apiUrl);
}
*/
getAll(): Observable<Neighborhood[]> {
return this.httpClient.get(this.apiUrl).pipe(
catchError(this.handleError),
map(this.jsonDataToNeighborhoods)
)
}
getById(id: number): Observable<Neighborhood> {
const url = `${this.apiUrl}/${id}`;
return this.httpClient.get(url).pipe(
catchError(this.handleError),
map(this.jsonDataToNeighborhood)
)
}
create(neighborhood: Neighborhood): Observable<Neighborhood> {
return this.httpClient.post(this.apiUrl, neighborhood).pipe(
catchError(this.handleError),
map(this.jsonDataToNeighborhood)
)
}
delete(id: number): Observable<any> {
const url = `${this.apiUrl}/${id}`;
return this.httpClient.delete(url).pipe(
catchError(this.handleError),
map(() => null)
)
}
update(neighborhood: Neighborhood): Observable<Neighborhood> {
const url = `${this.apiUrl}/${neighborhood.id}`;
return this.httpClient.put(url, neighborhood).pipe(
catchError(this.handleError),
map(() => neighborhood)
)
}
//PRIVATE METHODS
private jsonDataToNeighborhoods(jsonData: any[]): Neighborhood[] {
const neighborhoods: Neighborhood[] = [];
jsonData.forEach(element => neighborhoods.push(element as Neighborhood));
return neighborhoods;
}
private jsonDataToNeighborhood(jsonData: any): Neighborhood {
return jsonData as Neighborhood;
}
private handleError(error: any): Observable<any>{
console.log("ERRO NA REQUISIÇÃO => ", error);
return throwError(error);
}
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CompaniesRoutingModule } from './companies-routing.module';
import { CompanyListComponent } from './company-list/company-list.component';
import { CompanyFormComponent } from './company-form/company-form.component';
@NgModule({
declarations: [CompanyListComponent, CompanyFormComponent],
imports: [
CommonModule,
CompaniesRoutingModule
]
})
export class CompaniesModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
import { Neighborhood } from '../../shared/neighborhood.model';
import { NeighborhoodService } from '../../shared/neighborhood.service';
@Component({
selector: 'app-company-list',
templateUrl: './company-list.component.html',
styleUrls: ['./company-list.component.css']
})
export class CompanyListComponent implements OnInit {
neighborhoods: Neighborhood[] = [];
constructor(public neighborhoodService: NeighborhoodService) { }
ngOnInit(): void {
this.neighborhoodService.getAll().subscribe(
neighborhoods => this.neighborhoods = neighborhoods,
error => alert('Erro ao carregar a lista')
)
}
/*
getNeighborhoods(){
this.neighborhoodService.getAll().subscribe(data => {
this.neighborhoodsList = data.content;
console.log(this.neighborhoodsList);
});
}
*/
} | e8979dd731db70f388518ed3f6c178c8d8ec413b | [
"TypeScript"
] | 7 | TypeScript | alexandremcp/sanitary-inspection-front-end | 64b1d889a51700c37831e4bf6e622dd5e0d3d296 | f972041f03bcb143cc43f3a2dbc38e4cbf7e9ee4 |
refs/heads/master | <file_sep># Adversarial-sudoku
sudoku variant written in python
<file_sep>from functools import reduce
import operator
N = 2
matrix = [[y*x for y in range(1,N*N+1)] for x in range(1,N*N+1)]
x = list(map(lambda x:x[:2], matrix))
protounique = lambda lista : len(lista) == len(set(lista))
sliceVertical = lambda lista, columna: list(map(lambda x : x[fila] ,lista))
def mul(x,y):
if x == 0 and y != 0 :
x = 1
if y == 0 and x != 0 :
y = 1
return x*y
def cuandrantes(lista):
result = list(map(lambda x : [] , range(N*N)))
for cuadrante in range(N*N):
for y in range(N*N):
for x in range(N):
if x < mul(N,cuadrante) and y < mul(N,cuadrante):
#result[y].insert([y][x],lista)
result[cuadrante].append(lista[y][x])
return result
def sudoku(board):
horizontal = reduce( operator.and_, map( protounique , board))
flippedBoard = list(map(lambda x : sliceVertical(board,x),range(N*N)))
vertical = reduce( operator.and_, map( protounique , flippedBoard))
return vertical and horizontal
filtro = lambda lista : list(filter(None.__ne__,lista))
matriz = [
[1,0,0,2],
[0,0,0,0],
[0,0,0,0],
[3,0,0,4],
]
print(cuandrantes(matriz), sep ="\n")
| c4837a246a72240b987df9d28b05c38300e313fd | [
"Markdown",
"Python"
] | 2 | Markdown | GunpowderGuy/Adversarial-sudoku | 794d71126ce0ac1c88069428fdbd1c3e56df1d74 | 2ffb4e83d0135a98371883ad502902564ade6894 |
refs/heads/master | <file_sep>/*
Author: <NAME>
Index limits for different colors, especially white
and black, can be adjusted for prettier artistic effect.
*/
var NDVI = index (B08, B04); // calculate the index
if (NDVI < 0.1) {
return [1, 1, 1] // white
}
if (NDVI < 0.2) {
return [0.8, 0.2, 0.] // nice red
}
if (NDVI < 0.4) {
return [0.2, 0.2, 1] // nice blue
}
if (NDVI < 0.6) {
return [1., 0.7, 0.] // nice yellow
}
else {
return [0, 0, 0] // black
}
<file_sep># Homage-to-Mondrian
 | 
--- | ---
Fields in the Netherlands | <NAME>, Composition with Red Blue and Yellow-Green, 1920 [2]
> "To approach the spiritual in art, one will make as little use as possible
of reality, because reality is opposed to the spiritual."
>
> <NAME>, 1914
<NAME> was a Dutch
painter and theoretician who is regarded as one of the greatest artists of
the 20th century. He is known for being one of the pioneers of 20th century
abstract art, as he changed his artistic direction from figurative painting
to an increasingly abstract style, until he reached a point where his
artistic vocabulary was reduced to simple geometric elements [1].
## General description of the script
This is an artistic script to pay tribute to Dutch painter <NAME>.
It takes normalized difference vegetation index (NDVI) and paints pixels
in 5 different colors depending on its value. Colors are chosen to match
those in the most popular Mondrian's paintings.
The script is universally applicable but the best artistic effects are reached
in locations with repetitive and geometrically uniform landscape, for example in large
agricultural fields. It can be further improved by manually adjusting
limits of NDVI for each color, depending on geographic location and personal taste.
## Evaluate and visualize
Links to locations in EO Browser:
- [Flevoland province in the Netherlands](https://apps.sentinel-hub.com/eo-browser/?lat=52.64765&lng=5.74326&zoom=13&time=2019-10-30&preset=CUSTOM&datasource=Sentinel-2%20L1C&layers=B01,B02,B03&evalscript=dmFyIE5EVkkgPSBpbmRleCA<KEY>IC8v<KEY>0%3D)
- [Rakaia river in New Zealand](https://apps.sentinel-hub.com/eo-browser/?lat=-43.88861&lng=172.03406&zoom=13&time=2019-02-28&preset=CUSTOM&atmFilter=DOS1&gammaOverride=2.4&redRangeOverride=[0,1]&datasource=Sentinel-2%20L1C&layers=B01,B02,B03&evalscript=<KEY>7CglyZXR1cm4gWzAuMiwgMC4yLCAxXSAvLyBuaWNlIGJsdWUKfQppZiAoTkRWSSA8IDAuNykgewoJcmV0dXJuIFsxLiwgMC43LCAwLl0gLy8gbmljZSB5ZWxsb3cKfSAKZWxzZSB7IAoJcmV0dXJuIFswLCAwLCAwXSAvLyBibGFjawp9Cg%3D%3D)
## Author of the script
<NAME>
## Description of representative images
Composition No.II 1920 by Piet Mondrian [2]

Flevoland province in the Netherlands (Flevopolder)

Rakaia river outflow in New Zealand

Flevoland province in the Netherlands (Noordoostpolder)

## References
[1] [Piet Mondrian Wikipedia page](https://en.wikipedia.org/wiki/Piet_Mondrian)
[2] [https://www.piet-mondrian.org](https://www.piet-mondrian.org)
| f2f8fe1d263ba61d19f3b75fd1511a71c063714c | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | PintarM/Homage-to-Mondrian | 0b7a6c1e5c7fbd54f3513e464792a3e7082f22fa | 4767fc175bb1c0476a86f1c1a7c1cc88bff5fba7 |
refs/heads/master | <repo_name>MouniAch/App_Shop<file_sep>/app/Notifications/RepliedToCommand.php
<?php
namespace App\Notifications;
use App\Command;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class RepliedToCommand extends Notification
{
use Queueable;
protected $command;
public function __construct(Command $command)
{
$this->command=$command;
}
public function via($notifiable)
{
return ['database'];
}
public function toArray($notifiable)
{
return [
$data = 'We Have New Command ' .$command->adress ." <br> Added By " . $command->name
];
}
}
<file_sep>/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('/','UsersController@getIndex');
Route::get('admin',['middleware'=>'isalivreur',function(){
return view('admin');
}]);
Route::get('livreur', ['middleware'=>'auth',function(){
return view('livreur');
}]);
Auth::routes();
Route::post('form','CommandController@create');
Route::get('accessory',function(){
return view('accessory');
});
Route::get('profile',function(){
return view('profile');
});
/*Route::get('command.form',function(){
return view('command.form');
});*/
Route::get('/home', 'HomeController@index');
Route::get('/produits','ProduitController@index');
Route::get('produits/create','ProduitController@create');
Route::post('produits','ProduitController@store');
Route::get('produits/{id}/edit','ProduitController@edit');
Route::put('produits/{id}','ProduitController@update');
Route::delete('produits/{id}','ProduitController@destroy');
Route::get('/cats','CatController@index');
Route::get('cats/create','CatController@create');
Route::post('cats','CatController@store');
Route::get('cats/{id}/edit','CatController@edit');
Route::put('cats/{id}','CatController@update');
Route::delete('cats/{id}','CatController@destroy');
Route::get('orders','OrderController@index');
Route::get('orders/create','OrderController@create');
Route::post('orders','OrderController@store');
Route::get('orders/{id}/edit','OrderController@edit');
Route::put('orders/{id}','OrderController@update');
Route::delete('orders/{id}','OrderController@destroy');
Route::get('customers','CustomerController@index');
Route::get('customers/create','CustomerController@create');
Route::post('customers','CustomerController@store');
Route::get('customers/{id}/edit','CustomerController@edit');
Route::put('customers/{id}','CustomerController@update');
Route::delete('customers/{id}','CustomerController@destroy');
Route::get('users','UsersController@index');
Route::get('users/create','UsersController@create');
Route::post('users','UsersController@store');
Route::get('users/{id}/edit','UsersController@edit');
Route::get('users/{id}/detail','UsersController@detail');
Route::put('users/{id}','UsersController@update');
Route::delete('users/{id}','UsersController@destroy');
Route::get('page','ProduitController@list');
Route::get('produits/{id}','ProduitController@product');
Route::get('order.commande','OrderController@getcommande');
Route::get('produits/create','CatController@getcategory');
Route::resource('command','CommandController');
Route::get('/settings','UsersController@setting');
Route::get('/profile','ProfileController@profile');
Route::post('/updateprofile','ProfileController@updateprofile');
Route::get('/getaccessory','ProduitController@getaccessory');
Route::get('/admin', 'AdminController@statuser');
Route::get('commandes/{id_client}/detail', 'CommandController@detail');
Route::get('commandes/{id}/detail1', 'OrderController@detail1');
Route::delete('commandes/{id_client}','CommandController@destroy');
<file_sep>/app/Http/Controllers/ClientsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ClientsController extends Controller
{
public function getboutique(){
return view('client');
}
}
<file_sep>/app/Http/Controllers/CatController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests\catRequest;
use Illuminate\Http\Request;
use App\Cat;
use illuminate\Http\UploadedFile;
class CatController extends Controller
{
public function index() {
$listcat=Cat::all();
return view('cat.index',['cats'=>$listcat]);
}
public function create() {
return view('cat.create');
}
public function getcategory(){
$cats=Cat::all();
return view('produit.create',['cats'=>$cats]);
}
public function store(catRequest $request){
$cat=new Cat();
$cat->title=$request->input('title');
$cat->save();
return redirect('/cats');
}
public function edit($id){
$cat=Cat::find($id);
return view('cat.edit',['cat'=>$cat]);
}
//permet de modifier un produit
public function update(catRequest $request,$id){
$cat = Cat::find($id);
$cat->title=$request->input('title');
$cat->save();
return redirect('/cats');
}
// permet de supprimer un produit
public function destroy(catRequest $request,$id){
$cat=Cat::find($id);
$cat->delete();
return redirect('/cats');
}
}
<file_sep>/app/Http/Controllers/CustomerController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests\customerRequest;
use App\Customer;
use Illuminate\Http\Request;
class CustomerController extends Controller
{
public function index() {
$listcustomer=Customer::all();
return view('customer.index',['customers'=>$listcustomer]);
}
public function create() {
return view('customer.create');
}
public function store(customerRequest $request){
$customer=new Customer();
$customer->name=$request->input('name');
$customer->email=$request->input('email');
$customer->address=$request->input('address');
$customer->mobile=$request->input('mobile');
$customer->save();
return redirect('customers');
}
public function edit($id){
$customer=Customer::find($id);
return view('customer.edit',['customer'=>$customer]);
}
//permet de modifier un produit
public function update(customerRequest $request,$id){
$customer = Customer::find($id);
$customer->name=$request->input('name');
$customer->email=$request->input('email');
$customer->address=$request->input('address');
$customer->mobile=$request->input('mobile');
$customer->save();
return redirect('customers');
}
// permet de supprimer un produit
public function destroy(Request $request,$id){
$customer=Customer::find($id);
$customer->delete();
return redirect('customers');
}
}
<file_sep>/app/Http/Controllers/OrderController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests\orderRequest;
use Illuminate\Http\Request;
use App\Order;
use Auth;
use Illuminate\Support\Facades\DB;
class OrderController extends Controller
{
public function getcommande(){
$user=Auth::user();
$commandes = DB::table('orders')->where('name_deli',$user->name);
$commandes=$commandes->get();
return view('order.commande',['commandes'=>$commandes]);
}
public function index() {
/*$listorder=Order::all()->paginate(6);*/
$listorder=DB::table('orders')->paginate(3);
return view('order.index',['orders'=>$listorder]);
}
public function create() {
return view('order.create');
}
public function store(orderRequest $request){
$order=new Order();
$order->reference=$request->input('reference');
$order->date=$request->input('date');
$order->address=$request->input('address');
$order->price=$request->input('price');
$order->name_deli=$request->input('name_deli');
$order->save();
return redirect('orders');
}
public function edit($id){
$order=Order::find($id);
return view('order.edit',['order'=>$order]);
}
//permet de modifier un produit
public function update(orderRequest $request,$id){
$order = Order::find($id);
$order->reference=$request->input('reference');
$order->date=$request->input('date');
$order->address=$request->input('address');
$order->price=$request->input('price');
$order->name_deli=$request->input('name_deli');
$order->save();
return redirect('orders');
}
// permet de supprimer un produit
public function destroy(Request $request,$id){
$order=Order::find($id);
$order->delete();
return redirect('orders');
}
public function detail1($name_deli) {
$command=Order::find($name_deli);
return view('command.detail1',['commandes'=>$command]);
}
}
<file_sep>/app/Http/Controllers/LivreurController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests\livreurRequest;
use App\Livreur;
use Illuminate\Http\Request;
class LivreurController extends Controller
{
public function index() {
$listlivreur=Livreur::all();
return view('livreur.index',['livreurs'=>$listlivreur]);
}
public function create() {
return view('livreur.create');
}
public function store(livreurRequest $request){
$livreur=new Livreur();
$livreur->name=$request->input('name');
$livreur->email=$request->input('email');
$livreur->password=$request->input('password');
$livreur->ville=$request->input('ville');
$livreur->telephone=$request->input('telephone');
/*$livreur->mobile=$request->input('mobile');
$livreur->availability=$request->input('availability'); */
$livreur->save();
return redirect('livreurs');
}
public function edit($id){
$livreur=Livreur::find($id);
return view('livreur.edit',['livreur'=>$livreur]);
}
//permet de modifier un produit
public function update(livreurRequest $request,$id){
$livreur = Livreur::find($id);
$livreur->name=$request->input('name');
$livreur->email=$request->input('email');
$livreur->password=$request->input('password');
/*$livreur->address=$request->input('address');*/
$livreur->ville=$request->input('ville');
$livreur->telephone=$request->input('telephone');
/* $livreur->mobile=$request->input('mobile');
$livreur->availability=$request->input('availability'); */
$livreur->save();
return redirect('livreurs');
}
// permet de supprimer un produit
public function destroy(Request $request,$id){
$livreur=Livreur::find($id);
$livreur->delete();
return redirect('livreurs');
}
}
<file_sep>/app/Cat.php
<?php
namespace App;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
class Cat extends Model
{
protected $table= 'cats';
protected $fillable=['title'];
use SoftDeletes;
protected $dates = ['deleted_at'];
}
<file_sep>/app/Command.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Command extends Model
{
protected $table="command";
protected $primaryKey = 'id_client';
protected $dates = ['deleted_at'];
protected $fillable = [
'name', 'email', 'adress','product','quantity','phone','dispo'
];
}
<file_sep>/app/Http/Controllers/AdminController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class AdminController extends Controller
{
public function dashboard(){
return view('admin');
}
/*public function statorder(){
return view('admin',['orders'=>$orders]);
}*/
public function statuser(){
$orders = DB::table('orders');
$users = DB::table('users');
$commandes=DB::table('command');
return view('admin',array
(
'orders' => $orders,
'users' => $users,
'commandes' => $commandes,
));
}
}
<file_sep>/app/Http/Controllers/UsersController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests\livreurRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\User;
class UsersController extends Controller
{
public function getIndex(){
return view('index');
}
public function index() {
$listlivreur=User::all();
return view('livreur.index',['users'=>$listlivreur]);
}
public function create() {
return view('livreur.create');
}
public function store(livreurRequest $request){
$livreur=new User();
$livreur->name=$request->input('name');
$livreur->email=$request->input('email');
$livreur->password=<PASSWORD>($request->input('password'));
$livreur->ville=$request->input('ville');
$livreur->telephone=$request->input('telephone');
$livreur->type=$request->input('type');
$livreur->save();
return redirect('users');
}
public function edit($id){
$livreur=User::find($id);
return view('livreur.edit',['livreur'=>$livreur]);
}
//permet de modifier un produit
public function update(livreurRequest $request,$id){
$livreur = User::find($id);
$livreur->name=$request->input('name');
$livreur->email=$request->input('email');
$livreur->password=<PASSWORD>($request->input('password'));
$livreur->ville=$request->input('ville');
$livreur->telephone=$request->input('telephone');
$livreur->type=$request->input('type');
$livreur->save();
return redirect('users');
}
// permet de supprimer un produit
public function destroy(Request $request,$id){
$livreur=User::find($id);
$livreur->delete();
return redirect('users');
}
public function detail($id) {
$listuser=User::find($id);;
return view('livreur.detail',['users'=>$listuser]);
}
}
<file_sep>/app/Http/Controllers/CommandController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Command;
use App\User;
use App\Notification;
use App\Produit;
use App\Notifications\RepliedToCommand;
use DB;
use Illuminate\Support\Facades\Aut;
use Illuminate\Support\Facades\Redirect;
class CommandController extends Controller
{
public function index(){
$commandes=DB::table('command')->paginate('6');
return view('command.allcommand', compact('commandes'));
}
public function create(Request $request){
$produit=Produit::where('id',$request->id)->first();
$quantity=$request->quantity;
return view('command.form')->with([ 'produit'=>$produit,'quantity'=>$quantity]);
}
public function store(Request $request){
$command = new Command();
$command->name = $request->name;
$command->email = $request->email;
$command->phone = $request->phone;
$command->adress = $request->adress;
$command->dispo = $request->dispo;
/* $command->product = $request->prod_id;*/
$command->product = $request->product;
$command->quantity =$request->quantity;
$command->save();
return redirect('/');
}
/* public function form($id){
return view('form')->with(compact('produit'));
}*/
public function detail($id_client) {
$command=Command::find($id_client);
return view('command.detail',['commandes'=>$command]);
}
public function destroy(Request $request,$id_client){
$command=Command::find($id_client);
if($command != null){
$command->delete();
return back()->with(['message'=> 'Successfully deleted!!']);
}
return back()->with(['message'=> 'Wrong ID!!']);
}
}
<file_sep>/app/Http/Controllers/ProfileController.php
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class ProfileController extends Controller
{
public function profile(){
return view('profile');
}
public function updateprofile(Request $request){
$user=Auth::user();
$user->name=$request['name'];
$user->email=$request['email'];
$user->telephone=$request['telephone'];
$user->password=<PASSWORD>($request->input('password'));
$user->save();
return back();
}
}
<file_sep>/app/Http/Controllers/ProduitController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests\produitRequest;
use Illuminate\Http\Request;
Use App\Produit;
use App\Cat;
use illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\File;
use Illuminate\Support\Facades\DB;
class ProduitController extends Controller
{
function list(){
$produits=DB::table('produits')->paginate(6);
return view('page',['produits'=>$produits]);
}
//lister les produits
public function index(){
$listproduit=DB::table('produits')->paginate(3);
return view('produit.index',['produits'=>$listproduit]);
}
public function getaccessory(){
$produit=DB::table('produits')->where('section','ladies')
->where('category','2');
$produit=$produit->get();
return view('produit.ladies',['produit'=>$produit]);
}
// affiche le formulaire de creation de produit
public function create(){
return view('produit.create');
}
//enregistrer un produit
public function store(produitRequest $request){
$produit=new Produit();
$produit->designation=$request->input('designation');
$produit->description=$request->input('description');
$produit->category=$request->input('category');
$produit->price=$request->input('price');
$produit->section=$request->input('section');
if($request->hasfile('image'))
{
$file = $request->file('image');
$extension = $file->getClientOriginalExtension();
$filename = time(). '.' .$extension;
$file->move('uploads/produit/',$filename);
$produit->image = $filename;
}
$produit->save();
return redirect('produits');
}
//permet de récupérer un produit puis de le mettre dans un formulaire
public function edit($id){
$produit=Produit::find($id);
return view('produit.edit',['produit'=>$produit]);
}
//permet de modifier un produit
public function update(produitRequest $request,$id)
{
$produit = Produit::find($id);
if($request->hasfile('image'))
{
$image = $request->file('image');
$extension = $image->getClientOriginalExtension();
$filename = time(). '.' .$extension;
$location = storage_path('uploads/produit/'.$filename);
Image::make($image)->resize(800,400)->save($location);
Storage::delete($oldFilename);
$produit->image= $filename;
}
$produit->designation=$request->input('designation');
$produit->description=$request->input('description');
$produit->category=$request->input('category');
$produit->price=$request->input('price');
$produit->save();
return redirect('produits');
}
// permet de supprimer un produit
public function destroy(Request $request,$id){
$produit=Produit::find($id);
$produit->delete();
return redirect('produits');
}
public function product($id){
$produit=Produit::where('id',$id)->first();
return view('produit.detail')->with(compact('produit'));
}
}
| d6b15849bf4aa4a0628f0006ccf0e2a826ea0a96 | [
"PHP"
] | 14 | PHP | MouniAch/App_Shop | 46b338e6d3efa00405b1d98385f03c32a5f920b0 | 79f603765b37943c255879301c18004e631f14be |
refs/heads/master | <file_sep>git_scm
=======
<file_sep>puts "hello 1"
| 6b5e2211e4036c532e2b3c629efd920a878789f2 | [
"Markdown",
"Ruby"
] | 2 | Markdown | alfredov/git_scm | af80b2b1744387eefd575bed005f493db092e7d8 | a36de7c1cae61ee8fd5075da51c3497bd5eab4ac |
refs/heads/master | <repo_name>zhangchen9218/shop_admin<file_sep>/database/factories/ArticlesFactory.php
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\Model\Article;
use Faker\Generator as Faker;
$factory->define(Article::class, function (Faker $faker) {
return [
"title" => $faker->sentence,
"intro" => Str::limit($faker->paragraph,50),
"author" => $faker->name,
"comment_state" => rand(1,2),
"icon" => "aaa",
"column_id" => 1,
"source" => $faker->name,
"content" => $faker->paragraph,
"operator_id" => 1,
"verifier_id" => 1,
"impression" => rand(100,9999),
"category_id" => rand(1,4),
'key_words'=> "1,2,3,4,5",
"state" => rand(1,4)
];
});
<file_sep>/resources/lang/zh/validation.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages here.
|
*/
'accepted' => ':attribute 必须被认可',
'active_url' => ':attribute URL无效',
'after' => ':attribute 必须在 :date 之后',
'after_or_equal' => ':attribute 必须大于等于 :date',
'alpha' => ':attribute 只包含字母',
'alpha_dash' => ':attribute 只包含字母,数字,破折号和下划线',
'alpha_num' => ':attribute 只包含字母和数字',
'array' => ':attribute 只包含数组',
'before' => ':attribute 必须在 :date 之前',
'before_or_equal' => ':attribute 必须大于等于 :date',
'between' => [
'numeric' => ':attribute 必须在 :min - :max 之间',
'file' => ' :attribute 必须在 :min - :max 字节之间',
'string' => ' :attribute 必须在 :min - :max 字符之间',
'array' => ' :attribute 必须在 :min - :max 之间',
],
'boolean' => ' :attribute 字段必须为布尔型',
'confirmed' => ' :attribute 不匹配',
'date' => ' :attribute 不是有效日期',
'date_equals' => ' :attribute 必须等于 :date.',
'date_format' => ' :attribute 格式不匹配 :format.',
'different' => ' :attribute 与 :other 必须不同',
'digits' => ' :attribute 必须 :digits 位',
'digits_between' => ' :attribute 必须在 :min - :max 位数之间',
'dimensions' => ' :attribute 图像尺寸无效',
'distinct' => ' :attribute 字段具有重复的值。',
'email' => ' :attribute 必须是一个有效的电子邮件地址。',
'ends_with' => ' :attribute 必须是下列值之一: :values',
'exists' => ' :attribute 选项是无效的',
'file' => ' :attribute 必须是个文件',
'filled' => ' :attribute 必须有值',
'gt' => [
'numeric' => ' :attribute 必须大于 :value',
'file' => ' :attribute 必须大于 :value 字节',
'string' => ' :attribute 必须大于 :value 字符',
'array' => ' :attribute 必须大于 :value',
],
'gte' => [
'numeric' => ' :attribute 必须大于或等于 :value',
'file' => ' :attribute 必须大于或等于 :value 字节',
'string' => ' :attribute 必须大于或等于 :value 字符',
'array' => ' :attribute 必须有 :value 或者更多',
],
'image' => ' :attribute 必须是个图片',
'in' => ' 选项 :attribute 是无效的',
'in_array' => ' :attribute 不属于 :other',
'integer' => ' :attribute 必须是数字',
'ip' => ' :attribute 必须是一个有效的ip地址',
'ipv4' => ' :attribute 必须是有效的IPv4地址',
'ipv6' => ' :attribute 必须是一个有效的IPv6地址',
'json' => ' :attribute 必须是一个有效的JSON字符串',
'lt' => [
'numeric' => ' :attribute 必须小于 :value',
'file' => ' :attribute 必须小于 :value 字节',
'string' => ' :attribute 必须小于 :value 字符',
'array' => ' :attribute 必须小于 :value ',
],
'lte' => [
'numeric' => ' :attribute 必须小于或等于 :value',
'file' => ' :attribute 必须小于或等于 :value 字节.',
'string' => ' :attribute 必须小于或等于 :value 字符.',
'array' => ' :attribute 一定不能有超过 :value',
],
'max' => [
'numeric' => ' :attribute 不能大于 :max.',
'file' => ' :attribute 不能大于 :max 字节',
'string' => ' :attribute 不能大于 :max 字符.',
'array' => ' :attribute 不能有 :max ',
],
'mimes' => ' :attribute 必须是文件,类型: :values',
'mimetypes' => ' :attribute 必须是文件,类型: :values.',
'min' => [
'numeric' => ' :attribute 最小为 :min.',
'file' => ' :attribute 最小字节数为 :min ',
'string' => ' :attribute 最小长度为 :min ',
'array' => ' :attribute 最小长度 :min ',
],
'not_in' => ' 选项 :attribute 无效',
'not_regex' => ' :attribute 格式无效',
'numeric' => ' :attribute 必须是数字',
'present' => ' :attribute 不存在',
'regex' => ' :attribute 格式无效',
'required' => ' :attribute 必须填写',
'required_if' => ' :attribute 为 :other 时 :value 必须填写',
'required_unless' => ' :attribute 必须填写除非 :other 为 :values.',
'required_with' => '当 :values 存在时 :attribute 必须填写',
'required_with_all' => '当:values 存在时 :attribute 必须填写',
'required_without' => ' 当 :values 不存在时 :attribute',
'required_without_all' => '当 :values 不存在时 :attribute必须填写',
'same' => ' :attribute 和 :other 必须匹配',
'size' => [
'numeric' => ' :attribute 长度必须为 :size.',
'file' => ' :attribute 必须为 :size 个字节.',
'string' => ' :attribute 必须为 :size 个字符.',
'array' => ' :attribute 必须为 :size.',
],
'starts_with' => ' :attribute 必须是下列值: :values',
'string' => ' :attribute 必须是字符串',
'timezone' => ' :attribute 必须是有效区域',
'unique' => ' :attribute 已经存在',
'uploaded' => ' :attribute 上传失败',
'url' => ' :attribute 无效的url',
'uuid' => ' :attribute UUID无效',
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap our attribute placeholder
| with something more reader friendly such as "E-Mail Address" instead
| of "email". This simply helps us make our message more expressive.
|
*/
'attributes' => [
"account" => "账号",
"password" => "密码",
"captcha" => "验证码",
"category_id" => "分类",
"column_id" => "栏目",
"intro" => "简介",
"key_words" => "关键字",
"title" => "标题",
"author" => "作者",
"source" => "来源",
"editor" => "内容",
"state" => "状态",
],
];
<file_sep>/app/Http/Controllers/Admin/RoleController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Events\AdminBackgroundLog;
use App\Http\Requests\RoleRequest;
use App\Model\Power;
use App\Model\Role;
use Illuminate\Http\Request;
class RoleController extends BaseController
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$roleRes = Role::paginate(20);
return view("admin.admin_role_list",["roleRes" => $roleRes]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(Power $power)
{
$list = $power->powerTree();
return view("admin.admin_role_add", ['list'=> $list]);
}
/**
* @param Request $request
* @param Role $role
*/
public function store(RoleRequest $request, Role $role)
{
$data = [
"code" => CODE_SUCCESS,
"msg" => ["添加身份成功"],
];
$role['name'] = $request->input("name");
$role['describe'] = $request->input("describe","");
$power_ids = $request->input("power_ids","");
$role['power_ids'] = implode(",", $power_ids);
$bool = $role->save();
if(!$bool){
$data = [
"code" => CODE_FAIL,
"msg" => ["添加身份失败"],
];
}
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "添加身份")));
return response()->json($data);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* @param Role $role
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function edit( Role $role,Power $power)
{
$list = $power->powerTree();
$powerIds = explode(",",$role->power_ids);
return view("admin.admin_role_update", ['list'=> $list, 'role'=>$role ,'powerIds'=>$powerIds]);
}
/**
* @param RoleRequest $request
* @param Role $role
* @return \Illuminate\Http\JsonResponse
*/
public function update(RoleRequest $request, Role $role)
{
$data = [
"code" => CODE_SUCCESS,
"msg" => ["修改身份成功"],
];
$role['name'] = $request->input("name");
$role['describe'] = $request->input("describe","");
$power_ids = $request->input("power_ids","");
$role['power_ids'] = implode(",", $power_ids);
$bool = $role->save();
if(!$bool){
$data = [
"code" => CODE_FAIL,
"msg" => ["修改身份失败"],
];
}
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "修改身份")));
return response()->json($data);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Request $request)
{
$request->validate([
"id" => "required",
]);
$data = [
"code" => CODE_SUCCESS,
"msg" => ["删除成功"],
];
$ids = $request->input("id");
$bool = Role::destroy($ids);
if(!$bool){
$data = [
"code" => CODE_FAIL,
"msg" => ["删除失败"],
];
}
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "删除身份")));
return response()->json($data);
}
}
<file_sep>/app/Http/Middleware/CheckAdminPower.php
<?php
namespace App\Http\Middleware;
use App\Exceptions\Handler;
use Closure;
class CheckAdminPower
{
private $ignore = [
"article.show",
"template.show"
];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$routeName = $request->route()->getName();
if(!$routeName){
return $next($request);
}
if(in_array($routeName,$this->ignore)){
return $next($request);
}
$powers = session()->get("role_powers");
if(in_array($routeName,$powers)){
return $next($request);
}
return abort(401,"未授权禁止访问");
}
}
<file_sep>/database/migrations/2019_08_27_025620_create_articles_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArticlesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string("title",150); //标题
$table->string("intro")->nullable(); //简介
$table->string('author',100); //作者
$table->boolean("comment_state")->default(1);//允许评论1|允许,2|不允许
$table->string("icon",150)->nullable(); //封面
$table->unsignedBigInteger("template_id")->default(0); //模板id,默认为0,0为默认模板
$table->unsignedBigInteger("column_id"); //栏目id
$table->unsignedBigInteger("category_id"); //分类id
$table->string("source",100); //来源
$table->text('content'); //内容
$table->unsignedBigInteger("operator_id"); //操作者id
$table->unsignedBigInteger("verifier_id")->default(0); //审核者id
$table->unsignedInteger("impression")->default('0'); //点击量
$table->unsignedInteger("sort")->default(0); //排序默认为零
$table->string('key_words', 150);//关键字集合
$table->boolean("state")->default(1); //状态1草稿|2待审核|3已发布|4下架|5未通过
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('articles');
}
}
<file_sep>/app/Model/Seo.php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Seo extends Model
{
public function column()
{
return $this->belongsTo(Column::class);
}
}
<file_sep>/app/Http/Controllers/Admin/CategoryController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Model\Category;
use App\Events\AdminBackgroundLog;
use App\Http\Requests\CategoryRequest;
use Illuminate\Http\Request;
use Illuminate\Routing\Route;
class CategoryController extends BaseController
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$keyword = $request->input("keyword","");
if($keyword){
$categories = Category::where("id",$keyword)->orWhere("name","like","%".$keyword."%")->get();
}else{
$categories = Category::all();
}
return view("admin.article_category_list",["keyword"=>$keyword,"categories" => $categories]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view("admin.article_category_add");
}
/**
* @param Request $request
* @param Category $category
* @return \Illuminate\Http\JsonResponse
*/
public function store(CategoryRequest $request,Category $category)
{
$category['name'] = $request->input("name");
$category['state'] = ARTICLE_CATEGORY_START;
$category->save();
$data = [
"code" => CODE_SUCCESS,
"msg" => ["添加成功"],
];
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "添加资讯分类")));
return response()->json($data);
}
/**
* Display the specified resource.
*
* @param \App\Model\Category $category
* @return \Illuminate\Http\Response
*/
public function show(Category $category)
{
//
}
/**
* @param $id
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function edit($id)
{
$category = Category::find($id);
return view("admin.article_category_update",['category'=> $category]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Model\Category $category
* @return \Illuminate\Http\Response
*/
public function update(CategoryRequest $request, Category $category)
{
$category['name'] = $request->input("name");
$category->save();
$data = [
"code" => CODE_SUCCESS,
"msg" => ["修改成功"],
];
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "修改资讯分类")));
return response()->json($data);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Model\Category $category
* @return \Illuminate\Http\Response
*/
public function destroy(Request $request)
{
$request->validate([
"id" => "required",
]);
$data = [
"code" => CODE_SUCCESS,
"msg" => ["删除资讯成功"],
];
$ids = $request->input("id");
$bool = Category::destroy($ids);
if(!$bool){
$data = [
"code" => CODE_FAIL,
"msg" => ["删除资讯失败"],
];
}
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "删除资讯分类")));
return response()->json($data);
}
public function editState(Request $request){
$request->validate([
"id" => "required|integer",
"state" => "required|integer",
]);
$data = [
"code" => CODE_SUCCESS,
"msg" => ["修改状态成功"],
];
$id = $request->input("id");
$state = $request->input("state");
if(!is_array($id)){
$id = [$id];
}
Category::whereIn("id",$id)->update(['state' => $state]);
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "修改资讯分类状态")));
return response()->json($data);
}
}
<file_sep>/app/Http/Controllers/Admin/AdminController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Model\Admin;
use App\Events\AdminBackgroundLog;
use App\Http\Requests\AdminRequest;
use App\Model\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class AdminController extends BaseController
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$keyWord = $request->input("key_word","");
if($keyWord){
$adminRes = Admin::where("real_name","like","%{$keyWord}%")->paginate(20);
}else{
$adminRes = Admin::paginate(20);
}
return view("admin.admin_list",['adminRes'=>$adminRes]);
}
/**
* Show the form for creating a new resource.
* @param Role $role
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function create(Role $role)
{
$roleRes = $role->all();
return view("admin.admin_add",["roleRse"=>$roleRes]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(AdminRequest $request,Admin $admin)
{
$data = [
"code" => CODE_SUCCESS,
"msg" => ["添加管理员成功"],
];
$admin->real_name = $request->input("real_name");
$admin->password = <PASSWORD>($request->input("password"));
$admin->account = $request->input("account");
$admin->role = $request->input("role");
$admin->tel = $request->input("tel");
$admin->state = Admin::ADMIN_STATE_ON;
$row = $admin->save();
if(!$row){
$data = [
"code" => CODE_FAIL,
"msg" => ["添加管理员失败"],
];
}
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "添加管理员")));
return response()->json($data);
}
/**
* Display the specified resource.
*
* @param \App\Model\Admin $admin
* @return \Illuminate\Http\Response
*/
public function show(Admin $admin)
{
dd($admin);
}
/**
* @param Role $role
* @param Admin $admin
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function edit(Role $role, $id)
{
$admin = Admin::find($id);
$roleRes = $role->all();
return view("admin.admin_update",["roleRse"=>$roleRes,'admin'=>$admin]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Model\Admin $admin
* @return \Illuminate\Http\Response
*/
public function update(AdminRequest $request, $id)
{
$data = [
"code" => CODE_SUCCESS,
"msg" => ["修改管理员成功"],
];
$admin = Admin::find($id);
$admin->id = $request->input("id");
$admin->real_name = $request->input("real_name");
$admin->account = $request->input("account");
$admin->role = $request->input("role");
$admin->tel = $request->input("tel");
$password = $request->input("password","");
if($password) $admin->password = Hash::make($password);
$row = $admin->save();
if(!$row){
$data = [
"code" => CODE_FAIL,
"msg" => ["修改管理员失败"],
];
}
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "修改管理员")));
return response()->json($data);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Model\Admin $admin
* @return \Illuminate\Http\Response
*/
public function destroy(Request $request)
{
$request->validate([
"id" => "required",
]);
$data = [
"code" => CODE_SUCCESS,
"msg" => ["删除管理员成功"],
];
$id = $request->input("id");
$bool = Admin::destroy($id);
if(!$bool){
$data = [
"code" => CODE_FAIL,
"msg" => ["删除管理员失败"],
];
}
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "删除管理员")));
return response()->json($data);
}
public function editState(Request $request){
$request->validate([
"id" => "required|integer",
"state" => "required|integer",
]);
$data = [
"code" => CODE_SUCCESS,
"msg" => ["修改状态成功"],
];
$id = $request->input("id");
$admin = Admin::find($id);
$admin->state = $request->input("state");
$bool = $admin->save();
if(!$bool){
$data = [
"code" => CODE_FAIL,
"msg" => ["修改状态失败"],
];
}
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "修改管理员状态")));
return response()->json($data);
}
}
<file_sep>/app/Packages/MyAssistPackage/AssistServiceProvider.php
<?php
namespace App\Packages\MyAssistPackage;
use Illuminate\Support\Facades\App;
use Illuminate\Support\ServiceProvider;
class AssistServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
App::singleton("assist",function(){
return new Assist();
});
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
//
}
}
<file_sep>/database/seeds/AdminSeeder.php
<?php
use Illuminate\Database\Seeder;
class AdminSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('admins')->insert([
[
"account" => "admin",
"password" => \<PASSWORD>("<PASSWORD>"),
"real_name"=>"admin",
"role" => 1,
"tel" => "13888888888",
"state" => 1,
],
]);
}
}
<file_sep>/app/Model/Column.php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
class Column extends Model
{
protected $guarded = [];
public function article(){
return $this->hasMany(Article::class);
}
public function template(){
return $this->hasMany(ColTemplate::class);
}
public function seo(){
return $this->hasOne(Seo::class);
}
/**
* 获取栏目树
* @param int $pid
* @param int $state
* @return mixed
*/
public function getColumnTree($pid = 0, $state = 0){
$term[] = ["pid",$pid];
if($state){
$term[] = ["state",$state];
}
$columns = self::where($term)->get();
if($columns){
foreach($columns as &$column) {
$subset = $this->getColumnTree($column->id , $state);
if(collect($subset)->isNotEmpty()){
$column['subset'] = $subset;
}
}
}
return $columns;
}
/**
* 获取栏目子类id
* @param int $pid
* @return array
*/
public function getColumnSubsetId($pid = 0){
$term[] = ["pid",$pid];
$columnIds = self::where($term)->pluck("id");
if($columnIds){
$tempArr = $columnIds;
foreach($tempArr as &$id) {
$subset = $this->getColumnSubsetId($id);
if(collect($subset)->isNotEmpty()){
$columnIds = Arr::collapse([$columnIds ,$subset]);
}
}
}
return $columnIds;
}
/**
* @param $id
* @param int $carry
* @return string
*/
public function getColumnParentId($id){
$info = self::find($id);
if($info->pid){
$tmpe = $this->getColumnParentId($info->pid);
$id = $id.",".$tmpe;
}
return $id;
}
public function getColumnTreeByDate($search)
{
$columns = self::where("name","like","%".$search."%")->orWhere("id",$search)->get();
return $columns;
}
}
<file_sep>/app/Packages/MyAssistPackage/Facade/Assist.php
<?php
/**
* Created by PhpStorm.
* User: Other
* Date: 2019/9/3
* Time: 9:57
*/
namespace App\Packages\MyAssistPackage\Facade;
use Illuminate\Support\Facades\Facade;
class Assist extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'assist';
}
}<file_sep>/app/Packages/ColumnPackage/Column.php
<?php
namespace App\Packages\ColumnPackage;
use Illuminate\Support\Facades\View;
use Illuminate\Support\HtmlString;
/**
* Created by PhpStorm.
* User: Other
* Date: 2019/9/2
* Time: 18:24
*/
class Column{
function __construct()
{
}
function columnSelectList($columns, $selectId=0, $filter_id = 0 ,$view="admin.column._select_default" ){
if(!$columns || collect($columns)->isEmpty()){
return false;
}
return new HtmlString(View::make($view, ["columns"=>$columns, "selectId"=>$selectId, "view"=>$view ,"filter_id" => $filter_id])->render());
}
function columnTableList($columns ,$view="admin.column._table_default"){
if(!$columns || collect($columns)->isEmpty()){
return false;
}
return new HtmlString(View::make($view, ["columns"=>$columns])->render());
}
}<file_sep>/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("/admin/login","Admin\LoginController@index");
Route::post("/admin/do_login","Admin\LoginController@doLogin");
Route::get("/admin/login_out","Admin\LoginController@loginOut");
Route::middleware(['check.admin.login','check.admin.power'])->prefix('admin')->group(function(){
Route::get("/","Admin\IndexController@index");
Route::resource("role","Admin\RoleController");
Route::post("article/upload","Admin\ArticleController@upload");
Route::post("article/edit_state","Admin\ArticleController@editState")->name('article.edit_state');
Route::resource("article","Admin\ArticleController");
Route::post('art_category/edit_state', "Admin\CategoryController@editState")->name('art_category.edit_state');
Route::resource("art_category","Admin\CategoryController");
Route::post("column/edit_state","Admin\ColumnController@editState")->name('column.edit_state');
Route::resource("column","Admin\ColumnController");
Route::get("template/{template}/get_by_type","Admin\TemplateController@getTemplateByType");
Route::post("template/upload","Admin\TemplateController@upload");
Route::post("template/edit_state","Admin\TemplateController@editState")->name('template.edit_state');
Route::resource("template","Admin\TemplateController");
Route::resource("power","Admin\PowerController");
Route::post("adn/edit_state","Admin\AdminController@editState")->name('adn.edit_state');
Route::resource("adn","Admin\AdminController");
Route::post("user/edit_state","Admin\UserController@editState")->name('user.edit_state');
Route::resource("user","Admin\UserController");
});
Route::post("admin/user/getCityAreas/{id}","Admin\UserController@getCityAreas")->name('user.getCityAreas');<file_sep>/app/Model/User.php
<?php
namespace App\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password','sex','phone','address','state','avatar_id'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
// /**
// * 审查人员审查的文章
// * @return \Illuminate\Database\Eloquent\Relations\HasMany
// */
// public function verifierArticle()
// {
// return $this->hasMany(Article::class,"verifier_id");
// }
public function getSexAttribute($sex){
return $sex == 1 ? '男' : '女';
}
public function getStateAttribute($state){
return $state == 1 ? '有效' : '停用';
}
public function getAvatarIdAttribute($avatarId){
if(!$avatarId){
return null;
}
return Resource::find($avatarId)->path;
}
}
<file_sep>/app/Listeners/AdminBackgroundLog/AdminActionLog.php
<?php
namespace App\Listeners\AdminBackgroundLog;
use App\Events\AdminBackgroundLog;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Model\AdminActionLog as ALog;
class AdminActionLog
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* @param AdminBackgroundLog $event
*/
public function handle(AdminBackgroundLog $event)
{
$aLog = new ALog();
$aLog->admin_id = session()->get('admin_id');
$aLog->route = $event->data['route'];
$aLog->param = $event->data['param'] ? json_encode($event->data['param']) : "";
$aLog->describe = $event->data['describe'] ? $event->data['describe'] : "";
$aLog->save();
}
}
<file_sep>/app/Http/Controllers/Admin/TemplateController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Events\AdminBackgroundLog;
use App\Http\Requests\TemplateRequest;
use App\Model\Template;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class TemplateController extends BaseController
{
/**
* @param Request $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function index(Request $request)
{
$keyword = $request->input("keyword","");
if($keyword){
$templates = Template::where("name","like","%".$keyword."%")->simplePaginate(10);
}else{
$templates = Template::simplePaginate(10);
}
return view("admin.template_list",["templates"=>$templates]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view("admin.template_add");
}
/**
* @param TemplateRequest $request
* @param Template $template
* @return string
*/
public function store(TemplateRequest $request,Template $template)
{
$template["type"] = $request->input("type");
$template["name"] = $request->input("name");
$template["keyword"] = $request->input("keyword");
$template["icon"] = $request->input("icon","");
$template["describe"] = $request->input("describe","");
$template["templ_uri"] = Storage::putFileAS('page', $request->file('template'),$request->file('template')->hashName().".blade.php","private");
$template->save();
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "添加模板")));
return "<script>top.location.href='".url("admin/template")."'</script>";
}
/**
* Display the specified resource.
*
* @param \App\Model\Template $template
* @return \Illuminate\Http\Response
*/
public function show(Template $template)
{
$uri = "template/".Str::before($template->templ_uri,".blade.php");
return view($uri);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Model\Template $template
* @return \Illuminate\Http\Response
*/
public function edit(Template $template)
{
return view("admin.template_update",["template"=>$template]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Model\Template $template
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Template $template)
{
$request->validate([
'name' => 'required',
'type' => 'integer',
],[
"name.required" => "模板名称必须填写"
]);
$template['type'] = $request->input("type");
$template['name'] = $request->input("name");
$template['icon'] = $request->input("icon");
$template['keyword'] = $request->input("keyword","");
$template['describe'] = $request->input("describe","");
$template->save();
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "修改模板")));
return "<script>top.location.href='".url("admin/template")."'</script>";
}
/**
* Remove the specified resource from storage.
*
* @param \App\Model\Template $template
* @return \Illuminate\Http\Response
*/
public function destroy(Request $request)
{
$request->validate([
"id" => "required",
]);
$data = [
"code" => CODE_SUCCESS,
"msg" => ["删除资讯成功"],
];
$ids = $request->input("id");
$bool = Template::destroy($ids);
if(!$bool){
$data = [
"code" => CODE_FAIL,
"msg" => ["删除资讯失败"],
];
}
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "删除模板")));
return response()->json($data);
}
/**
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function upload(Request $request){
$request->validate([
"file" => "image"
],[
"file.image" => "上传类型必须是(jpeg, png, bmp, gif)"
]);
$path = Storage::putFile('public/template_icon', $request->file('file'), "public");
$path = Storage::url($path);
return response()->json(["data"=>$path]);
}
/**
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function editState(Request $request){
$request->validate([
"id" => "required|integer",
"state" => "required|integer",
]);
$data = [
"code" => CODE_SUCCESS,
"msg" => ["修改状态成功"],
];
$id = $request->input("id");
$template = Template::find($id);
$template['state'] = $request->input("state");
$template->save();
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "修改模板状态")));
return response()->json($data);
}
public function getTemplateByType($typeId){
$templateRes = Template::where("type" , $typeId)->get();
return view("admin.template_by_type_list",["templateRes"=>$templateRes]);
}
}
<file_sep>/app/Http/Controllers/Admin/ArticleController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Model\Category;
use App\Model\Article;
use App\Model\Column;
use App\Events\AdminBackgroundLog;
use App\Http\Requests\ArticleRequest;
use App\Packages\ColumnPackage\Facade\Column as FColumn;
use App\Packages\MyAssistPackage\Facade\Assist;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\HtmlString;
class ArticleController extends BaseController
{
/**
* Display a listing of the resource.
* @param object $request 表单
* @param object $article 查询对象
* @return \Illuminate\Http\Response
*/
public function index(Request $request,Article $article)
{
$search['category'] = $request->input("category","");
$search['state'] = $request->input("state","");
$search['startAt'] = $request->input("start_at","");
$search['endAt'] = $request->input("end_at","");
$search['title'] = $request->input("title","");
if(Assist::checkRoutePower("article.me","",true)){
$search['me'] = true;
}
$articles = $article->getArticleByTerm($search);
$categorys = Category::where("state",1)->get();
return view("admin/article_list", ['articles'=>$articles,'categorys'=>$categorys,'search'=>$search]);
}
/**
* @param Column $column
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function create(Column $column)
{
$categorys = Category::where("state",1)->get();
$columns = $column->getColumnTree(0,COLUMN_STATE_START);
$colList = FColumn::columnSelectList($columns);
return view("admin/article_add",['categorys'=>$categorys, "colList" => $colList]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(ArticleRequest $request,Article $article)
{
$data = [
"code" => CODE_SUCCESS,
"msg" => ["创建资讯成功"],
];
$article["title"] = $request->input("title");
$article["intro"] = $request->input("intro");
$article["author"] = $request->input("author");
$article["comment_state"] = $request->input("comment_state",0);
$article["icon"] = $request->input("icon","");
$article["template_id"] = $request->input("template_id",0);
$article["column_id"] = $request->input("column_id");
$article["category_id"] = $request->input("category_id");
$article["source"] = $request->input("source");
$article["content"] = $request->input("editor");
$article["sort"] = $request->input("sort",0);
$article["key_words"] = $request->input("key_words");
$article["state"] = $request->input("state",1);
$article["operator_id"] = $request->session()->get("admin_id");
$row = $article->save();
if(!$row){
$data = [
"code" => CODE_FAIL,
"msg" => ["创建资讯失败"],
];
}
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "添加资讯")));
return response()->json($data);
}
/**
* Display the specified resource.
*
* @param \App\Model\Article $article
* @return \Illuminate\Http\Response
*/
public function show(Article $article)
{
$template = ARTICLE_DEFAULT_SHOW_VIEW;
//获取模板
if(collect($article->template)->isNotEmpty() && $article->template->state == TEMPLATE_START){
$template = $article->template->templ_uri;
}
return view($template ,["articleInfo" => $article]);
}
/**
* @param Article $article
* @param Column $column
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function edit(Article $article,Column $column)
{
$categorys = Category::where("state",1)->get();
$columns = $column->getColumnTree(0,COLUMN_STATE_START);
$article->content = new HtmlString($article->content);
$colList = FColumn::columnSelectList($columns, $article->column_id);
return view("admin/article_update",['article'=>$article ,'categorys'=>$categorys, "colList" => $colList]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Model\Article $article
* @return \Illuminate\Http\Response
*/
public function update(ArticleRequest $request, Article $article)
{
$data = [
"code" => CODE_SUCCESS,
"msg" => ["修改资讯成功"],
];
$article["title"] = $request->input("title");
$article["intro"] = $request->input("intro");
$article["author"] = $request->input("author");
$article["comment_state"] = $request->input("comment_state",0);
$article["icon"] = $request->input("icon","");
$article["template_id"] = $request->input("template_id",0);
$article["column_id"] = $request->input("column_id");
$article["category_id"] = $request->input("category_id");
$article["source"] = $request->input("source");
$article["content"] = $request->input("editor");
$article["sort"] = $request->input("sort",0);
$article["key_words"] = $request->input("key_words");
$article["state"] = $request->input("state",1);
$article["operator_id"] = $request->session()->get("admin_id");
$row = $article->save();
if(!$row){
$data = [
"code" => CODE_FAIL,
"msg" => ["修改资讯失败"],
];
}
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "修改资讯")));
return response()->json($data);
}
/**
* @param Request $request
* @param Article $article
*/
public function destroy(Request $request)
{
$request->validate([
"id" => "required",
]);
$data = [
"code" => CODE_SUCCESS,
"msg" => ["删除资讯成功"],
];
$id = $request->input("id");
$bool = Article::destroy($id);
if(!$bool){
$data = [
"code" => CODE_FAIL,
"msg" => ["删除资讯失败"],
];
}
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "删除资讯")));
return response()->json($data);
}
/**
* 上传
* @param Request $request
* @return false|string
*/
public function upload(Request $request)
{
$request->validate([
"file" => "image"
],[
"file.image" => "上传类型必须是(jpeg, png, bmp, gif)"
]);
$path = Storage::putFile('public/article_icon', $request->file('file'), "public");
$path = Storage::url($path);
return response()->json(["data"=>$path]);
}
public function editState(Request $request){
$request->validate([
"id" => "required|integer",
"state" => "required|integer",
]);
$data = [
"code" => CODE_SUCCESS,
"msg" => ["修改状态成功"],
];
$id = $request->input("id");
$article = Article::find($id);
$article['state'] = $request->input("state");
$article['verifier_id'] = $request->session()->get("admin_id");
$bool = $article->save();
if(!$bool){
$data = [
"code" => CODE_FAIL,
"msg" => ["修改状态失败"],
];
}
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "修改资讯状态")));
return response()->json($data);
}
}
<file_sep>/app/Model/Power.php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Power extends Model
{
/**
* 获取权限树
* @return mixed
*/
public function powerTree(){
$powerT = $this->getPowerByAcmeChangeArr(1);
foreach ($powerT as $ak => &$acme){
$acme["index"] = $this->powerTreeStepOne($acme);
}
return $powerT;
}
/**
* 根据层级获取权限数组
* @param int $acme
* @return mixed
*/
public function getPowerByAcmeChangeArr($acme = 0){
$powerRes = Power::where("acme",$acme)->get()->toArray();
return $powerRes;
}
/**
* 获取权限树的第一层
* @param $acme
* @return array
*/
private function powerTreeStepOne($acme){
$res = $this->powerTreeStepTow($acme);
foreach($res as $key=>&$val){
$val['res'] = $this->powerTreeStepTow($val,"index");
}
return $res;
}
/**
* 获取权限树的第二层
* @param $power
* @param string $layout
* @return array
*/
private function powerTreeStepTow($power,$layout = "base"){
$powerRes = $this->getPowerByAcmeChangeArr();
$list = [];
foreach ($powerRes as $val){
if($layout == "base" && $val['belong_to'] == $power['id'] && Str::contains($val['field'], 'index')){
$list[] = $val;
}
if($layout == "index" && Str::before($power['field'],".") == Str::before($val['field'],".") && !Str::contains($val['field'], 'index')){
$list[] = $val;
}
}
return $list;
}
}
<file_sep>/app/Http/Requests/TemplateRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class TemplateRequest extends CommonRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
"type" => "integer",
"name" => "required"
];
}
public function messages()
{
return [
"name.required" => "模板名称必须填写"
];
}
public function withValidator($validator)
{
$validator->after(function ($validator) {
if(empty($this->file('template'))){
$validator->errors()->add('template', '请上传模板文件');
}
});
}
}
<file_sep>/app/Packages/MyAssistPackage/Assist.php
<?php
namespace App\Packages\MyAssistPackage;
use Illuminate\Support\Facades\Route;
/**
* Created by PhpStorm.
* User: Other
* Date: 2019/9/2
* Time: 18:24
*/
class Assist{
function __construct()
{
}
/**
* 通过uri获取路由名称
* @param string $uri
* @param string $method
* @param bool $acme
* @return bool
*/
function checkRoutePower($uri="admin/article/edit_state", $method = "get", $acme = false){
$routeName = $uri;
$powers = session()->get("role_powers");
if(!$acme){
$routeName = Route::getRoutes()->match(request()->create(url($uri),$method))->getName();
}
if($routeName && in_array($routeName , $powers)){
return true;
}
return false;
}
}<file_sep>/app/Model/Article.php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
protected $guarded = "";
/**
* 文章分类属性
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function category()
{
return $this->belongsTo(Category::class);
}
/**
* 文章的操作者
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function operator()
{
return $this->belongsTo(Admin::class,"operator_id");
}
/**
* 文章的审查者
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function verifier()
{
return $this->belongsTo(Admin::class,"verifier_id");
}
/**
* 获取模板
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function template()
{
return $this->belongsTo(Template::class);
}
/**
* 分页获取资讯
* @param array $data
* @param int $limit
* @return mixed
*/
public function getArticleByTerm($data = [], $limit =10)
{
$sql = $this->makeSql($data);
return self::where($sql)->paginate($limit);
}
/**
* 做查询条件
* @param array $data
* @return array
*/
private function makeSql($data = [])
{
$isWhere = [];
if(!empty($data['category'])){
$category = intval($data['category']);
$isWhere[] = ["category_id" , $category];
}
if(!empty($data['state'])){
$state = intval($data['state']);
$isWhere[] = ["state" , $state];
}
if(!empty($data['startAt'])){
$strtAt = trim($data['startAt']);
$isWhere[] = ["created_at", ">=",$strtAt];
}
if(!empty($data['endAt'])){
$endAt = trim($data['endAt']);
$isWhere[] = ["created_at", "<=",$endAt];
}
if(!empty($data['title'])){
$title = trim($data['title']);
$isWhere[] = ["title", $title];
}
if(!empty($data['me'])){
$isWhere[] = ["operator_id", session()->get("admin_id")];
}
return $isWhere;
}
}
<file_sep>/database/seeds/ColumnSeeder.php
<?php
use Illuminate\Database\Seeder;
class ColumnSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('columns')->insert([
["name" => "新闻资讯","cotegory_id" => 1,"pid"=>0,"level"=>1,"selectable"=>0,"state"=>1],
["name" => "行业动态","cotegory_id" => 1,"pid" =>1,"level"=>2,"selectable"=>1,"state"=>1],
["name" => "行业资讯","cotegory_id" => 1,"pid" =>1,"level"=>2,"selectable"=>1,"state"=>1],
["name" => "娱乐八卦","cotegory_id" => 1,"pid" =>0,"level"=>1,"selectable"=>1,"state"=>1],
["name" => "财经新闻","cotegory_id" => 1,"pid" =>1,"level"=>2,"selectable"=>0,"state"=>1],
["name" => "国外财经","cotegory_id" => 1,"pid" =>5,"level"=>3,"selectable"=>1,"state"=>2],
["name" => "国内财经","cotegory_id" => 1,"pid" =>5,"level"=>3,"selectable"=>1,"state"=>1],
]);
}
}
<file_sep>/database/migrations/2020_01_06_011924_add_fields_to_users_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddFieldsToUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedBigInteger('avatar_id')->comment('头像附件id')->after('password')->nullable();
$table->boolean("sex")->comment('性别')->after('password')->nullable();
$table->string('phone', 11)->comment("电话")->after('sex')->nullable();
$table->string('address')->comment('地址')->after('phone')->nullable();
$table->boolean('state')->comment('状态')->after('address')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['sex', 'phone', 'address','state','avatar_id']);
});
}
}
<file_sep>/app/Http/Requests/PowerRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Validation\Rule;
class PowerRequest extends CommonRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
"name" => "required",
"field" => "required",
"belong_to" => "required_without:acme",
];
}
public function messages()
{
return [
"name.required" => "请输入权限名称",
"field.required" => "字段不可为空",
"belong_to.required_without" => "如果是顶级分类请勾选否则所属不可为空",
];
}
}
<file_sep>/app/Http/Controllers/Admin/PowerController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Events\AdminBackgroundLog;
use App\Http\Requests\PowerRequest;
use App\Model\Power;
use Illuminate\Http\Request;
class PowerController extends BaseController
{
/**
* @param Request $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function index(Request $request)
{
$keyword = $request->input("keyword","");
if($keyword){
$powerRes = Power::where("name","like","%".$keyword."%")->paginate(20);
}else{
$powerRes = Power::paginate(20);
}
return view("admin.admin_permission",["powerRes"=>$powerRes,"keyword"=>$keyword]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$acmeRes = Power::where("acme",1)->get();
return view("admin.admin_permission_add",['acmeRes'=>$acmeRes]);
}
/**
* @param PowerRequest $request
* @param Power $power
* @return \Illuminate\Http\JsonResponse
*/
public function store (PowerRequest $request, Power $power)
{
$data = [
"code" => CODE_SUCCESS,
"msg" => ["添加节点成功"],
];
$power['name'] = $request->input("name");
$power['belong_to'] = $request->input("belong_to",0);
$power['field'] = $request->input("field","");
$power['acme'] = $request->input("acme",0);
$bool = $power->save();
if(!$bool){
$data = [
"code" => CODE_FAIL,
"msg" => ["添加节点失败"],
];
}
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "增加权限节点")));
return response()->json($data);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* @param Power $power
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function edit(Power $power)
{
$acmeRes = Power::where("acme",1)->get();
return view("admin.admin_permission_update",['power'=>$power,"acmeRes"=>$acmeRes]);
}
/**
* @param PowerRequest $request
* @param Power $power
*/
public function update(PowerRequest $request, Power $power)
{
$data = [
"code" => CODE_SUCCESS,
"msg" => ["修改节点成功"],
];
$power['name'] = $request->input("name");
$power['belong_to'] = $request->input("belong_to",0);
$power['field'] = $request->input("field","");
$power['acme'] = $request->input("acme",0);
$bool = $power->save();
if(!$bool){
$data = [
"code" => CODE_FAIL,
"msg" => ["修改节点失败"],
];
}
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "修改权限节点")));
return response()->json($data);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Request $request)
{
$request->validate([
"id" => "required",
]);
$data = [
"code" => CODE_SUCCESS,
"msg" => ["删除成功"],
];
$ids = $request->input("id");
$bool = Power::destroy($ids);
if(!$bool){
$data = [
"code" => CODE_FAIL,
"msg" => ["删除失败"],
];
}
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "删除权限节点")));
return response()->json($data);
}
}
<file_sep>/bootstrap/constants.php
<?php
/**
* Created by PhpStorm.
* User: Other
* Date: 2019/8/29
* Time: 10:03
*/
//code定义
define("CODE_SUCCESS",100); //请求成功
define("CODE_FAIL",99); //请求成功
//栏目开启关闭
define("COLUMN_STATE_START",1);
define("COLUMN_STATE_STOP",2);
define("CATEGORY_ARTICLE_ID",1);
define("CATEGORY_IMG_ID",2);
define("CATEGORY_GOODS_ID",3);
define("CATEGORY_VIDEO_ID",4);
define("CATEGORY_SPECIAL_ID",5);
define("CATEGORY_LINK_ID",6);
define(
"CATEGORY_IDS" ,
[
CATEGORY_ARTICLE_ID,
CATEGORY_IMG_ID,
CATEGORY_GOODS_ID,
CATEGORY_VIDEO_ID,
CATEGORY_SPECIAL_ID,
CATEGORY_LINK_ID
]
);
//栏目类型
define("COLUMN_CATEGORY",[
['id'=>CATEGORY_ARTICLE_ID ,'name'=>'文章'],
['id'=>CATEGORY_IMG_ID ,'name'=>'图片'],
['id'=>CATEGORY_GOODS_ID ,'name'=>'商品'],
['id'=>CATEGORY_VIDEO_ID ,'name'=>'视频'],
['id'=>CATEGORY_SPECIAL_ID ,'name'=>'专题'],
['id'=>CATEGORY_LINK_ID ,'name'=>'链接']
]);
//栏目模板类型
//首页
define("COL_TEMPLATES_INDEX" , 1);
//列表页
define("COL_TEMPLATES_LIST" , 2);
//详情页
define("COL_TEMPLATES_SHOW" , 3);
//
//栏目开启关闭
define("TEMPLATE_START",1);
define("TEMPLATE_STOP",2);<file_sep>/app/Http/Requests/AdminRequest.php
<?php
namespace App\Http\Requests;
class AdminRequest extends CommonRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$data = [];
if($this->route()->uri() == "admin/adn"){
$data = [
"account" => "required|min:8|max:20|unique:admins,account",
"password" => "<PASSWORD>",
"password_confirmation" => "<PASSWORD>:<PASSWORD>",
"real_name" => "required",
"role" => "required|integer",
"tel" => "required|regex:/^1[3456789][0-9]{9}$/",
];
}
if($this->route()->uri() == "admin/adn/{adn}/edit"){
$data = [
"id" => "required",
"account" => "required|min:8|max:20|unique:admins,account",
"password" => "<PASSWORD>",
"password_confirmation" => "<PASSWORD>",
"real_name" => "required",
"role" => "required|integer",
"tel" => "required|regex:/^1[3456789][0-9]{9}$/",
];
}
return $data;
}
public function messages()
{
return [
"account.required" => "账号不可为空",
"account.min" => "账号最少可输入8个字节",
"account.max" => "账号最多可输入20个字节",
"account.unique" => "账号已被申请",
"password.required" => "密码不可以为空",
"password.min" => "密码最少可输入8个字节",
"password.max" => "密码最多可输入20个字节",
"password_confirmation.required" => "确认密码不可为空",
"password_confirmation.same" => "与密码不符,请检查",
"real_name.required" => "真实姓名不可为空",
"role.required" => "身份不可为空",
"tel.required" => "电话不可为空",
"tel.regex" => "电话号码不合法"
];
}
}
<file_sep>/database/seeds/RoleSeeder.php
<?php
use Illuminate\Database\Seeder;
class RoleSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('roles')->insert([
[
"name" => "admin",
"describe"=>"admin",
"power_ids"=>"1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23",
],
]);
}
}
<file_sep>/app/Model/Admin.php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Admin extends Model
{
const ADMIN_STATE_ON = 1;
const ADMIN_STATE_OFF = 0;
protected $guarded = [];
public function adminRole()
{
return $this->belongsTo(Role::class,"role");
}
/**
* 操作人员的文章
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function operatorArticle()
{
return $this->hasMany(Article::class,"operator_id");
}
}
<file_sep>/app/Http/Requests/ArticleRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Validation\Rule;
class ArticleRequest extends CommonRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
"title" => "required|min:5|max:50",
"column_id" => [
"required",
Rule::exists("columns","id")->where('state',1)
],
"category_id" => [
"required",
Rule::exists("categories","id")->where('state',1)
],
"key_words" => "required|max:100",
"intro" => "required|max:200",
"author" => "required",
"source" => "required",
"editor" => "required",
"state" => [
"required",
Rule::in([1,2]),
],
];
}
public function messages()
{
return [
"column_id.exists" => "所选的栏目不存在",
"category_id.exists" => "所选分类不存在",
"state.in" => "请不要随意修改状态值",
"state.required" => "请不要随意修改状态值",
];
}
}
<file_sep>/app/Http/Controllers/Admin/LoginController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Events\AdminBackgroundLog;
use App\Http\Controllers\Controller;
use App\Http\Requests\LoginCheckRequest;
class LoginController extends Controller
{
//
public function index()
{
return view("/admin.login");
}
public function doLogin(LoginCheckRequest $request)
{
event(new AdminBackgroundLog(array("route" => $request->route()->uri,"param"=> "", "describe" => "登录成功")));
return redirect("/admin");
}
public function loginOut(){
session()->flush();
return redirect("/admin");;
}
}
<file_sep>/app/Packages/ColumnPackage/Facade/Column.php
<?php
/**
* Created by PhpStorm.
* User: Other
* Date: 2019/9/3
* Time: 9:57
*/
namespace App\Packages\ColumnPackage\Facade;
use Illuminate\Support\Facades\Facade;
class Column extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'column';
}
}<file_sep>/database/seeds/PowerSeeder.php
<?php
use Illuminate\Database\Seeder;
class PowerSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('powers')->insert([
//管理员管理
["name" => "管理员管理", "field"=>"adn", "belong_to"=>"0", "acme" => "1"],
["name" => "管理员列表", "field"=>"adn.index", "belong_to"=>"1", "acme" => "0"],
["name" => "管理员创建(执行)", "field"=>"adn.store", "belong_to"=>"1", "acme" => "0"],
["name" => "管理员创建", "field"=>"adn.create", "belong_to"=>"1", "acme" => "0"],
["name" => "管理员修改状态", "field"=>"adn.edit_state", "belong_to"=>"1", "acme" => "0"],
["name" => "管理员显示", "field"=>"adn.show", "belong_to"=>"1", "acme" => "0"],
["name" => "管理员修改(执行)", "field"=>"adn.update", "belong_to"=>"1", "acme" => "0"],
["name" => "管理员删除", "field"=>"adn.destroy", "belong_to"=>"1", "acme" => "0"],
["name" => "管理员修改", "field"=>"adn.edit", "belong_to"=>"1", "acme" => "0"],
//角色管理
["name" => "角色列表", "field"=>"role.index", "belong_to"=>"1", "acme" => "0"],
["name" => "角色创建(执行)", "field"=>"role.store", "belong_to"=>"1", "acme" => "0"],
["name" => "角色创建", "field"=>"role.create", "belong_to"=>"1", "acme" => "0"],
["name" => "角色显示", "field"=>"role.show", "belong_to"=>"1", "acme" => "0"],
["name" => "角色修改(执行)", "field"=>"role.update", "belong_to"=>"1", "acme" => "0"],
["name" => "角色删除", "field"=>"role.destroy", "belong_to"=>"1", "acme" => "0"],
["name" => "角色修改", "field"=>"role.edit", "belong_to"=>"1", "acme" => "0"],
//权限管理
["name" => "权限列表", "field"=>"power.index", "belong_to"=>"1", "acme" => "0"],
["name" => "权限创建(执行)", "field"=>"power.store", "belong_to"=>"1", "acme" => "0"],
["name" => "权限创建", "field"=>"power.create", "belong_to"=>"1", "acme" => "0"],
["name" => "权限显示", "field"=>"power.show", "belong_to"=>"1", "acme" => "0"],
["name" => "权限修改(执行)", "field"=>"power.update", "belong_to"=>"1", "acme" => "0"],
["name" => "权限删除", "field"=>"power.destroy", "belong_to"=>"1", "acme" => "0"],
["name" => "权限修改", "field"=>"power.edit", "belong_to"=>"1", "acme" => "0"],
//资讯管理
["name" => "资讯管理", "field"=>"article", "belong_to"=>"0", "acme" => "1"],
["name" => "资讯列表", "field"=>"article.index", "belong_to"=>"24", "acme" => "0"],
["name" => "资讯创建(执行)", "field"=>"article.store", "belong_to"=>"24", "acme" => "0"],
["name" => "资讯创建", "field"=>"article.create", "belong_to"=>"24", "acme" => "0"],
["name" => "资讯修改状态", "field"=>"article.edit_state", "belong_to"=>"24", "acme" => "0"],
["name" => "资讯显示", "field"=>"article.show", "belong_to"=>"24", "acme" => "0"],
["name" => "资讯修改(执行)", "field"=>"article.update", "belong_to"=>"24", "acme" => "0"],
["name" => "资讯删除", "field"=>"article.destroy", "belong_to"=>"24", "acme" => "0"],
["name" => "资讯修改", "field"=>"article.edit", "belong_to"=>"24", "acme" => "0"],
["name" => "分类列表", "field"=>"art_category.index", "belong_to"=>"24", "acme" => "0"],
["name" => "分类创建(执行)", "field"=>"art_category.store", "belong_to"=>"24", "acme" => "0"],
["name" => "分类创建", "field"=>"art_category.create", "belong_to"=>"24", "acme" => "0"],
["name" => "分类修改状态", "field"=>"art_category.edit_state", "belong_to"=>"24", "acme" => "0"],
["name" => "分类显示", "field"=>"art_category.show", "belong_to"=>"24", "acme" => "0"],
["name" => "分类修改(执行)", "field"=>"art_category.update", "belong_to"=>"24", "acme" => "0"],
["name" => "分类删除", "field"=>"art_category.destroy", "belong_to"=>"24", "acme" => "0"],
["name" => "分类修改", "field"=>"art_category.edit", "belong_to"=>"24", "acme" => "0"],
//模板管理
["name" => "模板管理", "field"=>"template", "belong_to"=>"0", "acme" => "1"],
["name" => "模板列表", "field"=>"template.index", "belong_to"=>"41", "acme" => "0"],
["name" => "模板创建(执行)", "field"=>"template.store", "belong_to"=>"41", "acme" => "0"],
["name" => "模板创建", "field"=>"template.create", "belong_to"=>"41", "acme" => "0"],
["name" => "模板修改状态", "field"=>"template.edit_state", "belong_to"=>"41", "acme" => "0"],
["name" => "模板显示", "field"=>"template.show", "belong_to"=>"41", "acme" => "0"],
["name" => "模板修改(执行)", "field"=>"template.update", "belong_to"=>"41", "acme" => "0"],
["name" => "模板删除", "field"=>"template.destroy", "belong_to"=>"41", "acme" => "0"],
["name" => "模板修改", "field"=>"template.edit", "belong_to"=>"41", "acme" => "0"],
//系统管理
["name" => "系统管理", "field"=>"system", "belong_to"=>"0", "acme" => "1"],
["name" => "栏目列表", "field"=>"column.index", "belong_to"=>"50", "acme" => "0"],
["name" => "栏目创建(执行)", "field"=>"column.store", "belong_to"=>"50", "acme" => "0"],
["name" => "栏目创建", "field"=>"column.create", "belong_to"=>"50", "acme" => "0"],
["name" => "栏目修改状态", "field"=>"column.edit_state", "belong_to"=>"50", "acme" => "0"],
["name" => "栏目显示", "field"=>"column.show", "belong_to"=>"50", "acme" => "0"],
["name" => "栏目修改(执行)", "field"=>"column.update", "belong_to"=>"50", "acme" => "0"],
["name" => "栏目删除", "field"=>"column.destroy", "belong_to"=>"50", "acme" => "0"],
["name" => "栏目修改", "field"=>"column.edit", "belong_to"=>"50", "acme" => "0"],
//会员管理
["name" => "会员管理", "field"=>"user", "belong_to"=>"0", "acme" => "1"],
["name" => "会员列表", "field"=>"user.index", "belong_to"=>"59", "acme" => "0"],
["name" => "会员创建(执行)", "field"=>"user.store", "belong_to"=>"59", "acme" => "0"],
["name" => "会员创建", "field"=>"user.create", "belong_to"=>"59", "acme" => "0"],
["name" => "会员修改状态", "field"=>"user.edit_state", "belong_to"=>"59", "acme" => "0"],
["name" => "会员显示", "field"=>"user.show", "belong_to"=>"59", "acme" => "0"],
["name" => "会员修改(执行)", "field"=>"user.update", "belong_to"=>"59", "acme" => "0"],
["name" => "会员删除", "field"=>"user.destroy", "belong_to"=>"59", "acme" => "0"],
["name" => "会员修改", "field"=>"user.edit", "belong_to"=>"59", "acme" => "0"],
]);
}
}
<file_sep>/app/Http/Controllers/Admin/ColumnController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Model\ColTemplate;
use App\Model\Column;
use App\Events\AdminBackgroundLog;
use App\Http\Requests\ColumnRequest;
use App\Packages\ColumnPackage\Facade\Column as FColumn;
use App\Model\Seo;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Storage;
class ColumnController extends BaseController
{
/**
* @param Request $request
* @param Column $column
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function index(Request $request, Column $column)
{
$keyword = $request->input("keyword","");
if($keyword){
$columnRes = $column -> getColumnTreeByDate($keyword);
$columnRes->keyword = $keyword;
}else{
$columnRes = $column -> getColumnTree();
}
$list = FColumn::columnTableList($columnRes);
return view("admin.system_column_list" ,["list"=>$list,"keyword"=>$keyword]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(Column $column)
{
$columnRes = $column -> getColumnTree();
$html = FColumn::columnSelectList($columnRes,0,0,"admin.column._select_choosable");
return view("admin.system_column_add",["html"=>$html]);
}
/**
* @param ColumnRequest $request
* @param Column $column
* @param ColTemplate $colTemplate
* @param Seo $seo
*/
public function store(ColumnRequest $request,Column $column, Seo $seo)
{
$column['pid'] = $request->input("pid", 0);
$column['level'] = $request->input("level", 0);
$column['name'] = $request->input("name");
$column['cotegory_id'] = $request->input("cotegory_id");
$column['selectable'] = $request->input("selectable", 0);
$bool = $column->save();
if($bool){
$seo['keyword'] = $request->input("keyword");
$seo['describe'] = $request->input("describe");
if($seo["keyword"] || $seo['describe']){
$seo['column_id'] = $column->id;
$seo->save();
}
$colTemplate['column_id'] = $column->id;
$colTemplate['limit'] = intval($request->input("limit"));
if(!empty($request->file('index_page'))){
$path = Storage::putFileAS('index', $request->file('index_page'),$request->file('index_page')->hashName().".blade.php","private");
$colTemplate['templ_uri'] = Storage::url($path);
$colTemplate['templ_type'] = COL_TEMPLATES_INDEX;
ColTemplate::create($colTemplate);
}
if(!empty($request->file('list_page'))){
$path = Storage::putFileAS('list', $request->file('list_page'),$request->file('list_page')->hashName().".blade.php","private");
$colTemplate['templ_uri'] = Storage::url($path);
$colTemplate['templ_type'] = COL_TEMPLATES_LIST;
ColTemplate::create($colTemplate);
}
if(!empty($request->file('show_page'))){
$path = Storage::putFileAS('show', $request->file('show_page'),$request->file('show_page')->hashName().".blade.php","private");
$colTemplate['templ_uri'] = Storage::url($path);
$colTemplate['templ_type'] = COL_TEMPLATES_SHOW;
ColTemplate::create($colTemplate);
}
}
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "添加栏目")));
return "<script>top.location.href='".url("admin/column")."'</script>";
}
/**
* Display the specified resource.
*
* @param \App\Model\Column $column
*/
public function show(Column $column)
{
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Model\Column $column
* @return \Illuminate\Http\Response
*/
public function edit(Column $column)
{
$columnRes = $column -> getColumnTree();
$html = FColumn::columnSelectList($columnRes,$column->pid,$column->id,"admin.column._select_choosable");
return view("admin.system_column_update",["html"=>$html,"column"=>$column]);
}
/**
* @param ColumnRequest $request
* @param Column $column
* @return string
*/
public function update(ColumnRequest $request, Column $column)
{
$column['pid'] = $request->input("pid");
$column['level'] = $request->input("level");
$column['name'] = $request->input("name");
$column['cotegory_id'] = $request->input("cotegory_id");
$column['selectable'] = $request->input("selectable", 0);
$column->save();
if(!$column->seo){
$column->seo = new Seo();
$column->seo['column_id'] = $column->id;
}
$column->seo['keyword'] = !$request->input("keyword") ? : $request->input("keyword");
$column->seo['describe'] = !$request->input("describe") ? : $request->input("describe");
$column->seo->save();
$limit = intval($request->input("limit"));
ColTemplate::where("column_id",$column->id)->update(["limit"=>$limit]);
if(!empty($request->file('index_page'))){
$path = Storage::putFileAS('index', $request->file('index_page'),$request->file('index_page')->hashName().".blade.php","private");
ColTemplate::where([
["column_id",$column->id],
["templ_type",COL_TEMPLATES_INDEX]
])->update(['templ_uri'=>Storage::url($path)]);
}
if(!empty($request->file('list_page'))){
$path = Storage::putFileAS('list', $request->file('list_page'),$request->file('list_page')->hashName().".blade.php","private");
ColTemplate::where([
["column_id",$column->id],
["templ_type",COL_TEMPLATES_LIST]
])->update(['templ_uri'=>Storage::url($path)]);
}
if(!empty($request->file('show_page'))){
$path = Storage::putFileAS('show', $request->file('show_page'),$request->file('show_page')->hashName().".blade.php","private");
ColTemplate::where([
["column_id",$column->id],
["templ_type",COL_TEMPLATES_LIST]
])->update(['templ_uri'=>Storage::url($path)]);
}
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "修改栏目")));
return "<script>top.location.href='".url("admin/column")."'</script>";
}
/**
* @param Request $request
* @param Column $column
* @return \Illuminate\Http\JsonResponse
*/
public function destroy(Request $request)
{
$request->validate([
"id" => "required",
]);
$data = [
"code" => CODE_SUCCESS,
"msg" => ["删除资讯成功"],
];
$cids = $request->input("id");
$column = new Column();
if(is_array($cids)){
$tempArr = $cids;
foreach($tempArr as $id) {
$cids = Arr::collapse([$column->getColumnSubsetId($id), $cids]);
}
}else{
$temp = $cids;
$cids = $column->getColumnSubsetId($cids);
$cids[] = $temp;
}
$bool = Column::destroy($cids);
if(!$bool){
$data = [
"code" => CODE_FAIL,
"msg" => ["删除资讯失败"],
];
}
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "删除栏目")));
return response()->json($data);
}
public function editState(Request $request){
$request->validate([
"id" => "required|integer",
"state" => "required|integer",
]);
$data = [
"code" => CODE_SUCCESS,
"msg" => ["修改状态成功"],
];
$id = $request->input("id");
$state = $request->input("state");
$column = new Column();
$cids = $column->getColumnSubsetId($id);
$cids[] = $id;
Column::whereIn("id",$cids)->update(['state' => $state]);
event(new AdminBackgroundLog(array("route" => $request->route()->uri, "param" => $request->toArray(), "describe" => "修改栏目状态")));
return response()->json($data);
}
}
<file_sep>/app/Http/Requests/ColumnRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class ColumnRequest extends CommonRequest
{
/**
* Get the validation rules that apply to the request.
* inta
* @return array
*/
public function rules()
{
return [
"pid" => "required|integer",
"level" => "integer",
"name" => "required|min:2|max:10",
"cotegory_id" => [
"required",
"integer",
Rule::in(CATEGORY_IDS)
],
"selectable" => "boolean",
];
}
public function messages()
{
return [
"pid.required" => "请选择父类标签,如没有父类请选择顶级标签",
"pid.integer" => "请选择有效父类",
"level.integer" => "请选择有效分类等级",
"name.required" => "请输入栏目名称",
"name.min" => "分类名称不能少于两个字",
"name.max" => "分类名称不能大于10个字",
"selectable.boolean" => "请进行有效操作",
"index_page.mimes" => "请选择有效首页",
"list_page.mimes" => "请选择有效列表页",
"show_page.mimes" => "请选择有效详情页",
];
}
}
<file_sep>/app/Http/Requests/LoginCheckRequest.php
<?php
namespace App\Http\Requests;
use App\Model\Admin;
use App\Model\Power;
use App\Model\Role;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Hash;
class LoginCheckRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
"account" => "required|max:20",
"password" => "<PASSWORD>",
"captcha" => "required|captcha"
];
}
public function messages()
{
return [
"captcha.captcha" => "验证码错误"
];
}
public function withValidator($validator)
{
$validator->after(function ($validator) {
$account = $this->input("account");
$password = $this->input("password");
//通过账号获取用户信息
$adminInfo = Admin::where("account","=", $account)->first();
if($adminInfo && Hash::check($password,$adminInfo->password)){
$aInfo["admin_id"] = $adminInfo->id;
$aInfo["admin_name"] = $adminInfo->real_name;
$role = Role::find($adminInfo->role);
$aInfo["role_name"] = $role->name;
$powerIds = explode(",",$role->power_ids);
$powerRes = Power::whereIn("id",$powerIds)->pluck("field")->toArray();
$powerRes = explode(",",implode(",",$powerRes));
$aInfo["role_powers"] = $powerRes;
session($aInfo);
}else {
$validator->errors()->add('password', '用户名或密码错误');
}
});
}
}
<file_sep>/app/Helpers/CityGanged.php
<?php
use App\Model\ChinaArea;
function provinces(){
return ChinaArea::where('parent_id','1')->get();
}
function cityAreas($id){
return ChinaArea::where('parent_id', $id)->get();
}
<file_sep>/bootstrap/article.php
<?php
/**
* Created by PhpStorm.
* User: Other
* Date: 2019/9/3
* Time: 13:49
*/
//草稿
define("ARTICLE_STATE_DRAFT",1);
define("ARTICLE_STATE_DRAFT_STR","草稿");
//待审核
define("ARTICLE_STATE_AUDIT",2);
define("ARTICLE_STATE_AUDIT_STR","待审核");
//已发布
define("ARTICLE_STATE_PUBLISH",3);
define("ARTICLE_STATE_PUBLISH_STR","已发布");
//下架
define("ARTICLE_STATE_UNSHELVE",4);
define("ARTICLE_STATE_UNSHELVE_STR","已下架");
//未通过
define("ARTICLE_STATE_FAIL",5);
define("ARTICLE_STATE_FAIL_STR","未通过");
define("ARTICLE_STATE" , [
ARTICLE_STATE_DRAFT => ARTICLE_STATE_DRAFT_STR,
ARTICLE_STATE_AUDIT => ARTICLE_STATE_AUDIT_STR,
ARTICLE_STATE_PUBLISH => ARTICLE_STATE_PUBLISH_STR,
ARTICLE_STATE_UNSHELVE => ARTICLE_STATE_UNSHELVE_STR,
ARTICLE_STATE_FAIL => ARTICLE_STATE_FAIL_STR
]);
//资讯详情默认模板
define("ARTICLE_DEFAULT_SHOW_VIEW","article.article_default_show");
//资讯分类状态
define("ARTICLE_CATEGORY_START", 1);
define("ARTICLE_CATEGORY_STOP", 0); | 9d5451b0968aadd0003260e300cf473960882519 | [
"PHP"
] | 39 | PHP | zhangchen9218/shop_admin | 9619cc38d3310afcba66d890363b81027b562255 | c94c9ec62f09dbdfaa273f5dd884da458449d857 |
refs/heads/master | <repo_name>ganesan/Corona-SDK-In-App-Purchasing-Module<file_sep>/main.lua
local ui = require("ui")
local storeMod = require("storeMod")
----@start interface features here we are making some interface features to get the storemod working
local screen = display.newGroup()
local background = display.newRect(0,0,display.contentWidth, display.contentHeight)
background:setFillColor(255,255,0)
screen:insert(background)
---we can use this to restore the store connection
local button = ui.newButton({
default= "button.png",
over="button.png",
text = "Test Reset",
onRelease = function(event)
storeMod.restore()
end
})
button.xScale = 2.0
button.yScale = 2.0
button:translate(display.contentWidth*0.8,display.contentHeight*0.8)
screen:insert(button)
---@end interface features
--- below is all the code you need to activate the storeMod
---this function sets the transaction event callback for making purchases in the app
----NOTE, if you need to download your in-app purchases, you may need to alter the transaction event function in storeMod
---to work like that
storeMod.setTransactionEvent(function(state, transaction)
if state == 'purchased' then
print("success buying item "..transaction.productIdentifier)
print("bought on: "..transaction.date)
elseif state == "cancelled" then
print("error buying item")
end
end)
local products = {
"com.anscamobile.NewExampleInAppPurchase.ConsumableTier1",
"com.anscamobile.NewExampleInAppPurchase.NonConsumableTier1",
}
---this gives you all the information you need form your products
---pressing this activates the store and gives you the product information
storeMod.startStore(products,function(validProducts, invalidProducts)
--now you can poplate your info to make in app purchasing
for k,v in ipairs(validProducts) do
local button = ui.newButton({
default= "button.png",
over="button.png",
text=v.title.." - "..v.price,
onRelease = function(event)
local productIdentifier = event.target.product.productIdentifier
storeMod.purchaseItem(productIdentifier)
end
})
button.product = v
button.xScale = 2.0
button.yScale = 2.0
button:translate(display.contentWidth*0.5,100*k)
screen:insert(button)
end
end)
| c4ecb2f7ff053e1c22002120642b2d1f54682938 | [
"Lua"
] | 1 | Lua | ganesan/Corona-SDK-In-App-Purchasing-Module | af1953355f2253cbda9c5946f725683eaf1bdc49 | 63435344c11bf324e853053943cf27ed6e5b1703 |
refs/heads/master | <repo_name>OBarronCS/finalgame<file_sep>/spawncontrol.py
import entity, random
class SpawnControl:
def __init__(self, match):
self.match = match
# this includes only references to the AI things. Main game has on list that includes them as well
self.spawners = []
self.entities = []
# calculate direction of entities every 5th step. Might delegate this to indivual spanwers later
self.max_calc_step = 5
self.calc_step = self.max_calc_step
def step(self):
for spawner in self.spawners:
spawner.createBot()
self.calc_step -= 1
if self.calc_step <= 0:
self.calc_step = self.max_calc_step
for entity in self.entities:
# first find closest player entity
target_player = None
biggest_distance = 500**2
for player_e in self.match.playerentities:
distance = (player_e.x - entity.x)**2 + (player_e.y - entity.y)**2
if distance < biggest_distance:
biggest_distance = distance
target_player = player_e
if target_player is not None:
move_command = [0,0]
if target_player.x > entity.x:
move_command[0] = 2 + random.random()
else:
move_command[0] = -2 + random.random()
if target_player.y > entity.y:
move_command[1] = 2 + random.random()
else:
move_command[1] = -2 + random.random()
entity.current_dx = move_command[0]
entity.current_dy = move_command[1]
else:
entity.current_dx = (random.random() * 2 - 1) * 1.5
entity.current_dy = (random.random() * 2 - 1) * 1.5
# actually moves them
for entity in self.entities:
entity.applyInputSetAngle([entity.current_dx, entity.current_dy], 76)
def addEntity(self, x, y):
# cap number of enemies to 100
if len(self.entities) > 150:
return
e = entity.Entity(self.match, x, y, True)
e.entity_id = self.match.entity_id_num
e.health = 45
self.match.entity_id_num += 1
self.entities.append(e)
self.match.entities.append(e)
<file_sep>/static/js/fixedentity.js
// Will represent an entity that we got the initial timestamp, position, and velocity of, so I can
// predict its actual location until it disappears or server sends event to destroy it
const Sprite = PIXI.Sprite;
const resources = PIXI.Loader.shared.resources;
export default class FixedEntity {
constructor(match, x,y, r, spd, angle, time, max_dis){
this.initial_x = x
this.initial_y = y;
this.x = x;
this.y = y;
this.r = r;
this.speed = spd
this.angle = angle
this.initial_time = time;
this.max_dis = max_dis
this.sprite = null
this.setSprite("static/images/basic_proj.png")
this.sprite.width = r;
this.sprite.height = r;
this.sprite.angle = this.angle
this.match = match
this.inc_x = this.speed * Math.cos(angle * (Math.PI/180))
this.inc_y = this.speed * Math.sin(angle * (Math.PI/180))
match.tick_objects.push(this)
this.ticks = 0;
}
tick(current_time){
const delta = (current_time - this.initial_time) / 1000 // to convert to seconds
//console.log(delta)
this.setPosition(this.initial_x + (delta * this.inc_x), this.initial_y + (delta * this.inc_y))
}
destroy(){
this.match.deleteTickingObject(this)
window.renderer.removeSprite(this.sprite)
}
setPosition(new_x, new_y){
this.x = new_x;
this.y = new_y;
const a = new_x - this.initial_x;
const b = new_y - this.initial_y;
const c = Math.sqrt( a*a + b*b );
if(c > this.max_dis){
this.destroy()
return;
}
if(this.sprite != null){
this.sprite.x = new_x;
this.sprite.y = new_y;
}
}
setSprite(filepath_string){
this.sprite = new Sprite(
resources[filepath_string].texture
);
this.sprite.x = this.x
this.sprite.y = this.y
// set origin to middle
this.sprite.anchor.x = 0.5;
this.sprite.anchor.y = 0.5;
window.renderer.addSprite(this.sprite,0)
}
}<file_sep>/spawner.py
import random
class Spawner:
def __init__(self, spawncontrol, pixel_x, pixel_y):
self.spawncontrol = spawncontrol
self.x = pixel_x
self.y = pixel_y
self.maxsteps = 120
self.steps = self.maxsteps
def createBot(self):
self.steps -= 1
if self.steps <= 0:
self.steps = self.maxsteps
biggest_distance = 1000**2
for player_e in self.spawncontrol.match.playerentities:
distance = (player_e.x - self.x)**2 + (player_e.y - self.y)**2
if distance < biggest_distance:
biggest_distance = distance
if biggest_distance < 1000**2:
self.spawncontrol.addEntity(self.x + ((random.random() * 2 - 1) * 5), self.y + ((random.random() * 2- 1) * 5))
<file_sep>/tilemap.py
# holds tile map of walls
# defines world dimensions
import enum
import spawner
from math import floor
import random
# creating enumerations using class
class Tile(enum.Enum):
EMPTY = 0
WALL = 1
SPAWNER = 2
class TileMap:
def __init__(self, match, width, height, cellwidth):
self.match = match
self.width = width
self.height = height
self.cellwidth = cellwidth
self.gridwidth = floor(width/cellwidth)
self.gridheight = floor(height/cellwidth)
self.tilemap = [[Tile.EMPTY for x in range(self.gridwidth)] for y in range(self.gridheight)]
self.empty_tiles = []
self.walls_send = []
self.spawners_send = []
self.addWalls()
self.addSpawners()
# temporary
def addWalls(self):
i = 0
while(i < 450):
if(random.random() > .4):
self.tilemap[floor(random.random() * self.gridheight)][floor(random.random() * self.gridwidth)] = Tile.WALL
i += 1;
j = 0
while(j < self.gridheight):
k = 0
while(k < self.gridwidth):
if self.tilemap[j][k] == Tile.WALL:
self.walls_send.append([j,k])
k += 1
j += 1
def addSpawners(self):
i = 0
while(i < 10):
gridx = floor(random.random() * self.gridheight)
gridy = floor(random.random() * self.gridwidth)
self.tilemap[gridx][gridy] = Tile.SPAWNER
s = spawner.Spawner(self.match.spawncontrol, gridx * self.cellwidth + (self.cellwidth / 2), gridy * self.cellwidth + (self.cellwidth / 2))
self.match.spawncontrol.spawners.append(s)
i += 1
j = 0
while(j < self.gridheight):
k = 0
while(k < self.gridwidth):
if self.tilemap[j][k] == Tile.SPAWNER:
self.spawners_send.append([j,k])
elif self.tilemap[j][k] == Tile.EMPTY:
self.empty_tiles.append([j,k])
k += 1
j += 1
# returns wall to be sent to client
def getTileMapInfo(self):
return {"w":self.gridwidth, "h":self.gridheight, "c":self.cellwidth}
def getWalls(self):
return self.walls_send
def getSpawners(self):
return self.spawners_send
def wallCollision(self, hitbox):
left_tile = floor(hitbox.left / self.cellwidth)
right_tile = floor( hitbox.right / self.cellwidth)
top_tile = floor( hitbox.top / self.cellwidth)
bottom_tile = floor(hitbox.bottom / self.cellwidth)
# print(f"{left_tile},{right_tile},{top_tile},{bottom_tile}")
# returns True (yes collision) if you end up outside the bounds of the map
if(left_tile < 0):
return True
#left_tile = 0
if(right_tile >= self.gridwidth):
return True
# right_tile = self.gridwidth - 1
if(top_tile < 0):
return True
# top_tile = 0
if(bottom_tile >= self.gridheight):
return True
# bottom_tile = self.gridheight - 1
i = left_tile;
while(i <= right_tile):
j = top_tile
while(j <= bottom_tile):
if(self.tilemap[i][j] == Tile.WALL):
# print("WALL COLLISION")
return True
j += 1
i += 1
return False
def getOpenCoords(self):
gridspot = random.choice(self.empty_tiles)
return [((i * self.cellwidth) + (self.cellwidth/2)) for i in gridspot]<file_sep>/static/js/entity.js
const Sprite = PIXI.Sprite;
const resources = PIXI.Loader.shared.resources;
export default class Entity {
constructor(x,y, entity_id){
this.x = x;
this.y = y;
this.entity_id = entity_id;
this.angle = 0;
this.radius = 11;
this.max_health = 100
this.health = this.max_health;
this.sprite = null
// holds timestamped coordinate data for this client, held for the past 1 second.
this.state_buffer = []
// HEALTH INFO
this.health_text = new PIXI.Text(`HP: ${this.health}`, {fontFamily : "\"Lucida Console\", Monaco, monospace", fontSize: 8, fill : 0x5298fa})
this.health_back = new PIXI.Graphics();
window.renderer.addSprite(this.health_back,0);
this.health_front = new PIXI.Graphics();
window.renderer.addSprite(this.health_front,0);
this.health_length = 28
this.health_text.x = this.x - 14
this.health_text.y = this.y - 30
window.renderer.addSprite(this.health_text,0);
// first index is timestamp, second is info
}
updateHealth(new_health){
if(new_health > this.max_health){
this.max_health = new_health
}
this.health = new_health
this.health_back.clear()
this.health_front.clear()
this.health_back.beginFill(0x000000)
this.health_back.drawRect(this.x - (this.health_length / 2), this.y - 21, this.health_length, 6)
this.health_back.endFill()
this.health_front.beginFill(0x1cbd5a)
this.health_front.drawRect(this.x - (this.health_length / 2), this.y - 21, (Math.max(0,this.health)/this.max_health) * this.health_length, 6)
this.health_front.endFill()
this.health_text.text = `HP: ${Math.round(this.health)}`
this.health_text.x = this.x - 14
this.health_text.y = this.y - 30
}
// this function is called every step
interpolate(target_time){
if(this.state_buffer.length >= 2){
while(this.state_buffer.length > 2 && target_time >= this.state_buffer[1][0]){
// removes first index
this.state_buffer.shift();
}
// target time should now be between index 0 and 1
let fraction = (target_time - this.state_buffer[0][0]) / (this.state_buffer[1][0] - this.state_buffer[0][0])
// total changes over the two periods
let delta_x = this.state_buffer[1][1]["x"] - this.state_buffer[0][1]["x"];
let delta_y = this.state_buffer[1][1]["y"] - this.state_buffer[0][1]["y"];
const angle0 = this.state_buffer[0][1]["a"]
const angle1 = this.state_buffer[1][1]["a"]
let angledif = (angle1 - (angle0) + 540) % 360 - 180;
this.setPosition(this.state_buffer[0][1]["x"] + (delta_x * fraction),this.state_buffer[0][1]["y"] + (delta_y * fraction));
let a = this.getAngle();
this.setAngleDegrees(angle0 + (angledif * fraction))
//console.log(this.getAngle() - a)
} else {
this.setPosition(this.state_buffer[0][1]["x"],this.state_buffer[0][1]["y"])
}
this.updateHealth(this.health)
}
turnByDegrees(degrees){
this.setAngleDegrees(this.angle + degrees)
}
setAngleDegrees(angle){
this.angle = angle;
if(this.angle > 360){
this.angle -= 360
}
if(this.angle < 0){
this.angle += 360;
}
this.sprite.angle = angle
}
cleanUp(){
this.deleteSprite()
this.health_front.destroy()
this.health_back.destroy()
this.health_text.destroy()
}
deleteSprite(){
window.renderer.removeSprite(this.sprite)
}
//none of this takes into considering anything smooth or good looking
setPosition(new_x, new_y){
this.x = new_x;
this.y = new_y;
if(this.sprite != null){
this.sprite.x = new_x;
this.sprite.y = new_y;
}
}
setSprite(filepath_string){
this.sprite = new Sprite(
resources[filepath_string].texture
);
this.sprite.x = this.x
this.sprite.y = this.y
// set origin to middle
this.sprite.anchor.x = 0.5;
this.sprite.anchor.y = 0.5;
window.renderer.addSprite(this.sprite,0)
}
getPosition(){
return `${this.x},${this.y}`
}
getX(){
return this.x;
}
getY(){
return this.y;
}
getHitBox(){
return {"right":this.x + this.radius, "top":this.y - this.radius, "left":this.x - this.radius, "bottom":this.y + this.radius, }
}
getAngle(){
return this.angle
}
}<file_sep>/static/js/app.js
//This is where the app starts
import ServerConnection from "./serverconnection.js";
import Renderer from "./renderer.js";
const renderer = new Renderer(window.innerWidth - 25,window.innerHeight- 25);
window.renderer = renderer;
window.pixiapp = renderer.getPixiApp();
PIXI.Loader.shared.load(() => {
console.log("Sprites loaded");
console.log("Initiating Connection")
//Set this global so other things can access it.
window.mouse = window.pixiapp.renderer.plugins.interaction.mouse.global
const server = new ServerConnection();
server.joinGame();
});
<file_sep>/static/js/hitscan.js
export default class HitScan {
constructor(match,start_array, angle){
this.match = match
this.objects = []
this.rect = new PIXI.Graphics();
this.rect.lineStyle(1, 0xdbbf70);
this.rect.drawRect(0,0,860,2);
this.rect.pivot.y = 1
this.rect.x = start_array[0]
this.rect.y = start_array[1]
this.rect.angle = angle;
this.objects.push(this.rect)
let i;
for(i = 0; i < this.objects.length; i++){
window.renderer.addSprite(this.objects[i],0)
}
match.tick_objects.push(this)
}
tick(current_time){
let todelete = [];
let i;
for(i = 0; i < this.objects.length; i++){
this.objects[i].alpha -= .06
if(this.objects[i].alpha <= 0){
todelete.push(this.objects[i])
}
}
let j;
outer:
for(j = 0; j < todelete.length; j++){
let k;
inner:
for(k = 0; k < this.objects.length; k++){
if(todelete[j] == this.objects[k]){
//console.log("DELETE")
this.objects[k].destroy();
this.objects.splice(k,1)
continue outer;
}
}
}
if(this.objects.length == 0){
this.match.deleteTickingObject(this)
}
}
}<file_sep>/gamelogic.py
#This class represents an game, holding info on clients and such
import eventlet;
eventlet.monkey_patch();
import entity, client, threading, time, random, collisionhandler, tilemap, spawncontrol
class Game(threading.Thread):
# Game loop in here?
def __init__(self, socketio,app):
threading.Thread.__init__(self);
self.socketio = socketio;
self.app = app;
self.entity_id_num = 0;
self.clients = [];
self.entities = [];
# used for bots to lock onto
self.playerentities = [];
self.tickrate = 20
self.spawncontrol = spawncontrol.SpawnControl(self)
self.collision = collisionhandler.CollisionHandler(self)
self.tilemap = tilemap.TileMap(self, 2048, 2048, 32)
# This one is not in used RN
self.last_processed_input = [];
self.sid_to_client = {}
self.events = []
def queueInput(self, sid, horz, vert, input_num, angle_delta, mousedown):
client = self.sid_to_client.get(sid, None)
if client is None:
# this is called alot right after someone joins as they have yet to be created in the world
print("movement linked to no client")
return;
client.addInput(horz, vert, input_num, angle_delta, mousedown)
def processInputs(self):
for client in self.clients:
client.processInput(self.tickrate)
eventlet.sleep(0);
def disconnectPlayer(self, sid):
# this is called from the server, basically just kills the entity
remove_client = self.sid_to_client.get(sid, None)
# this happens most likely when someone connects to server, but never gets to connect to the game;
if(remove_client is None):
return;
remove_entity = remove_client.entity;
# removes all reference to this player and his entity
del self.sid_to_client[sid]
self.clients.remove(remove_client);
self.deleteEntity(remove_entity)
# have to notify people that he has died
def deleteEntity(self, entity):
if entity in self.entities:
self.entities.remove(entity)
if entity in self.spawncontrol.entities:
self.spawncontrol.entities.remove(entity)
if entity in self.playerentities:
self.playerentities.remove(entity)
self.events.append([1, entity.entity_id])
def sendWorldState(self, timestamp):
#all clients are in room 1
time_ms = int(timestamp * 1000) # int floors the value
game_messages = {};
world_state = []
for entity in self.entities:
world_state.append(entity.getState())
'''
for client in self.clients:
entity = client.entity;
world_state.append(entity.getState())
'''
game_messages.update({"state":world_state})
game_messages.update({"timestamp":time_ms})
game_messages.update({"e":self.events})
self.events = []
# Broadcast world state to everyone
#print(time_ms)
for client in self.clients:
self.socketio.emit("gamestate",{"pvt":{"v_id" : client.last_verified_input, "p":client.ping}, "game":game_messages}, room = client.sid)
eventlet.sleep(0)
# when the thread is started, this is run
def run(self):
print("thread started")
#total time that the game logic has processed
t = 0;
#frame rate
dt = 1/self.tickrate;
currentTime = time.time()
accumulator = 0;
ping_accumulator = 0;
while (True):
#frametime = time that that last frame took
newTime = time.time();
frameTime = newTime - currentTime;
currentTime = newTime;
accumulator += frameTime;
ping_accumulator += frameTime;
# for now, sending all pings at once... later disperse them over different time periods
# every .3 seconds check ping
if(ping_accumulator > .3):
ping_accumulator = 0;
for client in self.clients:
self.send_ping(client)
eventlet.sleep(0)
#if the frame time as elapsed do the frame logic as many times as needed, then eventually send the world staet once everything has been done;
if(accumulator >= dt):
while (accumulator >= dt):
#print(accumulator);
self.processInputs();
self.collision.step(dt)
self.spawncontrol.step()
accumulator -= dt;
t += dt;
#print("sent world state")
self.sendWorldState(newTime);
eventlet.sleep(0);
def send_ping(self,client):
ping_id = client.next_ping_id
self.socketio.emit("p", ping_id, room = client.sid)
client.sent_pings.update({ping_id:time.time()*1000})
client.next_ping_id += 1
eventlet.sleep(0)
def ping_return(self, sid, pingid):
client = self.sid_to_client.get(sid, None)
if client is None:
print("ping linked to no client")
return;
return_time = time.time() * 1000
client.calc_ping(pingid, return_time)
# connects a new client to this game
def addNewClient(self,sid):
#random spawn locations
spawn = self.tilemap.getOpenCoords()
spawn_x = spawn[0]
spawn_y = spawn[1]
# gives new client an unique player_id
new_client = client.Client(self, 60 / self.tickrate , self.entity_id_num, sid);
self.entity_id_num += 1;
new_entity = entity.Entity(self,spawn_x, spawn_y, False)
new_entity.entity_id = new_client.player_id;
# give client object a reference to the entity they are controlling
new_client.entity = new_entity;
self.entities.append(new_entity)
self.playerentities.append(new_entity)
self.clients.append(new_client)
self.sid_to_client.update({sid:new_client});
self.socketio.emit("join match", {"player_id":new_client.player_id,"state":new_entity.getState(), "tickrate":self.tickrate, "winfo":self.tilemap.getTileMapInfo() , "walls":self.tilemap.getWalls(), "spawners":self.tilemap.getSpawners(),"timestamp":int(time.time() * 1000)}, room = sid)
<file_sep>/static/js/serverconnection.js
import MatchConnection from "./matchcontroller.js";
export default class ServerConnection {
constructor(){
//this.socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
this.socket = io({transports: [ 'websocket' ]});
this.game = null;
///////////////
window.testtest = this;
this.time = Date.now();
//////////////
window.socket = this.socket;
this.setSocketListeners();
}
joinGame(){
this.socket.emit("join room", "yes, I would like to join a room please!")
}
setSocketListeners(){
this.socket.on('connect', () => {
console.log("Successfully connnected to the server");
});
this.socket.on("join match", (data) => {
console.log(data);
this.game = new MatchConnection(this.socket, data);
})
//Server calls this periodically to get the round trip time
this.socket.on("p", (data) => {
//console.log("P")
this.socket.emit("p", data)
});
///// TESTING
this.socket.on("testpong", (data) => {
console.log(Date.now() - this.time);
});
}
///TESTING PURPOSES
ping(){
this.time = Date.now();
this.socket.emit("testping","hi")
}
getSocket(){
return this.socket();
}
}<file_sep>/collisionhandler.py
from math import cos, sin, pi, sqrt
class CollisionHandler:
def __init__(self,match):
self.match = match
# they have format [projectile id, origin entity_id]
self.projectiles = []
self.to_destroy = []
# self.match.entities is list of entities.
def step(self, delta):
for proj in self.projectiles:
proj.step(delta)
for entity in self.match.entities:
if entity.entity_id != proj.entity_id:
dis = sqrt((proj.x - entity.x)**2 + (proj.y - entity.y)**2)
if dis < entity.radius + 2:
# print("COLLISION")
entity.health -= 11
self.checkBotDeath(entity)
self.match.events.append([2,entity.entity_id,entity.health])
self.to_destroy.append(proj)
break;
for proj in self.to_destroy:
self.destroy_proj(proj)
for bot in self.match.spawncontrol.entities:
for entity in self.match.playerentities:
dis_squared = (bot.x - entity.x)**2 + (bot.y - entity.y)**2
if dis_squared < entity.r_squared + 2:
entity.health -= .8
self.match.events.append([2,entity.entity_id,entity.health])
# print(len(self.projectiles))
self.to_destroy = []
def destroy_proj(self, proj):
try:
self.projectiles.remove(proj)
except ValueError:
pass # this sometimes has an error, and idk why
# checking for their collisions
def checkBotDeath(self, entity):
if entity.health > 0:
return
for bot in self.match.spawncontrol.entities:
if bot == entity:
self.match.deleteEntity(entity)
def start_projectile(self, proj):
self.projectiles.append(proj)
def hitscan_collision(self, start_x, start_y, angle, length, origin_id):
inc = 10
inc_x = inc * cos(angle * (pi/180))
inc_y = inc * sin(angle * (pi/180))
x = start_x;
y = start_y;
i = 0;
# extremely(!!!!) inneffiecient, but it works for now
while(i < (length / inc) + 1):
for entity in self.match.entities:
if entity.entity_id != origin_id:
dis = sqrt((x - entity.x)**2 + (y - entity.y)**2)
if dis < entity.radius + 2:
sofar = sqrt((x - start_x)**2 + (y - start_y)**2)
percent = sofar/length
entity.health -= 3.5 * percent
self.checkBotDeath(entity)
self.match.events.append([2,entity.entity_id,entity.health])
x += inc_x
y += inc_y
i += 1;
<file_sep>/hitbox.py
# used for tile map collision in walls
class HitBox:
def __init__(self, right, top, left, bottom):
self.right = right
self.top = top
self.left = left
self.bottom = bottom
def setHitBox(self, right, top, left, bottom):
self.right = right
self.top = top
self.left = left
self.bottom = bottom
<file_sep>/static/js/clientcontroller.js
import ClientInputListener from "./clientinput.js";
import Entity from "./entity.js";
import HitScan from "./hitscan.js";
import FixedEntity from "./fixedentity.js"
import Renderer from "./renderer.js";
// This deals with everything specifically to do with the object that the client controls.
export default class ClientObjectController {
//{"player_id":new_client.player_id,"state": BELOW})
//{"entity_id":self.entity_id, "x":self.x, "y": self.y}
constructor(data, match){
this.input = new ClientInputListener();
this.match = match;
///------- Adds the rectangle showing where you are actually aiming
this.graphics = new PIXI.Graphics();
this.graphics.lineStyle(2, 0xFF0000);
window.renderer.addSprite(this.graphics, 1);
//0, 0 in reference to this object
/*
this.graphics.drawRect(0, 0, 12, 12);
// MAKE SURE THESE ARE HALF OF WIDTH SO MOUSE STAYS IN MIDDLE
this.graphics.pivot.x = 6
this.graphics.pivot.y = 6
*/
//graphics.beginFill(color hex code);
//LINES
this.posline = new PIXI.Graphics();
this.posline.lineStyle(1, 0xFFFFFF);
this.posline.alpha = .2
this.posline.lineTo(250, 0);
window.renderer.addSprite(this.posline,0);
this.negline = new PIXI.Graphics();
this.negline.lineStyle(1, 0xFFFFFF);
this.negline.alpha = .2
this.negline.lineTo(250, 0);
window.renderer.addSprite(this.negline,0);
this.entity_id = data["player_id"];
let new_entity = new Entity(data["state"]["x"], data["state"]["y"],data["player_id"]);
new_entity.setSprite("static/images/player.png");
this.entity = new_entity;
// Add this entity to the clients list of entities
match.entities[data["player_id"]] = new_entity;
//max degrees per step can turn
this.max_angle_turn = 2.5
// amount of degrees each way that I can "see/aim"
this.max_angle_view = 20
// stores all the ones the server has yet to verify with us.
// form: [0] = input number [1] is the input itself
this.unauthorized_inputs = [];
this.input_number = 0;
this.last_verified_num = -1;
this.speed = 75;
this.adjust_x = 0;
this.adjust_y = 0;
this.adjusting = false;
/* some more commands to know
//app.stage.removeChild(anySprite)
//anySprite.visible = false;
// place where WEB-GL texture caches are stored:
//let texture = PIXI.utils.TextureCache["images/anySpriteImage.png"];
//let sprite = new PIXI.Sprite(texture);
*/
}
getInput(){
return this.input.getMovementState();
}
processInputs(dt){
//not only process inputs, but interpolate me a bit
//this code slowly adjusts our position to where we should be
if(this.adjusting){
//console.log("adjust loop")
const maxtween_x = .1 * 6//this.adjust_x;
const maxtween_y = .1 * 6//this.adjust_y;
let cx = this.entity.getX();
let cy = this.entity.getY();
//how much we should move our charaacter in each axis to get to a ideal location points
let comp_x = -Math.sign(this.adjust_x) * Math.min(Math.abs(maxtween_x), Math.abs(this.adjust_x))
let comp_y = -Math.sign(this.adjust_y) * Math.min(Math.abs(maxtween_y), Math.abs(this.adjust_y))
this.adjust_x += comp_x;
this.adjust_y += comp_y;
cx += comp_x;
cy += comp_y;
if(Math.abs(this.adjust_x) < .1 && Math.abs(this.adjust_y) < .1){
this.adjusting = false;
}
this.entity.setPosition(cx,cy);
}
const mousepoint = this.input.getMousePoint();
let mouseangle = Math.atan2(mousepoint.x - this.entity.getX(),- mousepoint.y + this.entity.getY());
mouseangle *= (180/Math.PI)
mouseangle -= 90
//mouseangle now = angle to mouse in degrees
//difference between current angle and angle to mouse
const angledif = parseFloat(((this.entity.getAngle() - mouseangle + 540) % 360 - 180).toFixed(3));
let angle_delta = Math.min(Math.abs(angledif), Math.abs(this.max_angle_turn)).toFixed(3);
angle_delta *= -Math.sign(angledif);
this.entity.turnByDegrees(angle_delta)
const new_angledif = parseFloat(((this.entity.getAngle() - mouseangle + 540) % 360 - 180).toFixed(3));
///// ----------- DRAWING THE AIM RECTANGL
//distance from player to mouse
const mouse_dis = Math.sqrt(Math.pow(mousepoint.x - this.entity.x,2) + (Math.pow(mousepoint.y - this.entity.y,2)))
//clear completely clears all settings and past draw things with this object
this.graphics.x = this.entity.x;
this.graphics.y = this.entity.y;
this.graphics.clear()
this.graphics.lineStyle(2, 0xFF0000);
this.graphics.pivot.x = 6
this.graphics.pivot.y = 6
let rect_angle = parseFloat(Math.min(this.max_angle_view, Math.abs(new_angledif)).toFixed(3));
this.graphics.angle = this.entity.getAngle() + -(Math.sign(new_angledif) * rect_angle)
this.graphics.drawRect(mouse_dis, 0, 12, 12);
/// ----- CALCING TARGET LOCATION---- ///
let target_x = this.entity.getX() + (mouse_dis * Math.cos((Math.PI/180)*this.graphics.angle));
let target_y = this.entity.getY() + (mouse_dis * Math.sin((Math.PI/180)*this.graphics.angle));
//console.log(`${target_x},${target_y}`)
this.posline.clear()
this.negline.clear()
if(this.graphics.angle == this.entity.getAngle() + this.max_angle_view || this.graphics.angle == this.entity.getAngle() - this.max_angle_view){
this.posline.lineStyle(1, 0xFFFFFF);
this.posline.alpha = .2
this.posline.lineTo(250, 0);
this.posline.x = this.entity.x;
this.posline.y = this.entity.y
this.posline.angle = this.entity.getAngle() + this.max_angle_view;
this.negline.lineStyle(1, 0xFFFFFF);
this.negline.alpha = .2
this.negline.lineTo(250, 0);
this.negline.x = this.entity.x;
this.negline.y = this.entity.y
this.negline.angle = this.entity.getAngle() - this.max_angle_view;
}
//console.log(`There are ${this.unauthorized_inputs.length} unauthorized inputs`)
if(this.entity == null){
return;
}
let sample_input = this.input.getMovementState();
if(angle_delta == -0){
angle_delta = 0;
}
// happens when renderer breaks. would break server rn becuase not validating inputs
if(isNaN(angle_delta)){
return;
}
const mousedown = this.input.getMouseDown();
if(mousedown){
//new HitScan(this.match, [this.entity.getX(), this.entity.getY()],this.graphics.angle)
//new FixedEntity(this.match, this.entity.getX(),this.entity.getY(),this.entity.getAngle())
}
if(sample_input != false || angle_delta != 0 || mousedown){
//Client side prediction here
if(sample_input == false){
sample_input = { "horz": 0, "vert": 0 }
}
this.applyInput(sample_input)
this.unauthorized_inputs.push([this.input_number,sample_input, this.entity.getX(), this.entity.getY()])
window.socket.emit("cmd", sample_input.horz, sample_input.vert, this.input_number, angle_delta, mousedown)
this.input_number += 1;
}
this.entity.updateHealth(this.entity.health)
}
//get server state and last authorized input, and from that get our current position
reconcile(entity_state, verified_num){
if(this.last_verified_num == verified_num){
return;
}
this.last_verified_num = verified_num;
if(this.unauthorized_inputs.length == 0){
//console.log("0 to start")
return;
}
//if our first one is greater than the num, that means we have already discarded it..
//which happens when we snap back
if(this.unauthorized_inputs[0][0] > verified_num){
//console.log("middle")
return;
}
while(this.unauthorized_inputs.length > 0 && this.unauthorized_inputs[0][0] < verified_num){
this.unauthorized_inputs.shift()
}
// at this point, 0 index should = the verified_num
if(this.unauthorized_inputs.length == 0){
// console.log("last")
return;
}
const _x = Math.round(this.unauthorized_inputs[0][2])
const _y = Math.round(this.unauthorized_inputs[0][3])
const distance = Math.sqrt(Math.pow(_x - entity_state["x"],2) + (Math.pow(_y - entity_state["y"],2)))
// console.log(distance)
//if get to far away , , , snap back
if(distance > 40){
// snap reconciliation
console.log("SNAP RECONCILIATION");
this.entity.setPosition(entity_state["x"],entity_state["y"]);
this.unauthorized_inputs = [];
// clears this stuff
this.adjusting = false;
this.adjust_x = 0;
this.adjust_y = 0;
return;
} else if(distance > 7 && !this.adjusting){
console.log("ADJUSTING")
// these nums tell us how much ahead we are on each axis
this.adjust_x = _x - entity_state["x"]; // how much we need to move to be at our desired location
this.adjust_y = _y - entity_state["y"];
this.adjusting = true;
// OLD CODE BELOW
/*
this.entity.setPosition(entity_state["x"],entity_state["y"])
this.unauthorized_inputs.shift();
let i;
for(i = 0; i < this.unauthorized_inputs.length; i++){
this.applyInput(this.unauthorized_inputs[i][1]);
}
*/
}
}
applyInput(input){
if(this.entity == null){
return;
}
let last_x = this.entity.getX();
this.entity.setPosition(last_x + this.speed * (input["horz"]/60),this.entity.getY())
if(this.match.tilemap.wallCollision(this.entity.getHitBox())){
this.entity.setPosition(last_x,this.entity.getY())
}
let last_y = this.entity.getY();
this.entity.setPosition(this.entity.getX(), last_y + this.speed * (input["vert"]/60))
if(this.match.tilemap.wallCollision(this.entity.getHitBox())){
this.entity.setPosition(this.entity.getX(), last_y)
}
}
update_state(){
if(this.entity = null){
return;
}
this.processInputs();
}
}
/*
if(this.entity == null){
return;
}
// this.match.tilemap.wallCollision(this.entity.getHitBox())
let cx = this.entity.getX();
let cy = this.entity.getY();
cx += this.speed * (input["horz"]/60)
cy += this.speed * (input["vert"]/60)
this.entity.setPosition(cx,cy)
*/<file_sep>/entity.py
import hitbox
class Entity:
def __init__(self,match,x,y, is_bot):
self.match = match
self.x = x;
self.y = y;
self.is_bot = is_bot
self.position_buffer = [];
self.entity_id = None;
self.speed = 75; # pixels per second
self.angle = 0;
# collision box is a circle
self.radius = 11
self.r_squared = self.radius**2
self.health = 100
self.hitbox = hitbox.HitBox(x + self.radius, y - self.radius, x - self.radius, y + self.radius)
# following are used if this is a bot
self.current_dx = 0
self.current_dy = 0
def getState(self):
# rounds position -> int(round(x), to make the packet smaller
return {"e_id":self.entity_id, "x":int(round(self.x)), "y": int(round(self.y)), "a":round(self.angle), "h":self.health}
def getFullState(self):
# [event_id, entity_id, x, y, angle, hp]
return [self.entity_id, int(round(self.x)), int(round(self.y)), round(self.angle), self.health]
def death(self):
pass
def applyInput(self,move_data, angle_change):
self.angle += angle_change;
last_x = self.x
self.x += (move_data[0]/60) * self.speed;
self.hitbox.setHitBox(self.x + self.radius, self.y - self.radius, self.x - self.radius, self.y + self.radius)
if(self.match.tilemap.wallCollision(self.hitbox)):
self.x = last_x
self.hitbox.setHitBox(self.x + self.radius, self.y - self.radius, self.x - self.radius, self.y + self.radius)
last_y = self.y
self.y += (move_data[1]/60) * self.speed;
self.hitbox.setHitBox(self.x + self.radius, self.y - self.radius, self.x - self.radius, self.y + self.radius)
if(self.match.tilemap.wallCollision(self.hitbox)):
self.y = last_y
self.hitbox.setHitBox(self.x + self.radius, self.y - self.radius, self.x - self.radius, self.y + self.radius)
if self.angle > 360:
self.angle -= 360
if self.angle < 0:
self.angle += 360
def applyInputSetAngle(self,move_data, angle):
self.angle = angle;
last_x = self.x
self.x += (move_data[0]/60) * self.speed;
self.hitbox.setHitBox(self.x + self.radius, self.y - self.radius, self.x - self.radius, self.y + self.radius)
if(self.match.tilemap.wallCollision(self.hitbox)):
self.x = last_x
self.hitbox.setHitBox(self.x + self.radius, self.y - self.radius, self.x - self.radius, self.y + self.radius)
last_y = self.y
self.y += (move_data[1]/60) * self.speed;
self.hitbox.setHitBox(self.x + self.radius, self.y - self.radius, self.x - self.radius, self.y + self.radius)
if(self.match.tilemap.wallCollision(self.hitbox)):
self.y = last_y
self.hitbox.setHitBox(self.x + self.radius, self.y - self.radius, self.x - self.radius, self.y + self.radius)
if self.angle > 360:
self.angle -= 360
if self.angle < 0:
self.angle += 360
<file_sep>/application.py
import eventlet;
eventlet.monkey_patch();
import gamelogic;
import client;
import entity;
import json, atexit, time, logging, os
from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO, emit, join_room, leave_room
app = Flask(__name__);
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
socketio = SocketIO(app, async_mode='eventlet')
game = gamelogic.Game(socketio, app);
game.daemon = True;
game.start();
@app.route("/")
def index():
print("user went to site")
timestamp = int(time.time());
return render_template("index.html", timestamp = timestamp)
@socketio.on("connect")
def connect():
print("A user has connected");
@socketio.on("disconnect")
def disconnect():
print(f"{request.sid} has disconnected")
leave_room(1)
leave_room(request.sid)
game.disconnectPlayer(request.sid);
@socketio.on("join room")
def joinmatch(data):
print("A player has requested to join the game")
sid = request.sid;
join_room(1) # this doesnt really mean anything yet
join_room(sid)
game.addNewClient(sid)
@socketio.on("cmd")
def movement(horz,vert,input_num,angle_delta, mousedown):
game.queueInput(request.sid, horz, vert, input_num, angle_delta, mousedown);
# client returns
@socketio.on("p")
def ping_return(data):
game.ping_return(request.sid, data)
# TESTING
@socketio.on("testping")
def testping(data):
emit("testpong","hi")
# error handling
@socketio.on_error_default
def default_error_handler(e):
print("Error in input!")
print(request.event["message"]) # "my error event"
print(request.event["args"]) # (data,)
if __name__ == '__main__':
print("__main__")
# this only runs when locally testing, mate!
#socketio.run(app)
port = int(os.environ.get('PORT', 5000))
#socketio.run(app, host="0.0.0.0", port=port)
print("asdvuiasfduyasfduy")
socketio.run(app, host="0.0.0.0", port="80")<file_sep>/projectile.py
from math import cos, sin, pi, sqrt
import time
class Projectile:
def __init__(self, match, entity_id, x, y, r, spd, angle, distance):
self.match = match
self.entity_id = entity_id
self.initial_x = x
self.initial_y = y
self.x = x
self.y = y
self.r = r
self.spd = spd # pixels per second
self.angle = angle
self.distance = distance # max distance it can travel
self.inc_x = spd * cos(angle * (pi/180))
self.inc_y = spd * sin(angle * (pi/180))
self.steps = 0;
self.match.events.append([3, x, y, r, spd, angle, int(time.time() * 1000), distance])
def step(self, delta):
self.x += self.inc_x * delta
self.y += self.inc_y * delta
# print(f"{self.x},{self.y}")
self.steps += 1
a = self.x - self.initial_x
b = self.y - self.initial_y
c = sqrt( a*a + b*b );
if(c > self.distance):
self.match.collision.to_destroy.append(self)
<file_sep>/static/js/renderer.js
export default class Renderer {
constructor(width, height) {
this.pixiapp = new PIXI.Application({ width: width, height: height, backgroundColor : 0x4d5c63 })
this.pixiapp.sortableChildren = true;
this.camera_width = width
this.camera_height = height;
this.camera = new PIXI.Container();
this.camera.sortableChildren = true;
this.camera.zIndex = 0;
this.pixiapp.stage.addChild(this.camera)
this.gui = new PIXI.Container();
this.gui.zIndex = 1;
this.pixiapp.stage.addChild(this.gui)
const displayDiv = document.querySelector('#display')
displayDiv.appendChild(this.pixiapp.view);
console.log("Renderer loaded")
const game_sprites = ["static/images/spawner.png","static/images/player.png", "static/images/basic_proj.png","static/images/basic_wall.png"];
PIXI.Loader.shared
.add(game_sprites)
const _bind = this;
window.onresize = function (event){
const w = window.innerWidth;
const h = window.innerHeight;
//this part resizes the canvas but keeps ratio the same
this.pixiapp.view.width = w - 25;
this.pixiapp.view.height = h - 25;
_bind.camera_width = w - 25;
_bind.camera_height = h - 25;
}
}
// adds the given sprite to the canvas at the given z layer. The higher the layer, the closer to the top
addGUI(sprite){
this.gui.addChild(sprite)
}
addSprite(sprite, z){
sprite.zIndex = z;
this.camera.addChild(sprite)
this.camera.sortChildren();
}
removeSprite(sprite){
this.camera.removeChild(sprite)
}
// takes in the entity it is following
updateScreen(entity, tilemap){
// the top left corner of screen. camera x,y
let _x = Math.max(0,entity.x - (this.camera_width / 2));
let _y = Math.max(0,entity.y - (this.camera_height / 2));
_x = Math.min(_x, tilemap.pixelwidth - this.camera_width)
_y = Math.min(_y, tilemap.pixelheight - this.camera_height)
this.camera.pivot.x = _x;
this.camera.pivot.y = _y
//this.camera.x = _x;
//this.camera.y = _y;
}
getPixiApp() {
return this.pixiapp;
}
}
<file_sep>/client.py
from math import copysign, ceil
import projectile, time
class Client:
def __init__(self, match, maxInputs, player_id, sid):
# unique ID to identify player ((length of things))
self.match = match
self.maxInputs = maxInputs;
self.player_id = player_id;
# unique socket session ID of this user
self.sid = sid;
# the entity you are controlling
self.entity = None;
self.last_received_input = None;
self.last_verified_input = None;
self.move = [0,0]
self.next_move = [0,0]
# list dict of last pings sent, code : timestamp in MS
self.sent_pings = {}
self.next_ping_id = 0
# list of pings times to this client
self.ping_list = []
self.ping = 0
# TODO_ --> Auto sync with client on connection
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
self.max_angle_turn = 2.5 * (60/20)
self.angle_change = 0
self.next_angle_change = 0;
# numbers of times mouse was down TEMPORARY
self.mousedown = 0
def calc_ping(self, pingid, return_time):
sent_time = self.sent_pings.get(pingid, None)
if sent_time is None:
print("PING ID unrecognized")
return;
del self.sent_pings[pingid]
self.ping_list.append(return_time - sent_time)
if len(self.ping_list) > 10:
self.ping_list.pop(0)
# print(sum(self.ping_list))
# rough average. later can make it favor recent ones more
self.ping = ceil(sum(self.ping_list) / len(self.ping_list))
def processInput(self, tick):
if(self.entity.health <= 0):
self.entity.health = 100
self.move[0] += self.next_move[0];
self.move[1] += self.next_move[1];
self.next_move = [0,0];
# checks for the overflow amount of inputs
# max amount of inputs is defined as !!!!! 60 / game.tickrate !!!!
# this might be bad
self.angle_change += self.next_angle_change;
self.next_angle_change = 0
angle_sign = copysign(1,self.angle_change)
angle_overFlow = abs(self.angle_change) - self.max_angle_turn
if angle_overFlow > 0:
# print("ANGLE OVERFLOW")
self.angle_change -= (angle_sign * angle_overFlow);
self.next_angle_change += (angle_sign * angle_overFlow);
i = 0;
while(i < 2):
# can be negative
inputNum = self.move[i];
sign = copysign(1,inputNum);
overFlow = abs(inputNum) - self.maxInputs;
# if we have more inputs than the maximum possible
if(overFlow > 0):
# print("OVERFLOW")
self.move[i] -= (sign * overFlow); # truncates it to max amount
# design choice, +=. just = would punish people with very inconsistent output of inputs
self.next_move[i] += (sign * overFlow);
i += 1;
# print(f"{self.move[0],self.move[1]} | Overflow --> {self.next_move[0]},{self.next_move[1]}")
self.entity.applyInput(self.move, self.angle_change)
self.last_verified_input = self.last_received_input;
# if user had mousedown in past 3 ticks (need to adjust it to an array so multiple shots can go thru)
b = 0;
while(b < self.mousedown):
self.match.events.append([0,self.entity.x, self.entity.y, self.entity.angle])
self.match.collision.hitscan_collision(self.entity.x, self.entity.y,self.entity.angle,860, self.entity.entity_id)
# projectile thing!
self.match.collision.start_projectile(projectile.Projectile(self.match, self.player_id, self.entity.x, self.entity.y, 15, 200, self.entity.angle, 400))
b += 1;
self.mousedown = 0
self.angle_change = 0;
self.move = [0,0]
def addInput(self, horz, vert, input_num, angle_delta, mousedown):
# currently hackable if user sets horz or vert to something else than -1,0,1
self.last_received_input = input_num
self.move[0] += horz
self.move[1] += vert
self.angle_change += angle_delta;
self.mousedown += mousedown
<file_sep>/requirements.txt
gunicorn
Flask
Flask-SocketIO
eventlet<file_sep>/static/js/tilemap.js
const Sprite = PIXI.Sprite;
const resources = PIXI.Loader.shared.resources;
export default class TileMap {
constructor(match, serverinfo){
this.cellwidth = serverinfo["winfo"]["c"]
this.gridheight = serverinfo["winfo"]["h"]
this.gridwidth = serverinfo["winfo"]["w"]
this.pixelwidth = this.cellwidth * this.gridwidth
this.pixelheight = this.cellwidth * this.gridheight
console.log(this.gridheight)
console.log(this.gridwidth)
this.tilemap = []
for(let i = 0; i < this.gridheight;i++){
const arr = []
for(let j = 0; j < this.gridwidth;j++){
arr.push(0)
}
this.tilemap.push(arr)
}
const walls = serverinfo["walls"]
const spawners = serverinfo["spawners"]
for(let i = 0; i < walls.length;i++){
this.tilemap[walls[i][0]][walls[i][1]] = 1
const w = new Sprite(
resources["static/images/basic_wall.png"].texture
);
w.width = this.cellwidth;
w.height = this.cellwidth;
w.x = walls[i][0] * this.cellwidth;
w.y = walls[i][1] * this.cellwidth;
window.renderer.addSprite(w,-1)
}
for(let i = 0; i < spawners.length;i++){
this.tilemap[spawners[i][0]][spawners[i][1]] = 2
const w = new Sprite(
resources["static/images/spawner.png"].texture
);
w.width = this.cellwidth;
w.height = this.cellwidth;
w.x = spawners[i][0] * this.cellwidth;
w.y = spawners[i][1] * this.cellwidth;
window.renderer.addSprite(w,-1)
}
}
wallCollision(hitbox){
let left_tile = Math.floor(hitbox.left / this.cellwidth);
let right_tile = Math.floor( hitbox.right / this.cellwidth);
let top_tile = Math.floor( hitbox.top / this.cellwidth);
let bottom_tile = Math.floor(hitbox.bottom / this.cellwidth);
// console.log(`${left_tile},${right_tile},${top_tile},${bottom_tile}`)
if(left_tile < 0) return true; //left_tile = 0
if(right_tile >= this.gridwidth) return true; //right_tile = self.gridwidth - 1
if(top_tile < 0) return true; //top_tile = 0
if(bottom_tile >= this.gridheight) return true; //bottom_tile = self.gridheight - 1
let i = left_tile;
while(i <= right_tile){
let j = top_tile
while(j <= bottom_tile){
if(this.tilemap[i][j] == 1){
// console.log("WALL COLLISION")
return true
}
j += 1
}
i += 1
}
return false
}
} | 83a6dc66e940d6cc7a96253f9d03cfc6975a0eea | [
"JavaScript",
"Python",
"Text"
] | 19 | Python | OBarronCS/finalgame | 12fd8cf9a0924ceb90ac9e97560ab118201920de | a3d8f8c18dfe537053437b4f0054035c6c52dc68 |
refs/heads/master | <file_sep>package in.co.everyrupee.controller.overview;
import in.co.everyrupee.constants.GenericConstants;
import in.co.everyrupee.constants.income.DashboardConstants;
import in.co.everyrupee.pojo.TransactionType;
import in.co.everyrupee.pojo.user.AccountCategories;
import in.co.everyrupee.service.income.IUserTransactionService;
import in.co.everyrupee.service.user.IBankAccountService;
import java.util.Optional;
import javax.validation.Valid;
import javax.validation.constraints.Size;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Manage Overview page in Dashboard
*
* @author Nagarjun
*/
@RestController
@RequestMapping("/api/overview")
@Validated
public class OverviewController {
@Autowired private IUserTransactionService userTransactionService;
@Autowired private IBankAccountService bankAccountService;
/**
* Get user transactions sorted by creation date - DESC
*
* @param pFinancialPortfolioId
* @param userPrincipal
* @return
*/
@RequestMapping(value = "/recentTransactions", method = RequestMethod.GET)
public Object getUserTransactionByFinancialPortfolioId(
@RequestParam(DashboardConstants.Overview.DATE_MEANT_FOR) @Size(min = 0, max = 10)
String dateMeantFor,
@RequestParam(DashboardConstants.Overview.FINANCIAL_PORTFOLIO_ID)
@Size(min = 0, max = GenericConstants.MAX_ALLOWED_LENGTH_FINANCIAL_PORTFOLIO)
String pFinancialPortfolioId) {
return getUserTransactionService()
.fetchUserTransactionByCreationDate(pFinancialPortfolioId, dateMeantFor);
}
/**
* Fetch the lifetime average income / average expense /
*
* @param userPrincipal
* @param type
* @param fetchAverage
* @return
*/
@RequestMapping(value = "/lifetime", method = RequestMethod.GET)
public Object getLifetimeIncomeByFinancialPortfolioId(
@Valid @RequestParam(required = false, name = DashboardConstants.Overview.TYPE_PARAM)
TransactionType type,
@RequestParam(DashboardConstants.Overview.AVERAGE_PARAM) boolean fetchAverage,
@RequestParam(DashboardConstants.Overview.FINANCIAL_PORTFOLIO_ID)
@Size(min = 0, max = GenericConstants.MAX_ALLOWED_LENGTH_FINANCIAL_PORTFOLIO)
String pFinancialPortfolioId,
@Valid
@RequestParam(
required = false,
name = DashboardConstants.Overview.ACCOUNT_CATEGORIES_PARAM)
Optional<AccountCategories> accountCategories) {
// Check if the account type is present
if (accountCategories.isPresent()) {
return getBankAccountService()
.calculateTotal(accountCategories, pFinancialPortfolioId, fetchAverage);
}
return getUserTransactionService()
.fetchLifetimeCalculations(type, fetchAverage, pFinancialPortfolioId);
}
private IUserTransactionService getUserTransactionService() {
return userTransactionService;
}
private IBankAccountService getBankAccountService() {
return bankAccountService;
}
}
<file_sep>package in.co.everyrupee.service.income;
import in.co.everyrupee.pojo.income.Category;
import java.util.List;
public interface ICategoryService {
List<Category> fetchCategories();
Boolean categoryIncome(int categoryId);
}
<file_sep>package in.co.everyrupee.service.income;
import in.co.everyrupee.pojo.income.UserBudget;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.util.MultiValueMap;
public interface IUserBudgetService {
UserBudget saveAutoGeneratedUserBudget(
MultiValueMap<String, String> formData, String pFinancialPortfolioId);
List<UserBudget> updateAutoGeneratedBudget(
MultiValueMap<String, String> formData,
String formFieldName,
String financialPortfolioId,
String dateMeantFor);
void deleteAllUserBudgets(
String financialPortfolioId, String dateMeantFor, Boolean autoGenerated);
void deleteAutoGeneratedUserBudgets(
String categoryIds, String financialPortfolioId, String dateMeantFor);
List<UserBudget> fetchAllUserBudget(String pFinancialPortfolioId, String dateMeantFor);
List<UserBudget> fetchAutoGeneratedUserBudgetByCategoryIds(
String categoryIds, String pFinancialPortfolioId, String dateMeantFor);
void updateAutoGeneratedUserBudget(
String financialPortfolioId,
Map<Integer, Double> categoryIdAndCategoryTotal,
String dateMeantFor);
void deleteUserBudgets(String categoryIds, String financialPortfolioId, String dateMeantFor);
List<UserBudget> copyPreviousBudgetToSelectedMonth(
String financialPortfolioId, MultiValueMap<String, String> formData);
Set<Integer> fetchAllDatesWithUserBudget(String financialPortfolioId);
UserBudget changeCategoryWithUserBudget(
String financialPortfolioId, MultiValueMap<String, String> formData);
void deleteAllUserBudgets(String financialPortfolioId);
void copyFromPreviousMonth();
}
<file_sep>/** */
package in.co.everyrupee.events.user;
import in.co.everyrupee.pojo.income.UserTransaction;
import java.util.List;
import org.springframework.context.ApplicationEvent;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* On deleting the user transaction event
*
* @author Nagarjun
*/
public class OnDeleteUserTransactionCompleteEvent extends ApplicationEvent {
private static final long serialVersionUID = -2233313482197986444L;
private List<UserTransaction> userTransactionList;
public OnDeleteUserTransactionCompleteEvent(List<UserTransaction> userTransactionList) {
super(SecurityContextHolder.getContext().getAuthentication().getPrincipal());
this.userTransactionList = userTransactionList;
}
public List<UserTransaction> getUserTransactionList() {
return userTransactionList;
}
}
<file_sep>package in.co.everyrupee.controller.income;
import in.co.everyrupee.constants.GenericConstants;
import in.co.everyrupee.constants.income.DashboardConstants;
import in.co.everyrupee.pojo.income.UserBudget;
import in.co.everyrupee.service.income.IUserBudgetService;
import in.co.everyrupee.utils.GenericResponse;
import java.security.Principal;
import java.util.List;
import java.util.Set;
import javax.validation.constraints.Size;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Manage Budget For Users
*
* @author Nagarjun
*/
@RestController
@RequestMapping("/api/budget")
@Validated
public class UserBudgetController {
@Autowired private IUserBudgetService userBudgetService;
// Get All User Budgets
@RequestMapping(value = "/{financialPortfolioId}", method = RequestMethod.GET)
public List<UserBudget> getUserBudgetByFinancialPortfolioId(
@PathVariable String financialPortfolioId,
@RequestParam(DashboardConstants.Budget.DATE_MEANT_FOR) @Size(min = 0, max = 10)
String dateMeantFor) {
return getUserBudgetService().fetchAllUserBudget(financialPortfolioId, dateMeantFor);
}
// Save User Budgets
@RequestMapping(
value = "/save/{financialPortfolioId}",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public UserBudget updateAutoGeneratedUserBudget(
@PathVariable @Size(min = 0, max = GenericConstants.MAX_ALLOWED_LENGTH_FINANCIAL_PORTFOLIO)
String financialPortfolioId,
@RequestBody MultiValueMap<String, String> formData,
Principal userPrincipal) {
UserBudget userBudgetResponse =
getUserBudgetService().saveAutoGeneratedUserBudget(formData, financialPortfolioId);
return userBudgetResponse;
}
// Delete User Budgets
@RequestMapping(value = "/{financialPortfolioId}/{categoryIds}", method = RequestMethod.DELETE)
public GenericResponse deleteAutoGeneratedUserBudgetById(
@PathVariable @Size(min = 0, max = GenericConstants.MAX_ALLOWED_LENGTH_FINANCIAL_PORTFOLIO)
String financialPortfolioId,
@PathVariable String categoryIds,
Principal userPrincipal,
@RequestParam(DashboardConstants.Budget.DATE_MEANT_FOR) @Size(min = 0, max = 10)
String dateMeantFor,
@RequestParam(DashboardConstants.Budget.DELETE_ONLY_AUTO_GENERATED_BUDGET_PARAM)
Boolean deleteOnlyAutoGenerated) {
if (deleteOnlyAutoGenerated) {
getUserBudgetService()
.deleteAutoGeneratedUserBudgets(categoryIds, financialPortfolioId, dateMeantFor);
} else {
getUserBudgetService().deleteUserBudgets(categoryIds, financialPortfolioId, dateMeantFor);
}
return new GenericResponse("success");
}
// Delete All User Budgets
@RequestMapping(value = "/{financialPortfolioId}", method = RequestMethod.DELETE)
public GenericResponse deleteAllUserBudgetById(
@PathVariable @Size(min = 0, max = GenericConstants.MAX_ALLOWED_LENGTH_FINANCIAL_PORTFOLIO)
String financialPortfolioId,
@RequestParam(DashboardConstants.Budget.DATE_MEANT_FOR) @Size(min = 0, max = 10)
String dateMeantFor,
@RequestParam(DashboardConstants.Budget.AUTO_GENERATED_BUDGET_PARAM) Boolean autoGenerated) {
getUserBudgetService().deleteAllUserBudgets(financialPortfolioId, dateMeantFor, autoGenerated);
return new GenericResponse("success");
}
// Update budget in user budget
@RequestMapping(
value = "/{financialPortfolioId}/update/{formFieldName}/{dateMeantFor}",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public List<UserBudget> updateAutoGeneratedUserBudgetById(
@PathVariable @Size(min = 0, max = GenericConstants.MAX_ALLOWED_LENGTH_FINANCIAL_PORTFOLIO)
String financialPortfolioId,
@PathVariable @Size(min = 0, max = GenericConstants.MAX_ALLOWED_LENGTH_FINANCIAL_PORTFOLIO)
String formFieldName,
@PathVariable @Size(min = 0, max = 10) String dateMeantFor,
@RequestBody MultiValueMap<String, String> formData) {
List<UserBudget> userBudgetSaved =
getUserBudgetService()
.updateAutoGeneratedBudget(formData, formFieldName, financialPortfolioId, dateMeantFor);
return userBudgetSaved;
}
// Copy all previous budgeted month to the current month
@RequestMapping(
value = "/copyPreviousBudget/{financialPortfolioId}",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public List<UserBudget> copyPreviousBudgetById(
@PathVariable @Size(min = 0, max = GenericConstants.MAX_ALLOWED_LENGTH_FINANCIAL_PORTFOLIO)
String financialPortfolioId,
Principal userPrincipal,
@RequestBody MultiValueMap<String, String> formData) {
return getUserBudgetService().copyPreviousBudgetToSelectedMonth(financialPortfolioId, formData);
}
// Fetch all the dates with the user budget data for the user
@RequestMapping(
value = "/fetchAllDatesWithData/{financialPortfolioId}",
method = RequestMethod.GET)
public Set<Integer> fetchAllDatesWithUserBudgetById(
@PathVariable @Size(min = 0, max = GenericConstants.MAX_ALLOWED_LENGTH_FINANCIAL_PORTFOLIO)
String financialPortfolioId,
Principal userPrincipal) {
return getUserBudgetService().fetchAllDatesWithUserBudget(financialPortfolioId);
}
// Fetch all the dates with the user budget data for the user
@RequestMapping(
value = "/changeCategory/{financialPortfolioId}",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public UserBudget changeCategoryWithUserBudgetById(
@PathVariable @Size(min = 0, max = GenericConstants.MAX_ALLOWED_LENGTH_FINANCIAL_PORTFOLIO)
String financialPortfolioId,
Principal userPrincipal,
@RequestBody MultiValueMap<String, String> formData) {
UserBudget userBudgetSaved =
getUserBudgetService().changeCategoryWithUserBudget(financialPortfolioId, formData);
return userBudgetSaved;
}
/**
* Delete All User Budget
*
* @param financialPortfolioId
* @param dateMeantFor
* @param autoGenerated
* @return
*/
@RequestMapping(value = "/", method = RequestMethod.DELETE)
public GenericResponse deleteAllUserBudget(
@RequestParam @Size(min = 0, max = GenericConstants.MAX_ALLOWED_LENGTH_FINANCIAL_PORTFOLIO)
String financialPortfolioId) {
getUserBudgetService().deleteAllUserBudgets(financialPortfolioId);
return new GenericResponse("success");
}
// Fetch all the dates with the user budget data for the user
@RequestMapping(
value = "/copyFromPreviousMonth",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public GenericResponse copyFromPreviousMonth() {
getUserBudgetService().copyFromPreviousMonth();
return new GenericResponse("success");
}
public IUserBudgetService getUserBudgetService() {
return userBudgetService;
}
}
<file_sep>package in.co.everyrupee.service.income;
import in.co.everyrupee.pojo.TransactionType;
import in.co.everyrupee.pojo.income.UserTransaction;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.util.MultiValueMap;
public interface IUserTransactionService {
Object fetchUserTransaction(String financialPortfolioId, String dateMeantFor);
UserTransaction saveUserTransaction(
MultiValueMap<String, String> formData, String financialPortfolioId);
void deleteUserTransactions(
String transactionalIds, String financialPortfolioId, String dateMeantFor);
UserTransaction updateTransactions(
MultiValueMap<String, String> formData, String formFieldName, String financialPortfolioId);
Map<Integer, Double> fetchCategoryTotalAndUpdateUserBudget(
String financialPortfolioId, String dateMeantFor, boolean updateBudget);
List<UserTransaction> fetchUserTransactionByCreationDate(
String financialPortfolioId, String dateMeantFor);
Object fetchLifetimeCalculations(
TransactionType type, boolean fetchAverage, String pFinancialPortfolioId);
Double fetchUserTransactionCategoryTotal(
String financialPortfolioId, Integer categoryId, Date dateMeantFor);
void deleteUserTransactions(String pFinancialPortfolioId);
void deleteTransactionsByBankAccount(int bankAccountById);
void copyFromPreviousMonth();
}
<file_sep>package in.co.everyrupee.events.listener.income;
import in.co.everyrupee.events.user.OnDeleteBankAccountCompleteEvent;
import in.co.everyrupee.service.income.IUserTransactionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* Asynchronously delete transactions by account id
*
* @author Nagarjun
*/
@Component
public class DeleteTransactionsByAccountIdListener {
@Autowired private IUserTransactionService userTransactionsService;
Logger logger = LoggerFactory.getLogger(this.getClass());
/** Save Auto generated budget */
@Async
@EventListener
public void deleteTransactionsByAccountId(final OnDeleteBankAccountCompleteEvent event) {
userTransactionsService.deleteTransactionsByBankAccount(event.getBankAccountById());
}
}
<file_sep>package in.co.everyrupee.service.income;
import in.co.everyrupee.constants.GenericConstants;
import in.co.everyrupee.constants.income.DashboardConstants;
import in.co.everyrupee.exception.ResourceNotFoundException;
import in.co.everyrupee.pojo.income.Category;
import in.co.everyrupee.repository.income.CategoryRepository;
import in.co.everyrupee.utils.ERStringUtils;
import java.util.List;
import java.util.Optional;
import javax.transaction.Transactional;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Transactional
@Service
public class CategoryService implements ICategoryService {
@Autowired private CategoryRepository categoryRepository;
Logger LOGGER = LoggerFactory.getLogger(this.getClass());
@Override
@Cacheable(value = DashboardConstants.Category.CATEGORY_CACHE_NAME, key = "#root.method.name")
public List<Category> fetchCategories() {
List<Category> categoriesList = categoryRepository.fetchAllCategories();
if (CollectionUtils.isEmpty(categoriesList)) {
throw new ResourceNotFoundException("Category", "categories", "all");
}
return categoriesList;
}
@Override
@Cacheable(value = DashboardConstants.Category.CATEGORY_INCOME_OR_NOT, key = "#categoryId")
public Boolean categoryIncome(int categoryId) {
List<Category> categoriesList = categoryRepository.fetchAllCategories();
if (CollectionUtils.isEmpty(categoriesList)) {
throw new ResourceNotFoundException("Category", "categories", "all");
}
Optional<Category> category =
categoriesList.stream().filter(x -> categoryId == x.getCategoryId()).findFirst();
if (category.isPresent()) {
Category currentCategory = category.get();
boolean categoryIncome =
ERStringUtils.equalsIgnoreCase(
currentCategory.getParentCategory(), GenericConstants.INCOME_CATEGORY);
LOGGER.debug(
"Category to search is "
+ categoryId
+ " which is a category income - "
+ categoryIncome);
if (categoryIncome) {
return true;
}
return false;
}
return false;
}
}
<file_sep>package in.co.everyrupee.configuration;
import java.util.concurrent.Executor;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
* Create a custom Async Configuration which overrides the default core size, max size and pool size
* for efficiency
*
* @author nagarjun
*/
@EnableAsync
@Configuration
@ConfigurationProperties(prefix = "async.thread.pool")
public class AsyncConfiguration implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
executor.setThreadNamePrefix("worker-exec-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
/** Custom exception for async errors */
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return (ex, method, params) -> {
Class<?> targetClass = method.getDeclaringClass();
Logger logger = LoggerFactory.getLogger(targetClass);
logger.error(ex.getMessage(), ex);
};
}
}
<file_sep>package in.co.everyrupee.repository.income;
import in.co.everyrupee.pojo.income.UserBudget;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
/**
* Repository to handle the budget for the user
*
* @author Nagarjun
*/
@Repository
public interface UserBudgetRepository extends JpaRepository<UserBudget, BigInteger> {
/**
* Fetch all user budget by financial portfolio id
*
* @param financialPortfolioId
* @return
*/
List<UserBudget> findByFinancialPortfolioId(String financialPortfolioId);
/**
* Fetches all user with category ids specified in {@code ids} parameter
*
* @param ids List of category ids
*/
@Query("SELECT u FROM UserBudget u where u.financialPortfolioId in ?1 and u.dateMeantFor in ?2")
List<UserBudget> fetchAllUserBudget(String financialPortfolioId, Date dateMeantFor);
/**
* Fetches all user with category ids specified in {@code ids} parameter
*
* @param ids List of category ids
*/
@Query(
"SELECT u FROM UserBudget u where u.categoryId in ?1 and u.financialPortfolioId in ?2 and"
+ " u.dateMeantFor in ?3 and u.autoGeneratedBudget is true")
List<UserBudget> fetchAutoGeneratedUserBudgetWithCategoryIds(
List<Integer> categoryIds, String financialPortfolioId, Date dateMeantFor);
/**
* Delete all user budget with category ids specified in {@code ids} parameter with auto
* generation as true
*
* @param ids List of category ids
*/
@Modifying
@Query(
"delete from UserBudget u where u.categoryId in ?1 and u.financialPortfolioId in ?2 and"
+ " u.autoGeneratedBudget is true and u.dateMeantFor in ?3")
void deleteAutoGeneratedUserBudgetWithCategoryIds(
List<Integer> categoryIds, String financialPortfolioId, Date dateMeantFor);
/**
* Delete all user budget with financial portfolio id and the chosen date and auto generated as
* true/false
*
* @param ids List of category ids
*/
@Modifying
@Query(
"delete from UserBudget u where u.financialPortfolioId in ?1 and u.dateMeantFor in ?2 and"
+ " u.autoGeneratedBudget is ?3")
void deleteAllUserBudget(
String financialPortfolioId, Date dateMeantFor, boolean autoGeneratedBudget);
/**
* Delete all user budget with financial portfolio id and the chosen date
*
* @param ids List of category ids
*/
@Modifying
@Query("delete from UserBudget u where u.financialPortfolioId in ?1 and u.dateMeantFor in ?2")
void deleteAllUserBudget(String financialPortfolioId, Date dateMeantFor);
/**
* Fetches all user with category ids specified in {@code ids} parameter
*
* @param ids List of category ids
*/
@Query(
"SELECT u FROM UserBudget u where u.categoryId in ?1 and u.financialPortfolioId in ?2 and"
+ " u.dateMeantFor in ?3")
List<UserBudget> fetchUserBudgetWithCategoryIds(
List<Integer> categoryIds, String financialPortfolioId, Date dateMeantFor);
/**
* Delete all user budget with category ids specified in {@code ids} parameter
*
* @param ids List of category ids
*/
@Modifying
@Query(
"delete from UserBudget u where u.categoryId in ?1 and u.financialPortfolioId in ?2 and"
+ " u.dateMeantFor in ?3")
void deleteUserBudgetWithCategoryIds(
List<Integer> categoryIdsAsIntegerList, String financialPortfolioId, Date date);
/**
* Fetch all user dates by financial portfolio id
*
* @param financialPortfolioId
* @return
*/
@Query("SELECT u.dateMeantFor FROM UserBudget u where u.financialPortfolioId in ?1")
List<Date> findAllDatesByFPId(String financialPortfolioId);
/**
* Delete all user budget with financial portfolio id
*
* @param ids List of category ids
*/
@Modifying
@Query("delete from UserBudget u where u.financialPortfolioId in ?1")
void deleteAllUserBudgets(String financialPortfolioId);
/**
* Fetch all user budget by date
*
* @param financialPortfolioId
* @return
*/
@Query("SELECT u FROM UserBudget u where u.dateMeantFor in ?1")
List<UserBudget> findAllBudgetsFromDate(Date from);
}
<file_sep>package in.co.everyrupee.pojo.income;
import in.co.everyrupee.constants.income.DashboardConstants;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.PositiveOrZero;
import javax.validation.constraints.Size;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import org.springframework.beans.factory.annotation.Value;
/**
* POJO for User Budget
*
* @author Nagarjun
*/
@Entity
@Table(name = DashboardConstants.Budget.USER_BUDGET_TABLE)
public class UserBudget implements Serializable {
/** */
private static final long serialVersionUID = 234253456352089085L;
@Id
@Column(name = DashboardConstants.Budget.BUDGET_ID)
private BigInteger budgetId;
@NotNull
@Column(name = DashboardConstants.Budget.FINANCIAL_PORTFOLIO_ID)
@Size(max = 60)
private String financialPortfolioId;
@NotNull
@Column(name = DashboardConstants.Budget.CATEGORY_ID)
@PositiveOrZero
private int categoryId;
@NotNull
@Column(name = DashboardConstants.Budget.PLANNED)
private double planned;
@NotNull
@Value("${value.autoGeneratedBudgetDefault:true}")
@Column(
name = DashboardConstants.Budget.AUTO_GENERATED_BUDGET,
columnDefinition = DashboardConstants.BOOLEAN_DEFAULT_TRUE,
nullable = false)
private boolean autoGeneratedBudget;
@NotNull
@Column(name = DashboardConstants.Budget.DATE_MEANT_FOR)
@Temporal(TemporalType.TIMESTAMP)
private Date dateMeantFor;
@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = DashboardConstants.CREATION_DATE, nullable = false, updatable = false)
private Date createDate;
@UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = DashboardConstants.MODIFICATION_DATE)
private Date modifyDate;
@PrePersist
protected void onCreate() {
if (getDateMeantFor() == null) {
setDateMeantFor(new Date());
}
}
public BigInteger getBudgetId() {
return budgetId;
}
public void setBudgetId(BigInteger budgetId) {
this.budgetId = budgetId;
}
public String getFinancialPortfolioId() {
return financialPortfolioId;
}
public void setFinancialPortfolioId(String financialPortfolioId) {
this.financialPortfolioId = financialPortfolioId;
}
public int getCategoryId() {
return categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
public double getPlanned() {
return planned;
}
public void setPlanned(double planned) {
this.planned = planned;
}
public Date getDateMeantFor() {
return dateMeantFor;
}
public void setDateMeantFor(Date dateMeantFor) {
this.dateMeantFor = dateMeantFor;
}
/** @return the autoGeneratedBudget */
public boolean getAutoGeneratedBudget() {
return autoGeneratedBudget;
}
/** @param autoGeneratedBudget the autoGeneratedBudget to set */
public void setAutoGeneratedBudget(boolean autoGeneratedBudget) {
this.autoGeneratedBudget = autoGeneratedBudget;
}
}
<file_sep>insert into every_rupee.category (category_id, category_name, parent_category) VALUES (1, "Expenses", "");
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (2, "Income", "");
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (3, "Beauty", 1);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (4, "Bills & Fees", 1);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (5, "Car", 1);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (6, "Education", 1);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (7, "Entertainment", 1);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (8, "Family & Personal", 1);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (9, "Gifts", 1);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (10, "Groceries", 1);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (11, "Heathcare", 1);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (12, "Home", 1);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (13, "Other", 1);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (14, "Shopping", 1);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (15, "Sport & Hobbies", 1);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (16, "Transport", 1);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (17, "Travel", 1);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (18, "Work", 1);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (19, "Business", 2);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (20, "Extra Income", 2);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (21, "Gifts", 2);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (22, "Insurance Payout", 2);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (23, "Salary", 2);
insert into every_rupee.category (category_id, category_name, parent_category) VALUES (24, "Other", 2);
commit;
<file_sep>buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "com.gradle:build-scan-plugin:1.16"
}
}
plugins {
id 'java'
id "org.sonarqube" version "3.3"
id 'org.springframework.boot' version '2.1.3.RELEASE'
id 'io.spring.dependency-management' version '1.0.7.RELEASE'
}
group = 'com.blitzbudget'
version = '0.0.1-SNAPSHOT'
bootJar {
baseName = 'bb-core'
version = '0.5.40'
}
apply plugin : 'eclipse'
// Default Spring Profile
//springProfile = 'dev'
repositories {
mavenCentral()
maven { url 'https://repo.spring.io/milestone' }
maven { url 'https://repo.spring.io/snapshot' }
}
dependencies {
implementation("org.apache.commons:commons-collections4:4.0")
implementation("org.passay:passay:1.4.0")
implementation("com.google.guava:guava:20.0")
implementation("org.springframework:spring-web")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-mail")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("mysql:mysql-connector-java")
implementation("org.apache.commons:commons-lang3:3.9")
implementation("org.springframework.boot:spring-boot-configuration-processor")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.springframework.security:spring-security-test")
testImplementation('org.springframework.boot:spring-boot-starter-cache')
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation('org.springframework.boot:spring-boot-starter-test')
}
bootRun {
bootRun.systemProperty 'spring.profiles.active', "dev"
}
task unpack(type: Copy) {
dependsOn bootJar
from(zipTree(tasks.bootJar.outputs.files.singleFile))
into("build/dependency")
}
sonarqube {
properties {
property "sonar.projectKey", "NagarjunNagesh_every-rupee-api"
property "sonar.organization", "blitzbudget"
property "sonar.host.url", "https://sonarcloud.io"
}
}
<file_sep>package in.co.everyrupee.controller.income;
import in.co.everyrupee.constants.GenericConstants;
import in.co.everyrupee.constants.income.DashboardConstants;
import in.co.everyrupee.pojo.income.UserTransaction;
import in.co.everyrupee.service.income.IUserTransactionService;
import in.co.everyrupee.utils.GenericResponse;
import java.security.Principal;
import java.util.Map;
import javax.validation.constraints.Size;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Manage API User Transactions
*
* @author <NAME>
*/
@RestController
@RequestMapping("/api/transactions")
@Validated
public class UserTransactionsController {
@Autowired private IUserTransactionService userTransactionService;
/**
* Get User Transactions with Financial Portfolio Id
*
* @param pFinancialPortfolioId
* @param userPrincipal
* @return
*/
@RequestMapping(value = "/{pFinancialPortfolioId}", method = RequestMethod.GET)
public Object getUserTransactionByFinancialPortfolioId(
@PathVariable @Size(min = 0, max = GenericConstants.MAX_ALLOWED_LENGTH_FINANCIAL_PORTFOLIO)
String pFinancialPortfolioId,
Principal userPrincipal,
@RequestParam(DashboardConstants.Transactions.DATE_MEANT_FOR) @Size(min = 0, max = 10)
String dateMeantFor) {
return userTransactionService.fetchUserTransaction(pFinancialPortfolioId, dateMeantFor);
}
/**
* Fetch category total and update user budget
*
* @param pFinancialPortfolioId
* @param userPrincipal
* @return
*/
@RequestMapping(value = "/categoryTotal/{pFinancialPortfolioId}", method = RequestMethod.GET)
public Map<Integer, Double> getCategoryTotalByFinancialPortfolioId(
@PathVariable @Size(min = 0, max = GenericConstants.MAX_ALLOWED_LENGTH_FINANCIAL_PORTFOLIO)
String pFinancialPortfolioId,
@RequestParam(DashboardConstants.Transactions.DATE_MEANT_FOR) @Size(min = 0, max = 10)
String dateMeantFor,
@RequestParam(DashboardConstants.Transactions.UPDATE_BUDGET_PARAM) boolean updateBudget) {
return userTransactionService.fetchCategoryTotalAndUpdateUserBudget(
pFinancialPortfolioId, dateMeantFor, updateBudget);
}
/**
* Saves a UserTransaction
*
* @param pFinancialPortfolioId
* @param formData
* @param userPrincipal
* @return
*/
@RequestMapping(
value = "/save/{pFinancialPortfolioId}",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public UserTransaction save(
@PathVariable @Size(min = 0, max = GenericConstants.MAX_ALLOWED_LENGTH_FINANCIAL_PORTFOLIO)
String pFinancialPortfolioId,
@RequestBody MultiValueMap<String, String> formData,
Principal userPrincipal) {
UserTransaction userTransactionResponse =
userTransactionService.saveUserTransaction(formData, pFinancialPortfolioId);
return userTransactionResponse;
}
/**
* Delete a User Transaction
*
* @param pFinancialPortfolioId
* @param transactionIds
* @param userPrincipal
* @return
*/
@RequestMapping(
value = "/{pFinancialPortfolioId}/{transactionIds}",
method = RequestMethod.DELETE)
public GenericResponse deleteUserTransactionById(
@PathVariable @Size(min = 0, max = GenericConstants.MAX_ALLOWED_LENGTH_FINANCIAL_PORTFOLIO)
String pFinancialPortfolioId,
@PathVariable String transactionIds,
Principal userPrincipal,
@RequestParam(DashboardConstants.Transactions.DATE_MEANT_FOR) @Size(min = 0, max = 10)
String dateMeantFor) {
userTransactionService.deleteUserTransactions(
transactionIds, pFinancialPortfolioId, dateMeantFor);
return new GenericResponse("success");
}
/**
* Update description, transaction & category in user transactions
*
* @param pFinancialPortfolioId
* @param formFieldName
* @param formData
* @param userPrincipal
* @return
*/
@RequestMapping(
value = "/{pFinancialPortfolioId}/update/{formFieldName}",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public UserTransaction updateDescriptionByUserTransactionById(
@PathVariable @Size(min = 0, max = GenericConstants.MAX_ALLOWED_LENGTH_FINANCIAL_PORTFOLIO)
String pFinancialPortfolioId,
@PathVariable @Size(min = 0, max = GenericConstants.MAX_ALLOWED_LENGTH_FINANCIAL_PORTFOLIO)
String formFieldName,
@RequestBody MultiValueMap<String, String> formData,
Principal userPrincipal) {
UserTransaction userTransactionSaved =
userTransactionService.updateTransactions(formData, formFieldName, pFinancialPortfolioId);
return userTransactionSaved;
}
/**
* Delete all User Transactions
*
* @param pFinancialPortfolioId
* @return
*/
@RequestMapping(value = "/{pFinancialPortfolioId}", method = RequestMethod.DELETE)
public GenericResponse deleteAllUserTransactions(
@PathVariable @Size(min = 0, max = GenericConstants.MAX_ALLOWED_LENGTH_FINANCIAL_PORTFOLIO)
String pFinancialPortfolioId) {
userTransactionService.deleteUserTransactions(pFinancialPortfolioId);
return new GenericResponse("success");
}
// Fetch all the dates with the user budget data for the user
@RequestMapping(
value = "/copyFromPreviousMonth",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public GenericResponse copyFromPreviousMonth() {
userTransactionService.copyFromPreviousMonth();
return new GenericResponse("success");
}
}
<file_sep>package in.co.everyrupee.constants.user;
public final class BankAccountConstants {
// Prevent instantiation
private BankAccountConstants() {}
public static final String BANK_ACCOUNT_TABLE = "bank_account";
public static final String BANK_ACCOUNT_ID = "id";
public static final String BANK_ACCOUNT_NAME = "bank_account_name";
public static final String LINKED_ACCOUNT = "linked";
public static final String BANK_ACCOUNT_NUMBER = "bank_account_number";
public static final String FINANCIAL_PORTFOLIO_ID = "financial_portfolio_id";
public static final String ACCOUNT_BALANCE = "account_balance";
public static final String USER_ID = "user_id";
public static final String BANK_ACCOUNT_CACHE = "bankAccountCache";
public static final String BANK_ACCOUNT_NAME_PARAM = "bankAccountName";
public static final String LINKED_ACCOUNT_PARAM = "linked";
public static final String ACCOUNT_BALANCE_PARAM = "accountBalance";
public static final String ACCOUNT_TYPE = "account_type";
public static final String ACCOUNT_TYPE_COLUMN_DEFINITION = "varchar(64) default 'CASH'";
public static final String ACCOUNT_TYPE_PARAM = "accountType";
public static final String SELECTED_ACCOUNT = "selected_account";
public static final String SELECTED_ACCOUNT_PARAM = "selectedAccount";
public static final String NUMBER_OF_TIMES_SELECTED = "number_of_times_selected";
public static final String FINANCIAL_PORTFOLIO_ID_PARAM = "financialPortfolioId";
public static final String USER_ID_PARAM = "userId";
public static final String TRANSFER_TO_ACCOUNT = "transferToAccount";
}
<file_sep>package in.co.everyrupee.controller.overview;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import in.co.everyrupee.constants.income.DashboardConstants;
import in.co.everyrupee.pojo.TransactionType;
import in.co.everyrupee.pojo.user.AccountCategories;
import in.co.everyrupee.pojo.user.AccountType;
import in.co.everyrupee.pojo.user.BankAccount;
import in.co.everyrupee.repository.income.UserTransactionsRepository;
import in.co.everyrupee.repository.user.BankAccountRepository;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
/**
* Overview Controller Test (Controller)
*
* @author Nagarjun
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class OverviewIntegrationTest {
@Autowired private WebApplicationContext context;
@MockBean private UserTransactionsRepository userTransactionRepository;
@MockBean private BankAccountRepository bankAccountRepository;
private List<BankAccount> allBankAccounts;
private MockMvc mvc;
private static final String DATE_MEANT_FOR = "01082019";
private static final String FINANCIAL_PORTFOLIO_ID = "193000000";
@Before
public void setUp() {
setMvc(MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build());
// Build data
BankAccount bankAccount2 = new BankAccount();
bankAccount2.setFinancialPortfolioId(FINANCIAL_PORTFOLIO_ID);
bankAccount2.setLinked(true);
bankAccount2.setBankAccountName("ABCD");
bankAccount2.setNumberOfTimesSelected(100);
bankAccount2.setAccountBalance(324);
bankAccount2.setAccountType(AccountType.CASH);
BankAccount bankAccount = new BankAccount();
bankAccount.setFinancialPortfolioId(FINANCIAL_PORTFOLIO_ID);
bankAccount.setLinked(false);
bankAccount.setBankAccountName("EFGH");
bankAccount.setNumberOfTimesSelected(1);
bankAccount.setAccountBalance(100);
bankAccount.setAccountType(AccountType.CREDITCARD);
setAllBankAccounts(new ArrayList<BankAccount>());
getAllBankAccounts().add(bankAccount);
getAllBankAccounts().add(bankAccount2);
}
/**
* TEST: Get User Transactions by financial Portfolio id
*
* @throws Exception
*/
@WithMockUser(value = "spring")
@Test
public void getUserTransactionsByFinancialPortfolioId() throws Exception {
getMvc()
.perform(
get("/api/overview/recentTransactions")
.contentType(MediaType.APPLICATION_JSON)
.param(DashboardConstants.Overview.DATE_MEANT_FOR, DATE_MEANT_FOR)
.param(DashboardConstants.Overview.FINANCIAL_PORTFOLIO_ID, FINANCIAL_PORTFOLIO_ID))
.andExpect(status().isOk());
verify(getUserTransactionRepository(), times(1))
.findByFinancialPortfolioIdAndDate(Mockito.anyString(), Mockito.any());
}
/**
* TEST: Get lifetime income by financial Portfolio id
*
* @throws Exception
*/
@WithMockUser(value = "spring")
@Test
public void getLifetimeIncomeByFinancialPortfolioId() throws Exception {
getMvc()
.perform(
get("/api/overview/lifetime")
.contentType(MediaType.APPLICATION_JSON)
.param(DashboardConstants.Overview.TYPE_PARAM, TransactionType.INCOME.toString())
.param(DashboardConstants.Overview.AVERAGE_PARAM, "true")
.param(DashboardConstants.Overview.FINANCIAL_PORTFOLIO_ID, FINANCIAL_PORTFOLIO_ID))
.andExpect(status().isOk());
verify(getUserTransactionRepository(), times(1))
.findByFinancialPortfolioIdAndCategories(Mockito.anyString(), Mockito.any());
when(getBankAccountRepository().findByFinancialPortfolioId(FINANCIAL_PORTFOLIO_ID))
.thenReturn(getAllBankAccounts());
getMvc()
.perform(
get("/api/overview/lifetime")
.contentType(MediaType.APPLICATION_JSON)
.param(
DashboardConstants.Overview.ACCOUNT_CATEGORIES_PARAM,
AccountCategories.ALL.toString())
.param(DashboardConstants.Overview.AVERAGE_PARAM, "true")
.param(DashboardConstants.Overview.FINANCIAL_PORTFOLIO_ID, FINANCIAL_PORTFOLIO_ID))
.andExpect(status().isOk())
.andExpect(jsonPath("$").isNotEmpty());
}
private MockMvc getMvc() {
return mvc;
}
private void setMvc(MockMvc mvc) {
this.mvc = mvc;
}
private UserTransactionsRepository getUserTransactionRepository() {
return userTransactionRepository;
}
private BankAccountRepository getBankAccountRepository() {
return bankAccountRepository;
}
private List<BankAccount> getAllBankAccounts() {
return allBankAccounts;
}
private void setAllBankAccounts(List<BankAccount> allBankAccounts) {
this.allBankAccounts = allBankAccounts;
}
}
<file_sep>package in.co.everyrupee.service.user;
import in.co.everyrupee.constants.user.BankAccountConstants;
import in.co.everyrupee.events.user.OnDeleteBankAccountCompleteEvent;
import in.co.everyrupee.exception.InvalidAttributeValueException;
import in.co.everyrupee.pojo.user.AccountCategories;
import in.co.everyrupee.pojo.user.AccountType;
import in.co.everyrupee.pojo.user.BankAccount;
import in.co.everyrupee.repository.user.BankAccountRepository;
import in.co.everyrupee.utils.ERStringUtils;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.Valid;
import javax.validation.constraints.Size;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
@Transactional
@Service
@CacheConfig(cacheNames = {BankAccountConstants.BANK_ACCOUNT_CACHE})
public class BankAccountService implements IBankAccountService {
@Autowired private BankAccountRepository bankAccountRepository;
@Autowired private ApplicationEventPublisher eventPublisher;
Logger LOGGER = LoggerFactory.getLogger(this.getClass());
@Override
@Cacheable(key = "#pFinancialPortfolioId")
public List<BankAccount> getAllBankAccounts(String pFinancialPortfolioId) {
return bankAccountRepository.findByFinancialPortfolioId(pFinancialPortfolioId);
}
@Override
@CacheEvict(key = "#formData.getFirst(\"financialPortfolioId\")")
public BankAccount addNewBankAccount(MultiValueMap<String, String> formData) {
if (ERStringUtils.isBlank(formData.getFirst(BankAccountConstants.LINKED_ACCOUNT))) {
throw new InvalidAttributeValueException(
"addNewBankAccount", BankAccountConstants.LINKED_ACCOUNT, null);
}
BankAccount newAccount = new BankAccount();
newAccount.setLinked(
Boolean.parseBoolean(formData.getFirst(BankAccountConstants.LINKED_ACCOUNT_PARAM)));
newAccount.setFinancialPortfolioId(
formData.getFirst(BankAccountConstants.FINANCIAL_PORTFOLIO_ID_PARAM));
newAccount.setBankAccountName(formData.getFirst(BankAccountConstants.BANK_ACCOUNT_NAME_PARAM));
newAccount.setAccountBalance(
Double.parseDouble(formData.getFirst(BankAccountConstants.ACCOUNT_BALANCE_PARAM)));
// Replace all space in the text to without space
newAccount.setAccountType(
AccountType.valueOf(
formData.getFirst(BankAccountConstants.ACCOUNT_TYPE_PARAM).replaceAll("\\s+", "")));
return bankAccountRepository.save(newAccount);
}
@Override
public List<BankAccount> previewBankAccounts(String financialPortfolioId) {
List<BankAccount> linkedBA = getAllBankAccounts(financialPortfolioId);
List<BankAccount> selectedBA = new ArrayList<BankAccount>();
// Fetch the first selected account
for (BankAccount bankAccount : linkedBA) {
if (bankAccount.isSelectedAccount()) {
selectedBA.add(bankAccount);
break;
}
}
// Sort the list of bank accounts by number of times selected
linkedBA.sort(Comparator.comparing(BankAccount::getNumberOfTimesSelected).reversed());
int count = 0;
for (BankAccount bankAccount : linkedBA) {
// Fetches the first four accounts for preview
if (count >= 3) {
break;
}
// If there is none selected then set the first one as selected
if (CollectionUtils.isEmpty(selectedBA)) {
bankAccount.setSelectedAccount(true);
// Saves the bank account as selected and stores the result in the selectedBA
selectedBA.add(bankAccountRepository.save(bankAccount));
continue;
} else if (selectedBA.get(0).getId() == bankAccount.getId()) {
// If the bank account is already present in the object (selectedBA)
continue;
}
selectedBA.add(bankAccount);
count++;
}
return selectedBA;
}
@Override
public void selectAccount(MultiValueMap<String, String> formData) {
String bankAccountId = formData.getFirst(BankAccountConstants.BANK_ACCOUNT_ID);
String selectedAccount = formData.getFirst(BankAccountConstants.SELECTED_ACCOUNT_PARAM);
List<BankAccount> bankAccountList = bankAccountRepository.findAll();
// Convert bank account to selected
for (BankAccount bankAccount : bankAccountList) {
if (bankAccount.getId() == Integer.parseInt(bankAccountId)) {
bankAccount.setSelectedAccount(Boolean.parseBoolean(selectedAccount));
bankAccount.setNumberOfTimesSelected(bankAccount.getNumberOfTimesSelected() + 1);
bankAccountRepository.save(bankAccount);
} else if (bankAccount.isSelectedAccount()) {
bankAccount.setSelectedAccount(false);
bankAccountRepository.save(bankAccount);
}
}
}
@Override
public Map<String, Set<BankAccount>> categorizeBankAccount(String pFinancialPortfolioId) {
List<BankAccount> bankAccountList = getAllBankAccounts(pFinancialPortfolioId);
Map<String, Set<BankAccount>> categorizeBankAccount = new HashMap<String, Set<BankAccount>>();
for (BankAccount bankAccount : bankAccountList) {
Set<BankAccount> bankAccountSet = new HashSet<BankAccount>();
if (categorizeBankAccount.keySet().contains(bankAccount.getAccountType().getType())) {
bankAccountSet = categorizeBankAccount.get(bankAccount.getAccountType().getType());
}
bankAccountSet.add(bankAccount);
categorizeBankAccount.put(bankAccount.getAccountType().getType(), bankAccountSet);
}
return categorizeBankAccount;
}
@Override
@CacheEvict(key = "#pFinancialPortfolioId")
public void deleteAllBankAccounts(String pFinancialPortfolioId) {
bankAccountRepository.deleteAllBankAccounts(pFinancialPortfolioId);
}
@Override
public BankAccount fetchSelectedAccount(String pFinancialPortfolioId) {
BankAccount bankAccount = new BankAccount();
List<BankAccount> bankAccountList =
bankAccountRepository.findSelectedAccountsByFinancialPortfolioId(pFinancialPortfolioId);
if (CollectionUtils.isNotEmpty(bankAccountList)) {
bankAccount = bankAccountList.get(0);
} else {
// Create a cash account and
BankAccount newAccount = new BankAccount();
newAccount.setLinked(false);
newAccount.setSelectedAccount(true);
newAccount.setFinancialPortfolioId(pFinancialPortfolioId);
newAccount.setBankAccountName(AccountType.CASH.toString());
newAccount.setAccountBalance(0d);
newAccount.setAccountType(AccountType.CASH);
bankAccount = bankAccountRepository.save(newAccount);
}
return bankAccount;
}
@Override
@CacheEvict(key = "#bankAccount.getFinancialPortfolioId()")
public void updateBankBalance(BankAccount bankAccount, Double amountModified) {
// If amountModified is null then return
if (amountModified == null
|| amountModified.isNaN()
|| amountModified.isInfinite()
|| bankAccount == null) {
LOGGER.warn(
"Unable to update the account balance as the amount modified is {0} and the bank account"
+ " is {1}",
amountModified, bankAccount);
return;
}
// Update the new bank balance
bankAccount.setAccountBalance(bankAccount.getAccountBalance() + amountModified);
bankAccountRepository.save(bankAccount);
}
@Override
@CacheEvict(key = "#bankAccountOld.getFinancialPortfolioId()")
public BankAccount updateBankAccount(String bankAccountId, BankAccount bankAccountOld) {
Optional<BankAccount> bankAccount =
bankAccountRepository.findById(Integer.parseInt(bankAccountId));
if (bankAccount.isPresent()) {
bankAccount.get().setAccountBalance(bankAccountOld.getAccountBalance());
return bankAccountRepository.save(bankAccount.get());
}
LOGGER.warn(
"Bank account with Id {0} was not found for the financial portfolio id {1}",
bankAccountId, bankAccountOld.getFinancialPortfolioId());
return null;
}
@Override
@CacheEvict(key = "#pFinancialPortfolioId")
public void deleteBankAccount(
@Size(min = 0, max = 60) String pBankAccountId,
@Size(min = 0, max = 60) String pFinancialPortfolioId) {
int bankAccountIdInt = Integer.parseInt(pBankAccountId);
bankAccountRepository.deleteById(bankAccountIdInt);
// Delete all transactions with account ID
eventPublisher.publishEvent(new OnDeleteBankAccountCompleteEvent(bankAccountIdInt));
}
@Override
public Optional<BankAccount> fetchBankAccountById(Integer accountId) {
return bankAccountRepository.findById(accountId);
}
@Override
public List<BankAccount> fetchAllBankAccount(Set<Integer> accountIds) {
return bankAccountRepository.findAllById(accountIds);
}
@Override
public void saveAll(List<BankAccount> bankAccountList) {
bankAccountRepository.saveAll(bankAccountList);
}
@Override
public Object calculateTotal(
@Valid Optional<AccountCategories> accountCategories,
@Size(min = 0, max = 60) String pFinancialPortfolioId,
boolean fetchAverage) {
if (pFinancialPortfolioId == null) {
throw new InvalidAttributeValueException(
"fetchUserTransactionByCreationDate", "financialPortfolioId", pFinancialPortfolioId);
}
switch (accountCategories.get()) {
case ASSET:
// TODO
case LIABILITY:
// TODO
case ALL:
return calculateAllAccountBalance(fetchAverage, pFinancialPortfolioId);
default:
LOGGER.error("fetchLifetimeCalculations: TransactionType is not mapped to the ENUM class");
break;
}
return null;
}
/**
* Calculate account balance for all accounts
*
* @param fetchAverage
* @param pFinancialPortfolioId
* @return
*/
private Object calculateAllAccountBalance(
boolean fetchAverage, @Size(min = 0, max = 60) String pFinancialPortfolioId) {
if (fetchAverage) {
List<BankAccount> bankAccounts =
bankAccountRepository.findByFinancialPortfolioId(pFinancialPortfolioId);
// Segregate bank account by ASSET / LIABILITY
Map<Boolean, List<BankAccount>> bankAccountByType =
bankAccounts.parallelStream()
.collect(
Collectors.partitioningBy(
ba ->
(ba.getAccountType().equals(AccountType.CREDITCARD)
|| ba.getAccountType().equals(AccountType.LIABILITY))));
List<BankAccount> liabliltyBA = bankAccountByType.get(true);
List<BankAccount> assetBA = bankAccountByType.get(false);
// Calculate the subtotal and return
Map<String, Double> assetAndLiableAmount = new HashMap<>();
double liabileAmount = 0d;
if (CollectionUtils.isNotEmpty(liabliltyBA)) {
liabileAmount =
liabliltyBA.parallelStream()
.collect(Collectors.summingDouble(BankAccount::getAccountBalance));
}
// Assign Liable Amount
assetAndLiableAmount.put("liability", liabileAmount);
double assetAmount = 0d;
if (CollectionUtils.isNotEmpty(assetBA)) {
assetAmount =
assetBA.parallelStream()
.collect(Collectors.summingDouble(BankAccount::getAccountBalance));
}
// Assign asset amount
assetAndLiableAmount.put("asset", assetAmount);
return assetAndLiableAmount;
}
return null;
}
}
<file_sep>/** */
package in.co.everyrupee.event.listener.user;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import in.co.everyrupee.events.user.OnAffectBankAccountBalanceEvent;
import in.co.everyrupee.pojo.user.BankAccount;
import in.co.everyrupee.repository.user.BankAccountRepository;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Bank Account Balance Update Listener Test (Listener)
*
* @author Nagarjun
*/
@RunWith(SpringRunner.class)
public class BankAccountBalanceUpdateListenerTest {
@Autowired private ApplicationEventPublisher eventPublisher;
@MockBean private BankAccountRepository bankAccountRepository;
private static final int ACCOUNT_ID = 1930;
@Before
public void setup() {
BankAccount bankAccount = new BankAccount();
bankAccount.setAccountBalance(12d);
bankAccount.setId(ACCOUNT_ID);
when(getBankAccountRepository().findById(ACCOUNT_ID)).thenReturn(Optional.of(bankAccount));
}
@Test
@WithMockUser(value = "spring")
public void updateBankAccountBalance() {
eventPublisher.publishEvent(new OnAffectBankAccountBalanceEvent(null, 11d, ACCOUNT_ID));
// Check if ASYNC is invoked properly
verify(getBankAccountRepository(), times(0)).findById(ACCOUNT_ID);
}
private BankAccountRepository getBankAccountRepository() {
return bankAccountRepository;
}
}
<file_sep>/** */
package in.co.everyrupee.events.user;
import org.springframework.context.ApplicationEvent;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* On deleting the user transaction event
*
* @author Nagarjun
*/
public class OnDeleteBankAccountCompleteEvent extends ApplicationEvent {
private static final long serialVersionUID = -2233313482197986444L;
private int bankAccountById;
public OnDeleteBankAccountCompleteEvent(int bankAccountById) {
super(SecurityContextHolder.getContext().getAuthentication().getPrincipal());
this.bankAccountById = bankAccountById;
}
public int getBankAccountById() {
return bankAccountById;
}
}
<file_sep>package in.co.everyrupee.controller.income;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import in.co.everyrupee.constants.income.DashboardConstants;
import in.co.everyrupee.pojo.RecurrencePeriod;
import in.co.everyrupee.pojo.income.UserTransaction;
import in.co.everyrupee.pojo.user.BankAccount;
import in.co.everyrupee.repository.income.UserTransactionsRepository;
import in.co.everyrupee.repository.user.BankAccountRepository;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.cache.CacheManager;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
/**
* User Transaction Test (Cache, Controller. Service)
*
* @author Nagarjun
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class UserTransactionIntegrationTest {
@Autowired private WebApplicationContext context;
private MockMvc mvc;
@MockBean private UserTransactionsRepository userTransactionRepository;
@MockBean private BankAccountRepository bankAccountRepository;
@MockBean private ApplicationEventPublisher eventPublisher;
@Autowired CacheManager cacheManager;
private Date dateMeantFor;
private List<String> cacheObjectKey;
private List<UserTransaction> userTransactionsList;
Logger logger = LoggerFactory.getLogger(this.getClass());
private static final String FINANCIAL_PORTFOLIO_ID = "193000000";
private static final String DATE_MEANT_FOR = "01062019";
@Before
public void setUp() {
setUserTransactionsList(new ArrayList<UserTransaction>());
UserTransaction userTransaction = new UserTransaction();
setMvc(MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build());
DateFormat format = new SimpleDateFormat(DashboardConstants.DATE_FORMAT, Locale.ENGLISH);
try {
setDateMeantFor(format.parse(DATE_MEANT_FOR));
} catch (ParseException e) {
logger.error(e + " Unable to add date to the user Transactions");
}
// sets a user Transactions for user Transactions list
userTransaction.setFinancialPortfolioId(FINANCIAL_PORTFOLIO_ID);
userTransaction.setCategoryId(3);
userTransaction.setAmount(300);
// Bank Acount integration test
BankAccount newAccount = new BankAccount();
newAccount.setId(123);
Mockito.when(getBankAccountRepository().save(Mockito.any(BankAccount.class)))
.thenReturn(newAccount);
// Appends the above created user Transactions to the list
getUserTransactionsList().add(userTransaction);
setCacheObjectKey(new ArrayList<String>());
getCacheObjectKey().add(FINANCIAL_PORTFOLIO_ID);
getCacheObjectKey().add(DATE_MEANT_FOR);
// Testing the Cache Layer
when(getUserTransactionRepository()
.findByFinancialPortfolioIdAndDate(FINANCIAL_PORTFOLIO_ID, getDateMeantFor()))
.thenReturn(getUserTransactionsList());
}
/**
* TEST: Get user Transaction by financial portfolio Id
*
* @throws Exception
*/
@WithMockUser(value = "spring")
@Test
public void getUserTransactionByFinancialPortfolioId() throws Exception {
getMvc()
.perform(
get("/api/transactions/193000000")
.param(DashboardConstants.Transactions.DATE_MEANT_FOR, DATE_MEANT_FOR)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
// Call the REST controller twice but the method should be invoked once
getMvc()
.perform(
get("/api/transactions/193000000")
.param(DashboardConstants.Transactions.DATE_MEANT_FOR, DATE_MEANT_FOR)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.3").isNotEmpty());
// Ensuring that the cache contains the said values
assertThat(
getCacheManager()
.getCache(DashboardConstants.Transactions.TRANSACTIONS_CACHE_NAME)
.get(getCacheObjectKey()),
is(notNullValue()));
}
/**
* TEST: Get user Transactions by financial portfolio Id
*
* @throws Exception
*/
@WithMockUser(value = "spring")
@Test
public void save() throws Exception {
List<Integer> categoryIds = new ArrayList<Integer>();
categoryIds.add(3);
getMvc()
.perform(
get("/api/transactions/193000000")
.param(DashboardConstants.Transactions.DATE_MEANT_FOR, DATE_MEANT_FOR)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
// Ensuring that the cache contains the said values
assertThat(
getCacheManager()
.getCache(DashboardConstants.Transactions.TRANSACTIONS_CACHE_NAME)
.get(getCacheObjectKey()),
is(notNullValue()));
// Mock saving the user transaction
when(getUserTransactionRepository().save(Mockito.any(UserTransaction.class)))
.thenReturn(getUserTransactionsList().get(0));
getMvc()
.perform(
post("/api/transactions/save/193000000")
.param(DashboardConstants.Transactions.CATEGORY_OPTIONS, "3")
.param(
DashboardConstants.Transactions.FINANCIAL_PORTFOLIO_ID, FINANCIAL_PORTFOLIO_ID)
.param(DashboardConstants.Transactions.TRANSACTIONS_AMOUNT, "300")
.param(DashboardConstants.Transactions.DATE_MEANT_FOR, DATE_MEANT_FOR)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE))
.andExpect(status().isOk());
verify(getUserTransactionRepository(), times(1)).save(Mockito.any());
// Ensuring that the cache is evicted
assertNull(
getCacheManager()
.getCache(DashboardConstants.Transactions.TRANSACTIONS_CACHE_NAME)
.get(getCacheObjectKey()));
}
/**
* TEST: delete user Transactions by transaction Id
*
* @throws Exception
*/
@WithMockUser(value = "spring")
@Test
public void deleteUserTransactionById() throws Exception {
getMvc()
.perform(
get("/api/transactions/193000000")
.param(DashboardConstants.Transactions.DATE_MEANT_FOR, DATE_MEANT_FOR)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
// Ensuring that the cache contains the said values
assertThat(
getCacheManager()
.getCache(DashboardConstants.Transactions.TRANSACTIONS_CACHE_NAME)
.get(getCacheObjectKey()),
is(notNullValue()));
getMvc()
.perform(
delete("/api/transactions/193000000/3,4,5,6")
.param(DashboardConstants.Transactions.DATE_MEANT_FOR, DATE_MEANT_FOR)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
// Ensuring that the cache is evicted
assertNull(
getCacheManager()
.getCache(DashboardConstants.Transactions.TRANSACTIONS_CACHE_NAME)
.get(getCacheObjectKey()));
}
/**
* TEST: update user transaction by financial portfolio Id
*
* @throws Exception
*/
@WithMockUser(value = "spring")
@Test
public void updateDescriptionByUserTransactionById() throws Exception {
getMvc()
.perform(
get("/api/transactions/193000000")
.param(DashboardConstants.Transactions.DATE_MEANT_FOR, DATE_MEANT_FOR)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
// Ensuring that the cache contains the said values
assertThat(
getCacheManager()
.getCache(DashboardConstants.Transactions.TRANSACTIONS_CACHE_NAME)
.get(getCacheObjectKey()),
is(notNullValue()));
// Testing the Cache Layer
List<Optional<UserTransaction>> optionalUserTransaction =
getUserTransactionsList().stream().map((o) -> Optional.of(o)).collect(Collectors.toList());
when(getUserTransactionRepository().findById(200)).thenReturn(optionalUserTransaction.get(0));
when(getUserTransactionRepository().save(Mockito.any()))
.thenReturn(getUserTransactionsList().get(0));
getMvc()
.perform(
post("/api/transactions/193000000/update/category")
.param(DashboardConstants.Transactions.CATEGORY_ID_JSON, "3")
.param(DashboardConstants.Transactions.TRANSACTIONS__ID_JSON, "200")
.accept(MediaType.APPLICATION_JSON)
.param(DashboardConstants.Transactions.DATE_MEANT_FOR, DATE_MEANT_FOR)
.contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE))
.andExpect(status().isOk());
verify(getUserTransactionRepository(), times(1)).findById(200);
// Making sure the Budget Listener was called
verify(getUserTransactionRepository(), times(1)).save(Mockito.any());
}
/**
* TEST: Get user Transactions by financial portfolio Id (EXCEPTION) without Transaction Amount
*
* @throws Exception
*/
@WithMockUser(value = "spring")
@Test
public void saveResourceNotFound() throws Exception {
getMvc()
.perform(
post("/api/transactions/save/193000000")
.param(DashboardConstants.Transactions.CATEGORY_OPTIONS, "3")
.param(
DashboardConstants.Transactions.FINANCIAL_PORTFOLIO_ID, FINANCIAL_PORTFOLIO_ID)
.param(DashboardConstants.Transactions.DATE_MEANT_FOR, DATE_MEANT_FOR)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE))
.andExpect(status().isBadRequest());
}
/**
* Fetch Category total and update User budget test
*
* @throws Exception
*/
@WithMockUser(value = "spring")
@Test
public void fetchCategoryTotalAndUpdateUserBudget() throws Exception {
getMvc()
.perform(
get("/api/transactions/categoryTotal/193000000")
.param(DashboardConstants.Transactions.DATE_MEANT_FOR, DATE_MEANT_FOR)
.param(DashboardConstants.Transactions.UPDATE_BUDGET_PARAM, "true")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.3").isNotEmpty());
getMvc()
.perform(
get("/api/transactions/categoryTotal/193000000")
.param(DashboardConstants.Transactions.DATE_MEANT_FOR, DATE_MEANT_FOR)
.param(DashboardConstants.Transactions.UPDATE_BUDGET_PARAM, "false")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.3").isNotEmpty());
verify(getUserTransactionRepository(), times(2))
.findByFinancialPortfolioIdAndDate(FINANCIAL_PORTFOLIO_ID, getDateMeantFor());
}
/**
* TEST: Delete user Transactions by financial portfolio Id
*
* @throws Exception
*/
@WithMockUser(value = "spring")
@Test
public void deleteUserTransactions() throws Exception {
getMvc()
.perform(delete("/api/transactions/193000000").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$").isNotEmpty());
verify(getUserTransactionRepository(), times(1)).deleteAllUserTransactions(Mockito.anyString());
}
/**
* TEST: Copy Previous Months Recurring transactions
*
* @throws Exception
*/
@WithMockUser(value = "spring")
@Test
public void copyFromPreviousMonth() throws Exception {
LocalDate previousMonthSameDay = LocalDate.now().minus(1, ChronoUnit.MONTHS).withDayOfMonth(1);
Date previousMonthsDate =
Date.from(previousMonthSameDay.atStartOfDay(ZoneId.systemDefault()).toInstant());
List<UserTransaction> userTransactions = new ArrayList<>();
UserTransaction userTransaction = new UserTransaction();
userTransaction.setAccountId(123);
userTransactions.add(userTransaction);
// Fetch all budget mock
Mockito.when(
getUserTransactionRepository()
.findRecurringTransactions(previousMonthsDate, RecurrencePeriod.MONTHLY))
.thenReturn(userTransactions);
getMvc()
.perform(
post("/api/transactions/copyFromPreviousMonth")
.contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$").isNotEmpty());
verify(getUserTransactionRepository(), times(1))
.findRecurringTransactions(previousMonthsDate, RecurrencePeriod.MONTHLY);
verify(getUserTransactionRepository(), times(1)).saveAll(Mockito.any());
}
private MockMvc getMvc() {
return mvc;
}
private UserTransactionsRepository getUserTransactionRepository() {
return userTransactionRepository;
}
private CacheManager getCacheManager() {
return cacheManager;
}
private void setMvc(MockMvc mvc) {
this.mvc = mvc;
}
private Date getDateMeantFor() {
return dateMeantFor;
}
private void setDateMeantFor(Date dateMeantFor) {
this.dateMeantFor = dateMeantFor;
}
private List<String> getCacheObjectKey() {
return cacheObjectKey;
}
private void setCacheObjectKey(List<String> cacheObjectKey) {
this.cacheObjectKey = cacheObjectKey;
}
private List<UserTransaction> getUserTransactionsList() {
return userTransactionsList;
}
private void setUserTransactionsList(List<UserTransaction> userTransactionsList) {
this.userTransactionsList = userTransactionsList;
}
private BankAccountRepository getBankAccountRepository() {
return bankAccountRepository;
}
}
<file_sep>/initialdatalod/InitialCategories.sql
/initialdatalod/InitialRole.sql<file_sep>package in.co.everyrupee;
import in.co.everyrupee.constants.GenericConstants;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* Initializing Every Rupee Application
*
* @author Nagarjun
*/
@SpringBootApplication
@EnableCaching
@ComponentScan(GenericConstants.EVERYRUPEE_PACKAGE)
public class EveryRupeeApplication {
/**
* Password encryption for login and register
*
* @return
*/
@Bean
public BCryptPasswordEncoder passwordEncoder() {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
return bCryptPasswordEncoder;
}
public static void main(String[] args) {
SpringApplication.run(EveryRupeeApplication.class, args);
}
}
<file_sep>insert into every_rupee.role (role_id, role) VALUES (1, "ADMIN");
insert into every_rupee.role (role_id, role) VALUES (2, "USER");
insert into every_rupee.role (role_id, role) VALUES (3, "ADMIN_CATEGORIZATION");
commit;
<file_sep>package in.co.everyrupee.utils;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* Generic utility services
*
* @author Nagarjun
*/
public class GenericUtils {
public static List<Integer> removeAll(List<Integer> list, int element) {
return list.stream().filter(e -> !Objects.equals(e, element)).collect(Collectors.toList());
}
}
<file_sep># bb-core
Use run it in the EC2
sudo java -jar changeme.jar &
Transfer the jar file to ec2
sudo scp -i pathreference/to/file.pem /path/to/file.jar user@awsenpoint:~
Kill Process in EC2
ps -aux | grep bb-core
kill $PID
<file_sep>/** */
package in.co.everyrupee.repository.income;
import in.co.everyrupee.pojo.RecurrencePeriod;
import in.co.everyrupee.pojo.income.UserTransaction;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
/**
* Reference user transactions
*
* @author Nagarjun
*/
@Repository
public interface UserTransactionsRepository extends JpaRepository<UserTransaction, Integer> {
/**
* @param financialPortfolioId
* @return
*/
List<UserTransaction> findByFinancialPortfolioId(String financialPortfolioId);
/**
* Find all the transactions for the month specified (Orders by creation date desc)
*
* @param financialPortfolioId
* @param dateMeantFor
* @return
*/
@Query(
"select u from UserTransaction u where u.financialPortfolioId in ?1 and u.dateMeantFor in ?2"
+ " order by date(createDate) desc ")
List<UserTransaction> findByFinancialPortfolioIdAndDate(
String financialPortfolioId, Date dateMeantFor);
/**
* Delete all user with ids specified in {@code ids} parameter
*
* @param ids List of user ids
*/
@Modifying
@Query("delete from UserTransaction u where u.id in ?1 and u.financialPortfolioId in ?2")
void deleteUsersWithIds(List<Integer> ids, String financialPortfolioId);
/**
* @param financialPortfolioId
* @return
*/
@Query(
"select u from UserTransaction u where u.financialPortfolioId in ?1 and u.categoryId in ?2"
+ " order by date(createDate) asc ")
List<UserTransaction> findByFinancialPortfolioIdAndCategories(
String financialPortfolioId, List<Integer> categoryIds);
/**
* Fetches all user with category ids specified in {@code ids} parameter
*
* @param ids List of category ids
*/
@Query(
"SELECT u FROM UserTransaction u where u.categoryId in ?1 and u.financialPortfolioId in ?2"
+ " and u.dateMeantFor in ?3")
List<UserTransaction> fetchUserTransactionWithCategoryId(
Integer categoryId, String financialPortfolioId, Date dateMeantFor);
/**
* Delete all user transactions with financial portfolio id
*
* @param financialPortfolioId
*/
@Modifying
@Query("delete from UserTransaction u where u.financialPortfolioId in ?1")
void deleteAllUserTransactions(String financialPortfolioId);
/**
* Fetch all user dates by financial portfolio id
*
* @param financialPortfolioId
* @return
*/
@Query("SELECT u.dateMeantFor FROM UserTransaction u where u.financialPortfolioId in ?1")
List<Date> findAllDatesByFPId(String financialPortfolioId);
/**
* Delete by bank account id
*
* @param pBankAccountId
*/
@Modifying
@Query("delete from UserTransaction u where u.accountId in ?1")
void deleteByBankAccount(int pBankAccountId);
/**
* Fetch all user transactions by date
*
* @param financialPortfolioId
* @return
*/
@Query("SELECT u FROM UserTransaction u where u.dateMeantFor in ?1 and u.recurrence in ?2")
List<UserTransaction> findRecurringTransactions(Date from, RecurrencePeriod recurrencePeriod);
}
<file_sep>package in.co.everyrupee.repository.user;
import in.co.everyrupee.pojo.user.BankAccount;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
/**
* Repository to handle the Bank Account for the user
*
* @author Nagarjun
*/
@Repository
public interface BankAccountRepository extends JpaRepository<BankAccount, Integer> {
/**
* Fetch all bank account by financial Portfolio id
*
* @param financialPortfolioId
* @return
*/
List<BankAccount> findByFinancialPortfolioId(String financialPortfolioId);
/**
* Delete all user budget with financial portfolio id specified in {@code ids} parameter
*
* @param financialPortfolioId
*/
@Modifying
@Query("delete from BankAccount u where u.financialPortfolioId in ?1")
void deleteAllBankAccounts(String financialPortfolioId);
/**
* Fetch all selected bank accounts
*
* @param financialPortfolioId
* @return
*/
@Query(
"select u from BankAccount u where u.financialPortfolioId in ?1 and u.selectedAccount is"
+ " true")
List<BankAccount> findSelectedAccountsByFinancialPortfolioId(String financialPortfolioId);
}
<file_sep>/** */
package in.co.everyrupee.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* Implement Security Configuration for Web Application
*
* @author <NAME>
*/
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll().and().csrf().disable();
}
}
| 94a8cee7939d872f30bad632b06707986dba949d | [
"Markdown",
"Java",
"SQL",
"Gradle"
] | 28 | Java | NagarjunNagesh/Every-Rupee-API | 70b5e640c264473e7d2089373d1ffcea87a177b4 | f3e3699cedf999b022ff65e374db944a642a05c7 |
refs/heads/master | <repo_name>hui09241/Network-programming-009<file_sep>/Readme.txt
參考上課範例,實作一多人聊天室,具有以下功能
1 其中一人發言,其他人會收到。
2 人數限制:當超過5人時,會告知系統已滿,並斷線。
3 進入通知:當一人連上時,會通知站上其他人
client請用多緒版本(echo-client-thread)。
<file_sep>/Server.c
//TCP Echo server v2
// v1: show (pre-accept) non-block echo
// v2: show incoming at any time
#include<stdio.h>
#include<winsock.h>
#define MAXRECV 1024
#define MAXCLI 10
int main(int argc , char *argv[])
{
WSADATA wsadata;
SOCKET serv_sd , new_socket,cli_sd[MAXCLI];
struct sockaddr_in serv, cli;
int activity, cli_len, i, n, client_num=0;
fd_set readfds; //set of socket descriptors
char str[MAXRECV],str1[MAXRECV]="system is full";
int new=0,j;
for(i=0;i<MAXCLI;i++)
cli_sd[i]=0;
WSAStartup(0x101, &wsadata); //呼叫 WSAStartup() 註冊 WinSock DLL 的使用
serv_sd=socket(AF_INET, SOCK_STREAM, 0);// 開啟 TCP socket
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = INADDR_ANY;
serv.sin_port = htons( 5678 );
bind(serv_sd, (LPSOCKADDR) &serv, sizeof(serv));
listen(serv_sd , 3);
while(TRUE)
{
printf("[1]clear the socket fd set. \n");
FD_ZERO(&readfds);
printf("[2]add serv_sd to fd set \n");
FD_SET(serv_sd, &readfds);
printf("[2]add cli_sd[] to fd set \n");
for(i=0;i<MAXCLI;i++)
if(cli_sd[i]>0)
FD_SET(cli_sd[i], &readfds);
//wait for an activity on any of the sockets, timeout is NULL , so wait indefinitely
printf("[3]call select() and waiting \n");
activity = select( 0 , &readfds , NULL , NULL , NULL);
printf("[4]wake up from select()\n");
if ( activity == SOCKET_ERROR ){
printf("select call failed with error code : %d" , WSAGetLastError());
exit(EXIT_FAILURE);
}
//check serv_sd -> accept(),add new client into cli_sd[]
if (FD_ISSET(serv_sd , &readfds)){
cli_len = sizeof(cli);
new_socket = accept(serv_sd , (struct sockaddr *)&cli, (int *)&cli_len);
printf("New connection: socket fd is %d , ip is : %s , port : %d \n" , new_socket ,
inet_ntoa(cli.sin_addr) , ntohs(cli.sin_port));
if(client_num>=5)
{
strcpy(str,"人數已滿");
send(new_socket, str, strlen(str)+1, 0);
closesocket( new_socket);
}
else
{
for(i=0;i<MAXCLI;i++){
if(cli_sd[i]==0){
cli_sd[i]=new_socket;
new=i;
client_num ++;
printf("The %d client socket is in cli_sd[%d]\n",client_num,i);
break;
}
}
strcpy(str,"有新成員加入0.0");
for(j=0;j<MAXCLI;j++)
{
if(cli_sd[j]>0)
{
if(j!=new)
send(cli_sd[j], str, strlen(str)+1, 0);
}
}
}
}
//check each cli_sd client 1 presend in read sockets
for(i=0;i<MAXCLI;i++){
if(FD_ISSET( cli_sd[i] , &readfds) ){
n = recv( cli_sd[i] , str, MAXRECV, 0);
char who[10];
if( n == SOCKET_ERROR){
int error_code = WSAGetLastError();
if(error_code == WSAECONNRESET){
//Somebody disconnected , get his details and print
printf("Host disconnected unexpectedly\n");
closesocket( cli_sd[i] );
cli_sd[i] = 0;
client_num --;
}
else
printf("recv failed with error code : %d" , error_code);
}
if ( n == 0){
//Somebody disconnected , get his details and print
printf("Host disconnected. \n" );
closesocket( cli_sd[i] );
cli_sd[i] = 0;
client_num --;
}
if (n > 0) {
printf("recv from and echo to cli[%d]: %s \n" ,i, str);
for(j=0;j<MAXCLI;j++)
{
if(cli_sd[j]>0)
{
if(j!=i)
{
int num=i+1;
sprintf(who,"%d",num);
strcat(who," : ");
strcat(who,str);
send(cli_sd[j], who, strlen(who)+1, 0);
}
}
}
}//if
}
}//for
}// while
closesocket(serv_sd);
WSACleanup();
system("pause");
return 0;
}
| 73b0953d519729daddeaf0c77a34860cf285ffa6 | [
"C",
"Text"
] | 2 | Text | hui09241/Network-programming-009 | 14891d1f8bed02f48997d340a843c580c05ad4f5 | 30111fe73d866a09c66435068d1fc32621ef6be0 |
refs/heads/master | <repo_name>raute-null/todolist<file_sep>/src/app/app.component.ts
import { Component } from '@angular/core';
import { TodoItem } from './todo-item';
@Component({
selector: 'todolist-app',
template:`
<div id="titleBar">
<img src="./img/icon.png" height="24" />
<span id="appTitle">TodoList</span>
</div>
<div id="content">
<div id="newItemInputWrapper">
<input #newItemText id="newItemInput" placeholder="Enter new todo item..."
(keyup.enter)="addItem(newItemText.value); newItemText.value = '';" />
<button (click)="addItem(newItemText.value); newItemText.value = ''; newItemText.focus()"
title="Click to add the entered todo item">Add</button>
</div>
<div id="todoListWrapper">
<ul id="todoList">
<li class="todoListItem" *ngFor="let todoItem of todoItems.slice().reverse()"
[class.done]="todoItem.done === true"
[id]="todoItem.id">
<input type="checkbox" class="todoItemDoneTrigger" [(ngModel)]="todoItem.done"
[attr.title]="todoItem.done ? 'Mark item as undone' : 'Mark item as done'"
/>
<span class="todoItemText">{{todoItem.name}}</span>
<img src="./img/delete.png" height="20" class="todoItemDelete" (click)="onDelete(todoItem)"
title="Delete this todo item" />
</li>
</ul>
</div>
</div>
`
})
export class AppComponent {
title = 'TodoList';
todoItems: TodoItem[] = [];
/**
* Deletes the given todo item from the list.
*
* @param selectedTodoItem the selected todo item to be deleted
*/
onDelete(selectedTodoItem: TodoItem): void {
var index = this.todoItems.indexOf(selectedTodoItem, 0);
if (index > -1) {
this.todoItems.splice(index, 1);
}
}
/**
* Adds the item with the given text to the list of todo items.
*
* @param text the name for the todo item to be added
*/
addItem(text: string) {
if (text) {
let newItem = new TodoItem();
newItem.name = text;
newItem.done = false;
newItem.id = this.findNextFreeId();
this.todoItems.push(newItem);
}
}
/**
* Returns the next free ID value.
*
* @return the next unused ID value
*/
findNextFreeId(): number {
if (this.todoItems.length === 0) {
return 0;
}
let latestItem = this.todoItems.slice(-1)[0];
let latestItemId = latestItem.id;
return ++latestItemId;
}
}
<file_sep>/README.md
## TodoList
A simple application to get used to Angular2 and TypeScript.
<file_sep>/src/app/todo-item.ts
/**
* Class representing a single item in the todo list.
*/
export class TodoItem {
id: number;
name: string;
done: boolean;
}
| 29cd03d9391ab1f755272ec0acab591c99699ba4 | [
"Markdown",
"TypeScript"
] | 3 | TypeScript | raute-null/todolist | 7b7ce8d1e35d05a1c4d35d02f645fbfac661fa35 | bcb0c162253c6152832dd4530ed153118255b998 |
refs/heads/master | <repo_name>qynglang/Decision-tree-batch-update<file_sep>/algorithm/train.py
import pandas as pd
import numpy as np
from sklearn.preprocessing import OneHotEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from six.moves import cPickle
enc = OneHotEncoder(handle_unknown='ignore',sparse=False)
data=pd.read_csv("pp-complete.csv",header=None,skiprows=5000,nrows=5000)
n=[2,4,6,11,1]
data_reduced=np.array(data.iloc[:,n])
enc.fit(data_reduced[:,1:3])
#data generator
def data_processor(m,n):
# loading:
for i in range (m,n):
data=pd.read_csv("pp-complete.csv",header=None,skiprows=m*5000,nrows=5000)
n=[2,4,6,11,1]
data_reduced=np.array(data.iloc[:,n])
# one hot encoding:
data_onehot=enc.transform(data_reduced[:,1:3])
data_reduced[np.where(data_reduced[:,0]<'2016-01-01 00:00')[0],0]=0
data_reduced[np.where(data_reduced[:,0]!=0)[0],0]=1
data_reduced[np.where(data_reduced[:,3]=='LONDON')[0],3]=1
data_reduced[np.where(data_reduced[:,3]!=1)[0],3]=0
data_onehot=np.hstack((data_reduced[:,0].reshape(5000,1),data_onehot,data_reduced[:,3].reshape(5000,1)))
#stacking 5000 rows into 25000 matrices:
if i==m:
data_p=data_onehot
ans=np.int8(data_reduced[:,4])
else:
data_p=np.vstack((data_p,data_onehot))
ans=np.vstack((ans.reshape(ans.shape[0],1),np.int8(data_reduced[:,4]).reshape(5000,1)))
return data_p, ans
#training process
def main():
m=0
err=np.zeros(100)
for i in range (0,100):
# data generation:
data,ans=data_processor(i*50,i*50+50)
# cross validation sets:
x_train,x_test,y_train,y_test=train_test_split(data[np.where(data[:,0]==0)[0],:],ans[np.where(data[:,0]==0)[0]],test_size=0.2)
# define algorithms:
rf = RandomForestClassifier(n_estimators=10)
df_x_train = x_train[:,1::]
rf.fit(df_x_train,y_train)
# save single model:
with open('rf'+str(i)+'.pkl', 'wb') as f:
cPickle.dump(rf, f)
df_x_test = x_test[:,1::]
if i>0:
# load model and make prediction:
for k in range (m,i):
with open('rf'+str(k)+'.pkl', 'rb') as f:
rf = cPickle.load(f)
pred = rf.predict(df_x_test)
if k==0:
y_pred=pred
else:
y_pred+=pred
err[k]=mean_squared_error(y_pred/(k+1),y_test)
# termination
if k>5:
if err[k]<=np.min(err[k-5:k-1]):
print(k-3)
break
break
m=i
print(k-3) | 72c5afb692400e165964d832b4ff81f2bd47251c | [
"Python"
] | 1 | Python | qynglang/Decision-tree-batch-update | 2c9fbe059ca4ba4697b393bccef07851627d961d | 39d11bded31286676f910a4c1f4e742248dff736 |
refs/heads/master | <repo_name>manu-r/class_manager<file_sep>/faculty/src/main/java/com/bitspilani/admin/util/User.java
package com.bitspilani.admin.util;
/**
* Created by I311849 on 16/Jun/2016.
*/
public class User {
private String userId;
private String email;
public User(String userId, String email) {
this.userId = userId;
this.email = email;
}
public String getUserId() {
return userId;
}
public String getEmail() {
return email;
}
}
<file_sep>/faculty/src/main/java/com/bitspilani/admin/util/ExcelHelper.java
package com.bitspilani.admin.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import jxl.CellView;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.Alignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
/**
* Created by I311849 on 17/Jun/2016.
*/
public class ExcelHelper {
private WritableCellFormat cellFormat;
private File outputFile;
private ArrayList<Faculty> faculties;
public void setOutputFile(File outputFile) {
this.outputFile = outputFile;
}
public void write(ArrayList<Faculty> faculties) throws IOException, WriteException {
this.faculties = faculties;
WorkbookSettings settings = new WorkbookSettings();
settings.setLocale(Locale.ENGLISH);
WritableWorkbook writableWorkbook = Workbook.createWorkbook(this.outputFile, settings);
writableWorkbook.createSheet("Session", 0);
WritableSheet writableSheet = writableWorkbook.getSheet(0);
formatHeadingCells(writableSheet);
createHeadings(writableSheet);
createContent(writableSheet);
CellView cell;
for (int i = 0; i < 9; i++) {
cell = writableSheet.getColumnView(i);
cell.setSize(20 * 256);
cell.setAutosize(true);
writableSheet.setColumnView(i, cell);
}
writableWorkbook.write();
writableWorkbook.close();
}
private void createHeadings(WritableSheet writableSheet) throws WriteException {
WritableFont headingFont = new WritableFont(WritableFont.ARIAL, 12);
headingFont.setBoldStyle(WritableFont.BOLD);
// Define the cell format
cellFormat = new WritableCellFormat(headingFont);
cellFormat.setAlignment(Alignment.CENTRE);
Label label;
//Faculty Details ================================================================
label = new Label(0, 0, "Name", cellFormat);
writableSheet.addCell(label);
label = new Label(1, 0, "Email", cellFormat);
writableSheet.addCell(label);
label = new Label(2, 0, "Ph. No.", cellFormat);
writableSheet.addCell(label);
//Session Details ================================================================
label = new Label(3, 0, "Session Timings", cellFormat);
writableSheet.addCell(label);
label = new Label(3, 2, "Start", cellFormat);
writableSheet.addCell(label);
label = new Label(4, 2, "End", cellFormat);
writableSheet.addCell(label);
//Cab Details ====================================================================
label = new Label(5, 0, "Cab Details", cellFormat);
writableSheet.addCell(label);
label = new Label(5, 1, "Location", cellFormat);
writableSheet.addCell(label);
label = new Label(7, 1, "Timings", cellFormat);
writableSheet.addCell(label);
label = new Label(5, 2, "Pickup", cellFormat);
writableSheet.addCell(label);
label = new Label(6, 2, "Drop", cellFormat);
writableSheet.addCell(label);
label = new Label(7, 2, "Pickup", cellFormat);
writableSheet.addCell(label);
label = new Label(8, 2, "Return", cellFormat);
writableSheet.addCell(label);
}
private void createContent(WritableSheet writableSheet) throws WriteException {
WritableFont contentFont = new WritableFont(WritableFont.ARIAL, 10);
// Define the cell format
cellFormat = new WritableCellFormat(contentFont);
cellFormat.setAlignment(Alignment.LEFT);
Label label;
int row = 3;
for(Faculty faculty : this.faculties) {
label = new Label(0, row, faculty.getFirstName(), cellFormat);
writableSheet.addCell(label);
label = new Label(1, row, faculty.getEmail(), cellFormat);
writableSheet.addCell(label);
label = new Label(2, row, faculty.getPhNo(), cellFormat);
writableSheet.addCell(label);
label = new Label(3, row, faculty.getSessionStart().toString(), cellFormat);
writableSheet.addCell(label);
label = new Label(4, row, faculty.getSessionEnd().toString(), cellFormat);
writableSheet.addCell(label);
label = new Label(5, row, faculty.getPickupLocation(), cellFormat);
writableSheet.addCell(label);
label = new Label(6, row, faculty.getDropLocation(), cellFormat);
writableSheet.addCell(label);
label = new Label(7, row, faculty.getPickupTime().toString(), cellFormat);
writableSheet.addCell(label);
label = new Label(8, row, faculty.getReturnTime().toString(), cellFormat);
writableSheet.addCell(label);
row++;
}
}
private void formatHeadingCells(WritableSheet writableSheet) throws WriteException {
//Merge rows
writableSheet.mergeCells(0, 0, 0, 2);
writableSheet.mergeCells(1, 0, 1, 2);
writableSheet.mergeCells(2, 0, 2, 2);
//Merge rows & columns
writableSheet.mergeCells(3, 0, 4, 1);
//Merge Columns
writableSheet.mergeCells(5, 0, 8, 0);
writableSheet.mergeCells(5, 1, 6, 1);
writableSheet.mergeCells(7, 1, 8, 1);
}
}
<file_sep>/faculty/src/main/java/com/bitspilani/admin/util/AppUtil.java
package com.bitspilani.admin.util;
import android.util.Log;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by I311849 on 14/Jun/2016.
*/
public class AppUtil {
private static final String TAG = "AppUtil";
public static String formatTime(Time time) {
return AppUtil.formatTime(time.getHour(), time.getMinute());
}
public static String formatTime(int hourOfDay, int minute) {
int iHour = hourOfDay % 12;
if(iHour == 0) {
iHour = 12;
}
String a = hourOfDay / 12 == 0 ? "AM" : "PM";
return String.format(Locale.ENGLISH, "%02d:%02d %s", iHour, minute, a);
}
public static Time getTime(String time) {
String pattern = "([0][1-9]|[1][0-2]):([0-5][0-9]) (AM|PM)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(time);
m.matches();
String hour = m.group(1);
String minute = m.group(2);
String a = m.group(3);
Log.d(TAG, "getTime: " +hour);
int iHour = Integer.parseInt(hour);
Log.d(TAG, "getTime: " +minute);
int iMinute = Integer.parseInt(minute);
iHour += a.equals("PM") ? 12 : 0;
return new Time(iHour, iMinute);
}
}
<file_sep>/faculty/src/main/java/com/bitspilani/admin/util/AppConstants.java
package com.bitspilani.admin.util;
/**
* Created by I311849 on 31/May/2016.
*/
public interface AppConstants {
String USER_DATA = "user_data";
String EMAIL = "email";
int GOOGLE_SIGNIN = 0;
String ACCESS_TOKEN = "access_token";
String LAST_NAME = "last_name";
String FIRST_NAME = "first_name";
String ID = "id";
}
<file_sep>/faculty/src/main/java/com/bitspilani/admin/activity/UserListFragment.java
package com.bitspilani.admin.activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.bitspilani.admin.R;
import com.bitspilani.admin.adapters.UserListAdapter;
import com.bitspilani.admin.util.User;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class UserListFragment extends Fragment implements ValueEventListener, View.OnClickListener {
private OnFragmentInteractionListener mListener;
private ArrayList<User> users;
FirebaseDatabase firebaseDB;
DatabaseReference dbRef;
UserListAdapter userListAdapter;
public UserListFragment() {
}
public static UserListFragment newInstance() {
return new UserListFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
users = new ArrayList<>();
firebaseDB = FirebaseDatabase.getInstance();
dbRef = firebaseDB.getReference();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_user_list, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_userlist);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
userListAdapter = new UserListAdapter(users);
recyclerView.setAdapter(userListAdapter);
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab_add_user);
fab.setOnClickListener(this);
dbRef.child("auth_ids").addValueEventListener(this);
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> children = dataSnapshot.getChildren();
users.clear();
for (DataSnapshot child : children) {
String userId = child.getKey();
String email = child.child("email").getValue().toString();
if (child.child("userType").getValue().toString().equals("faculty")) {
User user = new User(userId, email);
users.add(user);
}
}
userListAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.fab_add_user:
final Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.add_user);
dialog.setCancelable(true);
dialog.setTitle(R.string.add_user);
final Button btnAddUser = (Button) dialog.findViewById(R.id.btn_add_user);
btnAddUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText editTextUsername = (EditText) dialog.findViewById(R.id.new_username);
EditText editTextEmail = (EditText) dialog.findViewById(R.id.new_user_email);
if (editTextEmail.getText().toString().isEmpty() ||
editTextUsername.getText().toString().isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Enter a username and valid email");
} else {
String email = editTextEmail.getText().toString();
String username = editTextUsername.getText().toString();
Map<String, Object> user = new HashMap<>();
if (dbRef.child("auth_ids").child(username) != null) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Username already exists. Please enter a new one.");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setCancelable(false);
builder.show();
}
user.put("email", email);
user.put("userType", "faculty");
dbRef.child("auth_ids").child(username).updateChildren(user, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
Toast.makeText(getActivity(), "User added.", Toast.LENGTH_SHORT).show();
}
}
});
dialog.cancel();
}
}
});
dialog.show();
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction();
}
}
| 30117dd68cb292935306df0652ea0e40e7b845be | [
"Java"
] | 5 | Java | manu-r/class_manager | 89686801042e7400982a29399bfb466aaed35cea | 84c04846df4447e48fc195ad4c0bdc5cad1d5f6c |
refs/heads/master | <repo_name>yashwant12/01-JShunt<file_sep>/solutions/09a_length/length.js
var myString = "hello";
console.log(myString.length);
<file_sep>/solutions/01_hello_html/age.js
var age = readString("what is your age?");
console.log(age);
function submitPress() {
var name = document.getElementById('name').value;
alert(name)
}
| f6ebf31996444296efb354a0a9838910429bff29 | [
"JavaScript"
] | 2 | JavaScript | yashwant12/01-JShunt | 9ebc4b779eeb4d2e1e229248d00cc17a29a4318f | 891c8ffa802016b569223a2257e32b579505e662 |
refs/heads/master | <repo_name>Luxusproblem/RayCharles2<file_sep>/Illumination.py
from WorldGeometry import *
class Light(object):
def __init__(self, position, intensity=1):
assert(type(position) is Point)
self.position = position
self.intensity = intensity
class Ray(object):
def __init__(self, origin, direction):
assert(type(origin) is Point and type(direction is Vector))
self.origin = origin # point
self.direction = direction.normalized() # vector
def __repr__(self):
return 'Ray(%s,%s)' % (repr(self.origin), repr(self.direction))
def pointAtParameter(self, t):
return self.origin + self.direction.scale(t)
def reflect(self, normal, newPoint=None):
if not newPoint:
newPoint = self.origin
return Ray(newPoint, self.direction.reflect(normal))<file_sep>/View.py
# -*- coding: utf-8 -*-
from Tkinter import *
from Camera import Camera
from Illumination import *
from Surface import *
from WorldObjects import *
from WorldGeometry import *
default = 400
fov = math.radians(45)
scale = 1
width = int(default * scale)
height = int(default * scale)
# Default colors
floor = Color(118,118,118)
magenta = Color(255,90,148)
turkis = Color(42,152,105)
blue = Color(94,146,255)
yellow = Color(200, 240, 178)
# Default surfaces (Farbe, ambient, diffuser anteil, specularer Anteil, Glattheit)
surf_floor = Surface(floor, 1, 0.5, 0.2, 0.2)
surf_m = Surface(magenta, 0.3, 0.8, 0.2, 0.2)
surf_t = Surface(turkis, 0.3, 0.8, 0.2, 0.2)
surf_b = Surface(blue, 0.3, 0.8, 0.2, 0.2)
surf_y = Surface(yellow, 0.3, 0.8, 0.2, 0.2)
surf_check = ComplexSurface()
lightList = [Light(Point(30, 30, 30),1), Light(Point(-1, 29, -10), 0.2)]
objectList = [Triangle(Point(2.5, 3, -10),Point(-2.5, 3, -10), Point(0, 7, -10), surf_y),
Sphere(Point(2.5, 3, -10), 2, surf_m),
Sphere(Point(-2.5, 3, -10), 2, surf_t),
Sphere(Point(0, 7, -10), 2, surf_b),
Plane(Point(0, 0, 0), Vector(0, 1, 0), surf_check)]
def rainbow(list):
#zufällig gefärbte Objekte
for e in list:
if type(e.surface) is type(surf_check):
print "check"
else:
e.surface = randomcolored()
def removeCheck(list):
for e in list:
if type(e.surface) is type(surf_check):
e.surface = surf_floor
def putpixel(x, y, color):
canvas.create_line(x, height - y, x + 1, height - (y + 1), fill=color.toHexString())
def randomcolored():
return Surface(floor.randomColor(), 0.3, 0.8, 0.2, 0.2)
if __name__ == '__main__':
promptval = raw_input("Willkommen bei RayTracer\nStarten mit zufälligen Farben ? j/n \n")
if(promptval == "j" ):
rainbow(objectList)
promptval = raw_input("Schachbrett ? j/n \n")
if(promptval == "n"):
removeCheck(list)
promptval = raw_input("Wie tief soll gerendert werden? Level 0-5 \n")
level = int(promptval)
root = Tk()
root._root().wm_title("Ray Charles")
frame = Frame(root, width=width, height=height)
frame.pack()
canvas = Canvas(frame, width=width, height=height, bg="white")
canvas.pack()
camera = Camera(Point(0,2,10), Vector(0,1,0), Point(0,3,0), fov)
camera.setScreenSize(width, height)
# (renderfunktion, objekte, lichter, hindergrund , rendertiefe)
print "Start rendering"
print "Anzahl Lichter: %d \nAnzahl Objekte: %d \n" % (len(lightList),len(objectList))
camera.render(putpixel, objectList, lightList, Color(97,97,130), level)
root.mainloop()<file_sep>/WorldGeometry.py
# -*- coding: utf-8 -*-
import math
class Vector(object):
# Vector enthält punkte x,y,z
# Vector enthält ebenfalls einen Tupel der Punkte (x,y,z)
# safety first
def __init__(self, vec, y=0, z=0):
# Akzeptiert tuple und einzelne Werte
# wenn vec ein tuple ist (x,y,z)
if type(vec) is tuple:
self.vec = vec
else:
self.vec = (vec, y, z)
(self.x, self.y, self.z) = self.vec
self.vec = tuple(map(float, self.vec))
def __repr__(self):
return 'Vector(%s, %s, %s)' % (repr(self.x), repr(self.y), repr(self.z))
def __add__(self, v2):
# vector1 + vector2
assert (type(v2) == type(self))
result = (self.x + v2.x, + self.y + v2.y, self.z + v2.z)
return type(self)(result)
def __sub__(self, v2):
# vector1 - vector2
assert (type(v2) == type(self))
result = (self.x - v2.x, + self.y - v2.y, self.z - v2.z)
return type(self)(result)
def __div__(self, num):
# Skalieren.
assert (type(num) == int or type(num) == float)
scaled_v = (self.x / num, self.y / num, self.z / num)
# Tuple aus sklaierten vectorwerten casten zu vector
return type(self)(scaled_v)
def __mul__(self, num):
# vector * saklierungswert = skalierter Vektor
assert (type(num) == int or type(num) == float)
scaled_v = (self.x * num, self.y * num, self.z * num)
# Tuple aus sklaierten vectorwerten casten zu vector
return type(self)(scaled_v)
def __eq__(self, v2):
return self.vec == v2.vec
def length(self):
# sqrt(x^2, y^2, z^2) = Länge des vectors
vLenght = math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
return vLenght
def dot(self, v2):
# scalar = x1 * x2 + y1 * y2 + z1 * z2
assert (type(v2) == Vector)
scalar = self.x * v2.x + self.y * v2.y + self.z * v2.z
return scalar
def cross(self, v2):
# Kreuzprodukt siehe vorlesung oder formelsammlung
# NICHT MIT PUUNKTEN !!!!
assert (type(v2) == type(self))
x = self.y * v2.z - self.z * v2.y
y = self.z * v2.x - self.x * v2.z
z = self.x * v2.y - self.y * v2.x
return type(self)(x, y, z)
def scale(self, scalar):
return self * scalar
def normalized(self):
# vector Einheitsvektor hat die länge 1.
# um einen normierten Vektor zu erhalten v /||v||
return self / self.length()
def inversed(self):
# vector ^(-1)
v = tuple(map(lambda coord: 1.0 / coord, self.vec))
return type(self)(v)
def angle(self, v2):
# alpha = acos ( <v1,v2> / ||v1|| * ||v2|| )
return math.acos(self.dot(v2) / (self.length() * v2.length()))
def reflect(self, vReflector):
# vector und reflectionsVector Spannen eine Ebene auf
# die aufgespannte ebene und der Reflectionsvetor spannen dann die Spiegelebene auf
# print(vReflector)
ebene = self.cross(vReflector)
spiegel = ebene.cross(vReflector).normalized()
d = self.cross(vReflector.normalized()).length()
# hier sollte eigentlich ein minus hin aber ich weiss nicht warums mit Plus klappt
# Folie 48 ?
newDirection = self + spiegel * d * 2
return type(self)(newDirection.vec)
class Point(object):
def __init__(self, point, y=0, z=0):
# Point hat 3 punkte thats it. kann als Tupel initiiert werden oder mit 3 übergabe parametern
# kommt aufs selbe hinaus
if (type(point) == tuple):
self.point = point
else:
self.point = (point, y, z)
def __repr__(self):
return 'Point(%s, %s, %s)' % (repr(self.point[0]), repr(self.point[1]), repr(self.point[2]))
def __eq__(self, p2):
return self.point == p2.point
def __sub__(self, p2):
# Subtraktion von 2 punkten ergibt einen Vector NICHT punkt
assert (type(p2) == Point)
v = (self.point[0] - p2.point[0], self.point[1] - p2.point[1], self.point[2] - p2.point[2])
return Vector(v)
def __add__(self, v):
# Punkt + vector = Punkt
assert (type(v) == Vector)
p = (self.point[0] + v.x, self.point[1] + v.y, self.point[2] + v.z)
return type(self)(p)
<file_sep>/Surface.py
# -*- coding: utf-8 -*-
from WorldGeometry import Vector
import random
import math
# <NAME>
MAXC = 255
class Color(Vector):
def __init__(self, r, g=0, b=0):
Vector.__init__(self, r, g, b)
self.r = self.x
self.g = self.y
self.b = self.z
def realColor(self):
(r, g, b) = self.vec
c = [r, g, b]
c = (Color(tuple([MAXC if x > MAXC else x for x in c])))
return c
def __mul__(self, other):
return super(Color, self).__mul__(other)
def __add__(self, other):
return super(Color, self).__add__(other)
def toHexString(self):
return '#%02X%02X%02X' % (self.r, self.g, self.b)
def randomColor(self):
def r(): return random.randint(0,255)
return Color(r(), r(), r())
black = Color(1, 1, 1)
white = Color(255, 255, 255)
bgColor = Color(97, 97, 130)
class Surface(object):
def __init__(self, color=None, ambient=0, diffuse=0.8, specular=0.2, texture=0.05):
self.color = color
if not color:
self.color = Color(128, 128, 128)
self.ambient = ambient
self.diffuse = diffuse
self.specular = specular
self.texture = texture
def renderColor(self, lightRay, normal, lightIntensity, rayDirection):
color = black
reflectedLight = (lightRay.direction).reflect(normal)
diffuseFactor = lightRay.direction.dot(normal)
expo = MAXC / 4 * self.texture + 1
if (diffuseFactor > 0):
color += self.color * (diffuseFactor * self.diffuse) * lightIntensity
specularFactor = reflectedLight.dot(rayDirection * -1)
if specularFactor > 0:
specConst = (expo + 2) / (math.pi * 2)
color += white * specConst * ((specularFactor ** expo) * self.specular) * lightIntensity
return color
class ComplexSurface():
def __init__(self, color=Color(30, 30, 30), color2=Color(200, 200, 200), ambient=0, diffuse=0.8, specular=0.2,
texture=0.05):
self.color = color
self.color2 = color2
self.checksize = 0.05
self.ambient = ambient
self.diffuse = diffuse
self.specular = specular
self.texture = texture
def renderColor(self, lightRay, normal, lightIntensity, rayDirection):
color = black
reflectedLight = (lightRay.direction).reflect(normal)
diffuseFactor = lightRay.direction.dot(normal)
v = reflectedLight
v = v.scale(1.0 / self.checksize)
expo = MAXC / 4 * self.texture + 1
if (int(abs(v.x) + 0.5) + int(abs(v.y) + 0.5) + int(abs(v.z) + 0.5)) % 2 == 1:
color = self.color
if (diffuseFactor > 0):
color += self.color * (diffuseFactor * self.diffuse) * lightIntensity
specularFactor = reflectedLight.dot(rayDirection * -1)
if specularFactor > 0:
specConst = (expo + 2) / (math.pi * 2)
color += white * specConst * (specularFactor ** expo * self.specular) * lightIntensity
return color
else:
color = self.color2
if (diffuseFactor > 0):
color += self.color2 * (diffuseFactor * self.diffuse) * lightIntensity
specularFactor = reflectedLight.dot(rayDirection * -1)
if specularFactor > 0:
specConst = (expo + 2) / (math.pi * 2)
color += white * specConst * (specularFactor ** expo * self.specular) * lightIntensity
return color
<file_sep>/WorldObjects.py
import math
from Surface import Surface
class Triangle(object):
def __init__(self, a, b, c, material=None):
self.a = a
self.b = b
self.c = c
self.u = self.b -self.a # direction Vector
self.v = self.c -self.a # direction Vector
self.surface = material
if not material:
self.surface = Surface()
def __repr__(self):
return 'Trangle(%s%s&s)' %(repr(self.a), repr(self.b), repr(self.c))
def intersectionParameter(self, ray):
w = ray.origin - self.a
dv= ray.direction.cross(self.v)
dvu = dv.dot(self.u)
if dvu == 0.0:
return None
wu = w.cross (self.u)
r = dv.dot(w) / dvu
s = wu.dot(ray.direction)/ dvu
if 0 <= r and r <= 1 and 0 <= s and s <= 1 and r+s <= 1:
return wu.dot(self.v) /dvu
else:
return None
def normalAt(self, p):
return self.u.cross(self.v).normalized()
class Sphere(object):
def __init__(self, center, radius, surface=None):
self.center = center # point
self.radius = radius # scalar
self.surface = surface
if not surface:
self.surface = Surface()
def __repr__(self):
return 'Sphere(%s,%s)' % (repr(self.center), self.radius)
def intersectionParameter(self, ray):
co = self.center - ray.origin
v = co.dot(ray.direction)
discriminant = v**2 - co.dot(co) + self.radius**2
if discriminant < 0:
return None
else:
return v - math.sqrt(discriminant)
def normalAt(self, p):
return (p - self.center).normalized()
class Plane(object):
def __init__(self, point, normal, surface=None):
self.point = point
self.normal = normal.normalized()
self.surface = surface
if not surface:
self.surface = Surface()
def __repr__(self):
return "Plane(%s, %s)" % (repr(self.point), repr(self.normal))
def intersectionParameter(self, ray):
op = ray.origin - self.point
a = op.dot(self.normal)
b = ray.direction.dot(self.normal)
if b:
return -a / b
else:
return None
def normalAt(self, p):
return self.normal
<file_sep>/Camera.py
# -*- coding: utf-8 -*-
from Illumination import Ray, Light
import Surface
import math
class Camera(object):
def __init__(self, eye, up, focalpoint, fov):
self.eye = eye
self.up = up
self.focalpoint = focalpoint
self.fov = fov
# Weltkoordinatensystem
self.z = (focalpoint - eye).normalized()
self.x = self.z.cross(up).normalized()
self.y = self.x.cross(self.z)
def setScreenSize(self, width, height):
# Definition der Betrachtungsgeometrie
# Bildgröße in Pixel
# höhe und breite.
# Hier wird für das Kamera Objet ein Verhältnis zum aspektRatio ausgerechnet
self.width = width
self.height = height
ratio = width / float(height)
alpha = self.fov / 2.0
self.sceneHeight = 2 * math.tan(alpha)
self.sceneWidth = ratio * self.sceneHeight
# Auflösungsberechnung
self.pixelWidth = self.sceneWidth / (width - 1)
self.pixelHeight = self.sceneHeight / (height - 1)
def build_ray(self, x, y):
#Vorlesung Folie 33
xComp = self.x * (x * self.pixelWidth - self.sceneWidth / 2.0)
yComp = self.y * (y * self.pixelHeight - self.sceneHeight / 2.0)
return Ray(self.eye, self.z + xComp + yComp)
def getMinDistAndObj(self, ray, objectList):
closer = None
minimum = float('inf')
for obj in objectList:
dist = obj.intersectionParameter(ray)
if dist and dist > 0 and dist < minimum:
minimum = dist
closer = obj
return minimum, closer
def shading(self, objectList, lightRay):
for obj in objectList:
t = obj.intersectionParameter(lightRay)
if t > 0:
return t
return 0
def calculateColor(self, objectList, lightList, rayDir, point, obj):
# Richtung des Strahls auf den Punkt der berechnet werden soll
normal = obj.normalAt(point)
color = obj.surface.color * obj.surface.ambient
# Farbe des zurberechneten Objekts
for light in lightList:
lightRay = Ray(point, light.position - point)
if not self.shading(objectList, lightRay):
color += obj.surface.renderColor(lightRay, normal, light.intensity, rayDir)
# Objektfarbe ohne Spiegelung!!!!!!
return color
def renderRay(self, objectList, lightList, ray, bgColor, level):
(dist, obj) = self.getMinDistAndObj(ray, objectList)
if dist and dist > 0 and dist < float('inf'):
point = ray.origin + ray.direction * dist
normal = obj.normalAt(point)
if level == 0:
return self.calculateColor(objectList, lightList, ray.direction, point, obj)
else:
color = self.calculateColor(objectList, lightList, ray.direction, point, obj)
reflectedRay = Ray(point, ray.direction.reflect(normal) * -1)
reflectedColor = self.renderRay(objectList, lightList, reflectedRay, bgColor, level - 1)
return (color * (1 - obj.surface.texture) + reflectedColor * obj.surface.texture).realColor()
else:
return bgColor
def render(self, render_func, objectList, lightList, bgColor=Surface.bgColor, level=1):
for y in range(self.height + 1):
for x in range(self.width + 1):
ray = self.build_ray(x, y)
color = self.renderRay(objectList, lightList, ray, bgColor, level)
render_func(x, y, color)
def __repr__(self):
return 'Camera(position:%s, up:%s, f_point:%s, fieldOfView:%s, x:%s, y:%s, z:%s)' % (
repr(self.eye), repr(self.up), repr(self.focalpoint), repr(self.fov), repr(self.x), repr(self.y),
repr(self.z))
| 570ae6418483fc7070342ccb374e7e42c1077222 | [
"Python"
] | 6 | Python | Luxusproblem/RayCharles2 | 9fc6683eed06409ce8a324dbb3d9a74535d672e2 | 96c61a186a1206d90930a74177f391e910353316 |
refs/heads/Text | <repo_name>sanyaoyao/PowerTrafficeApp<file_sep>/app/src/main/java/com/example/powertrafficeapp/fragment/lukou/frag.java
package com.example.powertrafficeapp.fragment.lukou;
/**
* Created by 小新 on 2017/10/18.
*/
public class frag {
}
<file_sep>/app/src/main/java/com/example/powertrafficeapp/fragment/Fragment_6.java
package com.example.powertrafficeapp.fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.powertrafficeapp.R;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import java.util.ArrayList;
import java.util.Random;
/**
* Created by dell on 2017/07/30.
*/
public class Fragment_6 extends Fragment {
int ss = 0;
String week[] = {"昨天", "今天", "明天", "周五", "周六", "周日", "周一"};
Handler handler = new Handler();
Bar bar = new Bar();
private BarChart chart;
private LineChart lineChart;
private Random random;
private BarData data;
private LineData data1;
private LineData data2;
private BarDataSet dataSet;
private LineDataSet dataSet1;
private LineDataSet dataSet2;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout06, container, false);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
lineChart = (LineChart) getActivity().findViewById(R.id.chart_line);
chart = (BarChart) getActivity().findViewById(R.id.chart_f);
handler.postDelayed(bar, 3000);
LineChart();
}
public void barchart() {
ArrayList<BarEntry> entries = new ArrayList<>();//显示条目
ArrayList<String> xVals = new ArrayList<String>();//横坐标标签
random = new Random();//随机数
for (int i = 0; i < 12; i++) {
int profit = random.nextInt(100);
//entries.add(BarEntry(float val,int positon);
entries.add(new BarEntry(profit, i));
xVals.add((i + 1) + "月");
}
dataSet = new BarDataSet(entries, "公司年利润报表");
dataSet.setColors(ColorTemplate.COLORFUL_COLORS);//颜色模板
data = new BarData(dataSet);
chart.setData(data);
//设置Y方向上动画animateY(int time);
chart.animateY(3000);
//图表描述
Description description = new Description();
description.setText("公司前半年财务报表(单位:万元)");
chart.setDescription(description);
}
public void LineChart() {
ArrayList<String> xeVals = new ArrayList<>();
ArrayList<Entry> yVals = new ArrayList<>();
ArrayList<Entry> yValse = new ArrayList<>();
yVals.add(new Entry(15, 0));
yVals.add(new Entry(4, 1));
yVals.add(new Entry(6, 2));
yVals.add(new Entry(9, 3));
yVals.add(new Entry(12, 4));
yVals.add(new Entry(15, 5));
yVals.add(new Entry(12, 6));
yValse.add(new Entry(15, 2));
yValse.add(new Entry(4, 9));
yValse.add(new Entry(6, 3));
yValse.add(new Entry(9, 8));
yValse.add(new Entry(12, 12));
yValse.add(new Entry(15, 20));
yValse.add(new Entry(12, 18));
// random = new Random();//产生随机数字
for (int i = 0; i < week.length; i++) {
xeVals.add(week[i]);
}
dataSet1 = new LineDataSet(yVals, "温度");//创建数据集并设置标签
dataSet1.setValueTextColor(Color.BLUE);//设置Value值的显示文字颜色,字体大小和字体种类,这里我没有添加对应字体可以自己修改
dataSet1.setValueTextSize(10.0f);
dataSet1.setValueTypeface(null);
dataSet2 = new LineDataSet(yValse, "温度cc");//创建数据集并设置标签
dataSet2.setValueTextColor(Color.BLUE);//设置Value值的显示文字颜色,字体大小和字体种类,这里我没有添加对应字体可以自己修改
dataSet2.setValueTextSize(10.0f);
dataSet2.setColor(R.color.color1);
dataSet2.setValueTypeface(null);
data1 = new LineData(dataSet1);//创建LineData,x轴List和Y轴数据集为参数
data1.addDataSet(dataSet2);
Legend legend = lineChart.getLegend();
legend.setTextColor(Color.CYAN); //设置Legend 文本颜色
lineChart.setData(data1);//给图表添加数据
Description description = new Description();
description.setText("温度变化表");
lineChart.setDescription(description);//设置图表描述的内容位置,字体等等
lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);//设置X轴的显示位置,通过XAxisPosition枚举类型来设置
lineChart.getAxisRight().setEnabled(false);//关闭右边的Y轴,因为默认有两条,左边一条,右边一条,MPAndroidChart中有setEnabled方法的元素基本上都是使能的作用
lineChart.animateY(3000);//动画效果,MPAndroidChart中还有很多动画效果可以挖掘
lineChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
@Override
public void onValueSelected(Entry entry, Highlight highlight) {
// Toast.makeText(getActivity(), String.valueOf(entry.getVal()), Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected() {
// TODO Auto-generated method stub
}
});
}
class Bar implements Runnable {
@Override
public void run() {
ss++;
ArrayList<BarEntry> entries = new ArrayList<>();//显示条目
final ArrayList<Integer> xVals = new ArrayList<>();//横坐标标签
random = new Random();//随机数
for (int i = 0; i < ss; i++) {
int profit = random.nextInt(100);
//entries.add(BarEntry(float val,int positon);
entries.add(new BarEntry(i, profit));
xVals.add(ss * 3);
}
XAxis xAxis = chart.getXAxis();
xAxis.setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float v, AxisBase axisBase) {
return String.valueOf(xVals.get((int) v));
}
@Override
public int getDecimalDigits() {
return 0;
}
});
dataSet = new BarDataSet(entries, "公司年利润报表");
dataSet.setColors(ColorTemplate.COLORFUL_COLORS);//颜色模板
data = new BarData(dataSet);
chart.setData(data);
//设置Y方向上动画animateY(int time);
chart.animateY(3000);
//图表描述
Description description = new Description();
description.setText("公司前半年财务报表(单位:万元)");
chart.setDescription(description);
if (ss > 20) {
handler.removeCallbacks(bar);
} else {
handler.postDelayed(bar, 3000);
}
}
}
}
<file_sep>/app/src/main/java/com/example/powertrafficeapp/fragment/Chart_Fragment/Chart_Fragment_4.java
package com.example.powertrafficeapp.fragment.Chart_Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.powertrafficeapp.R;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import java.util.Random;
/**
* Created by dell on 2017/08/01.
*/
public class Chart_Fragment_4 extends Fragment {
private BarChart chart;
private LineChart lineChart;
private Random random;
private BarData data;
private LineData data1;
private BarDataSet dataSet;
private LineDataSet dataSet1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.chart_fragment_layout4, container, false);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
chart = (BarChart) getActivity().findViewById(R.id.bar2);
}
}
<file_sep>/app/src/main/java/com/example/powertrafficeapp/fragment/lukou/lukou_fragment_4.java
package com.example.powertrafficeapp.fragment.lukou;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.powertrafficeapp.R;
import com.example.powertrafficeapp.View.MyTableTextView;
import com.example.powertrafficeapp.util.UrlBean;
import com.example.powertrafficeapp.util.Util;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
/**
* Created by dell on 2017/08/30.
*/
public class lukou_fragment_4 extends Fragment {
int ddd;
int[] arrayw = {1, 2, 3, 4, 5};
List<String> list;
ArrayAdapter adapter;
String urlHost;
int honglu = 1;
int d = 0;
String hong1;
String huang1;
String lv1;
String hong2;
String huang2;
String lv2;
String hong3;
String huang3;
String lv3;
String hong4;
String huang4;
String lv4;
String hong5;
String huang5;
String lv5;
Button button;
CheckBox check;
private Button buttonF3Refer;
private Button buttonF3Pl;
private TextView textViewH1;
private TextView textViewL1;
private TextView textViewHu1;
private TextView textView57;
private TextView textViewH2;
private TextView textViewL2;
private TextView textViewHu2;
private TextView textView58;
private TextView textViewH3;
private TextView textViewL3;
private TextView textViewHu3;
private TextView textView56;
private TextView textViewH4;
private TextView textViewL4;
private TextView textViewHu4;
private TextView textView54;
private TextView textViewH5;
private TextView textViewL5;
private TextView textViewHu5;
private Button buttonBaocunF3;
private Button buttonQusiaoF3;
private Button buttonCuo;
private LinearLayout Ralativeee;
private UrlBean urlBean;
private View relativeLayout;
private String[] name = {"路口", "红灯时长", "黄灯时长", "绿灯时长", "操作项", " 设置 "};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.lukou_fragment_4, container, false);
return view;
}
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle)
*/
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Ralativeee = (LinearLayout) getActivity().findViewById(R.id.Ralativeerrssrsess);
relativeLayout = LayoutInflater.from(getActivity()).inflate(R.layout.table, null);
urlBean = Util.loadSetting(getContext());
MyTableTextView title = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_1);
title.setText(name[0]);
title.setTextColor(Color.BLUE);
title = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_2);
title.setText(name[1]);
title.setTextColor(Color.BLUE);
title = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_3);
title.setText(name[2]);
title.setTextColor(Color.BLUE);
title = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_4);
title.setText(name[3]);
title.setTextColor(Color.BLUE);
title = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_5);
title.setText(name[4]);
title.setTextColor(Color.BLUE);
title = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_6);
title.setText(name[5]);
title.setTextColor(Color.BLUE);
check = (CheckBox) relativeLayout.findViewById(R.id.checkbox);
check.setVisibility(View.GONE);
button = (Button) relativeLayout.findViewById(R.id.btn_shezhi);
button.setVisibility(View.GONE);
Ralativeee.addView(relativeLayout);
urlHost = "http://" + urlBean.getUrl() + ":" + urlBean.getPort() + "/transportservice/type/jason/action/GetTrafficLightConfigAction.do";
JSONObject object = new JSONObject();
try {
object.put("TrafficLightId", honglu);
} catch (JSONException e) {
e.printStackTrace();
}
getAllCarrrValue(urlHost, object);
}
private void getAllCarValue(String urlHostAction, JSONObject params) {
RequestQueue mQueue = Volley.newRequestQueue(getContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, urlHostAction, params, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// TODO Auto-generated method stu
Log.i("TAG volley", response.toString());
String str = response.toString();
if (honglu == 1) {
try {
JSONObject df = new JSONObject(str);
String dsd = df.getString("serverinfo");
JSONObject dfee = new JSONObject(dsd);
String hong = dfee.getString("RedTime");
String huang = dfee.getString("YellowTime");
String lv = dfee.getString("GreenTime");
relativeLayout = LayoutInflater.from(getActivity()).inflate(R.layout.table, null);
MyTableTextView txt = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_1);
txt.setText(String.valueOf(1));
txt = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_2);
txt.setText(hong);
txt = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_3);
txt.setText(huang);
txt = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_4);
txt.setText(lv);
check = (CheckBox) relativeLayout.findViewById(R.id.checkbox);
check.isChecked();
button = (Button) relativeLayout.findViewById(R.id.btn_shezhi);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialoge();
Toast.makeText(getActivity(), "1", Toast.LENGTH_SHORT).show();
}
});
button.setText(" 设置 ");
Ralativeee.addView(relativeLayout);
Log.i("TAG volley", dsd);
shujue();
} catch (JSONException e) {
e.printStackTrace();
}
} else if (honglu == 2) {
try {
JSONObject df = new JSONObject(str);
String dsd = df.getString("serverinfo");
JSONObject dfee = new JSONObject(dsd);
String hong = dfee.getString("RedTime");
String huang = dfee.getString("YellowTime");
String lv = dfee.getString("GreenTime");
relativeLayout = LayoutInflater.from(getActivity()).inflate(R.layout.table, null);
MyTableTextView txt = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_1);
txt.setText(String.valueOf(2));
txt = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_2);
txt.setText(hong);
txt = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_3);
txt.setText(huang);
txt = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_4);
txt.setText(lv);
check = (CheckBox) relativeLayout.findViewById(R.id.checkbox);
check.isChecked();
button = (Button) relativeLayout.findViewById(R.id.btn_shezhi);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialoge();
Toast.makeText(getActivity(), "2", Toast.LENGTH_SHORT).show();
}
});
button.setText(" 设置 ");
Ralativeee.addView(relativeLayout);
Log.i("TAG volley", dsd);
shujue();
} catch (JSONException e) {
e.printStackTrace();
}
} else if (honglu == 3) {
try {
JSONObject df = new JSONObject(str);
String dsd = df.getString("serverinfo");
JSONObject dfee = new JSONObject(dsd);
String hong = dfee.getString("RedTime");
String huang = dfee.getString("YellowTime");
String lv = dfee.getString("GreenTime");
relativeLayout = LayoutInflater.from(getActivity()).inflate(R.layout.table, null);
MyTableTextView txt = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_1);
txt.setText(String.valueOf(3));
txt = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_2);
txt.setText(hong);
txt = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_3);
txt.setText(huang);
txt = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_4);
txt.setText(lv);
check = (CheckBox) relativeLayout.findViewById(R.id.checkbox);
check.isChecked();
button = (Button) relativeLayout.findViewById(R.id.btn_shezhi);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialoge();
Toast.makeText(getActivity(), "3", Toast.LENGTH_SHORT).show();
}
});
button.setText(" 设置 ");
Ralativeee.addView(relativeLayout);
Log.i("TAG volley", dsd);
shujue();
} catch (JSONException e) {
e.printStackTrace();
}
} else if (honglu == 4) {
try {
JSONObject df = new JSONObject(str);
String dsd = df.getString("serverinfo");
JSONObject dfee = new JSONObject(dsd);
String hong = dfee.getString("RedTime");
String huang = dfee.getString("YellowTime");
String lv = dfee.getString("GreenTime");
relativeLayout = LayoutInflater.from(getActivity()).inflate(R.layout.table, null);
MyTableTextView txt = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_1);
txt.setText(String.valueOf(4));
txt = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_2);
txt.setText(hong);
txt = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_3);
txt.setText(huang);
txt = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_4);
txt.setText(lv);
check = (CheckBox) relativeLayout.findViewById(R.id.checkbox);
check.isChecked();
button = (Button) relativeLayout.findViewById(R.id.btn_shezhi);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialoge();
Toast.makeText(getActivity(), "4", Toast.LENGTH_SHORT).show();
}
});
button.setText(" 设置 ");
Ralativeee.addView(relativeLayout);
Log.i("TAG volley", dsd);
shujue();
} catch (JSONException e) {
e.printStackTrace();
}
} else if (honglu == 5) {
try {
JSONObject df = new JSONObject(str);
String dsd = df.getString("serverinfo");
JSONObject dfee = new JSONObject(dsd);
String hong = dfee.getString("RedTime");
String huang = dfee.getString("YellowTime");
String lv = dfee.getString("GreenTime");
relativeLayout = LayoutInflater.from(getActivity()).inflate(R.layout.table, null);
MyTableTextView txt = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_1);
txt.setText(String.valueOf(5));
txt = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_2);
txt.setText(hong);
txt = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_3);
txt.setText(huang);
txt = (MyTableTextView) relativeLayout.findViewById(R.id.list_1_4);
txt.setText(lv);
check = (CheckBox) relativeLayout.findViewById(R.id.checkbox);
check.isChecked();
button = (Button) relativeLayout.findViewById(R.id.btn_shezhi);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialoge();
Toast.makeText(getActivity(), "5", Toast.LENGTH_SHORT).show();
}
});
button.setText(" 设置 ");
Ralativeee.addView(relativeLayout);
Log.i("TAG volley", dsd);
shujue();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Toast.makeText(getContext(), "失败", Toast.LENGTH_SHORT).show();
Log.i("TAG volley", error.toString());
}
});
mQueue.add(jsonObjectRequest);
}
private void getAllCarrrValue(String urlHostAction, JSONObject params) {
RequestQueue mQueue = Volley.newRequestQueue(getContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, urlHostAction, params, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// TODO Auto-generated method stu
Log.i("TAG volley", response.toString());
String str = response.toString();
if (honglu == 1) {
try {
JSONObject df = new JSONObject(str);
String dsd = df.getString("serverinfo");
JSONObject dfee = new JSONObject(dsd);
hong1 = dfee.getString("RedTime");
huang1 = dfee.getString("YellowTime");
lv1 = dfee.getString("GreenTime");
shuju();
} catch (JSONException e) {
e.printStackTrace();
}
} else if (honglu == 2) {
try {
JSONObject df = new JSONObject(str);
String dsd = df.getString("serverinfo");
JSONObject dfee = new JSONObject(dsd);
hong2 = dfee.getString("RedTime");
huang2 = dfee.getString("YellowTime");
lv2 = dfee.getString("GreenTime");
shuju();
} catch (JSONException e) {
e.printStackTrace();
}
} else if (honglu == 3) {
try {
JSONObject df = new JSONObject(str);
String dsd = df.getString("serverinfo");
JSONObject dfee = new JSONObject(dsd);
hong3 = dfee.getString("RedTime");
huang3 = dfee.getString("YellowTime");
lv3 = dfee.getString("GreenTime");
shuju();
} catch (JSONException e) {
e.printStackTrace();
}
} else if (honglu == 4) {
try {
JSONObject df = new JSONObject(str);
String dsd = df.getString("serverinfo");
JSONObject dfee = new JSONObject(dsd);
hong4 = dfee.getString("RedTime");
huang4 = dfee.getString("YellowTime");
lv4 = dfee.getString("GreenTime");
shuju();
} catch (JSONException e) {
e.printStackTrace();
}
} else if (honglu == 5) {
try {
JSONObject df = new JSONObject(str);
String dsd = df.getString("serverinfo");
JSONObject dfee = new JSONObject(dsd);
hong5 = dfee.getString("RedTime");
huang5 = dfee.getString("YellowTime");
lv5 = dfee.getString("GreenTime");
int s1 = Integer.parseInt(lv1);
int s2 = Integer.parseInt(lv2);
int s3 = Integer.parseInt(lv3);
int s4 = Integer.parseInt(lv4);
int s5 = Integer.parseInt(lv5);
int[] array = {s1, s2, s3, s4, s5};
for (int e = 0; e < (array.length - 1); e++) {
for (int j = e + 1; j < array.length; j++) {
if (array[e] < array[j]) {
int zhong = array[e];
array[e] = array[j];
array[j] = zhong;
int hong = arrayw[e];
arrayw[e] = arrayw[j];
arrayw[j] = hong;
}
}
}
urlBean = Util.loadSetting(getContext());
urlHost = "http://" + urlBean.getUrl() + ":" + urlBean.getPort() + "/transportservice/type/jason/action/GetTrafficLightConfigAction.do";
JSONObject object = new JSONObject();
try {
object.put("TrafficLightId", arrayw[0]);
} catch (JSONException e) {
e.printStackTrace();
}
honglu = arrayw[0];
Log.i("dasdsssss", String.valueOf(object));
Log.i("asdasdkkkk", String.valueOf(arrayw[0]) + "#" + String.valueOf(arrayw[1]) + "#" + String.valueOf(arrayw[2])
+ "#" + String.valueOf(arrayw[3]) + "#" + String.valueOf(arrayw[4]));
Log.i("asdasdkkkk", String.valueOf(array[0]) + "#" + String.valueOf(array[1]) + "#" + String.valueOf(array[2]) + "#"
+ String.valueOf(array[3]) + "#" + String.valueOf(array[4]));
getAllCarValue(urlHost, object);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Toast.makeText(getContext(), "失败", Toast.LENGTH_SHORT).show();
Log.i("TAG volley", error.toString());
}
});
mQueue.add(jsonObjectRequest);
}
public void shuju() {
honglu++;
urlBean = Util.loadSetting(getContext());
urlHost = "http://" + urlBean.getUrl() + ":" + urlBean.getPort() + "/transportservice/type/jason/action/GetTrafficLightConfigAction.do";
JSONObject object = new JSONObject();
try {
object.put("TrafficLightId", honglu);
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("dasds", String.valueOf(object));
getAllCarrrValue(urlHost, object);
}
public void shujue() {
d++;
if (d <= 4) {
urlBean = Util.loadSetting(getContext());
urlHost = "http://" + urlBean.getUrl() + ":" + urlBean.getPort() + "/transportservice/type/jason/action/GetTrafficLightConfigAction.do";
JSONObject object = new JSONObject();
try {
object.put("TrafficLightId", arrayw[d]);
} catch (JSONException e) {
e.printStackTrace();
}
honglu = arrayw[d];
Log.i("dasdssssss", String.valueOf(honglu));
Log.i("dasdsss", String.valueOf(object));
getAllCarValue(urlHost, object);
} else {
return;
}
}
public void dialoge() {
final Dialog dialoge = new Dialog(getActivity());
Log.i("TAG volley", "sdfsdfsdfsdfsdfsdfs");
dialoge.setTitle("查询结果");
dialoge.getWindow().setContentView(R.layout.dialog_sdf_f3);
buttonCuo = (Button) dialoge.getWindow().findViewById(R.id.button_cuo);
buttonCuo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialoge.dismiss();
}
});
dialoge.show();
}
}
<file_sep>/app/src/main/java/com/example/powertrafficeapp/fragment/Fragment_3.java
/**
*
*/
package com.example.powertrafficeapp.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.powertrafficeapp.R;
import com.example.powertrafficeapp.fragment.lukou.lukou_fragment_1;
import com.example.powertrafficeapp.fragment.lukou.lukou_fragment_3;
import com.example.powertrafficeapp.fragment.lukou.lukou_fragment_4;
import java.util.ArrayList;
import java.util.List;
public class Fragment_3 extends Fragment {
List<String> list;
ArrayAdapter adapter;
private Spinner spinnerF3;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout03, container, false);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
spinnerF3 = (Spinner) getActivity().findViewById(R.id.spinner_f3);
list = new ArrayList<String>();
list.add("路口升序");
list.add("路口降序");
list.add("绿灯升序");
list.add("绿灯降序");
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerF3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (i) {
case 0:
String data = (String) spinnerF3.getItemAtPosition(i);//从spinner中获取被选择的数据
getFragmentManager().beginTransaction().replace(R.id.sdsadfsdas, new lukou_fragment_1()).commit();
break;
case 1:
String datad = (String) spinnerF3.getItemAtPosition(i);//从spinner中获取被选择的数据
Toast.makeText(getActivity(), datad, Toast.LENGTH_SHORT).show();
break;
case 2:
String datadd = (String) spinnerF3.getItemAtPosition(i);//从spinner中获取被选择的数据
Toast.makeText(getActivity(), datadd, Toast.LENGTH_SHORT).show();
getFragmentManager().beginTransaction().replace(R.id.sdsadfsdas, new lukou_fragment_3()).commit();
break;
case 3:
String dataddd = (String) spinnerF3.getItemAtPosition(i);//从spinner中获取被选择的数据
Toast.makeText(getActivity(), dataddd, Toast.LENGTH_SHORT).show();
getFragmentManager().beginTransaction().replace(R.id.sdsadfsdas, new lukou_fragment_4()).commit();
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
spinnerF3.setAdapter(adapter);
}
}
| 83caf1ed6c12590e43a027452cdc4d97cd792ecc | [
"Java"
] | 5 | Java | sanyaoyao/PowerTrafficeApp | a7cae1d413eedcdeffc6ae8abd8a5b768f9aa8b1 | 44213f6329d314ba5d407e700b6b3dd1f28649bd |
refs/heads/master | <repo_name>mdubbs/respondr<file_sep>/README.md
# Respondr
Responder is a lightweight (2016 keyword of the year) NodeJS/MongoDB API for gathering and managing feedback from SMS messages sent to phone number(s)/short code(s) on Twilio (think of it like a ticketing system that people text).
## Getting started
- Clone the repository
- `npm install`
- Create a `secrets.json` file in the root (see the development configuration section below for more details)
- `npm start`
- Setup a Twilio SMS Messaging Service and set its `REQUEST URL` to `https://YOURDOMAIN.COM/webhooks/twilio/sms`
## Current Endpoints
```
POST /webhooks/twilio/sms // TwiML Messaging Service SMS Handler
GET /admin/messages // List all messages received from Twilio
GET /admin/message/:id // View specific message by id
DELETE /admin/message // Delete a message by id
GET /admin/tickets // View ticket chains
```
## Development Configuration
**secrets.json**
```
{
"MESSAGING_SID": "XXX", // Twilio Messaging Service ID (restricts your endpoint to your messaging service)
"MONGO_URI": "XXX", // the MongoDB connection string
"API_USERNAME": "XXX", // the username used for basic auth
"API_PASSWORD": "XXX", // the password user for basic auth
"ROLLBAR_TOKEN": "XXX" // your Rollbar key for error tracking
}
```
## Production Configuration
Respondr will look for ENV variables with the same names as the ones in `secrets.json`
## Deployment
This application can be deployed pretty much anywhere NodeJS applications can (YMMV). We currently have it deployed on Microsoft Azure (albeit it feels kind of strange) using an app service and IISNODE for the web server (and it seems pretty performant).
**Supported Platforms (confirmed)**
- Microsoft Azure<file_sep>/models/ticket.js
var mongoose = require("mongoose");
var ticket = new mongoose.Schema({
sender: String,
type: String,
status: String,
assigned: String,
received: { type: Date, default: Date.now },
reviewed: { type: Boolean, default: false },
messages: [mongoose.Schema.Types.Mixed]
});
module.exports = mongoose.model('tickets', ticket);<file_sep>/helpers/basicAuth.js
var basicAuth = require('basic-auth');
var BasicAuth = function(req, res, next) {
// grab the user information using the basic-auth library
var user = basicAuth(req);
// set the username and password to env vars or ones set in the secrets.json file
// TODO: build out a manageable user system
if(req.app.get('env') === 'development') {
var sjson = require('../secrets.json');
var username = sjson.API_USERNAME;
var password = <PASSWORD>;
} else {
var username = process.env.API_USERNAME
var password = <PASSWORD>.API_PASSWORD
}
// if no user, or missing username || password reject
if(!user || !user.name || !user.pass) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
res.status(401);
res.send(JSON.stringify({message: "Authorization Required"}));
return;
}
// check for match
if(user.name === username && user.pass === <PASSWORD>) {
// if match continue
next();
} else {
// return authorization requried
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
res.status(401);
res.send(JSON.stringify({message: "Authorization Required"}));
return;
}
}
module.exports = BasicAuth;<file_sep>/app.js
var compression = require('compression');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var rollbar = require('rollbar');
var mongoose = require('mongoose');
// helpers
var basicAuth = require('./helpers/basicAuth');
// route files
var routes = require('./routes/index');
var webhooks = require('./routes/webhooks');
var admin = require('./routes/admin');
var app = express();
app.use(compression());
app.use(function (req, res, next) {
res.contentType('application/json');
next();
});
var env = process.env.NODE_ENV || 'development';
app.set('port', process.env.PORT || 3000);
app.locals.ENV = env;
app.locals.ENV_DEVELOPMENT = env == 'development';
// setup messaing sid and mongo uri
app.set('MESSAGING_SID', env === 'development' ? require('./secrets.json').MESSAGING_SID : process.env.MESSAGING_SID);
app.set('MONGO_URI', env === 'development' ? require('./secrets.json').MONGO_URI : process.env.MONGO_URI);
// setup Rollbar
if (env === 'development') {
var sjson = require('./secrets.json');
app.use(rollbar.errorHandler(sjson.ROLLBAR_TOKEN, {environment: env}));
}
else
app.use(rollbar.errorHandler(process.env.ROLLBAR_TOKEN, {environment: env}));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
mongoose.connect(app.get('MONGO_URI'), function (err, res) {
if (err) {
console.log ('ERROR connecting to mongo/documentdb' + '. ' + err);
} else {
console.log ('SUCCESS connecting to mongo/documentdb');
}
});
app.use('/', routes);
app.use('/webhooks', webhooks);
app.use('/admin', basicAuth, admin);
/// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
console.log(err);
res.status(err.status || 500);
res.send(JSON.stringify({
message: err.message,
}));
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
console.log(err);
res.status(err.status || 500);
res.send(JSON.stringify({
message: "something went wrong",
}));
});
module.exports = app;
<file_sep>/routes/webhooks.js
var express = require('express');
var router = express.Router();
var assert = require('assert');
var mongoose = require('mongoose');
var rollbar = require('rollbar');
var lang = require('../lang/text.json');
// models
var Message = require('../models/message');
var Ticket = require('../models/ticket');
router.post('/twilio/sms', function(req, res) {
if(req.body.MessagingServiceSid === req.app.get('MESSAGING_SID'))
{
res.setHeader('Content-Type', 'text/plain');
var messageItem = req.body;
var messageBody = req.body.Body.toLowerCase();
var message = new Message({
messageType: messageType,
content: messageItem
});
if(messageBody === 'problem' || messageBody === 'comments')
{
// set response message
var responseMessage = messageBody === 'problem' ? lang.problemResponseText : lang.commentsResponseText;
var messageType = messageBody === 'problem' ? "Problem" : "Comments";
//check for existing ticket within last hour
Ticket.findOne({sender: messageItem.From, type: messageType, received:{$gte: new Date(Date.now() - 1000 * 60 * 30)}}, function(err, retTicket){
if(retTicket == null) {
// no ticket found -- save message and create ticket
message.save(function(err){
if(err){
// error
console.log(err);
res.send(lang.genericErrorText)
} else {
var ticket = new Ticket({
sender: messageItem.From,
type: messageType,
status: "Open",
messages: [message]
});
ticket.save(function(err){
if(err) {
// error
console.log(err);
res.send(lang.genericErrorText)
} else {
res.send(responseMessage);
}
});
}
});
}
});
} else {
//check for chain in the last hour and append
Ticket.findOne({sender: messageItem.From, received:{$gte: new Date(Date.now() - 1000 * 60 * 30)}}, function(err, resTicket){
if(resTicket == null) {
//no existing chain, return dont understand message
res.send(lang.keywordMissResponseText);
} else {
//append message to the chain
message.save(function(err){
if(err) {
console.log(err);
res.send(lang.genericErrorText);
} else {
resTicket.messages.push(message);
resTicket.save(function(err){
if(err) {
console.log(err);
res.send(lang.genericErrorText);
} else {
res.send(lang.thanksAppendedText);
}
});
}
});
}
});
}
} else {
var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
rollbar.reportMessage("Unrecognized Messaging Service from: "+ip);
res.setHeader('Content-Type', 'application/json');
res.status(401);
res.send(JSON.stringify({message:lang.sidNotRecognizedText}));
}
});
module.exports = router;<file_sep>/models/message.js
var mongoose = require("mongoose");
var message = new mongoose.Schema({
received: { type: Date, default: Date.now },
messageType: String,
content: mongoose.Schema.Types.Mixed
});
module.exports = mongoose.model('messages', message); | 660bd95ab8f37dd13a7379aba9fa3df8a8e6e7d1 | [
"Markdown",
"JavaScript"
] | 6 | Markdown | mdubbs/respondr | cf0c61e3f96637857453703c53e506dd50d8ef67 | c06a10e809eddf5e5c1d30150a9c68db7c058a55 |
refs/heads/master | <file_sep>$(document).ready(function(){
// Кнопка меню "Гамбургер"
const hamburger = $('.hamburger')
// Блок мобильной навигации
const navigationMobile = $('.navigation--mobile')
// Изменение вида кнопки меню "Гамбургер" по клику
hamburger.click(function(){
$(this).toggleClass('hamburger--is-active');
if ( $(this).hasClass('hamburger--is-active') ) {
navigationMobile.show()
} else {
navigationMobile.hide()
}
})
// Закрыть мобильную навигацию при клике по ссылке
$('.navigation__item--mobile').on('click', function(){
hamburger.removeClass('hamburger--is-active');
navigationMobile.hide()
})
// Фон для кнопки "Гамбургер" вверху страницы при скролле и сдвиг кнопки
$( window ).scroll(function() {
if ($(this).scrollTop() > 13) {
$('.hamburger__bg').show()
$('.hamburger').addClass('hamburger--scroll')
} else {
$('.hamburger__bg').hide()
$('.hamburger').removeClass('hamburger--scroll')
}
})
//slide2id - плавная прокрутка по ссылкам внутри страницы
$(".logo,.navigation__link,a[href='#top'],a[rel='m_PageScroll2id'],a.PageScroll2id,a.mouse_scroll").mPageScroll2id({
highlightSelector:"nav a",
offset:55
});
// слайдер шапки
const headerSlider = $('#headerSlider')
// Инициализация плагина OwlCarousel для слайдера шапки
headerSlider.owlCarousel({
loop: true,
items: 1,
smartSpeed: 2000,
autoplay: true,
autoplayTimeout: 30000
})
// Повесить события для прокрутки слайдов в шапке на кастомные кнопки
// Go to the next item
$('#headerSliderRight').click(function() {
headerSlider.trigger('next.owl.carousel')
})
// Go to the previous item
$('#headerSliderLeft').click(function() {
headerSlider.trigger('prev.owl.carousel')
})
// Аккордеон
Array.from(document.querySelectorAll('.accordion__item')).forEach(function(e, i) {
e.addEventListener("click", function (){
$(e).siblings().removeClass('accordion__item--active')
$(e).addClass('accordion__item--active')
})
})
// MixItUp - фильтрация работ в портфолио
$('#portfolio-projects').mixItUp()
$('.portfolio__category').on('click', function(){
$('.portfolio__category').removeClass('portfolio__category--active')
$(this).addClass('portfolio__category--active')
})
// слайдер отзывов в блоке клиентов
const clientsReviewsSlider = $('#clientsReviewsSlider')
// Инициализация плагина OwlCarousel для слайдера отзывов в блоке клиентов
clientsReviewsSlider.owlCarousel({
loop: true,
items: 1,
smartSpeed: 2000,
autoplay: true,
autoplayTimeout: 30000
})
})
<file_sep># Creativia
Шаблон PSD "Creativia" для тренировки.
https://vk.com/webcademy?w=wall-40137828_7373
## Layout
https://serrjik.github.io/Creativia/
<file_sep>ymaps.ready(function(){
// Указывается идентификатор HTML-элемента.
var egyptMap = new ymaps.Map("egypt-map", {
center: [26.86, 32.42],// [широта, долгота] — используется по умолчанию;
zoom: 7.2,
controls: []
});
egyptMap.behaviors.disable('scrollZoom');
});
| d03c8eec91569b4461aa4e8c138aadae867a5bde | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | Serrjik/Creativia | 4de736b93a97ebc315bf6afbba64d19d7ba00775 | ee2d318ea4fdc9d72af7928940612c1821859471 |
refs/heads/master | <repo_name>Team4028/Example-Swerve<file_sep>/src/main/java/com/swervedrivespecialties/exampleswerve/commands/shooter/ResetServo.java
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package com.swervedrivespecialties.exampleswerve.commands.shooter;
import com.swervedrivespecialties.exampleswerve.subsystems.Shooter;
import edu.wpi.first.wpilibj2.command.CommandBase;
import edu.wpi.first.wpilibj2.command.InstantCommand;
public class ResetServo extends CommandBase {
Shooter _shooter;
public ResetServo(Shooter shooter) {
_shooter = shooter;
}
@Override
public void initialize() {
_shooter.resetServo();
}
@Override
public void execute(){
_shooter.resetServo();
}
@Override
public boolean isFinished(){
return _shooter.isServoReset();
}
}
<file_sep>/src/main/java/com/swervedrivespecialties/exampleswerve/commands/shooter/RunShooterFromVision.java
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package com.swervedrivespecialties.exampleswerve.commands.shooter;
import com.swervedrivespecialties.exampleswerve.subsystems.Limelight;
import com.swervedrivespecialties.exampleswerve.subsystems.Shooter;
import com.swervedrivespecialties.exampleswerve.subsystems.Limelight.Target;
import com.swervedrivespecialties.exampleswerve.util.ShooterTable;
import com.swervedrivespecialties.exampleswerve.util.util;
import edu.wpi.first.wpilibj2.command.CommandBase;
import edu.wpi.first.wpilibj2.command.InstantCommand;
public class RunShooterFromVision extends CommandBase {
Shooter _shooter;
Limelight _ll = Limelight.getInstance();
double _curTargVelo;
double _actuatorVal;
public RunShooterFromVision(Shooter shooter) {
_shooter = shooter;
addRequirements(_shooter);
}
// Called when the command is initially scheduled.
@Override
public void initialize() {
System.out.println("SHOOTER INITIALIZING");
getSpeed();
_shooter.runShooter(_curTargVelo, _actuatorVal);
}
@Override
public void execute(){
getSpeed();
_shooter.runShooter(_curTargVelo, _actuatorVal);
//System.out.println("hudghfhew");
}
@Override
public boolean isFinished(){
return false;
}
@Override
public void end(boolean interrupted){
_shooter.runShooter(0.0, 0);
}
private void getSpeed(){
//if (_ll.getDistanceToTarget(Target.HIGH) > 0 && _ll.getDistanceToTarget(Target.HIGH) < 420){
//double dist = util.inchesToFeet(_ll.getDistanceToTarget(Target.HIGH));
double dist = 22;
double targetSpeed = ShooterTable.getInstance().CalcShooterValues(dist).MotorTargetRPM;
double targetActuatorVal = ShooterTable.getInstance().CalcShooterValues(dist).ActuatorVal;
_curTargVelo = targetSpeed;
_actuatorVal = targetActuatorVal;
}
// }
}
<file_sep>/src/main/java/com/swervedrivespecialties/exampleswerve/commands/drive/RobotOrientedLineDrive.java
package com.swervedrivespecialties.exampleswerve.commands.drive;
import java.util.function.Supplier;
import com.swervedrivespecialties.exampleswerve.auton.Trajectories;
import com.swervedrivespecialties.exampleswerve.subsystems.DrivetrainSubsystem;
import org.frcteam2910.common.control.Trajectory;
import org.frcteam2910.common.math.Rotation2;
import org.frcteam2910.common.math.Vector2;
import edu.wpi.first.wpilibj2.command.CommandBase;
public class RobotOrientedLineDrive extends CommandBase {
DrivetrainSubsystem _drive;
Vector2 vecRobotOriented;
int numStallCycles = 1;
Rotation2 targetRot;
public RobotOrientedLineDrive(DrivetrainSubsystem drive, Vector2 vec, Rotation2 targetRotation) {
_drive = drive;
vecRobotOriented = vec;
targetRot = targetRotation;
}
public RobotOrientedLineDrive(DrivetrainSubsystem drive, Vector2 vec){
this(drive, vec, null);
}
// Called just before this Command runs the first time
@Override
public void initialize() {
Rotation2 rot =_drive.getGyroAngle();
Vector2 vecFieldOriented = vecRobotOriented.rotateBy(rot);
Trajectory traj;
if (targetRot == null){
traj = Trajectories.generateLineTrajectory(vecFieldOriented, rot, rot);
} else {
traj = Trajectories.generateLineTrajectory(vecFieldOriented, rot, targetRot);
}
Supplier<Trajectory> trajSupplier = () -> traj;
CommandBase followTraj = DriveSubsystemCommands.getFollowTrajectoryCommand(trajSupplier);
followTraj.schedule();
}
// Make this return true when this Command no longer needs to run execute()
@Override
public boolean isFinished() {
return true;
}
}<file_sep>/src/main/java/com/swervedrivespecialties/exampleswerve/commands/drive/ZeroGyro.java
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package com.swervedrivespecialties.exampleswerve.commands.drive;
import com.swervedrivespecialties.exampleswerve.subsystems.DrivetrainSubsystem;
import edu.wpi.first.wpilibj2.command.CommandBase;
public class ZeroGyro extends CommandBase {
DrivetrainSubsystem _drive;
/**
* Creates a new ZeroGyro.
*/
public ZeroGyro(DrivetrainSubsystem drive) {
_drive = drive;
}
// Called when the command is initially scheduled.
@Override
public void initialize() {
System.out.println("Should Be Running");
_drive.resetGyroscope();
}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
}
// Called once the command ends or is interrupted.
@Override
public void end(boolean interrupted){
}
// Returns true when the command should end.
@Override
public boolean isFinished() {
return true;
}
}<file_sep>/src/main/java/com/swervedrivespecialties/exampleswerve/commands/drive/DriveCommand.java
package com.swervedrivespecialties.exampleswerve.commands.drive;
import com.swervedrivespecialties.exampleswerve.Robot;
import com.swervedrivespecialties.exampleswerve.RobotContainer;
import com.swervedrivespecialties.exampleswerve.subsystems.DrivetrainSubsystem;
import edu.wpi.first.wpilibj.geometry.Translation2d;
import edu.wpi.first.wpilibj2.command.CommandBase;
import org.frcteam2910.common.robot.Utilities;
public class DriveCommand extends CommandBase {
DrivetrainSubsystem _drive;
public DriveCommand(DrivetrainSubsystem subsystem) {
_drive = subsystem;
addRequirements(_drive);
}
@Override
public void execute() {
double minSS = DrivetrainSubsystem.getInstance().getMinControllerSpeed();
double additionalSS = Robot.getRobotContainer().getPrimaryRightTrigger();
double speedScale = minSS + (1 - minSS) * additionalSS * additionalSS;
double forward = -Robot.getRobotContainer().getPrimaryLeftYAxis();
forward = Utilities.deadband(forward);
// Square the forward stick
forward = speedScale * Math.copySign(Math.pow(forward, 2.0), forward);
double strafe = -Robot.getRobotContainer().getPrimaryLeftXAxis();
strafe = Utilities.deadband(strafe);
// Square the strafe stick
strafe = speedScale * Math.copySign(Math.pow(strafe, 2.0), strafe);
double rotation = -Robot.getRobotContainer().getPrimaryRightXAxis();
rotation = Utilities.deadband(rotation);
// Square the rotation stick
rotation = speedScale * Math.copySign(Math.pow(rotation, 2.0), rotation);
_drive.drive(new Translation2d(forward, strafe), rotation, _drive.getFieldOriented());
}
@Override
public boolean isFinished() {
return false;
}
}
<file_sep>/src/main/java/com/swervedrivespecialties/exampleswerve/commands/drive/FollowTrajectory.java
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package com.swervedrivespecialties.exampleswerve.commands.drive;
import java.util.function.Supplier;
import com.swervedrivespecialties.exampleswerve.subsystems.DrivetrainSubsystem;
import com.swervedrivespecialties.exampleswerve.util.InertiaGain;
import java.util.Optional;
import org.frcteam2910.common.control.HolonomicMotionProfiledTrajectoryFollower;
import org.frcteam2910.common.control.PidConstants;
import org.frcteam2910.common.control.Trajectory;
import org.frcteam2910.common.math.RigidTransform2;
import org.frcteam2910.common.math.Vector2;
import org.frcteam2910.common.util.DrivetrainFeedforwardConstants;
import org.frcteam2910.common.util.HolonomicDriveSignal;
import org.frcteam2910.common.util.HolonomicFeedforward;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.command.InstantCommand;
import edu.wpi.first.wpilibj.geometry.Translation2d;
import edu.wpi.first.wpilibj2.command.CommandBase;
public class FollowTrajectory extends CommandBase {
DrivetrainSubsystem _drive;
///////////// PATH FOLLOWING CONSTANTS //////////////////
private static final double kMaxVelo = 12 * 12; //This is the physical max velocity of the machine, not of any path
private static final double kInterceptVoltage = .015; //the physical minimum voltage to make the robot move forward
private static final double kPathFollowingVeloFeedForward = 0.0051896679;
private static final double kPathFollowingAccelFeedForward = 0;
private static final double kPathFollowingTranslationP = .05;
private static final double kPathFollowingTranslationI = 0;
private static final double kPathFollowingTranslationD = 0;
private static final double kPathFollowingRotationP = .5;
private static final double kPathFollowingRotationI = 0;
private static final double kPathFollowingRotationD = .06;
////////////////////////////////////////////////////////////
//create appropriate constant classes and eventually a TrajectoryFollower from constants given above
PidConstants translationConstants = new PidConstants(kPathFollowingTranslationP, kPathFollowingTranslationI, kPathFollowingTranslationD);
PidConstants rotationConstants = new PidConstants(kPathFollowingRotationP, kPathFollowingRotationI, kPathFollowingRotationD);
double kFeedForwardVelocity = (1 - kInterceptVoltage) / kMaxVelo;
DrivetrainFeedforwardConstants feedforwardConstants = new DrivetrainFeedforwardConstants(kPathFollowingVeloFeedForward, kPathFollowingAccelFeedForward, kInterceptVoltage);
HolonomicFeedforward feedforward = new HolonomicFeedforward(feedforwardConstants); //can have separate forward and strafe feed forwards if desired.
HolonomicMotionProfiledTrajectoryFollower follower;
private Trajectory trajectory;
private Supplier<Trajectory> trajectorySupplier;
private InertiaGain iGain;
double timestamp;
double lastTimestamp;
double dt;
public FollowTrajectory(DrivetrainSubsystem drive, Supplier<Trajectory> trajSupplier, InertiaGain i) {
_drive = drive;
addRequirements(_drive);
trajectorySupplier = trajSupplier;
iGain = i;
}
public FollowTrajectory(DrivetrainSubsystem drive, Supplier<Trajectory> trajSupplier){
this(drive, trajSupplier, InertiaGain.id);
}
// Called when the command is initially scheduled.
@Override
public void initialize() {
follower = new HolonomicMotionProfiledTrajectoryFollower(translationConstants, rotationConstants, feedforward);
trajectory = trajectorySupplier.get();
timestamp = Timer.getFPGATimestamp();
resetDriveKinematics();
follower.follow(trajectory);
}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
updateTime();
Optional<HolonomicDriveSignal> driveSignal = calculate();
if (driveSignal.isPresent()){
holonomicDrive(iGain.apply(driveSignal.get()));
} else {
_drive.stop();
}
}
// Called once the command ends or is interrupted.
@Override
public void end(boolean interrupted) {
printInfo();
if (interrupted){
_drive.stop();
} else {
CommandBase finishRotate = DriveSubsystemCommands.getRotateToAngleCommand(trajectory.calculateSegment(trajectory.getDuration()).rotation.toDegrees());
finishRotate.schedule();
}
}
// Returns true when the command should end.
@Override
public boolean isFinished() {
return follower.getCurrentTrajectory().isEmpty();
}
////////////// Drivetrain-based utilities ///////////////
private RigidTransform2 getPose(){
return new RigidTransform2(_drive.getKinematicPosition(), _drive.getGyroAngle());
}
private void updateTime(){
lastTimestamp = timestamp;
timestamp = Timer.getFPGATimestamp();
dt = timestamp - lastTimestamp;
}
private Optional<HolonomicDriveSignal> calculate(){
return follower.update(getPose(), _drive.getKinematicVelocity(), _drive.getGyroRate(), timestamp, dt);
}
private void holonomicDrive(HolonomicDriveSignal sig){
_drive.drive(fromTranslation2(sig.getTranslation()), sig.getRotation(), sig.isFieldOriented());
}
private void resetDriveKinematics(){
_drive.reset();
}
private Translation2d fromTranslation2(Vector2 trans){
return new Translation2d(trans.x, trans.y);
}
private void printInfo(){
RigidTransform2 curPose = getPose();
RigidTransform2 goalPose = new RigidTransform2(trajectory.calculateSegment(trajectory.getDuration()).translation, trajectory.calculateSegment(trajectory.getDuration()).rotation);
System.out.println("Goal Pose: (" + Double.toString(goalPose.translation.x) + ", " + Double.toString(goalPose.translation.y) + ", " + Double.toString(goalPose.rotation.toDegrees()));
System.out.println("Current Pose: (" + Double.toString(curPose.translation.x) + ", " + Double.toString(curPose.translation.y) + ", " + Double.toString(curPose.rotation.toDegrees()));
}
}<file_sep>/src/main/java/com/swervedrivespecialties/exampleswerve/RobotMap.java
package com.swervedrivespecialties.exampleswerve;
public class RobotMap {
public static final int DRIVETRAIN_FRONT_LEFT_ANGLE_MOTOR = 1; // CAN
public static final int DRIVETRAIN_FRONT_LEFT_ANGLE_ENCODER = 0; // Analog
public static final int DRIVETRAIN_FRONT_LEFT_DRIVE_MOTOR = 2; // CAN
public static final int DRIVETRAIN_FRONT_RIGHT_ANGLE_MOTOR = 3; // CAN
public static final int DRIVETRAIN_FRONT_RIGHT_ANGLE_ENCODER = 1; // Analog
public static final int DRIVETRAIN_FRONT_RIGHT_DRIVE_MOTOR = 4; // CAN
public static final int DRIVETRAIN_BACK_LEFT_ANGLE_MOTOR = 5; // CAN
public static final int DRIVETRAIN_BACK_LEFT_ANGLE_ENCODER = 2; // Analog
public static final int DRIVETRAIN_BACK_LEFT_DRIVE_MOTOR = 6; // CAN
public static final int DRIVETRAIN_BACK_RIGHT_ANGLE_MOTOR = 7; // CAN
public static final int DRIVETRAIN_BACK_RIGHT_ANGLE_ENCODER = 3; // Analog
public static final int DRIVETRAIN_BACK_RIGHT_DRIVE_MOTOR = 8; // CAN
public static final int KICKER_TALON = 11;
public static final int SHOOTER_SLAVE_NEO = 9;
public static final int SHOOTER_MASTER_NEO = 10;
//infeed stuffs
public static final int CONVEYOR_MOTOR = 12;
public static final int SINGULATOR_MOTOR = 13;
public static final int INFEED_MOTOR = 14;
public static final int PRE_CONVEYOR_SENSOR = 0;
public static final int PRE_SHOOTER_SENSOR = 1;
public static final int POST_SINGULATOR_SENSOR = 2;
// Logging
// this is where the USB stick is mounted on the RoboRIO filesystem.
// You can confirm by logging into the RoboRIO using WinSCP
public static final String PRIMARY_LOG_FILE_PATH = "/media/sda1/logging";
public static final String ALTERNATE_LOG_FILE_PATH = "/media/sdb1/logging";
}<file_sep>/src/main/java/com/swervedrivespecialties/exampleswerve/commands/drive/MikeeDrive.java
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package com.swervedrivespecialties.exampleswerve.commands.drive;
import com.swervedrivespecialties.exampleswerve.Robot;
import com.swervedrivespecialties.exampleswerve.subsystems.DrivetrainSubsystem;
import edu.wpi.first.wpilibj.geometry.Translation2d;
import edu.wpi.first.wpilibj2.command.CommandBase;
public class MikeeDrive extends CommandBase {
DrivetrainSubsystem _drive;
double kRot = .025;
double kDeadBand = .06; //custom because of the unique demands of this task
boolean shouldFinish = false;
public MikeeDrive(DrivetrainSubsystem drive) {
// Use addRequirements() here to declare subsystem dependencies.
_drive = drive;
addRequirements(_drive);
}
// Called when the command is initially scheduled.
@Override
public void initialize() {
}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
double rotVal = -Robot.getRobotContainer().getPrimaryRightXAxis();
if (rotVal > kDeadBand){
_drive.drive(new Translation2d(), kRot, true);
} else if (rotVal < -kDeadBand){
_drive.drive(new Translation2d(), -kRot, true);
} else {
_drive.stop();
}
}
// Called once the command ends or is interrupted.
@Override
public void end(boolean interrupted) {
_drive.drive(new Translation2d(), 0, true);
}
// Returns true when the command should end.
@Override
public boolean isFinished(){
return false;
}
}
<file_sep>/src/main/java/com/swervedrivespecialties/exampleswerve/util/ShooterTable.java
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package com.swervedrivespecialties.exampleswerve.util;
import java.util.Iterator;
import java.util.LinkedList;
/**
* Add your docs here.
*/
public class ShooterTable {
private static ShooterTable _instance = new ShooterTable();
public static ShooterTable getInstance() {
return _instance;
}
private int _indexCounter;
private int _currentIndex = 0;
private ShooterTableEntry ste;
private LinkedList<ShooterTableEntry> _Table = null;
private ShooterTable()
{
_Table = LoadTable();
_currentIndex = 1;
Iterator<ShooterTableEntry> itr = _Table.iterator();
while(itr.hasNext()) {
ste = itr.next();
}
}
public ShooterTableEntry CalcShooterValues (double distanceInFeet)
{
ShooterTableEntry steBelow = null;
ShooterTableEntry steAbove = null;
ShooterTableEntry steCurrent = null;
Iterator<ShooterTableEntry> itr = _Table.iterator();
while(itr.hasNext()) {
steCurrent = itr.next();
if (steCurrent.DistanceInFeet < distanceInFeet) {
steBelow = steCurrent;
continue;
}
else if (steCurrent.DistanceInFeet == distanceInFeet) {
steBelow = steCurrent;
steAbove = steCurrent;
break;
}
// if longer, snapshot Above, stop looping
else if (steCurrent.DistanceInFeet > distanceInFeet) {
steAbove = steCurrent;
break;
}
}
if (steBelow != null && steAbove != null) {
// find the scale factor which is how far we are between the below & above ste
double scaleFactor = (distanceInFeet - steBelow.DistanceInFeet)
/ (steAbove.DistanceInFeet - steBelow.DistanceInFeet);
// round to int
double stg1Adj = scaleFactor * (steAbove.MotorTargetRPM - steBelow.MotorTargetRPM);
int stg1CalculatedRPM = steBelow.MotorTargetRPM + (int) (Math.round(stg1Adj));
double actuatorValue = steBelow.ActuatorVal + (scaleFactor * (steAbove.ActuatorVal - steBelow.ActuatorVal));
// build the return object
ste = new ShooterTableEntry(_indexCounter++, distanceInFeet, stg1CalculatedRPM, actuatorValue);
} else if (steAbove != null) {
ste = steAbove;
} else {
ste = steBelow;
}
return ste;
}
public ShooterTableEntry getNextEntry() {
if (!get_IsAtUpperEntry()) {
_currentIndex++;
}
return _Table.get(_currentIndex);
}
public ShooterTableEntry getCurrentEntry() {
return _Table.get(_currentIndex);
}
public ShooterTableEntry getPreviousEntry() {
if (!get_IsAtLowerEntry()) {
_currentIndex--;
}
return _Table.get(_currentIndex);
}
//============================================================================================
// properties follow
//============================================================================================
public Boolean get_IsAtUpperEntry() {
if (_currentIndex == _Table.size() - 1){
return true;
} else {
return false;
}
}
public Boolean get_IsAtLowerEntry() {
if (_currentIndex == 0){
return true;
} else {
return false;
}
}
//============================================================================================
// helpers follow
//============================================================================================
// create a linked list
private LinkedList<ShooterTableEntry> LoadTable() {
LinkedList<ShooterTableEntry> table = new LinkedList<ShooterTableEntry>();
_indexCounter = 0;
//======================================================================================
// Position feet Stg1
//======================================================================================
table.add(new ShooterTableEntry(_indexCounter++, 11.83, 4028, .6));
table.add(new ShooterTableEntry(_indexCounter++, 23.85, 4028, .6));
//table.add(new ShooterTableEntry(_indexCounter++, 30, -4264));
return table;
}
}
<file_sep>/src/main/java/com/swervedrivespecialties/exampleswerve/util/BoundedServo.java
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package com.swervedrivespecialties.exampleswerve.util;
import edu.wpi.first.wpilibj.Servo;
public class BoundedServo {
Servo servo;
double lower;
double upper;
public BoundedServo(int port, double lowerBound, double upperBound){
servo = new Servo(port);
lower = lowerBound;
upper = upperBound;
}
public void set(double val){
servo.set(Math.min(upper, Math.max(val, lower)));
}
public double get(){
return servo.get();
}
}
<file_sep>/src/main/java/com/swervedrivespecialties/exampleswerve/subsystems/Infeed.java
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package com.swervedrivespecialties.exampleswerve.subsystems;
import com.ctre.phoenix.motorcontrol.ControlMode;
import com.ctre.phoenix.motorcontrol.FeedbackDevice;
import com.ctre.phoenix.motorcontrol.NeutralMode;
import com.ctre.phoenix.motorcontrol.can.TalonSRX;
import com.ctre.phoenix.motorcontrol.can.VictorSPX;
import com.swervedrivespecialties.exampleswerve.RobotMap;
import com.swervedrivespecialties.exampleswerve.commands.infeed.InfeedSubsystemCommands;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.CommandBase;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
public class Infeed extends SubsystemBase {
public static final double kEncoderCountsPerBall = 7500;
private static final double kConveyorTalonConstantVBus = -0.35 ;
private static final double kConveyToShootConstantVBUS = -.7;
private static final double kInfeedVBus = .5;
private static final double kSingulatorVBus = -.45;
private static final double kSingulateToShootVBus = -.5;
private static final boolean kPreConveyorNormal = false;
private static final boolean kPreShooterNormal = false;
private static final boolean kPostSingulatorNormal = false;
private static Infeed _instance = new Infeed();
public static Infeed get_instance() {
return _instance;
}
private TalonSRX _conveyorTalon;
private DigitalInput _preConveyorSensor;
private DigitalInput _preShooterSensor;
private boolean _preConveyorSensorLastCycle;
private boolean _preConveyorSensorThisCycle;
private boolean _isFirstCycle;
private TalonSRX _singulatorTalon;
private VictorSPX _infeedVictor;
private DigitalInput _postSingulatorSensor;
/**
* Creates a new Infeed.
*/
private Infeed() {
_conveyorTalon = new TalonSRX(RobotMap.CONVEYOR_MOTOR);
_conveyorTalon.configSelectedFeedbackSensor(FeedbackDevice.CTRE_MagEncoder_Relative);
_preConveyorSensor = new DigitalInput(RobotMap.PRE_CONVEYOR_SENSOR);
_preShooterSensor = new DigitalInput(RobotMap.PRE_SHOOTER_SENSOR);
_conveyorTalon.setNeutralMode(NeutralMode.Brake);
_singulatorTalon = new TalonSRX(RobotMap.SINGULATOR_MOTOR);
_infeedVictor = new VictorSPX(RobotMap.INFEED_MOTOR);
_postSingulatorSensor = new DigitalInput(RobotMap.POST_SINGULATOR_SENSOR);
}
public void zeroEcnoder(){
_conveyorTalon.setSelectedSensorPosition(0);
}
public double getConveyorPosiiton(){
return _conveyorTalon.getSelectedSensorPosition();
}
public void conveyConveyor(){
_conveyorTalon.set(ControlMode.PercentOutput, kConveyorTalonConstantVBus);
}
public void conveyConveyorToShoot(){
_conveyorTalon.set(ControlMode.PercentOutput, kConveyToShootConstantVBUS);
}
public void stopConveyor(){
_conveyorTalon.set(ControlMode.PercentOutput, 0.0);
}
public void outputToSDB() {
SmartDashboard.putBoolean("PRE-SHOOTER SENSOR", _preShooterSensor.get());
SmartDashboard.putNumber("CONVEYOR TALON ENCODER", _conveyorTalon.getSelectedSensorPosition());
SmartDashboard.putBoolean("PRE-CONVEYOR SENSOR", _preConveyorSensor.get());
}
public boolean getHasBallConveyedBallLength(){
return _conveyorTalon.getSelectedSensorPosition() > kEncoderCountsPerBall;
}
public boolean preConveyorSensorPressed() {
if (_isFirstCycle) {
_preConveyorSensorThisCycle = getPreConveyorSensor();
_isFirstCycle = false;
return false;
} else {
_preConveyorSensorLastCycle = _preConveyorSensorThisCycle;
_preConveyorSensorThisCycle = getPreConveyorSensor();
return _preConveyorSensorThisCycle && !_preConveyorSensorLastCycle;
}
}
public boolean getPreConveyorSensor(){
return _preConveyorSensor.get() == kPreConveyorNormal;
}
public boolean getPreShooterSensor() {
return _preShooterSensor.get() == kPreShooterNormal;
}
public boolean getPostSingulatorSensor(){
return _postSingulatorSensor.get() == kPostSingulatorNormal;
}
public void runInfeed(){
_infeedVictor.set(ControlMode.PercentOutput, kInfeedVBus);
}
public void stopInfeed(){
_infeedVictor.set(ControlMode.PercentOutput, 0.0);
}
public void runSingulator(){
_singulatorTalon.set(ControlMode.PercentOutput, kSingulatorVBus);
}
public void runSingulatorToShoot(){
_singulatorTalon.set(ControlMode.PercentOutput, kSingulateToShootVBus);
}
public void stopSingulator(){
_singulatorTalon.set(ControlMode.PercentOutput, 0.0);
}
@Override
public void periodic() {
if (preConveyorSensorPressed()) {
CommandBase conveyorCommand = InfeedSubsystemCommands.getConveyCommand();
conveyorCommand.schedule();
}
}
}
<file_sep>/src/main/java/com/swervedrivespecialties/exampleswerve/commands/infeed/InfeedSubsystemCommands.java
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package com.swervedrivespecialties.exampleswerve.commands.infeed;
import com.swervedrivespecialties.exampleswerve.subsystems.Infeed;
import edu.wpi.first.wpilibj2.command.CommandBase;
import edu.wpi.first.wpilibj2.command.ParallelCommandGroup;
/**
* Add your docs here.
*/
public class InfeedSubsystemCommands {
public static Infeed infeed = Infeed.get_instance();
public static CommandBase getConveyToShootCommand(){
return new conveyToShoot(infeed);
}
public static CommandBase getConveyCommand(){
return new convey(infeed);
}
public static CommandBase getRunInfeedCommand(){
return new runInfeed(infeed);
}
public static CommandBase getRunSingulatorCommand(){
return new runSingulator(infeed);
}
public static CommandBase getAutonInfeedCommand(double ifTime, double singTime){
return new ParallelCommandGroup(getRunInfeedCommand().withTimeout(ifTime), getRunSingulatorCommand().withTimeout(singTime));
}
}
<file_sep>/src/main/java/com/swervedrivespecialties/exampleswerve/commands/drive/VictorySpin.java
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package com.swervedrivespecialties.exampleswerve.commands.drive;
import com.swervedrivespecialties.exampleswerve.subsystems.DrivetrainSubsystem;
import edu.wpi.first.wpilibj.geometry.Translation2d;
import edu.wpi.first.wpilibj2.command.CommandBase;
public class VictorySpin extends CommandBase {
DrivetrainSubsystem _drive;
/**
* Creates a new VictorySpin.
*/
public VictorySpin(DrivetrainSubsystem drive) {
// Use addRequirements() here to declare subsystem dependencies.
_drive = drive;
}
// Called when the command is initially scheduled.
@Override
public void initialize() {
}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
_drive.drive(new Translation2d(), 1.0, true);
}
// Called once the command ends or is interrupted.
@Override
public void end(boolean interrupted) {
_drive.stop();
}
// Returns true when the command should end.
@Override
public boolean isFinished() {
return false;
}
}
<file_sep>/src/main/java/com/swervedrivespecialties/exampleswerve/commands/drive/DriveSubsystemCommands.java
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package com.swervedrivespecialties.exampleswerve.commands.drive;
import java.util.function.Supplier;
import com.swervedrivespecialties.exampleswerve.subsystems.DrivetrainSubsystem;
import com.swervedrivespecialties.exampleswerve.subsystems.Limelight;
import com.swervedrivespecialties.exampleswerve.util.InertiaGain;
import org.frcteam2910.common.control.Trajectory;
import org.frcteam2910.common.math.Rotation2;
import org.frcteam2910.common.math.Vector2;
import edu.wpi.first.wpilibj2.command.CommandBase;
/**
* Add your docs here.
*/
public class DriveSubsystemCommands {
public static DrivetrainSubsystem drivetrainSubsystem = DrivetrainSubsystem.getInstance();
public static CommandBase getDriveCommand(){
return new DriveCommand(drivetrainSubsystem);
}
public static CommandBase getRotateToAngleCommand(double targetAngleDegrees, double timeout){
return new RotateToAngle(drivetrainSubsystem, targetAngleDegrees, timeout);
}
public static CommandBase getRotateToAngleCommand(double targetAngleDegrees){
return new RotateToAngle(DrivetrainSubsystem.getInstance(), targetAngleDegrees);
}
public static CommandBase getFieldOrientedLineDriveCommand(Vector2 vec, Rotation2 rot){
return new FieldOrientedLineDrive(drivetrainSubsystem, vec, rot);
}
public static CommandBase getFieldOrientedLineDriveCommand(Vector2 vec){
return new FieldOrientedLineDrive(drivetrainSubsystem, vec);
}
public static CommandBase getRobotOrientedLineDriveCommand(Vector2 vec, Rotation2 rot){
return new RobotOrientedLineDrive(drivetrainSubsystem, vec, rot);
}
public static CommandBase getRobotOrientedLineDriveCommand(Vector2 vec){
return new RobotOrientedLineDrive(drivetrainSubsystem, vec);
}
public static CommandBase getFollowTrajectoryCommand(Supplier<Trajectory> trajSupplier, InertiaGain i){
return new FollowTrajectory(drivetrainSubsystem, trajSupplier, i);
}
public static CommandBase getFollowTrajectoryCommand(Supplier<Trajectory> trajSupplier){
return new FollowTrajectory(drivetrainSubsystem, trajSupplier);
}
public static CommandBase getVictorySpinCommand(double timeout){
return new VictorySpin(drivetrainSubsystem).withTimeout(timeout);
}
public static CommandBase getLineDriveCommand(Vector2 vec, boolean isFieldOriented, Rotation2 rot, double timeOut){
return new LineDrive(vec, isFieldOriented, rot, timeOut);
}
public static CommandBase getLineDriveCommand(Vector2 vec, boolean isFieldOriented, Rotation2 rot){
return new LineDrive(vec, isFieldOriented, rot);
}
public static CommandBase getLineDriveCommand(Vector2 vec, boolean isFieldOriented){
return new LineDrive(vec, isFieldOriented);
}
public static CommandBase getLineDriveCommand(Vector2 vec){
return new LineDrive(vec);
}
public static CommandBase getZeroGyroCommand(){
return new ZeroGyro(drivetrainSubsystem);
}
public static CommandBase getToggleSpeedCommand(){
return new ToggleSpeed(drivetrainSubsystem);
}
public static CommandBase getToggleFieldOrientedCommand(){
return new ToggleSpeed(drivetrainSubsystem);
}
public static CommandBase getMikeeDriveCommand(){
return new MikeeDrive(drivetrainSubsystem);
}
public static CommandBase getLLRotateToTargetCommand(){
return new LLRotateToTarget(Limelight.getInstance(), drivetrainSubsystem).withTimeout(2.5);
}
}
| de7a4f060c8657755e8370508e6082965e7774d3 | [
"Java"
] | 14 | Java | Team4028/Example-Swerve | 629ea03e4e86de59de17fc80f38ea2901c37dcf0 | efdaa0bb97c81e5fde0b3a46f5c045088847a299 |
refs/heads/master | <file_sep> var wins = 1;
var losses = 1;
var guessesLeft = 10;
var computerChoices = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
var allUserGuess = [];
document.onkeyup = function(event) {
var userGuess = event.key;
var computerGuess = computerChoices[Math.floor(Math.random() * computerChoices.length)];
document.getElementById("allUserGuess").innerHTML = userGuess + "," + allUserGuess;
// For me.
console.clear(computerGuess);
console.log(computerGuess);
// Limits user picks to computerChoices array values.
if (computerChoices.indexOf(userGuess) !== -1) {
//add next userGuess to front of array
allUserGuess.unshift(" " + userGuess);
// Guesses Left Countdown.
if (guessesLeft > 0) {
guessesLeft--;
document.getElementById("guessesLeft").innerHTML = guessesLeft;
} else if (guessesLeft < 1) {
allUserGuess = [];
document.getElementById("allUserGuess").innerHTML = allUserGuess;
guessesLeft = guessesLeft + 10;
document.getElementById("guessesLeft").innerHTML = guessesLeft;
}
// Wins.
if (userGuess === computerGuess) {
allUserGuess = [];
document.getElementById("wins").innerHTML = wins;
guessesLeft = guessesLeft + (10 - guessesLeft);
document.getElementById("response").innerHTML = "You Win! Press Any Key To Keep Playing!"
wins++;
} else {
document.getElementById("response").innerHTML = "Try Again.";
}
// Losses.
if ((guessesLeft < 1) && (userGuess !== computerGuess)) {
document.getElementById("losses").innerHTML = losses;
document.getElementById("response").innerHTML = "You Lose! Press Any Letter To Play Again!";
losses++;
}
}
} | 78fb0f61ba442a23dabf1aee896de9a324c3b581 | [
"JavaScript"
] | 1 | JavaScript | Courtney6554/Psychic-Game | 33db9e6bfb0232c8b59c86f099de762b9a746e9b | 0468550f7d2909041b22864a07ac69162a7a34e5 |
refs/heads/master | <file_sep>package cn.itsource.aigou.product.service;
import cn.itsource.aigou.product.domain.ProductType;
import com.baomidou.mybatisplus.service.IService;
import java.util.List;
/**
* <p>
* 商品目录 服务类
* </p>
*
* @author wbtest
* @since 2019-05-09
*/
public interface IProductTypeService extends IService<ProductType> {
/**
* 获取树状结构
* @return
*/
List<ProductType> treeData();
}
<file_sep>package cn.itsource.aigou.product.service.impl;
import cn.itsource.aigou.product.domain.ProductType;
import cn.itsource.aigou.product.mapper.ProductTypeMapper;
import cn.itsource.aigou.product.service.IProductTypeService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
* 商品目录 服务实现类
* </p>
*
* @author wbtest
* @since 2019-08-01
*/
@Service
public class ProductTypeServiceImpl extends ServiceImpl<ProductTypeMapper, ProductType> implements IProductTypeService {
@Autowired
private ProductTypeMapper productTypeMapper;
@Override
public List<ProductType> treeData() {
//要实现树装结构:
//return treeDataRecursion(0L);
return treeDataLoop();
}
/**
* 1:查询出所有的数据
* 2:组装父子结构
* @return
*/
public List<ProductType> treeDataLoop() {
//返回的一级菜单
List<ProductType> result = new ArrayList<>();
//1:查询出所有的数据
List<ProductType> allProductTypes = productTypeMapper.selectList(null);
Map<Long,ProductType> map=new HashMap<>();
//循环:把所有的对象,放到一个map:
for (ProductType cur : allProductTypes) {
map.put(cur.getId(),cur);
}
//2:组装父子结构
for (ProductType current : allProductTypes) {
//找一级菜单
if(current.getPid()==0){
result.add(current);
}else{
//你不是一级菜单,你就是儿子: 你是谁的儿子??? 你是你老子的儿子
ProductType parent = null;//你老子
/*
嵌套循环了:不嵌套
for (ProductType cur : allProductTypes) {
if(cur.getId()==current.getPid()){
parent=cur;
}
}*/
parent = map.get(current.getPid());
/* List<ProductType> children = parent.getChildren();//你老子的儿子
children.add(current);//你自己是你老子的儿子*/
parent.getChildren().add(current);
}
}
return result;
}
/**
* 递归:
* 自己方法里调用自己,但是必须有一个出口:没有儿子就出去;
* 好么:
* 不好,因为每次都要发送sql,就要发送很多的sql:
* 要耗时;数据库的服务器要承受很多的访问量,压力大。
* ====》原因是发送了很多sql,我优化就少发送,至少发送1条。
* @return
*/
public List<ProductType> treeDataRecursion(Long pid) {
//所有的一级菜单
List<ProductType> allChildren = getAllChildren(pid);
//出口:没有儿子
if(allChildren==null||allChildren.size()==0){
return null;
}
//遍历:找当前遍历对象的儿子:
for (ProductType current : allChildren) {
//找当前对象的儿子
List<ProductType> productTypes = treeDataRecursion(current.getId());
current.setChildren(productTypes);
}
return allChildren;
}
/**
* 查询数据的pid=pid的:
* // select * from t_product_type where pid = 2
* @param pid
* @return
*/
public List<ProductType> getAllChildren(Long pid) {
Wrapper<ProductType> wrapper = new EntityWrapper<>();
wrapper.eq("pid",pid);
return productTypeMapper.selectList(wrapper);
}
}
<file_sep>package cn.itsource.aigou.client;
import cn.itsource.aigou.client.RedisClient;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;
@Component
public class RedisFall implements FallbackFactory<RedisClient> {
@Override
public RedisClient create(Throwable throwable) {
return new RedisClient() {
@Override
public void setRedis(String key, String value) {
}
@Override
public String getRedis(String key) {
return null;
}
};
}
}
| 0d9ed79b227101a41b1262eebb16b39cd30814f6 | [
"Java"
] | 3 | Java | dianchechihanxdd/aigou | 16add33ff7fd340c84c2c57c2da69edf48460cf9 | aa9d897d946a457f6268a68adfe81cadc7e033c2 |
refs/heads/master | <repo_name>amachi0/android_kotlin_mvp<file_sep>/app/src/main/java/net/soda/logintestmvp/Presenter/ILoginPresenter.kt
package net.soda.logintestmvp.Presenter
interface ILoginPresenter {
fun Login(email: String, password: String)
}<file_sep>/app/src/main/java/net/soda/logintestmvp/View/MainActivity.kt
package net.soda.logintestmvp.View
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import net.soda.logintestmvp.Presenter.LoginPresenter
import net.soda.logintestmvp.R
class MainActivity : AppCompatActivity(), ILoginView {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnLogin.setOnClickListener {
val email: String = editEmail.text.toString()
val password: String = editPassword.text.toString()
val loginPresenter: LoginPresenter = LoginPresenter(this)
loginPresenter.Login(email, password)
}
}
override fun onLoginResult(message: String) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
}
<file_sep>/app/src/main/java/net/soda/logintestmvp/Model/User.kt
package net.soda.logintestmvp.Model
import android.text.TextUtils
import android.util.Log
import android.util.Patterns
class User(email: String, password: String): IUser {
var mail: String = email
var passwords: String = password
override fun getEmail(): String {
return mail
}
override fun getPassword(): String {
return passwords
}
override fun isValidData(): Boolean {
Log.d("email", getEmail())
Log.d("password", getPassword())
if(!TextUtils.isEmpty(getEmail())){
Log.d("null", "success")
}
if(getPassword().length > 6){
Log.d("length", "success")
}
if(Patterns.EMAIL_ADDRESS.matcher(getEmail()).matches()){
Log.d("match", "success")
}
return !TextUtils.isEmpty(getEmail()) && getPassword().length > 6 && Patterns.EMAIL_ADDRESS.matcher(getEmail()).matches()
}
}<file_sep>/app/src/main/java/net/soda/logintestmvp/Presenter/LoginPresenter.kt
package net.soda.logintestmvp.Presenter
import net.soda.logintestmvp.Model.User
import net.soda.logintestmvp.View.ILoginView
class LoginPresenter(loginView: ILoginView): ILoginPresenter{
val mloginView: ILoginView = loginView
override fun Login(email: String, password: String) {
val user: User = User(email, password)
val isValid: Boolean = user.isValidData()
if (isValid == true){
mloginView.onLoginResult("Success")
} else{
mloginView.onLoginResult("False")
}
}
}<file_sep>/app/src/main/java/net/soda/logintestmvp/Model/IUser.kt
package net.soda.logintestmvp.Model
interface IUser {
fun getEmail(): String
fun getPassword(): String
fun isValidData(): Boolean
} | 8ea1d251bb47f18b1e30e7c22369b007290d0dad | [
"Kotlin"
] | 5 | Kotlin | amachi0/android_kotlin_mvp | a91bd97adf01887f4fdb1b98f2ead6a590b24822 | b64ff6988d677df2adb804d96b344658272d9b7d |
refs/heads/master | <file_sep>using System;
using System.Runtime.InteropServices;
namespace UnfuckMicrophone
{
public static class HandleYolo
{
[DllImport("kernel32.dll")]
public extern static IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public extern static bool ShowWindow(IntPtr hWnd, int nCmdShow);
public const int SW_HIDE = 0;
public const int SW_SHOW = 5;
}
}
<file_sep># UnfuckMicrophone
Skype 4 Business does automaticaly adjust your microphone volume 'for the best experience'.
There is an official workaround to disable this feature but this does not work on my side.
(Checkout this here: https://support.microsoft.com/en-us/help/4054427/disable-automatic-gain-control-skype-for-business-windows)
UnfuckMicrophone is a background process that maintains the main microphone volume to 100% to fix Skype 4 Business microphone mess.
For Windows only.<file_sep>using System.Threading;
using VideoPlayerController;
namespace UnfuckMicrophone
{
internal class Program
{
private static void Main(string[] args)
{
var handle = HandleYolo.GetConsoleWindow();
HandleYolo.ShowWindow(handle, HandleYolo.SW_HIDE);
while (true)
{
try
{
var t = AudioManager.GetComMicVolume();
if (t == 40) // F*ck skype for business.
AudioManager.SetComMivVolume(100);
}
catch
{
// Don't care. Happens if no microphone.
}
Thread.Sleep(1000 * 2);
}
}
}
}
| fd9256df39c8249256503262371c50b51c94e26c | [
"Markdown",
"C#"
] | 3 | C# | TomyCesaille/UnfuckMicrophone | e7fe978d8506dbf1f9f139895cf077b976ae0179 | 12482d94164e8a40cd0487ec9f29ada8d070c412 |
refs/heads/master | <file_sep># *L*<sup>2</sup>-methods for resonances
A resonance is *quasi-bound* or *temporary* state of a quantum state. It can be thought of as a discrete state embedded in and interacting with a continuum so that the discrete state can decay into the continuum and thus aquires a lifetimes.
In principle, resonances are features of a scattering continuum, however, imposing scattering boundary conditions is far more challenging than imposing bound-state (or *L*<sup>2</sup>) boundary conditions, and therefore many *L*<sup>2</sup>-methods for computing the energy and the lifetime of resonance states have been developed.
Even though these methods are based on completely different ideas, all *L*<sup>2</sup>-methods follow a similar computational protocol:
1. Parametrize the physical Hamiltonian **H** → **H**(λ).
2. Diagonalize **H**(λ) repeatedly.
3. Identify the resonance feature, normaly one- possibly two- trajectories *E*<sub>*n*</sub>(λ<sub>*j*</sub>).
4. Analyze the identified trajectories to find the resonance energy *E*<sub>*r*</sub> and the lifetime τ.
## Implementation
All methods are implememted as jupyter notebooks, but a substantial part of the auxilary functions are hidden in Python libraries.
* The **notebooks** directory contains subdirectories for the four major methods (see below), and two directories collect analytical (sympy) notebooks for Gaussian integrals and for gradients of the RAC extrapolation formulas.
* The **Python_libs** directories collects helper functions imported into various notebooks. See documentation of each function.
## Methods
The goal is to compare different *L*<sup>2</sup>-methods and, in particular, their variants on equal footing. To do so, a model potential is used:
*V*(*r*) = (*ar*<sup> 2</sup> - *b*) exp(-*cr*<sup> 2</sup>) + (l(l+1))/(2*r*<sup> 2</sup>)
where *l* = 1, and the parameters *a*, *b*, and *c* are chosen so that *V*(*r*) supports a bound state at *E* = -7.2 eV and a resonance at *E*<sub>*r*</sub> = 3.2 eV.
### *L*<sup>2</sup>-methods implemented
The four major methods implemented are:
1. Complex scaling (CS).
2. Complex absorbing potential (CAP).
3. Howard-Taylor stabilization (HTS).
4. Regularized analytic continuation (RAC).
### Basis sets
Each method needs to be combined with a represation of the Hamiltonian, that is, with a 'basis set'. Two basis set types are compared: A quasi-exact discrete variable representation (DVR)- a dense grid basis- and three small Gaussian basis sets modeling basis sets typically used in electronic structure theory (20 GTOs or less).
### Variants
The major method- CS, CAP, HTS, or RAC- and the basis essentially define steps 1 to 3. But each major methods has several analyis variants for step 4. In addition, RAC has also step 1 variants. It is these variants that are often brushed under the rug, but that turn out to yield vastly different resonance energies even though the input data for all variants of one major method are identical.
Two notebooks in each of the four main subdirectories deal with step 2: One DVR and one Gaussian basis notebook. The other notebooks deal with different analysis variants used in step 4.
### Licence
MIT licence.
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 2 08:54:27 2021
@author: <NAME>
"""
"""
A class to manage a Gaussian basis for the Jolanta potential with l=1
Lots of helper functions not in the class to keep the legacy notebooks working.
"""
import numpy as np
import scipy.special
from scipy.linalg import eigh
class GBR:
def __init__(self, alphas, param, contract=(0, 0), diffuse=(0, 1.4)):
"""
alphas: exponents alphas
aparam: Jolanta-3D parameters (a,b,c)
contract(nc, nu):
uses the lowest nc eigenvectors of H (only nc==1 makes sense)
and adds nu uncontracted GTOs starting from the smallest alpha
diffuse(n_diff, scale):
after contraction, add n_diff even-tempered diffuse functions
alphas[-1]/s, alphas[-1]/s**2, ...
"""
self.n_val = len(alphas)
self.n_diff, scale = diffuse
self.param = param
self.nc, self.nu = contract
self.alphas = np.zeros(self.n_val + self.n_diff)
self.alphas[:self.n_val] = np.sort(alphas)[::-1]
for j in range(self.n_diff):
self.alphas[self.n_val+j] = self.alphas[self.n_val+j-1]/scale
self.Ns = np.zeros(self.n_val + self.n_diff)
for j, a in enumerate(self.alphas):
self.Ns[j] = Jolanta_3D_PNorm(a)
""" uncontracted S, T, and V_Jolanta """
self.Sun, self.Tun, self.Vun = Jolanta_GTO_H(self.alphas, self.Ns, self.param)
""" contraction matrix C with shape (n_primitive, n)contracted) """
self.C = 0
if self.nc == 0:
""" no contraction = all basis function """
self.S, self.T, self.V = self.Sun, self.Tun, self.Vun
return
""" else: contract with valence eigenstates """
nv = self.n_val
Sval, Tval, Vval = self.Sun[:nv,:nv], self.Tun[:nv,:nv], self.Vun[:nv,:nv]
Es, cs = eigh(Tval + Vval, b=Sval)
n_prim = self.n_val + self.n_diff
n_cont = self.nc + self.nu + self.n_diff
self.C = np.zeros((n_prim, n_cont))
self.C[:nv,:self.nc] = cs[:,:self.nc]
for j in range(n_cont - self.nc):
self.C[-1-j,-1-j] = 1.0
self.S = np.linalg.multi_dot([self.C.T, self.Sun, self.C])
self.T = np.linalg.multi_dot([self.C.T, self.Tun, self.C])
self.V = np.linalg.multi_dot([self.C.T, self.Vun, self.C])
def exponents(self):
return self.alphas
def normalization_constants(self):
return self.Ns
def print_exp(self):
print(" alpha r0=1/sqrt(alpha) Norm")
for j, a in enumerate(self.alphas):
print(f" {a:15.8e} {np.sqrt(1/a):15.8e} {self.Ns[j]:11.4e}")
def contraction_matrix(self):
return self.C
def STV(self):
return self.S, self.T, self.V
def V_jolanta(self, params):
"""
returns the Jolanta(l=1) potential with different parameters
does not change self.V
"""
Sun, Tun, Vun = Jolanta_GTO_H(self.alphas, self.Ns, params)
if self.nc == 0:
return Vun
else:
return np.linalg.multi_dot([self.C.T, Vun, self.C])
def H_theta(self, theta, alpha):
"""
theta: scaling angle for the radial coordinate r: exp(i*theta)
returns: the complex scaled Hamiltonian H(r*exp(i*theta))
"""
z = alpha*np.exp(1j*theta)
f = z**(-2)
Vun_rot = Jolanta_GTO_VJrot(self.alphas, self.Ns, self.param, z)
Hun_rot = f*self.Tun + Vun_rot
if self.nc == 0:
return Hun_rot
else:
return np.linalg.multi_dot([self.C.T, Hun_rot, self.C])
def Wcap(self, rc):
""" real matrix W for the CAP, where W(r<rc) = 0 """
Wun = Jolanta_GTO_W(Jolanta_3D_Wcap, self.alphas, self.Ns, rc)
if self.nc == 0:
return Wun
else:
return np.linalg.multi_dot([self.C.T, Wun, self.C])
def V_Coulomb(self):
Vun = Jolanta_GTO_W(Jolanta_3D_Coulomb, self.alphas, self.Ns, 1.0)
if self.nc == 0:
return Vun
else:
return np.linalg.multi_dot([self.C.T, Vun, self.C])
def V_softbox(self, rc):
Vun = Jolanta_GTO_W(Jolanta_3D_softbox, self.alphas, self.Ns, rc)
if self.nc == 0:
return Vun
else:
return np.linalg.multi_dot([self.C.T, Vun, self.C])
def eval_vector(self, cs, rs, u=True):
"""
plotting a wavefunction psi(r) = Sum c_i f_i
where f_i can be primitive GTO or a contracted function
parameters:
cs : coefficient vector
rs : positions at which to evalutes psi(r)
u : return u(r) or R(r), where R(r) = u(r)/r
returns:
ys : psi(r)
"""
if self.nc > 0:
c_un = np.matmul(self.C, cs)
return Eval_GTO_wf_3D(self.alphas, self.Ns, c_un, rs, u)
else:
return Eval_GTO_wf_3D(self.alphas, self.Ns, cs, rs, u)
def Jolanta_3D_PNorm(a):
"""
see Analytic integrals notebook in Stab directory for formulas
integrals of two GTOs: r*exp(-a_j*r**2) dV = r**2 dr
return the normalization 1/sqrt(S_jj)
R is a p-fn, u is a D-fn:
4 * 2**(3/4) * sqrt(3) * a1**(5/4) / (3*pi**(1/4))
"""
return 4 * 2**(3/4) * np.sqrt(3) * a**(5/4) / (3*np.pi**(1/4))
def Jolanta_3D_GTO(a1, a2, param):
"""
see Analytic integrals notebook in GTO directory for formulas
integrals of two GTOs: x*exp(-a_j*x**2)
computes overlap, kinetic energy, and potential
R1 and R2 are p-fns, u1 and u2 are D-fns:
the parameter l is ignored (so that 1D and 3D may call the same fn)
"""
a, b, c = param
sqrt_pi = np.sqrt(np.pi)
S = 3 * sqrt_pi / (8*(a1 + a2)**2.5)
T = sqrt_pi * (1.875*a1*a2 - 0.25*(a1 + a2)**2)/(a1 + a2)**3.5
VJ = 3 * sqrt_pi * (5*a - 2*a1*b - 2*a2*b - 2*b*c)/(16*(a1 + a2 + c)**3.5)
VL = sqrt_pi / (4*(a1 + a2)**1.5)
return S, T, VJ+VL
def Jolanta_GTO_H(alphas, Ns, param):
"""
Hamiltonian matrix in the uncontracted GTO basis set
Parameters
----------
alphas : np.array of GTO exponents
Ns : np.array of normalization constants
param : (a, b, c): parameters of the Jolanta potential
Returns 3 numpy matrices
-------
S : overlap matrix
T : kinetic energy matrix
V : potential energy matrix
"""
nbas = len(alphas)
S=np.zeros((nbas,nbas))
T=np.zeros((nbas,nbas))
V=np.zeros((nbas,nbas))
for i in range(nbas):
ai, Ni = alphas[i], Ns[i]
S[i,i], T[i,i], V[i,i] = Jolanta_3D_GTO(ai, ai, param)
S[i,i] *= Ni*Ni
T[i,i] *= Ni*Ni
V[i,i] *= Ni*Ni
for j in range(i):
aj, Nj = alphas[j], Ns[j]
Sij, Tij, Vij = Jolanta_3D_GTO(ai, aj, param)
S[i,j] = S[j,i] = Ni*Nj * Sij
T[i,j] = T[j,i] = Ni*Nj * Tij
V[i,j] = V[j,i] = Ni*Nj * Vij
return S, T, V
def Jolanta_3D_CS(a12, param, z):
"""
computes int dr r**4 * exp(-ag*r**2) * (VJ + Vl)
VJ = (a*r**2 - b)*exp(-c*r**2) = Va - Vb
Vl = 1/r**2
for r -> r*exp(i*theta)
this is for a radial p-GTO: u(r) = R(r)*r
u1*u2 = r**4 * exp(-(a1+a2)*r**2)
z = alpha*exp(I*theta)
both Va and Vb are valid only for 2*theta <= pi/2
no problem as the max rotation angle is pi/4
VJ(z*r) = (3*sqrt(pi)*(5*a*z**2 - 2*b*(a12 + c*z**2))
/(16*(a12 + c*z**2)**(7/2))
"""
a, b, c = param
sp = np.sqrt(np.pi)
f = z**2
#Va = 15*sp*a*f / (16*(a12 + c*f)**(7/2))
#Vb = 3*sp*b / (8*(a12 + c*f)**(5/2))
VJ = ( 3*sp * (5*a*f - 2*b*(a12 + c*f))
/ (16*(a12 + c*f)**3.5) )
VL = sp / (4*(a12)**1.5) / f
return VJ + VL
def Jolanta_3D_Wcap(a, rc):
"""
computes int_rc^oo dr r**4 * exp(-a*r**2) * w(r)
w(r) = (r-rc)**2 for x > rc; else 0
this is for CAP radial p-GTO: u(r) = R(r)*r
u1*u2 = r**4 * exp(-(a1+a2)*r**2)
- rc*exp(-a*rc**2)/(8*a**3)
- 3*sqrt(pi)*rc**2*erf(sqrt(a)*rc)/(8*a**(5/2))
+ 3*sqrt(pi)*rc**2/(8*a**(5/2))
- 15*sqrt(pi)*erf(sqrt(a)*rc)/(16*a**(7/2))
+ 15*sqrt(pi)/(16*a**(7/2))
W = (- rc*exa/(8*a**3)
- 3*sp*rc**2 * erf / (8*a**(5/2))
+ 3*sp*rc**2 / (8*a**(5/2))
- 15*sp * erf / (16*a**(7/2))
+ 15*sp / (16*a**(7/2))
)
W = (- rc*exa / (8*a**3)
+ 3*sp*rc**2 / (8*a**(5/2)) * (1 - erf)
+ 15*sp / (16*a**(7/2)) * (1 - erf)
)
"""
sp = np.sqrt(np.pi)
exa = np.exp(-a*rc**2)
erf = scipy.special.erf(rc*np.sqrt(a))
W = (- rc*exa / (8*a**3)
+ 3*sp*rc**2 / (8*a**(5/2)) * (1 - erf)
+ 15*sp / (16*a**(7/2)) * (1 - erf)
)
return W
def Jolanta_3D_Coulomb(a, rc):
"""
computes int_rc^oo dr r**4 * exp(-a*r**2) * (-1/r)
this is for RAC radial p-GTO: u(r) = R(r)*r
u1*u2 = r**4 * exp(-(a1+a2)*r**2)
rc is ignored (needed for function uniformity)
returns -1/(2*a**2)
"""
return -1/(2*a**2)
def Jolanta_3D_softbox(a, rc):
"""
computes int_rc^oo dr r**4 * exp(-a*r**2) * w(r)
w(r) = exp(-4*rc**2/x**2) - 1
this is for RAC radial p-GTO: u(r) = R(r)*r
u1*u2 = r**4 * exp(-(a1+a2)*r**2)
+ 3*sqrt(pi)*rc*cosh(4*sqrt(a)*rc)/(2*a**2)
- 3*sqrt(pi)*rc*sinh(4*sqrt(a)*rc)/(2*a**2)
+ 2*sqrt(pi)*rc**2*cosh(4*sqrt(a)*rc)/a**(3/2)
- 2*sqrt(pi)*rc**2*sinh(4*sqrt(a)*rc)/a**(3/2)
+ 3*sqrt(pi)*cosh(4*sqrt(a)*rc)/(8*a**(5/2))
- 3*sqrt(pi)*sinh(4*sqrt(a)*rc)/(8*a**(5/2))
- 3*sqrt(pi)/(8*a**(5/2))
observe: cosh(a) - sinh(a) = exp(-a)
W = sp * ( 3*rc*cosh/(2*a**2)
- 3*rc*sinh/(2*a**2)
+ 2*rc**2*cosh/a**(3/2)
- 2*rc**2*sinh/a**(3/2)
+ 3*cosh/(8*a**(5/2))
- 3*sinh/(8*a**(5/2))
- 3/(8*a**(5/2))
)
"""
sp = np.sqrt(np.pi)
sqarc = np.sqrt(a)*rc
#sinh = np.sinh(4*sqarc)
#cosh = np.cosh(4*sqarc)
exa = np.exp(-4*sqarc)
W = sp * ( 3*rc*exa/(2*a**2)
+ 2*rc**2*exa/a**(3/2)
+ 3*(exa-1)/(8*a**(5/2))
)
return W
def Jolanta_GTO_W(GTO_fn, alphas, Ns, rc):
"""
potential w(r) matrix representation in a GTO basis set
GTO_fn can be:
Jolanta_3D_Wcap for the quadratic soft-box for CAP
Jolanta_3D_Coulomb for a Coulomb potential for RAC
Jolanta_3D_softbox for a inverse GTO soft-box for RAC
Parameters
----------
alphas : np.array of GTO exponents
Ns : np.array of normalization constants
rc : cutoff of w(r)
Returns
-------
W : matrix represention of w(r)
"""
nbas = len(alphas)
W=np.zeros((nbas,nbas))
for i in range(nbas):
ai, Ni = alphas[i], Ns[i]
W[i,i] = Ni * Ni * GTO_fn(ai+ai, rc)
for j in range(i):
aj, Nj = alphas[j], Ns[j]
W[i,j] = W[j,i] = Ni * Nj * GTO_fn(ai+aj, rc)
return W
def Jolanta_GTO_VJrot(alphas, Ns, param, z):
"""
rotated Jolanta potential V_J(r*exp(I*theta)) in a GTO basis set
----------
Parameters
alphas : np.array of GTO exponents
Ns : np.array of normalization constants
param = (a,b,c) parameters of V_J = (a*r**2 - b)*exp(-c*r**2)
z = alpha*exp(i*theta), where arg(z) < pi/4;
-------
Returns
Vrot : matrix represention of V_J(r*exp(I*theta))
"""
nbas = len(alphas)
W=np.zeros((nbas,nbas), complex)
for i in range(nbas):
ai, Ni = alphas[i], Ns[i]
W[i,i] = Ni * Ni * Jolanta_3D_CS(ai+ai, param, z)
for j in range(i):
aj, Nj = alphas[j], Ns[j]
W[i,j] = W[j,i] = Ni * Nj * Jolanta_3D_CS(ai+aj, param, z)
return W
def Eval_GTO_wf_3D(alphas, Ns, cs, xs, u=True):
"""
This is the 3D function of l=1
u(r) = r**2 * exp(-a*r**2)
R(r) = r * exp(-a*r**2)
input:
alphas, norms = a basis set
cs = GTO coefficient vector
alphas, Ns, and cs define a wavefunction
xs = positions at which the wf is to be evaluated
u=True evaluate the radial function u(r) = r*R(r)
u=False evaluate the radial function R(r) = u(r)/r
"""
if u:
l=2
else:
l=1
nx = len(xs)
nbas = len(cs)
ys = np.zeros(nx)
for i in range(nx):
y=0
xsq = xs[i]**2
for k in range(nbas):
y += cs[k] * Ns[k] * np.exp(-alphas[k]*xsq)
ys[i] = y*xs[i]**l
return ys
<file_sep>import numpy as np
import sys
def write_theta_run(fname, thetas, trajectories, header=False):
"""
write data created by complex scaling, a so-called theta-run
data file format:
1st column theta
then columns with ReE ImE pairs, all separated by whitespace
input:
the filename for the data file
the theta values, float, n
the trajectories, complex, n,m
"""
n_theta = len(thetas)
(n, m) = trajectories.shape
if n_theta != n:
sys.exit('incompatible array lengths in write_theta_run')
tr = np.zeros((n, 2 * m + 1))
tr[:, 0] = thetas
header = "theta"
for i in range(m):
tr[:, 2 * i + 1] = trajectories[:, i].real
tr[:, 2 * i + 2] = trajectories[:, i].imag
header = header + ', ReE' + str(i + 1) + ', ImE' + str(i + 1)
np.savetxt(fname, tr, fmt='%15.12f', delimiter=' ')
def read_theta_run(fname):
"""
read data created by complex scaling, a so-called theta-run
1st column theta
columns with ReE ImE pairs, all separated by whitespace
input:
the filename of the data file
output:
(n_thetas, n_energies), ints: number of theta values and energies
thetas, float: array with theta values
es, complex: matrix with energies, es[:,j] is the jth energy(theta)
"""
theta_run = np.loadtxt(fname)
(n_thetas, n_energies) = theta_run.shape
n_energies = (n_energies - 1) // 2
thetas = theta_run[:, 0]
es = np.zeros((n_thetas, n_energies), complex)
# put the complex energies together again
for j in range(n_energies):
es[:, j] = theta_run[:, 2 * j + 1] + 1j * theta_run[:, 2 * j + 2]
return (n_thetas, n_energies), thetas, es
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 2 09:41:41 2021
@author: thomas
"""
"""
GTO functions for the 1D Jolanta potential
this has not been used much as 1D should not work with RAC
"""
import numpy as np
def Jolanta_1D_Norm(a, l=1):
"""
see Analytic integrals notebook in Stab directory for formulas
integrals of two GTOs: x*exp(-a_j*x**2)
return the normalization 1/sqrt(S_jj)
S: 2**(1/4) * a1**(1/4) / pi**(1/4)
P: 2 * 2**(1/4) * a1**(3/4) / pi**(1/4)
"""
if l == 0:
return (2*a/np.pi)**0.25
else :
return 2 * (2/np.pi)**0.25 * a**0.75
def Jolanta_1D_GTO(a1, a2, param, l=1):
"""
see Analytic integrals notebook in Stab directory for formulas
integrals of two GTOs: x*exp(-a_j*x**2)
computes overlap, kinetic energy, and potential
"""
a, b, c = param
sqrt_pi = np.sqrt(np.pi)
if l == 0:
S = sqrt_pi /np.sqrt(a1 + a2)
T = sqrt_pi * a1 * a2 / (a1 + a2)**(3/2)
V = sqrt_pi*(a - 2*a1*b - 2*a2*b - 2*b*c)/(2*(a1 + a2 + c)**(3/2))
else:
S = sqrt_pi / (2*(a1 + a2)**(3/2))
T = 1.5 * sqrt_pi * a1 * a2 / (a1 + a2)**(5/2)
V = sqrt_pi*(3*a - 2*a1*b - 2*a2*b - 2*b*c)/(4*(a1 + a2 + c)**(5/2))
return S, T, V
def Jolanta_GTO_H(GTO_fn, alphas, Ns, param, l=1):
"""
Hamiltonian matrix in a GTO basis set
Parameters
----------
GTO_fn : either Jolanta_1D_GTO()
alphas : np.array of GTO exponents
Ns : np.array of normalization constants
param : (a, b, c): parameters of the Jolanta potential
l : = 0 (even) or 1 (odd) in the 1D case
Returns 3 numpy matrices
-------
S : overlap matrix
T : kinetic energy matrix
V : potential energy matrix
"""
nbas = len(alphas)
S=np.zeros((nbas,nbas))
T=np.zeros((nbas,nbas))
V=np.zeros((nbas,nbas))
for i in range(nbas):
ai, Ni = alphas[i], Ns[i]
S[i,i], T[i,i], V[i,i] = GTO_fn(ai, ai, param, l=l)
S[i,i] *= Ni*Ni
T[i,i] *= Ni*Ni
V[i,i] *= Ni*Ni
for j in range(i):
aj, Nj = alphas[j], Ns[j]
Sij, Tij, Vij = GTO_fn(ai, aj, param, l=l)
S[i,j] = S[j,i] = Ni*Nj * Sij
T[i,j] = T[j,i] = Ni*Nj * Tij
V[i,j] = V[j,i] = Ni*Nj * Vij
return S, T, V
def Eval_GTO_wf(alphas, Ns, cs, xs, l=1):
"""
This is the 1D function
input:
alphas, norms = a basis set
cs = GTO coefficient vector
alphas, Ns, and cs define a wavefunction
xs = positions at which the wf is to be evaluated
"""
nx = len(xs)
nbas = len(cs)
ys = np.zeros(nx)
for i in range(nx):
y=0
#xfactor = xs[i]**l
xsq = xs[i]**2
for k in range(nbas):
y += cs[k] * Ns[k] * np.exp(-alphas[k]*xsq)
ys[i] = y*xs[i]**l
return ys <file_sep>import numpy
from scipy import sqrt
""" helper functions using standard Pade approximants E = P/Q """
def pade_via_lstsq(np, nq, xs, ys, rcond=1e-14, return_lists=False, ycplx=False):
"""
compute the coeffients of a Pade np/np approximant using numpy.linalg.lstsq
the lstsq function will take any number of equations, so this should
work for any len(xs)=len(ys)
returned are the Pade coefficients ps and qs in highest-power first order
"""
N_coef = np + nq + 1
M_data = len(xs)
y_type = float
if ycplx:
y_type = complex
A = numpy.zeros((M_data,N_coef), y_type)
b = numpy.zeros(M_data, y_type)
for k_data in range(M_data):
i_coef = 0
for ip in range(np,1,-1): # counts from np down to 2
A[k_data,i_coef] = xs[k_data]**ip
i_coef += 1
A[k_data,i_coef] = xs[k_data]
i_coef += 1
A[k_data,i_coef] = 1.0
i_coef += 1
for iq in range(nq,1,-1): # counts from np down to 2
A[k_data,i_coef] = -ys[k_data] * xs[k_data]**iq
i_coef += 1
A[k_data,i_coef] = -ys[k_data] * xs[k_data]
b[k_data] = ys[k_data]
coefs, residual, rank, s = numpy.linalg.lstsq(A,b,rcond=rcond)
ps = coefs[:np+1]
qs = numpy.array(list(coefs[np+1:np+nq+1]) + [1])
if return_lists:
return ps, qs
else:
return numpy.poly1d(ps), numpy.poly1d(qs)
def eval_pade_lists(x, ps, qs):
""" evaluate a standard Pade approximant """
return numpy.polyval(ps,x)/numpy.polyval(qs,x)
def dEds(s, P, Q):
"""
we have: E = P/Q
therefore: dEds = E' = (P'Q - Q'P) / Q^2
input
P, Q: two polynomials that depend on L
s: the independent (scaling) variable
"""
Pp = P.deriv(1)(s)
Qp = Q.deriv(1)(s)
return (Pp*Q(s) - Qp*P(s)) / Q(s)**2
def EpoEpp(s, P, Q):
"""
we need E'/E'' need for Newton's method
this expression can be evaluated analytically:
E' = (P'Q - Q'P)/Q**2 = N/Q**2
E'' = (N'Q**2 - 2QQ'N) / Q**4
E'/ E'' = NQ / (N'Q - 2Q'N)
with N' = P''Q - Q''P
"""
QQ = Q(s)
PP = P(s)
Pp = P.deriv(1)(s)
Qp = Q.deriv(1)(s)
Ppp = P.deriv(2)(s)
Qpp = Q.deriv(2)(s)
N = Pp*QQ - Qp*PP
Np = Ppp*QQ - Qpp*PP
return (N*QQ) / (Np*QQ - 2*Qp*N)
<file_sep>"""
We minimize chi2 = 1/M sum_i (rac(k_i) - lambda_i)**2
for this purpose least_suares is superior to all local minimize() variations
three different ways to fit:
- simple least squares
- least squares with bounds
- basin-hopping with least squares as local minimizer
least-squares-with-bounds applies limits on the parameters
- all parameters are > 1e-7
- alpha, beta, lambda0 do not change more than 10% from their 21 values
basin hopping related functions of the rac code are in bh_with_lsq
basin_hopping needs
(a) a function returning chi2 that will be called directily: bh_chi2()
(b) a local minimizer, which is supposed to minimize chi2, but does not
get bh_chi2() as a parameter
This behavior is designed around scipy.optimize.minimize, yet, to use
scipy.optimize.least_squares(), which computes chi2 internally, a slight
modification is needed:
(a) basin_hopping gets its own chi2 function to compute chi2.
(b) The local minimizer (least_squares()) gets as an argument the rac-function
and rac-jacobian it neededs. These functions never evaluate chi2 explicitly,
but only the terms in the sum.
"""
import numpy as np
import rac_aux as racx
#import sys
from scipy.optimize import least_squares
from scipy.optimize import basinhopping
import matplotlib.pyplot as plt
from pandas import DataFrame
def simple_lsq(fun, jac, p0s, rac_args, nm, verbose=1):
""" straightforward call to least_squares plus convergence check """
res = least_squares(fun, p0s, method='trf', jac=jac, args=rac_args,
max_nfev=100*len(p0s)**2)
if not res.success:
print(' **** Pade-%s failed to converged ****' % (nm))
verbose = 4
if not res.success or verbose > 0:
print(" x:", abs(res.x))
if not res.success or verbose > 2:
print(" message:",res.message)
print(" success:",res.success)
print(" njev:",res.njev)
print(" cost:",res.cost)
print(" grad:",res.grad)
print(" Er=%f, Gamma=%f" % racx.res_ene(res.x[1], res.x[2]))
return res
def lsq_with_bounds(fun, jac, p0s, rac_args, bnds_on_lab=False,
gt=1e-7, verbose=1):
"""
least_squares with bounds:
fun, jac: the function to be minimized and its Jabobian
p0s : start parameters: lambda0, alpha, beta, ...
rac_args: additional arguments for fun (ls, ks, k2s, ...)
bnds_on_lab: bounds on the 1st three parameters, lambda0, alpha, beta
lambda0 plus/minus 5%
alpha and beta *1.5 and /1.5
all other parameters > gt
only used if len(p0s) > 3
calls scipy.least_squares()
returns the optimization result res
"""
n_para = len(p0s)
lower = np.full(n_para, 1e-7)
upper = np.full(n_para, np.inf)
bnds=(lower, upper)
if len(p0s) > 3 and bnds_on_lab:
lower[0], upper[0] = p0s[0]*0.95, p0s[0]*1.05
lower[1], upper[1] = p0s[1]/1.5, p0s[1]*1.5
lower[2], upper[2] = p0s[2]/1.5, p0s[2]*1.5
res = least_squares(fun, p0s, method='trf', jac=jac, args=rac_args,
bounds=bnds, max_nfev=300*len(p0s)**2)
if not res.success or verbose > 2:
print(" message:",res.message)
print(" success:",res.success)
print(" njev:",res.njev)
print(" cost:",res.cost)
print(" grad:",res.grad)
if not res.success or verbose > 0:
print(" Er=%f, Gamma=%f" % racx.res_ene(res.x[1], res.x[2]))
print(" x:", abs(res.x))
return res
def bh_with_lsq(p0s, n_bh, args, sane_bnds, T=1e-4, verbose=1):
"""
p0s: start parameters
n_bh: number of basin hopping steps
args: (ks, k2s, ls, function_lsq, jacobian_lsq)
sane_bnds = (Emin, Emax, Gmin, Gmax)
sensibility filter for identified solutions, say,
RAC-21 plus-minus 50%
T: temperature for Monte Carlo-like hopping decision
This is quite slow. Do callback w/o lists?
"""
jbh = 0
chi2s = np.zeros(n_bh+1)
alphas = np.zeros(n_bh+1)
betas = np.zeros(n_bh+1)
#ps = []
ps = np.zeros((n_bh+1, len(p0s)))
if verbose > 0:
print(' Doing %d basin hops.' % n_bh)
def bh_chi2(params, args=()):
"""
we need two chi2-returning functions
one called by basin_hopping() to evaluate a point=params
one called by the local minimizer
this is the former
at the moment 'args':(ks, k2s, ls, f_lsq, j_lsq)
"""
(ks, k2s, ls, sigmas, f_lsq, j_lsq) = args
diffs = f_lsq(params, ks, k2s, ls, sigmas)
return np.sum(np.square(diffs))
def lsq_wrapper(fun, x0, args=(), method=None, jac=None, hess=None,
hessp=None, bounds=None, constraints=(), tol=None,
callback=None, options=None):
"""
function called by basin_hopping() for local minimization
returns a Results object
"""
(ks, k2s, ls, sigmas, f_lsq, j_lsq) = args
res = least_squares(f_lsq, x0, method='trf', jac=j_lsq,
args=(ks, k2s, ls, sigmas))
res.fun = res.cost*2
#if not res.success:
# print('wrapper:', res.success)
# print(res.message)
# print(res.fun, res.x)
#delattr(res, 'njev')
return res
def bh_call_back(x, f, accepted):
"""
called after every local minimization
create lists with partial results
"""
nonlocal jbh, chi2s, alphas, betas
chi2s[jbh] = f
alphas[jbh], betas[jbh] = x[1], x[2]
#ps.append(x)
ps[jbh,:] = x
jbh += 1
""" Call the minimizer """
min_kwargs = {'method':lsq_wrapper, 'args':args, 'jac':True}
res = basinhopping(bh_chi2, p0s, minimizer_kwargs=min_kwargs, niter=n_bh,
T=T, seed=1, callback=bh_call_back)
if 'successfully' not in res.message[0] or verbose > 0:
print(" minimization failures:",res.minimization_failures)
if 'successfully' not in res.message[0] or verbose > 1:
print(" message:",res.message)
print(" x:", abs(res.x))
print(" nfev:",res.nfev)
print(" njev:",res.njev)
print(" nit:",res.nit)
print(" Er=%f, Gamma=%f" % racx.res_ene(res.x[1], res.x[2]))
""" Process the results stored by bh_call_back """
Er, G = racx.res_ene(res.x[1], res.x[2])
chi2 = res.lowest_optimization_result.cost*2
best = (Er, G, chi2)
sane, j_sane, df = process_minima(chi2s, alphas, betas, sane_bnds, verbose)
if verbose > 0:
print(' Best: %f %f %.4e' % best)
print(' Sane: %f %f %.4e' % sane)
if verbose > 2:
plot_chis(df)
if verbose > 4:
plot_map(df)
# this parameter set may be rubbish if no sane minimum has been found
# since ps[j_sane] will be recycled as start parameters
# this will lead to trouble down the line
# so we need to test and a default p0s independent of previous nms
#return best, sane, ps[j_sane], df
return best, sane, ps[j_sane,:], df
def process_minima(chis, alphas, betas, bounds, digits=5, verbose=1):
"""
process the minima visited by basin_hopping()
- compute Er and Gamma and put into a DataFrame
- sane DataFrame by filtering the minima by
bounds = (Emin, Emax, Gmin, Gmax)
- find the lowest chi2 and its original index (j_sane)
- find unique values by:
rounding to digits
combining Er and G to a string
using .unique
returns
- the best sane energy (Er, G, chi2)
- the index of this minimum, j_sane
- the DataFrame with unique sane minima
"""
Emin, Emax, Gmin, Gmax = bounds
Ers, Gms = racx.res_ene(alphas, betas)
df = DataFrame({'chis':chis, 'Er':Ers, 'G':Gms})
fltr = ((df.Er>Emin) & (df.Er<Emax) & (df.G>Gmin) & (df.G<Gmax))
df_sane = df[fltr].copy()
n = df_sane.shape[0]
if verbose > 0 or n < 1:
print(' %d sane minima found' % (n))
if n < 1:
return (0, 0, 0), 0, df
df_sane.sort_values('chis', inplace=True)
j_sane = df_sane.chis.idxmin()
sane = (df['Er'][j_sane], df['G'][j_sane], df['chis'][j_sane])
df_sane['logs'] = np.log10(df_sane['chis'])
#df=sane['Unique'] = str(np.round["Er"]) + "," + str(np.round["G"])
return sane, j_sane, df_sane
def plot_chis(df, nbins=200):
"""
show a histogram of the log10(chi2s)
"""
r, c = df.shape
n = min(r//4, nbins)
plt.cla()
pop, edges, patches = plt.hist(df.logs, bins=n)
plt.xlabel('$\log \chi^2$', fontsize=10)
plt.ylabel('number of minima', fontsize=10)
plt.show()
print(pop)
def plot_map(df, ymax=1.5):
""" plot complex energy plane and color code with chi2 """
plt.cla()
plt.scatter(df.Er.values, df.G.values, c=df.logs, s=20, cmap='viridis')
plt.ylim(0, ymax)
#cb = plt.colorbar()
plt.tick_params(labelsize=12)
plt.xlabel('$E_r$ [eV]', fontsize=10)
plt.ylabel('$\Gamma$ [eV]', fontsize=10)
plt.show(block=True)
<file_sep>"""
functions needed for the GPA analysis of stabilization graphs
convention:
the scaling variable is called L
L could be a box-size or a scaling factor of exponents
however, I have the suspicion is works only,
if s = 1/L^2 as in L = boxlength is used
"""
import numpy as np
#import pade
def dEdL(E, L, P, Q, R):
"""
we know: E^2*P + E*Q + P = 0
therefore:
dEdL = E' = -(E^2*P' + E*Q' + R')/(2*E*P + Q)
input:
P, Q, R: three polynomials that depend on L
E: the energy
L: the independent (scaling) variable
output:
dE/dL derivative of E
"""
Pp = P.deriv(1)(L)
Qp = Q.deriv(1)(L)
Rp = R.deriv(1)(L)
return -(E**2 * Pp + E * Qp + Rp) / (2 * E * P(L) + Q(L))
def E_from_L(L, A, B, C):
"""
given L, solve E^2*A + E*B + C = 0
return both roots
"""
P = np.poly1d([A(L), B(L), C(L)])
return P.roots
def E_and_Ep(L, A, B, C):
"""
combination of the two functions above
given L, first solve E^2*A + E*B + C = 0
for every root found, compute the 1st derivative |dEdL|
return energies and abs(derivatives)
"""
P = np.poly1d([A(L), B(L), C(L)])
roots = P.roots
ders = []
for E in roots:
ders.append(abs(dEdL(E, L, A, B, C)))
return roots, ders
#
# for Newton we solve dEdL = 0 or E' = 0
#
# so we iterate L[i+1] = L[i] - E'/E''
#
# the fraction E'/E'' can be worked out analytically:
#
# (E^2*P' + E*Q' + R') /
# (2*P*E'^2 + 4*E*E'*P' + E^2*P'' + 2*E'*Q' + E*Q'' + R'')
#
def EpoEpp(E, L, P, Q, R):
""" E'/E'' needed for Newton's method """
Pp = P.deriv(1)(L)
Qp = Q.deriv(1)(L)
Rp = R.deriv(1)(L)
Ep = -(E**2 * Pp + E * Qp + Rp) / (2 * E * P(L) + Q(L))
Ppp = P.deriv(2)(L)
Qpp = Q.deriv(2)(L)
Rpp = R.deriv(2)(L)
num = E**2 * Pp + E * Qp + Rp
den = 2 * P(L) * Ep**2 + 4 * E * Ep * Pp + E**2 * \
Ppp + 2 * Ep * Qp + E * Qpp + Rpp
return num / den
<file_sep>import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
from scipy.optimize import brentq
"""
aux functions for trajectory analysis:
"""
def naive_derivative(xs, ys):
""" naive forward or backward derivative """
return (ys[1]-ys[0])/(xs[1]-xs[0])
def central_derivative(xs, ys):
""" central derivative at x[1] """
return (ys[2]-ys[0])/(xs[2]-xs[0])
def five_point_derivative(xs, ys):
"""
five-point derivative at x[2]
(-ys[4] + 8*ys[3] - 8*ys[1] + ys[0])/(12*h)
"""
return (-ys[4] + 8*ys[3] - 8*ys[1] + ys[0])/(xs[4]-xs[0])/3
def simple_traj_der(xs, ys):
"""
y(x) is a real or complex trajectory of the real variable x
compute numerical derivatives of its speed dy/dx
this is appropriate for complex scaling E(theta)
don't use for CAPs as it assumes equal step length
"""
n_eta = len(xs)
ders = np.zeros(n_eta, complex)
ders[0] = naive_derivative(xs[0:2], ys[0:2])
ders[1] = central_derivative(xs[0:3], ys[0:3])
for k in range(2,n_eta-2):
ders[k] = five_point_derivative(xs[k-2:k+3], ys[k-2:k+3])
ders[-2] = naive_derivative(xs[-3:], ys[-3:])
ders[-1] = naive_derivative(xs[-2:], ys[-2:])
return ders
def trajectory_derivatives(etas, es):
"""
given an eta-trajectory es(etas)
compute the first derivative and its absolute value
as well as the second derivatives
these are logarithmic derivatives: dE/dln(eta)
returns:
corrs: corrected trajectory, corr = E - dE/dln(eta)
absd1, absd2: absolute values for 1st and 2nd derivative
careful, etas are expected to be exactly on a log-scale
"""
n_eta = len(etas)
lnetas = np.log(etas)
ders=np.zeros(n_eta, complex)
corrs=np.zeros(n_eta, complex)
absd2=np.zeros(n_eta)
ders[0] = naive_derivative(lnetas[0:2], es[0:2])
ders[1] = central_derivative(lnetas[0:3], es[0:3])
for k in range(2,n_eta-2):
ders[k] = five_point_derivative(lnetas[k-2:k+3], es[k-2:k+3])
ders[-2] = central_derivative(lnetas[-3:], es[-3:])
ders[-1] = naive_derivative(lnetas[-2:], es[-2:])
corrs = es - ders
for i in range(2,n_eta-2):
absd2[i] = np.abs( etas[i]*(corrs[i+1]-corrs[i-1])/(etas[i+1]-etas[i-1]) )
#print i, etas[i], es[i], ders[i]
#corrs[0] = es[0] - ders[0]
#corrs[-1] = es[-1] - ders[-1]
absd2[0]=absd2[1]=absd2[2]
absd2[-1]=absd2[-2]=absd2[-3]
absd1=np.abs(ders)
return corrs, absd1, absd2
def trajectory_derivatives_old(etas, es):
"""
given an eta-trajectory es(etas)
compute the first derivative and its absolute value
as well as the second derivatives
these are logarithmic derivatives: dE/dln(eta)
returns:
corrs: corrected trajectory, corr = E - dE/dln(eta)
absd1, absd2: absolute values for 1st and 2nd derivative
"""
n_eta = len(etas)
ders=np.zeros(n_eta, complex)
corrs=np.zeros(n_eta, complex)
absd2=np.zeros(n_eta)
for i in range(1,n_eta-1):
ders[i] = etas[i]*(es[i+1]-es[i-1])/(etas[i+1]-etas[i-1])
corrs[i] = es[i] - ders[i]
#print i, etas[i], es[i], ders[i]
for i in range(2,n_eta-2):
absd2[i] = np.abs( etas[i]*(corrs[i+1]-corrs[i-1])/(etas[i+1]-etas[i-1]) )
#print i, etas[i], es[i], ders[i]
ders[0]=ders[1]
ders[-1]=ders[-2]
corrs[0] = es[0] - ders[0]
corrs[-1] = es[-1] - ders[-1]
absd2[0]=absd2[1]=absd2[2]
absd2[-1]=absd2[-2]=absd2[-3]
absd1=np.abs(ders)
return corrs, absd1, absd2
def JZBEK_analysis(etas, es):
"""
Jagau, Zuev, Bravaya, Epifanovsky, Krylov, JCPL 5, 310, 2014
plot Re(Es) vs eta for Er
plot Im(Es) vs eta for Ei
find local min(Re(E)) and max(Im(E))
Input:
etas: at which the complex trajectory has been computed
E_traj: complex trajectory from following the resonance
Returns:
local min(Re(E)) and max(Im(E)) as lists
"""
def der1(x, a, b, c):
# spline = (a, b, c)
return interpolate.splev(x, (a,b,c), der=1)
ln_etas = np.log(etas)
re_sp = interpolate.splrep(ln_etas, es.real, s=0)
re_der = interpolate.splev(ln_etas, re_sp, der=1)
im_sp = interpolate.splrep(ln_etas, es.imag, s=0)
im_der = interpolate.splev(ln_etas, im_sp, der=1)
min_ReE = []
x_min = []
max_ImE = []
x_max= []
n=len(etas)
for i in range(0,n-1):
x1, x2 = ln_etas[i], ln_etas[i+1]
if re_der[i]*re_der[i+1] < 0:
x0 = brentq(der1, x1, x2, args=re_sp)
if interpolate.splev(x0, re_sp, der=2) >= 0:
min_ReE.append(interpolate.splev(x0, re_sp))
x_min.append(x0)
if im_der[i]*im_der[i+1] < 0:
x0 = brentq(der1, x1, x2, args=im_sp)
if interpolate.splev(x0, im_sp, der=2) <= 0:
max_ImE.append(interpolate.splev(x0, im_sp))
x_max.append(x0)
plot1 = plt.subplot2grid((2, 2), (0, 0))
plot2 = plt.subplot2grid((2, 2), (0, 1))
plot3 = plt.subplot2grid((2, 2), (1, 0))
plot4 = plt.subplot2grid((2, 2), (1, 1))
plot1.plot(ln_etas, es.real, color='blue', linestyle='-')
plot1.plot(x_min, min_ReE, 'o', color='blue')
plot1.set(ylabel='$Re(E)$')
plot3.plot(ln_etas, es.imag, color='darkgreen', linestyle='-')
plot3.plot(x_max, max_ImE, 'o', color='darkgreen')
plot3.set(ylabel='$Im(E)$')
plot3.set(xlabel=r'$\ln \eta$')
plot2.plot(ln_etas, re_der,'b-')
plot2.set(ylabel='$dRe(E)/d\ln\eta$')
plot4.plot(ln_etas, im_der,'-', color='darkgreen')
plot4.set(ylabel='$dIm(E)/d\ln\eta$')
plot4.set(xlabel=r'$\ln \eta$')
plt.tight_layout()
plt.show()
return x_min, min_ReE, x_max, max_ImE
def find_local_minima(etas, es):
"""
input: a real array es energies(eta)
output: all local minima
"""
n = len(es)
out = []
for i in range(1,n-1):
if es[i] < es[i-1] and es[i] < es[i+1]:
out.append((etas[i],es[i]))
return out
def find_local_maxima(etas, es):
"""
input: a real array es energies(eta)
output: all local maxima
"""
n = len(es)
out = []
for i in range(1,n-1):
if es[i] > es[i-1] and es[i] > es[i+1]:
out.append((etas[i],es[i]))
return out
<file_sep># *L*<sup>2</sup>-methods for resonances
A resonance is *quasi-bound* or *temporary* state of a quantum system. It can be thought of as a discrete state that is embedded in and interacts with a continuum so that the discrete state can decay and aquires a lifetimes or decay width.
In principle, resonances are features of a scattering continuum, however, imposing scattering boundary conditions is far more challenging than imposing bound-state (or *L*<sup>2</sup>) boundary conditions, and therefore many *L*<sup>2</sup>-methods for computing the energy and the lifetime of resonance states have been developed.
Even though these methods are based on completely different ideas, all *L*<sup>2</sup>-methods follow a similar computational protocol:
1. Parametrize the physical Hamiltonian **H** → **H**(λ).
2. Diagonalize **H**(λ) repeatedly.
3. Identify the resonance feature, normaly one- possibly two- trajectories *E*<sub>*n*</sub>(λ<sub>*j*</sub>).
4. Analyze the identified trajectories to find the resonance energy *E*<sub>*r*</sub> and the lifetime τ.
## Implementation
All methods are implememted as Jupyter notebooks, but a substantial part of the auxilary functions are hidden in Python libraries.
* The **notebooks** directory contains subdirectories for the four major methods (see below), and two directories collecting analytical (sympy) notebooks for Gaussian integrals and for gradients of the RAC extrapolation formulas.
* The **Python_libs** directory collects helper functions imported into various notebooks. See documentation of each function.
## Methods
The goal is to compare- on equal footing- different *L*<sup>2</sup>-methods and, in particular, their variants. This is virtually impossibe in an electronic structure context, so a model potential is used:
*V*(*r*) = (*ar*<sup> 2</sup> - *b*) exp(-*cr*<sup> 2</sup>) + (*l* (*l* + 1))/(2*r*<sup> 2</sup>)
where *l* = 1, and the parameters *a*, *b*, and *c* are chosen so that *V*(*r*) supports one bound state at *E* = -7.2 eV and a resonance at *E*<sub>*r*</sub> = 3.2 eV.
### *L*<sup>2</sup>-methods implemented
The four major methods implemented are:
1. Complex scaling (CS).
2. Complex absorbing potential (CAP).
3. Howard-Taylor stabilization (HTS).
4. Regularized analytic continuation (RAC).
### Basis sets
Each method needs to be combined with a represation of the Hamiltonian, that is, with a 'basis set'. Two basis set types are compared: A quasi-exact discrete variable representation (DVR)- a dense grid basis- and three small Gaussian basis sets modeling basis sets typically used in electronic structure theory (15 GTOs or less).
### Variants
Any combination of a major *L*<sup>2</sup>-method (CS, CAP, HTS, or RAC) with a basis (DVR or one of the Gaussian basis sets) defines a 'particular method' as well as steps 1 to 3. But each major *L*<sup>2</sup>-methods branches into several analyis variants for step 4. In addition, RAC has also step 1 variants. It is these variants that are often brushed under the rug, but that turn out to yield vastly different resonance energies even though the input data from steps 1 to 3 are identical.
Two notebooks in each of the four main subdirectories deal with steps 1 to 3: One DVR and one Gaussian basis set notebook. The other notebooks deal with different analysis variants used in step 4.
## Contribution
Please contribute:
* Many variants are missing.
* While Jupyter notebooks are great for learning a new method, a Python program is preferable for a 'production' environment.
* Step 2 needs user input. Automatization or at least a suggest-accept mechanism would safe a lot of time.
## Licence
MIT licence.
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 15 12:39:25 2021
@author: thomas
Functions for the selection of a plateau or crossing range
"""
# import sys
import numpy as np
from scipy import interpolate
from scipy.optimize import minimize_scalar, curve_fit, least_squares
def find_zero(xs, j0, up=True):
"""
Find the next "zero" (sign inversion) along xs
starting at index j0
up==True searches upwards
"""
step = -1
stop = 1
if up:
step = 1
stop = len(xs) - 1
for j in range(j0, stop, step):
x1 = xs[j]
x2 = xs[j + step]
if x1 * x2 < 0:
if np.abs(x1) < np.abs(x2):
return j
return j + step
return stop
def min_der(xs, ys, smooth=0):
"""
Find the minimum (abs) of the derivative along a curve, ys(xs)
derivative are computed using a spline interpolation
xs : pointwise curve, x values
ys : pointwise curve, y values
Returns:
jmin: index with the lowest derivative
xs[jmin]
ders[jmin]
"""
sp = interpolate.splrep(xs, ys, s=smooth)
ders = interpolate.splev(xs, sp, der=1)
jmin = np.argmin(abs(ders))
return jmin, xs[jmin], ders[jmin]
def der_and_curvature(xs, ys, smooth=0):
"""
Derivative and curvature of a pointwise provided curve y(x)
obtained by standard spline interpolation
normalized to range [-1,1]
Any branch of a stabilization graph goes through
a crossing-plateau-crossing structure, which are
defined by curavture extrema and a curvature zero inbetween.
xs : pointwise curve, x values
ys : pointwise curve, y values
Returns: the derivatives: dy/dx and d2y/dx2 at the xs
"""
sp = interpolate.splrep(xs, ys, s=smooth)
d1s = interpolate.splev(xs, sp, der=1)
d2s = interpolate.splev(xs, sp, der=2)
d1s /= np.max(np.abs(d1s))
d2s /= np.max(np.abs(d2s))
return d1s, d2s
def crossing(xs, E1, E2, select=0.5, smooth=0):
"""
find center of a crossing
select a range of points determined by drop of the
curvature
options:
use drop-offs to max(curature)*select
use drop-offs of sqrt(max(curvature))
Parameters:
xs : scaling parameter E1(x), E2(x)
E1, E2 : lower and upper branch of the crossing
select : selection range cutoff as determined by
the d2 reduction (0.0 = all to next plateaux)
if select < 0, use sqrt(d2_max)
Returns:
success : boolean
xc : center of the crossing
selected ranges of xs, E1, and E2
"""
sp1 = interpolate.splrep(xs, E1, s=smooth)
sp2 = interpolate.splrep(xs, E2, s=smooth)
d2s1 = interpolate.splev(xs, sp1, der=2)
d2s2 = interpolate.splev(xs, sp2, der=2)
j1_mn = np.argmin(d2s1)
j2_mx = np.argmax(d2s2)
jc = j1_mn
if j1_mn - j2_mx > 1:
if np.abs(xs[j1_mn] - xs[j2_mx]) > 0.05:
return (False, -1, (j1_mn, j2_mx), d2s1, d2s2)
else:
jc = (j1_mn + j2_mx) // 2
xc = xs[jc]
d2s1_mn, d2s2_mx = d2s1[j1_mn], d2s2[j2_mx]
d2s1_cut, d2s2_cut = select * d2s1_mn, select * d2s2_mx
if select < 0:
d2s1_cut = -np.sqrt(-d2s1_mn)
d2s2_cut = np.sqrt(d2s2_mx)
j_max = find_zero(d2s1 - d2s1_cut, j1_mn, up=True)
j_min = find_zero(d2s2 - d2s2_cut, j2_mx, up=False)
x_sel = xs[j_min:j_max + 1]
E1sel = E1[j_min:j_max + 1]
E2sel = E2[j_min:j_max + 1]
return (True, xc, x_sel, E1sel, E2sel)
def plateau(xs, ys, srch_range=(-1, -1), smooth=0):
"""
find
- index of minimum of derivative and exact zero of curvature
- indices and exact positions of extrema of the curvature
Parameters:
xs : pointwise curve, x values
ys : pointwise curve, y values
srch_range=(xmin, xmax): smaller search range from problems
Returns:
j0, j1, j2: indices of zero and extrema of ys
x0, x1, x2: precise positions of zero and extrema of d^2y/dx^2
jx = -1 indicates failure
"""
def der1(x, a, b, c):
# spline = (a, b, c)
return interpolate.splev(x, (a, b, c), der=1)
def der2(x, a, b, c):
# spline = (a, b, c)
return interpolate.splev(x, (a, b, c), der=2)
def mabsder2(x, a, b, c):
# spline = (a, b, c)
return -np.abs(interpolate.splev(x, (a, b, c), der=2))
failure = ((-1, -1, -1), (-1, -1, -1))
xmin, xmax = srch_range
# search range, default is xs[2,-2]
if xmin < 0:
jmin = 2
xmin = xs[jmin]
else:
jmin = np.argmin(np.abs(xs - xmin))
if xmax < 0:
jmax = len(xs) - 2
xmax = xs[jmax]
else:
jmax = np.argmin(np.abs(xs - xmax))
sp = interpolate.splrep(xs, ys, s=smooth)
d1s = interpolate.splev(xs, sp, der=1)
d2s = interpolate.splev(xs, sp, der=2)
# Find the center x0 and its index j0
j0 = np.argmin(np.abs(d1s[jmin:jmax])) + jmin
if j0 == jmin or j0 == jmax:
print('Failed to find a minimum of 1st derivative in search range.')
return failure
res = minimize_scalar(der1, (xmin, xs[j0], xmax), args=sp)
if res.success:
x0 = res.x
# Find extrema of der2 to identify adjenct crossings
j1 = jmin + np.argmin(d2s[jmin:j0])
j2 = j0 + np.argmax(d2s[j0:jmax])
if d2s[j1] * d2s[j2] > 0:
print('Trouble finding limiting min(der2) or max(der2)')
return (j0, j1, j2), (x0, -1, -1)
x1, x2 = -1, -1
dl, dc, du = np.abs(d2s[j1 - 1:j1 + 2])
if dc > dl and dc > du:
xl, xc, xu = xs[j1 - 1:j1 + 2]
res = minimize_scalar(mabsder2, (xl, xc, xu), args=sp)
if res.success:
x1 = res.x
dl, dc, du = np.abs(d2s[j2 - 1:j2 + 2])
if dc > dl and dc > du:
xl, xc, xu = xs[j2 - 1:j2 + 2]
res = minimize_scalar(mabsder2, (xl, xc, xu), args=sp)
if res.success:
x2 = res.x
return (j0, j1, j2), (x0, x1, x2)
def min_delta(xs, El, Eu):
"""
Find the minimum energy difference = the crossing
between two stabilization roots
This function looks across the whole range, and
may be less useful as dedicated search up/down
xs: scaling parameter
El, Eu: lower and upper branch
Returns:
jmin: min distance
xs[jmin]
Eu[jmin] - El[jmin]
"""
diff = Eu - El
jmin = np.argmin(diff)
return jmin, xs[jmin], diff[jmin]
def min_delta_search(xs, xp, Ep, Eo, up=True):
"""
Find the minimum energy difference = the crossing
between two stabilization roots
This function starts at xc and searches down in x
xs: scaling parameter
xp: center of the plateau of branch Ep
Eo: other branch (upper/lower branch for up=False/True)
up: search direction
Returns:
jmin: min distance
xs[jmin]
delta-E[jmin]
"""
jp = np.argmin(abs(xs - xp))
diff = abs(Ep - Eo)
step = -1
end = 0
if up:
step = 1
end = len(xs)
last_diff = diff[jp]
jmin = -1
for j in range(jp + step, end, step):
curr_diff = diff[j]
if curr_diff > last_diff:
jmin = j - step
break
last_diff = curr_diff
if jmin < 0:
return -1, -1, -1
return jmin, xs[jmin], diff[jmin]
def carlson_eq_3(z, a0, a1, A, B, z1):
"""
2-by-2 model for Hamiltonian for crossing
returns (E-, E+) value for z
"""
H11 = a0
H22 = a0 + a1 * (z - z1)
H12_sq = A + B * (z - z1)**2
f1 = (H11 + H22) * 0.5
f2 = 0.5 * ((H11 - H22)**2 + 4 * H12_sq)**0.5
return np.append(f1 - f2, f1 + f2)
def carlson_eq_3_lsq(params, xdata, ydata):
'''Returns residuals for eqn_3'''
a0, a1, A, B, z1 = params
return carlson_eq_3(xdata, a0, a1, A, B, z1) - ydata
def tbt_ana_curvefit(zs, E1s, E2s, cross_center):
"""
fits Carlson's 2-by-2 model Hamiltonian
to the crossing z1, E1, E2
cross_center is used as a guess (can be replaced by z of closest distance)
returns the stationary z and energy, and fit quality:
zr, zi, Er, Ei, chi2
"""
Es = np.append(E1s, E2s)
a0 = E2s[0] - (E2s[0] - E1s[-1]) / 2 # resonance H11 is constant
a1 = (E1s[0] - E2s[-1]) / (zs[0] - zs[-1]) # DC H22 is linear in z
A = (min(E2s - E1s) / 2)**2 # min distance squared
B = -1.0 # Guess arbitrary, negative number
z1 = cross_center
guess = [a0, a1, A, B, z1]
params = curve_fit(carlson_eq_3, zs, Es, p0=guess)
a0, a1, A, B, z1 = params[0]
# stationary point
zreal = z1
zimag = np.sqrt((a1 * A) / (abs(B) * (a1**2 + 4 * B)))
# resonance energy
Er = a0
Ei = -2 * (np.sqrt(A * abs(B))) / (np.sqrt(4 * B + a1**2))
# chi^2
Esfit = carlson_eq_3(zs, a0, a1, A, B, z1)
chi2 = sum((Esfit - Es)**2)
return zreal, zimag, Er, Ei, chi2
def tbt_ana_lsq(zs, E1s, E2s, cross_center):
"""
fits Carlson's 2-by-2 model Hamiltonian
to the crossing z1, E1s, E2s
cross_center is used as a guess (can be replaced by z of closest distance)
returns the stationary z and energy, and fit quality:
zr, zi, Er, Ei, chi2
"""
Es = np.append(E1s, E2s)
a0 = E2s[0] - (E2s[0] - E1s[-1]) / 2 # resonance H11 is constant
a1 = (E1s[0] - E2s[-1]) / (zs[0] - zs[-1]) # DC H22 is linear in z
A = (min(E2s - E1s) / 2)**2 # min distance squared
B = -1.0 # Guess arbitrary, negative number
z1 = cross_center
guess = [a0, a1, A, B, z1]
data = (zs, Es)
res = least_squares(carlson_eq_3_lsq, x0=guess, args=data)
if not res.success:
print('Fit failed:', res.message)
chi2 = res.cost * 2
a0, a1, A, B, z1 = res.x
# stationary point
zreal = z1
zimag = np.sqrt((a1 * A) / (abs(B) * (a1**2 + 4 * B)))
# resonance energy
Er = a0
Ei = -2 * (np.sqrt(A * abs(B))) / (np.sqrt(4 * B + a1**2))
return zreal, zimag, Er, Ei, chi2
<file_sep>import numpy as np
#from scipy import sqrt
"""
Helper functions for using generalized or super Pade approximants:
E^2*P + E*Q + R = 0
where P, Q, and R are polynomials
normally all three have the same order, so Pade-[n,n,n]
"""
def genpade2_via_lstsq(nQ, nP, nS, xs, ys, rcond=1e-14, return_lists=False):
"""
generalized Pade nq/np/ns approximant
y**2 * Q + y * P + S = 0
with Q, P, S being polynomials of x.
The coefficients of Q, P, and S are determined by LS fitting
numpy.linalg.lstsq is used, so any len(xs)=len(ys) will work.
One coefficient is redundant, and to account for this the linear
coefficient of Q is arbitrarily set to 1.
If this leads to huge coefficients, scale your x input.
input:
nQ, nP, nS: order of Q, P, and S
xs, ys array with data to fit
recond: handed to lstsq(); determines smoothness vs accuracy
return_lists: return coefficients as lists or poly1d polynomials
returned:
Pade coefficients for Q, P, and S in highest-power first order
"""
N_coef = nS + nP + nQ + 2
M_data = len(xs)
Q0=1
Q0 = max(xs)-min(xs)
if M_data < N_coef:
print('Warning: Underdetermined system in genpade2')
A=np.zeros((M_data,N_coef))
b=np.zeros(M_data)
for k_data in range(M_data):
i_coef = 0
E=ys[k_data]
E2=E*E
#
for iq in range(nQ,1,-1): # counts from np down to 2
A[k_data,i_coef] = E2*xs[k_data]**iq
i_coef += 1
if nQ > 0:
A[k_data,i_coef] = E2*xs[k_data]
i_coef += 1
#
for ip in range(nP,1,-1): # counts from np down to 2
A[k_data,i_coef] = E*xs[k_data]**ip
i_coef += 1
if nP > 0:
A[k_data,i_coef] = E*xs[k_data]
i_coef += 1
A[k_data,i_coef] = E
i_coef += 1
#
for ks in range(nS,1,-1): # counts from np down to 2
A[k_data,i_coef] = xs[k_data]**ks
i_coef += 1
if nS > 0:
A[k_data,i_coef] = xs[k_data]
i_coef += 1
A[k_data,i_coef] = 1.0
#
b[k_data] = -E2*Q0
coefs, residual, rank, s = np.linalg.lstsq(A,b,rcond=rcond)
Qs = np.array(list(coefs[:nQ]) + [Q0])
Ps = coefs[nQ:nQ+nP+1]
Ss = coefs[-nS-1:]
if return_lists:
return Qs, Ps, Ss
else:
return np.poly1d(Qs), np.poly1d(Ps), np.poly1d(Ss)
def E_lower(x, A, B, C):
""" lower branch of a generalized Pade approximant """
if A(x) < 0:
return -0.5 * (B(x) - np.sqrt(B(x)*B(x)-4*A(x)*C(x)) ) / A(x)
else:
return -0.5 * (B(x) + np.sqrt(B(x)*B(x)-4*A(x)*C(x)) ) / A(x)
def E_upper(x, A, B, C):
""" upper branch of a generalized Pade approximant """
if A(x) >= 0:
return -0.5 * (B(x) - np.sqrt(B(x)*B(x)-4*A(x)*C(x)) ) / A(x)
else:
return -0.5 * (B(x) + np.sqrt(B(x)*B(x)-4*A(x)*C(x)) ) / A(x)
def dEdL(E, L, P, Q, R):
"""
we know: E^2*P + E*Q + P = 0
therefore:
dEdL = E' = -(E^2*P' + E*Q' + R')/(2*E*P + Q)
input
P, Q, R: three polynomials that depend on L
E: the energy
L: the independent (scaling) variable
"""
Pp = P.deriv(1)(L)
Qp = Q.deriv(1)(L)
Rp = R.deriv(1)(L)
return -(E**2*Pp + E*Qp + Rp) / (2*E*P(L) + Q(L))
def E_from_L(L, A, B, C):
"""
given L, solve E^2*A + E*B + C = 0
return roots
"""
P = np.poly1d([A(L), B(L), C(L)])
return P.roots
def E_and_Ep(L, A, B, C):
"""
given L, solve E^2*A + E*B + C = 0
for every root, compute dEdL
return energies and abs(derivatives)
"""
P = np.poly1d([A(L), B(L), C(L)])
roots = P.roots
ders = []
for E in roots:
ders.append(abs(dEdL(E, L, A, B, C)))
return roots, ders
#
# for Newton we solve dEdL = 0 or E' = 0
#
# so we iterate L[i+1] = L[i] - E'/E''
#
# the fraction E'/E'' can be worked out analytically:
#
# (E^2*P' + E*Q' + R') /
# (2*P*E'^2 + 4*E*E'*P' + E^2*P'' + 2*E'*Q' + E*Q'' + R'')
#
def EpoEpp(E, L, P, Q, R):
""" E'/E'' needed for Newton's method """
Pp = P.deriv(1)(L)
Qp = Q.deriv(1)(L)
Rp = R.deriv(1)(L)
Ep = -(E**2*Pp + E*Qp + Rp) / (2*E*P(L) + Q(L))
Ppp = P.deriv(2)(L)
Qpp = Q.deriv(2)(L)
Rpp = R.deriv(2)(L)
num = E**2*Pp + E*Qp + Rp
den = 2*P(L)*Ep**2 + 4*E*Ep*Pp + E**2*Ppp + 2*Ep*Qp + E*Qpp + Rpp
return num/den
def GPA_NewtonRaphson(z_guess, polys, max_step=20, ztol=1e-8, Etol=1e-8, verbose=True):
"""
Newton-Raphson for generalized Pade in the complex plane
E^2 * A + E * B + C = 0 where A, B, C are polynomials in z
z_guess : start point
poly : list of the polynomials defining the GPA
max_step : maximal number of Newton steps
ztol, Etol : tolerances in z and E(z)
"""
z_curr = z_guess
A, B, C = polys
roots, ders = E_and_Ep(z_curr, A, B, C)
i_root = np.argmin(ders)
Ecurr=roots[i_root]
converged = False
if verbose:
print('Newton Raphson steps:')
print(' step z_curr E_curr')
print('-----------------------------------------------------')
#print(' 0 (0.9250560, 0.6512459) (3.1595040, 0.1494027)')
for i in range(max_step):
delta_z = EpoEpp(Ecurr, z_curr, A, B, C)
if i == 0:
delta_0 = abs(delta_z) * 10
z_curr = z_curr - delta_z
# compute new Ecurr (two roots, pick closer one to Ecurr)
Es = E_from_L(z_curr, A, B, C)
delta_E = min(abs(Es-Ecurr))
Ecurr = Es[np.argmin(abs(Es-Ecurr))]
if verbose:
# print table with L E
print("%3d (%.7f, %.7f) (%.7f, %.7f)" %
(i, z_curr.real, z_curr.imag, Ecurr.real, Ecurr.imag))
# check convergence
if abs(delta_z) > delta_0:
break
if abs(delta_z) < ztol and delta_E < Etol:
converged = True
break
Es, ders = E_and_Ep(z_curr, A, B, C)
iroot = np.argmin(ders)
return converged, z_curr, Es[iroot], ders[iroot]
<file_sep>[Link to the paper, free to read, but paywall for print or download](https://rdcu.be/cD7rr)
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 15 12:39:25 2021
@author: thomas
Functions for the selection of a plateau or crossing range
"""
#import sys
import numpy as np
from scipy import interpolate
from scipy.optimize import brentq, minimize_scalar
def find_zero(xs, j0, up=True):
"""
Find the next "zero" (sign inversion) along xs
starting at index j0
up==True searches upwards
"""
step = -1
stop = 1
if up:
step = 1
stop = len(xs)-1
for j in range(j0, stop, step):
x1 = xs[j]
x2 = xs[j+step]
if x1*x2 < 0:
if np.abs(x1) < np.abs(x2):
return j
return j+step
return stop
def min_der(xs, ys):
"""
Find the minimum (abs) of the derivative along a curve, ys(xs)
derivative are computed using a spline interpolation
xs : pointwise curve, x values
ys : pointwise curve, y values
Returns:
jmin: index with the lowest derivative
xs[jmin]
ders[jmin]
"""
sp = interpolate.splrep(xs, ys, s=0)
ders = interpolate.splev(xs, sp, der=1)
jmin = np.argmin(abs(ders))
return jmin, xs[jmin], ders[jmin]
def der_and_curvature(xs, ys):
"""
Derivative and curvature of a pointwise provided curve y(x)
obtained by standard spline interpolation
normalized to range [-1,1]
Any branch of a stabilization graph goes through
a crossing-plateau-crossing structure, which are
defined by curavture extrema and a curvature zero inbetween.
xs : pointwise curve, x values
ys : pointwise curve, y values
Returns: the derivatives: dy/dx and d2y/dx2 at the xs
"""
sp = interpolate.splrep(xs, ys, s=0)
d1s = interpolate.splev(xs, sp, der=1)
d2s = interpolate.splev(xs, sp, der=2)
d1s /= np.max(np.abs(d1s))
d2s /= np.max(np.abs(d2s))
return d1s, d2s
def crossing(xs, E1, E2, select=0.5):
"""
find center of a crossing
select a range of points determined by drop of the
curvature
options:
use drop-offs to max(curature)*select
use drop-offs of sqrt(max(curvature))
Parameters:
xs : scaling parameter E1(x), E2(x)
E1, E2 : lower and upper branch of the crossing
select : selection range cutoff as determined by
the d2 reduction (0.0 = all to next plateaux)
if select < 0, use sqrt(d2_max)
Returns:
success : boolean
xc : center of the crossing
selected ranges of xs, E1, and E2
"""
sp1 = interpolate.splrep(xs, E1, s=0)
sp2 = interpolate.splrep(xs, E2, s=0)
d2s1 = interpolate.splev(xs, sp1, der=2)
d2s2 = interpolate.splev(xs, sp2, der=2)
j1_mn = np.argmin(d2s1)
j2_mx = np.argmax(d2s2)
jc = j1_mn
if j1_mn - j2_mx > 1:
if np.abs(xs[j1_mn]-xs[j2_mx]) > 0.05:
return (False, -1, (j1_mn, j2_mx), d2s1, d2s2)
else:
jc = (j1_mn + j2_mx)//2
xc = xs[jc]
d2s1_mn, d2s2_mx = d2s1[j1_mn], d2s2[j2_mx]
d2s1_cut, d2s2_cut = select*d2s1_mn, select*d2s2_mx
if select < 0:
d2s1_cut = -np.sqrt(-d2s1_mn)
d2s2_cut = np.sqrt( d2s2_mx)
j_max = find_zero(d2s1-d2s1_cut, j1_mn, up=True)
j_min = find_zero(d2s2-d2s2_cut, j2_mx, up=False)
x_sel = xs[j_min:j_max+1]
E1sel = E1[j_min:j_max+1]
E2sel = E2[j_min:j_max+1]
return (True, xc, x_sel, E1sel, E2sel)
def plateau(xs, ys, srch_range=(-1, -1)):
"""
find
- index of minimum of derivative and exact zero of curvature
- indices and exact positions of extrema of the curvature
Parameters:
xs : pointwise curve, x values
ys : pointwise curve, y values
srch_range=(xmin, xmax): smaller search range from problems
Returns:
j0, j1, j2: indices of zero and extrema of ys
x0, x1, x2: precise positions of zero and extrema of d^2y/dx^2
jx = -1 indicates failure
"""
def der1(x, a, b, c):
# spline = (a, b, c)
return interpolate.splev(x, (a,b,c), der=1)
def der2(x, a, b, c):
# spline = (a, b, c)
return interpolate.splev(x, (a,b,c), der=2)
def mabsder2(x, a, b, c):
# spline = (a, b, c)
return -np.abs(interpolate.splev(x, (a,b,c), der=2))
failure = ((-1, -1, -1), (-1, -1, -1))
xmin, xmax = srch_range
# search range, default is xs[2,-2]
if xmin < 0:
jmin = 2
xmin = xs[jmin]
else:
jmin = np.argmin(np.abs(xs-xmin))
if xmax < 0:
jmax = len(xs) - 2
xmax = xs[jmax]
else:
jmax = np.argmin(np.abs(xs-xmax))
sp = interpolate.splrep(xs, ys, s=0)
d1s = interpolate.splev(xs, sp, der=1)
d2s = interpolate.splev(xs, sp, der=2)
# Find the center x0 and its index j0
j0 = np.argmin(np.abs(d1s[jmin:jmax]))+jmin
if j0 == jmin or j0 == jmax:
print('Failed to find a minimum of 1st derivative in search range.')
return failure
res = minimize_scalar(der1, (xmin, xs[j0], xmax), args=sp)
if res.success:
x0 = res.x
# Find extrema of der2 to identify adjenct crossings
j1 = jmin + np.argmin(d2s[jmin:j0])
j2 = j0 + np.argmax(d2s[j0:jmax])
if d2s[j1]*d2s[j2] > 0:
print('Trouble finding limiting min(der2) or max(der2)')
return (j0, j1, j2), (x0, -1, -1)
x1, x2 = -1, -1
dl, dc, du = np.abs(d2s[j1-1:j1+2])
if dc > dl and dc > du:
xl, xc, xu = xs[j1-1:j1+2]
res = minimize_scalar(mabsder2, (xl, xc, xu), args=sp)
if res.success:
x1 = res.x
dl, dc, du = np.abs(d2s[j2-1:j2+2])
if dc > dl and dc > du:
xl, xc, xu = xs[j2-1:j2+2]
res = minimize_scalar(mabsder2, (xl, xc, xu), args=sp)
if res.success:
x2 = res.x
return (j0, j1, j2), (x0, x1, x2)
def min_delta(xs, El, Eu):
"""
Find the minimum energy difference = the crossing
between two stabilization roots
This function looks across the whole range, and
may be less useful as dedicated search up/down
xs: scaling parameter
El, Eu: lower and upper branch
Returns:
jmin: min distance
xs[jmin]
Eu[jmin] - El[jmin]
"""
diff = Eu - El
jmin = np.argmin(diff)
return jmin, xs[jmin], diff[jmin]
def min_delta_search(xs, xp, Ep, Eo, up=True):
"""
Find the minimum energy difference = the crossing
between two stabilization roots
This function starts at xc and searches down in x
xs: scaling parameter
xp: center of the plateau of branch Ep
Eo: other branch (upper/lower branch for up=False/True)
up: search direction
Returns:
jmin: min distance
xs[jmin]
delta-E[jmin]
"""
jp = np.argmin(abs(xs-xp))
diff = abs(Ep - Eo)
step = -1
end = 0
if up:
step = 1
end = len(xs)
last_diff = diff[jp]
jmin = -1
for j in range(jp+step, end, step):
curr_diff = diff[j]
if curr_diff > last_diff:
jmin = j-step
break
last_diff = curr_diff
if jmin < 0:
return -1, -1, -1
return jmin, xs[jmin], diff[jmin]
<file_sep>import numpy as np
"""
Functions defining and evaluating the Jolanta model potential
used for plotting and DVR
"""
def Jolanta_1D(x, a=0.2, b=0.0, c=0.14):
"""
default 1D potential:
bound state: -12.26336 eV
resonance: (3.279526396 - 0.2079713j) eV
"""
return (a * x * x - b) * np.exp(-c * x * x)
def Jolanta_1Db(x, param):
"""
c.f. Jolanta_1D
"""
a, b, c = param
return (a * x * x - b) * np.exp(-c * x * x)
def Jolanta_3D(r, param, l=1, mu=1):
"""
standard 1D Jolanta potential in radial form
plus angular momentum potential
param=(0.028, 1.0, 0.028), l=1, and mu=1 gives
Ebound in eV = -7.17051, and
Eres in eV = (3.1729420714-0.160845j)
"""
a, b, c = param
return (a * r**2 - b) * np.exp(-c * r**2) + 0.5 * l * (l + 1) / r**2 / mu
def Jolanta_3D_old(r, a=0.1, b=1.2, c=0.1, l=1, as_parts=False):
"""
default 3D potential; has a resonance at 1.75 eV - 0.2i eV
use for DVRs
"""
if as_parts:
Va = a * r**2 * np.exp(-c * r**2)
Vb = b * np.exp(-c * r**2)
Vc = 0.5 * l * (l + 1) / r**2
return (Va, Vb, Vc)
else:
return (a * r**2 - b) * np.exp(-c * r**2) + 0.5 * l * (l + 1) / r**2
| c9dfaeffb2096af7d5c62ea6e561569ead8bd4e7 | [
"Markdown",
"Python"
] | 14 | Markdown | tsommerfeld/L2-methods_for_resonances | 62db4dcf15db5d8f305511e6eb305a63f3948319 | 0aa6aec0a9ce054b2871a0ee4f2af29c1bf5b819 |
refs/heads/master | <file_sep><?php
session_start();
require_once('assets/db.php');
require_once('assets/checklogin.php');
$userid = $_SESSION['userid'];
$postid = $_GET['postid'];
if(isset($_GET) & !empty($_GET)){
$res = $database->deletepost($postid);
if($res){
header('Location: post.php');
}else{
echo "delete failed";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Edit Page</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
</body>
</html><file_sep><?php
session_start();
require_once('assets/db.php');
$res = $database->showposthome();
?>
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php include('assets/heading.php'); ?>
<h1>Blog</h1>
<div class="clr20"></div>
<div id="wrap1000">
<?php while($rpost = mysqli_fetch_assoc($res)){ ?>
<div class="colblog">
<img src="images/<?php echo $rpost['image']; ?>" class="fimage">
<h2><?php echo $rpost['title']; ?></h2>
<div class="blogcont"><?php echo $rpost['description']; ?></div>
</div>
<div class="clr10"></div>
<?php } ?>
<div class="pagination"><?php $res = $database->page(); ?></div>
</div>
</body>
</html><file_sep><div id="wrapfull" class="heading">
<a href="index.php">Home</a>
<?php if(!isset($_SESSION['userid'])) { ?> <a href="login.php">Login</a> <a href="register.php">Register</a> <?php } ?> <?php if(isset($_SESSION['userid'])) { ?><a href="post.php">Blog</a> <a href="logout.php">Logout</a> <?php } ?>
</div><file_sep><?php
session_start();
require_once('assets/db.php');
require_once('assets/checklogin.php');
if(isset($_POST) & !empty($_POST)){
$userid = $_SESSION['userid'];
$title = $database->sanitize($_POST['title']);
$description = $database->sanitize($_POST['description']);
$image = $database->sanitize($_FILES['image']['name']);
if (move_uploaded_file($_FILES['image']['tmp_name'], getcwd() . "/images/" . $_FILES['image']['name'])) {
//echo "uploaded";
} else {
//echo "Upload failed!";
}
$res = $database->addpost($userid, $title, $description, $image);
if($res){
//echo "post added";
}else{
//echo "post failed";
}
}
$res = $database->showpost();
?>
<!DOCTYPE html>
<html>
<head>
<title>Add Post Page</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php include('assets/heading.php'); ?>
<h1>Welcome <?php echo $_SESSION['name']; ?></h1>
<h2>Add Post</h2>
<form enctype="multipart/form-data" method="POST">
<input type="text" name="title" placeholder="POST TITLE" >
<div class="clr10"></div>
<textarea name="description" placeholder="POST DESCRIPTION"></textarea>
<div class="clr10"></div>
<input type="file" name="image">
<div class="clr10"></div>
<input type="submit" value="Add Post">
</form>
<h2>Blog Post</h2>
<div id="wrap1000">
<?php while($rpost = mysqli_fetch_assoc($res)){ ?>
<div class="col1"><?php echo $rpost['title']; ?></div>
<div class="col2"><a href="edit.php?postid=<?php echo $rpost['postid']; ?>">edit</a></div>
<div class="col3"><a href="delete.php?postid=<?php echo $rpost['postid']; ?>">delete</a></div>
<?php } ?>
</div>
</body>
</html><file_sep><?php
require_once('assets/db.php');
if(isset($_POST) & !empty($_POST)){
$email = $database->sanitize($_POST['email']);
$name = $database->sanitize($_POST['name']);
$password = $database->sanitize($_POST['password']);
$res = $database->create('User',$email, $name, $password);
if($res){
//echo "registration successfull";
}else{
//echo "failed to register";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Registration Page</title>
<link rel="stylesheet" href="style.css">
<script src="https://cdn.jsdelivr.net/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js"></script>
<script src="validate.js"></script>
</head>
<body>
<?php include('assets/heading.php'); ?>
<h1>Registration Page</h1>
<form method="POST" id="form1" name="registration">
<input type="text" placeholder="EMAIL ADDRESS" name="email">
<div class="clr10"></div>
<input type="text" placeholder="NAME" name="name">
<div class="clr10"></div>
<input type="password" placeholder="<PASSWORD>" name="password">
<div class="clr10"></div>
<input type="<PASSWORD>" placeholder="<PASSWORD>" name="<PASSWORD>">
<div class="clr10"></div>
<input type="submit" value="Register">
</form>
</body>
</html> | 9d54dd8e16242d30301947560d3c81195e0ced3c | [
"PHP"
] | 5 | PHP | philswebdesign/simpleblog | 786c12879f10c2631a783ad878e384407a7b2098 | 4db6e0ce5d9efa99244dba3c076037a52b7608f8 |
refs/heads/master | <file_sep>import { Component, OnInit } from '@angular/core';
import {FormGroup, FormControl} from '@angular/forms';
import {HttpClient} from '@angular/common/http';
@Component({
selector: 'app-create-employee',
templateUrl: './create-employee.component.html',
styleUrls: ['./create-employee.component.css']
})
export class CreateEmployeeComponent implements OnInit {
employeeForm: FormGroup;
constructor(private http:HttpClient) { }
ngOnInit() {
this.employeeForm= new FormGroup({
userName: new FormControl(),
email: new FormControl(),
password: new FormControl()
});
}
onSubmit(): void{
console.log(this.employeeForm);
console.log(this.employeeForm.value);
this.http.post("http://localhost:8701/rest/user/add",this.employeeForm.value,{}).subscribe(response=>{
console.log("Reponse from Controller ",response)
localStorage.setItem("tokrn","ttbcv")
console.log(localStorage)
})
}
}
| bca8fb42d57cc6ec39ad2a35a2d5fcd971cc1705 | [
"TypeScript"
] | 1 | TypeScript | developersprojects/micro | a7af83c6f1bacfedec09d60a8f0339bac29838c5 | cd1081bd74378fb8157663ac0400dd107317e3be |
refs/heads/master | <repo_name>prazhit/Hi-Tech-Vision<file_sep>/cart.php
<?php include("include/header.php");?>
<section class="breadcrumbs py-4">
<div class="container-fluid px-5">
<h6><a href="home.php">Home</a><i class="fas red mx-2 fa-chevron-right"></i>Shopping Cart</h6>
<hr class="mt-4">
</div>
</section>
<section class="cart pb-5">
<div class="container-fluid px-5">
<div class="row">
<div class="col-lg-9 px-4 py-2">
<div class="row cart-title p-3 mb-1">
<div class="col-lg-3 col-md-3 offset-md-2 ">
<h6 class="font-weight-bold">ITEM(S)</h6>
</div>
<div class="col-lg-2 col-md-2 ">
<h6 class="font-weight-bold">PRICE</h6>
</div>
<div class="col-lg-3 col-md-3">
<h6 class="font-weight-bold pl-4">QUANTITY</h6>
</div>
<div class="col-lg-2 col-md-2 ">
<h6 class="font-weight-bold">TOTAL</h6>
</div>
</div>
<div class="row cart-content mt-2 p-3">
<div class="col-lg-2 col-md-2 image d-flex align-items-center">
<a href="detail.php"><img src="pics/flash-sale5.jpg"></a>
</div>
<div class="col-lg-3 col-md-3 d-flex align-items-center">
<a href="detail.php" data-toggle="tooltip" title="Samsung Galaxy S10 128GB+8GB RAM 48mp+8mp+13mp+2mp Back Camera 4100mah">Samsung Galaxy S10 128GB+8GB RAM </a>
</div>
<div class="col-lg-2 col-md-2 d-flex align-items-center">
<h5 class="my-2 red">Rs. 80,900</h5>
</div>
<div class="col-lg-3 col-md-3 d-flex align-items-center">
<div class="input-group plus-minus-input">
<div class="input-group-button">
<button type="button" class="hollow circle" data-quantity="minus" data-field="quantity">
<i class="fa fa-minus" aria-hidden="true"></i>
</button>
</div>
<input class="input-group-field mx-2" type="number" max="9" name="quantity" value="1">
<div class="input-group-button">
<button type="button" class="hollow circle" data-quantity="plus" data-field="quantity">
<i class="fa fa-plus" aria-hidden="true"></i>
</button>
</div>
</div>
</div>
<div class="col-lg-2 col-md-2 d-flex align-items-center">
<h5 class="my-2">Rs. 80,900</h5>
</div>
</div>
<div class="row edit p-3">
<div class="col-lg-12 col-md-12 ">
<a href="#" data-toggle="tooltip" title="Edit"><i class="far red fa-edit"></i></a>
<a href="#" data-toggle="tooltip" title="Delete"><i class="far red fa-times-circle"></i></a>
</div>
</div>
<div class="row cart-content mt-2 p-3">
<div class="col-lg-2 col-md-2 image d-flex align-items-center">
<a href="detail.php"><img src="pics/flash-sale1.jpg"></a>
</div>
<div class="col-lg-3 col-md-3 d-flex align-items-center">
<a href="detail.php" data-toggle="tooltip" title="OnePlus 7 Pro (6GB RAM, 128GB Storage) - Mirror Grey">OnePlus 7 Pro (6GB RAM, 128GB Storage) - Mirror Grey</a>
</div>
<div class="col-lg-2 col-md-2 d-flex align-items-center">
<h5 class="my-2 red">Rs. 75,600</h5>
</div>
<div class="col-lg-3 col-md-3 d-flex align-items-center">
<div class="input-group plus-minus-input">
<div class="input-group-button">
<button type="button" class="hollow circle" data-quantity="minus" data-field="quantity">
<i class="fa fa-minus" aria-hidden="true"></i>
</button>
</div>
<input class="input-group-field mx-2" type="number" max="9" name="quantity" value="1">
<div class="input-group-button">
<button type="button" class="hollow circle" data-quantity="plus" data-field="quantity">
<i class="fa fa-plus" aria-hidden="true"></i>
</button>
</div>
</div>
</div>
<div class="col-lg-2 col-md-2 d-flex align-items-center">
<h5 class="my-2">Rs. 75,600</h5>
</div>
</div>
<div class="row edit p-3">
<div class="col-lg-12 col-md-12 ">
<a href="#" data-toggle="tooltip" title="Edit"><i class="far red fa-edit"></i></a>
<a href="#" data-toggle="tooltip" title="Delete"><i class="far red fa-times-circle"></i></a>
</div>
</div>
<div class="row coupon-code mt-2 d-flex justify-content-between">
<div class=" apply my-2 d-flex align-items-center">
<input type="text" class="form-control" placeholder="Coupon Code">
<button class="button">Apply Coupon</button>
</div>
<div class="update-cart my-2">
<a class="btn mr-2" href="catagory.php">Back To Shopping</a>
<button class="button">Update Cart</button>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="row pt-2 mb-1">
<div class="summary col-lg-12">
<h6 class=" order-title text-center text-white font-weight-bold p-3">ORDER SUMMARY</h6>
<div class="order-content mt-2">
<h6 class="d-flex align-items-center justify-content-between p-3">
<p>Sub Total</p>
<p>Rs. 1,56,500</p>
</h6>
<h6 class="d-flex align-items-center justify-content-between p-3">
<p>Discount (Coupon)</p>
<p>Rs. 0</p>
</h6>
<h6 class="d-flex total red align-items-center justify-content-between p-3">
<p>Total</p>
<p>Rs. 1,56,500</p>
</h6>
</div>
<a href="checkout.php" class=" d-inline-block button mt-2">Proceed To Checkout</a>
</div>
</div>
</div>
</div>
</div>
</section>
<?php include("include/footer.php");?><file_sep>/contact.php
<?php include("include/header.php");?>
<section class="breadcrumbs py-4">
<div class="container-fluid px-5">
<h6><a href="home.php">Home</a><i class="fas red mx-2 fa-chevron-right"></i>Contact Us</h6>
</div>
</section>
<section class="contact py-4">
<div class="container-fluid px-5">
<div class="row">
<div class="col-lg-3 py-4">
<h4 class="font-weight-bold">CONTACT US</h4>
<div class="phone my-5 d-flex align-items-center">
<i class="fas fa-2x mr-3 red fa-mobile-alt"></i>
<p>+977 9813822002</p>
</div>
<div class="map my-5 d-flex align-items-center">
<i class="fas fa-2x mr-3 red fa-map-marker-alt"></i>
<p>Tinkune, KTM</p>
</div>
<div class="mail my-5 d-flex align-items-center">
<i class="far fa-2x mr-3 red fa-envelope-open"></i>
<p><EMAIL></p>
</div>
<div class="follow">
<h4 class="font-weight-bold">FOLLOW US</h4>
<div class="header-social-icons my-5">
<a href="#" style="color: #e4405f"> <i class="fab fa-instagram"></i></a>
<a href="#" style="color: #3b5998"> <i class="fab fa-facebook-f"></i></a>
<a href="#" style="color: #00acee"> <i class="fab fa-twitter"></i></a>
<a href="#" style="color: #dd4b39"> <i class="fab fa-google-plus-g"></i></a>
</div>
</div>
</div>
<div class="col-lg-5 py-4">
<h4 class="font-weight-bold">OUR LOCATION</h4>
<iframe class="my-5" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3533.091964212953!2d85.34678271440124!3d27.68355238280177!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x39eb19a18187378f%3A0x8ba2460dd7896e64!2sOnline%20Zeal!5e0!3m2!1sen!2snp!4v1572065502249!5m2!1sen!2snp" width="100%" height="350" frameborder="0" style="border:0; border-radius:10px;" allowfullscreen=""></iframe>
</div>
<div class="col-lg-4 write-us py-4">
<h4 class="font-weight-bold">WRITE US</h4>
<form class="form my-5" action="#">
<div class="form-group">
<p class="font-weight-bold mb-2">Full Name</p>
<div class="input-group d-flex align-items-center">
<i class="fas px-3 fa-user"></i>
<input type="text" class="form-control" placeholder="Please enter your name">
</div>
</div>
<div class="form-group">
<p class="font-weight-bold mb-2">Email</p>
<div class="input-group d-flex align-items-center">
<i class="fas px-3 fa-at"></i>
<input type="email" class="form-control" placeholder="Enter email here ...">
</div>
</div>
<p class="font-weight-bold mb-3">Message</p>
<textarea name="messag" id="#" class="form-control" rows="10" placeholder="Write your message here..."></textarea>
<button class="button mt-4" type="submit">Send Message</button>
</form>
</div>
</div>
</div>
</section>
<?php include("include/footer.php");?><file_sep>/checkout.php
<?php include("include/header.php");?>
<section class="breadcrumbs py-4">
<div class="container-fluid px-5">
<h6><a href="home.php">Home</a><i class="fas red mx-2 fa-chevron-right"></i>Checkout</h6>
</div>
</section>
<section class="checkout py-4">
<div class="container-fluid px-5 detail-box">
<form action="#">
<div class="row">
<div class="col-lg-6 col-md-6 py-4">
<div class="card mb-5">
<div class="card-head d-flex align-items-center">
<i class="fas fa-user-plus"></i>
<h6 class="font-weight-bold">PERSONAL DETAILS</h6>
</div>
<div class="form p-3">
<div class="input-group mb-3">
<input class="form-control mr-3" type="text" placeholder="First Name*">
<input class="form-control" type="text" placeholder="Last Name*">
</div>
<div class="form-group">
<input class="form-control" type="email" name="email" placeholder="E-mail*">
</div>
<div class="form-group">
<input class="form-control" type="number" name="num" placeholder="Phone no.*">
</div>
</div>
</div>
<div class="card mb-5">
<div class="card-head d-flex align-items-center">
<i class="fas fa-map-marker-alt"></i>
<h6 class="font-weight-bold">SHIPPING ADDRESS</h6>
</div>
<div class="form p-3">
<div class="form-group">
<select class="form-control" name="region">
<option class="bg-secondary" selected>Region</option>
<option>Bagmati</option>
<option>Bheri</option>
<option>janakpur</option>
<option>Gandaki</option>
</select>
</div>
<div class="form-group">
<select class="form-control" name="city">
<option class="bg-secondary" selected>City</option>
<option>Koteshwor</option>
<option>Baneshwor</option>
<option>Maitighar</option>
<option>Sardobato</option>
</select>
</div>
<div class="form-group">
<input class="form-control" type="text" placeholder="Address*">
</div>
<div class="form-group">
<input class="form-control" type="number" placeholder="Post Code*">
</div>
</div>
</div>
<div class="card mb-5">
<div class="card-head d-flex align-items-center">
<i class="fas fa-location-arrow"></i>
<h6 class="font-weight-bold">SHIPPING METHOD</h6>
</div>
<div class="form p-3">
<h6><label class="input-group d-flex align-items-center"><input class="mr-3" type="radio" checked>Flat Shipping Rate - Rs.120</label></h6>
</div>
</div>
</div>
<div class="col-lg-6 col-md-6">
<div class="card my-4 mb-5">
<div class="card-head d-flex align-items-center">
<i class="fas fa-money-check-alt"></i>
<h6 class="font-weight-bold">PAYMENT METHOD</h6>
</div>
<div class="form p-3">
<h6><label class="input-group d-flex align-items-center"><input class="mr-3" type="radio" checked>Cash on Delivery</label></h6>
</div>
</div>
<div class="card mb-5 d-none d-md-block">
<div class="card-head d-flex align-items-center">
<i class="fas fa-shopping-cart"></i>
<h6 class="font-weight-bold">SHOPPING CART</h6>
</div>
<div class="shopping-cart-title p-3 ">
<div class="row no-gutters mx-1">
<div class="col-lg-6">
<h6 class="title">PRODUCT NAME</h6>
<div data-mh="e1" class="content d-flex align-items-center">
<a href="detail.php"><img src="pics/flash-sale-1.jpg" alt="#"></a>
<h6><a href="detail.php"> Samsung Galaxy S10 128GB+8GB RAM</a> </h6>
</div>
<div data-mh="e2" class="content d-flex align-items-center">
<a href="detail.php"><img src="pics/flash-sale1.jpg" alt="#"></a>
<h6><a href="detail.php"> OnePlus 7 Pro (6GB RAM, 128GB Storage)</a> </h6>
</div>
</div>
<div class="col-lg-2">
<h6 class="title">QUANTITY</h6>
<div data-mh="e1" class="content d-flex align-items-center">
<input type="number" value="1" class="text-center">
<div class="edit">
<i class="far d-block m-2 fa-trash-alt"></i>
<i class="fas d-block m-2 fa-sync-alt"></i>
</div>
</div>
<div data-mh="e2" class="content d-flex align-items-center">
<input type="number" value="1" class="text-center">
<div class="edit">
<i class="far d-block m-2 fa-trash-alt"></i>
<i class="fas d-block m-2 fa-sync-alt"></i>
</div>
</div>
</div>
<div class="col-lg-2">
<h6 class="title">UNIT PRICE</h6>
<div data-mh="e1" class="content d-flex align-items-center">
<h6>Rs.80,900</h6>
</div>
<div data-mh="e2" class="content d-flex align-items-center">
<h6>Rs.75,600</h6>
</div>
</div>
<div class="col-lg-2">
<h6 class="title">TOTAL</h6>
<div data-mh="e1" class="content d-flex align-items-center">
<h6>Rs.80,900</h6>
</div>
<div data-mh="e2" class="content d-flex align-items-center">
<h6>Rs.75,600</h6>
</div>
</div>
</div>
<div class="row mx-1 no-gutters sub-total">
<div class="col-lg-6">
<h6 class="my-2 text-muted font-weight-bold pl-2">SUB-TOTAL:</h6>
</div>
<div class="col-lg-2 offset-lg-4">
<h6 class="my-2">Rs. 1,56,500</h6>
</div>
<div class="col-lg-6">
<h6 class="my-2 text-muted font-weight-bold pl-2">DISCOUNT (COUPON):</h6>
</div>
<div class="col-lg-2 offset-lg-4">
<h6 class="my-2">Rs. 0</h6>
</div>
<div class="col-lg-6">
<h6 class="my-2 text-muted font-weight-bold pl-2">TOTAL:</h6>
</div>
<div class="col-lg-2 offset-lg-4">
<h6 class="my-2 red">Rs. 1,56,500</h6>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-head d-flex align-items-center">
<i class="fas fa-comment"></i>
<h6 class="font-weight-bold">ADD COMMENTS ABOUT YOUR ORDER</h6>
</div>
<div class="form p-3">
<textarea name="comment" class="form-control" cols="30" rows="6"></textarea>
</div>
</div>
<label class="check-it my-4">I have read and agree to the FAQs
<input type="checkbox">
<span class="checkmark"></span>
</label>
<a href="confirm-order.php" class="button d-inline-block">CONFIRM ORDER</a>
</div>
</div>
</form>
</div>
</section>
<?php include("include/footer.php");?>
<file_sep>/faqs.php
<?php include("include/header.php");?>
<style>
.select-bar{
display: none!important;
}
.dropdown{
display: block!important;
}
</style>
<section class="breadcrumbs py-4">
<div class="container-fluid px-5">
<h6><a href="about.php">About Us</a><i class="fas red mx-2 fa-chevron-right"></i>FAQs</h6>
</div>
</section>
<section class="service-search py-5">
<div class="container-fluid d-flex align-items-center justify-content-center">
<div class="input-group">
<input type="search" class="form-control" placeholder="Search for questions...">
<i class="fas fa-search"></i>
</div>
</div>
</section>
<section class="service-que py-5">
<div class="container head py-4">
<h4 class="title red font-weight-bold"><span class="num text-white mr-4">1</span>What products are warranted?</h4>
<p class="my-3 text-muted">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Officia consectetur odio possimus nostrum voluptatibus debitis, ipsum earum molestias. Odit commodi, iusto nihil ratione facere adipisci suscipit repudiandae atque nam quaerat?. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<ul class="list-unstyled">
<li><p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Officia consectetur </p></li>
<li><p>voluptatibus debitis, ipsum earum molestias. Odit commodi, iusto nihil ratione facere </p></li>
<li><p>Ut enim ad minim veniam, quis nostrud exercitation </p></li>
<li><p>Ullamco laboris nisi ut aliquip ex ea commodo consequat. </p></li>
</ul>
</div>
<div class="container head py-4">
<h4 class="title red font-weight-bold"><span class="num text-white mr-4">2</span>Where to go for warranty service?</h4>
<p class="my-3 text-muted">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Officia consectetur odio possimus nostrum voluptatibus debitis, ipsum earum molestias. Odit commodi, iusto nihil ratione facere adipisci suscipit repudiandae atque nam quaerat?. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<div class="container head py-4">
<h4 class="title red font-weight-bold"><span class="num text-white mr-4">3</span>Can I exchange or return an item?</h4>
<p class="my-3 text-muted">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
<i class="italic mb-3">Lorem ipsum dolor sit amet conse ctetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet conse ctetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</i>
</div>
<div class="container head py-4">
<h4 class="title red font-weight-bold"><span class="num text-white mr-4">4</span>In some cases, the warranty is not provided?</h4>
<p class="my-3 text-muted">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Officia consectetur odio possimus nostrum voluptatibus debitis, ipsum earum molestias. Odit commodi, iusto nihil ratione facere adipisci suscipit repudiandae atque nam quaerat?. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<ul class="list-unstyled">
<li><p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Officia consectetur </p></li>
<li><p>voluptatibus debitis, ipsum earum molestias. Odit commodi, iusto nihil ratione facere </p></li>
<li><p>Ut enim ad minim veniam, quis nostrud exercitation </p></li>
<li><p>Ullamco laboris nisi ut aliquip ex ea commodo consequat. </p></li>
</ul>
</div>
</section>
<?php include("include/footer.php");?>
<file_sep>/about.php
<?php include("include/header.php");?>
<style>
.select-bar{
display: none!important;
}
.dropdown{
display: block!important;
}
</style>
<section class="about-us py-5 d-flex justify-content-between align-items-center flex-column">
<div class="bread text-white align-self-top">
<h1 class="font-weight-bold cav">About Us</h1>
</div>
<div class="container-fluid text-center py-4">
<h1 class="font-weight-bold display-4 mb-2 cav">Delivering Happiness On The Go !!</h1>
<h1 class="font-weight-bold happy">HAPPY SHOPPING</h1>
</div>
</section>
<section class="our-story py-5">
<div class="container story text-center">
<h1 class="font-weight-bold cav">Our Story</h1>
<div class="row">
<div class="col-lg-6 py-5 story-content">
<p>HiTech has a wide range of domain specific application software that provides efficient and effective management of operations. These applications have powerful features to take care of all requirements of Dealers, Distributors, Retailers, Departmental Stores, Corporate House, Restaurant, Couriers, Transport, Service Industry as well as Complex Manufacturing Industry including all types of medium and small business segment.</p><br>
<p>HiTech Solutions and Services Pvt. Ltd. is one of the premier business software solution providers in Nepal with its corporate office located at Kalimati, Kathmandu (Nepal). Promoted by professionals with more than a decade experience in accounting, </p>
</div>
<div class="col-lg-6 py-5 story-content">
<p>HiTech has a wide range of domain specific application software that provides efficient and effective management of operations. These applications have powerful features to take care of all requirements of Dealers, Distributors, Retailers, Departmental Stores, Corporate House, Restaurant, Couriers, Transport, Service Industry as well as Complex Manufacturing Industry including all types of medium and small business segment.</p><br>
<p>HiTech Solutions and Services Pvt. Ltd. is one of the premier business software solution providers in Nepal with its corporate office located at Kalimati, Kathmandu (Nepal). Promoted by professionals with more than a decade experience in accounting, </p>
</div>
</div>
</div>
</section>
<section class="our-values py-5">
<div class="container value text-center">
<h1 class="font-weight-bold cav">Our Values</h1>
<div class="row mt-3">
<div class="col-lg-6 py-5 value-image">
<img src="pics/value-img.jpg" alt="#" class="img-fluid">
</div>
<div class="col-lg-6 py-5 value-content">
<ul class="list-unstyled px-4">
<li>More than 15 years Experience in IT Products Services</li>
<li>More than 1500 Satisfied Clients all over Nepal</li>
<li>Providing service to almost all Corporate Houses in Nepal</li>
<li>Widest Support Network in Nepal, Offices in all Major Cities of Nepal.</li>
<li>Scientifically designed workspace with full Support Services</li>
<li>Team of Qualified and Skilled Software and Hardware Professionals</li>
<li>Proper Office Management System to provide quality Products and Services</li>
<li>We believe in giving the best to our customers, sellers & society.</li>
</ul>
</div>
</div>
</div>
</section>
</div>
<section class="our-values py-5">
<div class="container value text-center">
<h1 class="font-weight-bold cav">Goals & Objectives</h1>
<div class="row mt-3">
<div class="col-lg-6 py-5 value-content">
<ul class="list-unstyled px-4">
<li>More than 15 years Experience in IT Products Services</li>
<li>More than 1500 Satisfied Clients all over Nepal</li>
<li>Providing service to almost all Corporate Houses in Nepal</li>
<li>Widest Support Network in Nepal, Offices in all Major Cities of Nepal.</li>
<li>Scientifically designed workspace with full Support Services</li>
<li>Team of Qualified and Skilled Software and Hardware Professionals</li>
<li>Proper Office Management System to provide quality Products and Services</li>
<li>We believe in giving the best to our customers, sellers & society.</li>
</ul>
</div>
<div class="col-lg-6 py-5 value-image">
<img src="pics/our-goal.jpg" alt="#" class="img-fluid goal-img">
</div>
</div>
</div>
</section>
<section class="around py-5">
<div class="container py-5 text-white text-center d-flex justify-content-end">
<h1 class="font-weight-bold cav display-4">5 Countries, <br>Milions Of Products</h1>
</div>
</section>
<?php include("include/footer.php");?><file_sep>/home.php
<?php include('include/header.php');?>
<section class="banner py-4">
<div class="container-fluid px-5">
<div class="row">
<div class="col-lg-3 col-md-3 d-none d-md-block">
<div class="brand-nav">
<a class="drop-brand samsung" >Samsung</a>
<div class="drop-content drop-samsung container p-4">
<div class="row">
<div class="col-lg-6 col-md-6">
<h4 class="red mb-2">Electronics</h4>
<ul class="list-unstyled">
<li><a href="catagory.php">TV & Video</a></li>
<li><a href="catagory.php">Home, Audio & Theater</a></li>
<li><a href="catagory.php">Camera, Photo & Video</a></li>
<li><a href="catagory.php">Cellphones & Accessories</a></li>
<li><a href="catagory.php">Headphones</a></li>
<li><a href="catagory.php">Video Games</a></li>
</ul>
</div>
<div class="col-lg-5 col-md-5 offset-lg-1">
<h4 class="red mb-2">Computers</h4>
<ul class="list-unstyled">
<li><a href="catagory.php">Laptops & Tablets</a></li>
<li><a href="catagory.php">Desktop & Monitor</a></li>
<li><a href="catagory.php">Computer Accessories</a></li>
</ul>
</div>
<img src="pics/samsung-drop-bg.png">
</div>
</div>
<a class="drop-brand lg" >LG</a>
<div class="drop-content drop-lg container p-4">
<div class="row">
<div class="col-lg-6 col-md-6">
<h4 class="red mb-2">Electronics</h4>
<ul class="list-unstyled">
<li><a href="catagory.php">TV & Video</a></li>
<li><a href="catagory.php">Home, Audio & Theater</a></li>
<li><a href="catagory.php">Camera, Photo & Video</a></li>
<li><a href="catagory.php">Cellphones & Accessories</a></li>
<li><a href="catagory.php">Headphones</a></li>
<li><a href="catagory.php">Video Games</a></li>
</ul>
</div>
<div class="col-lg-5 col-md-5 offset-lg-1">
<h4 class="red mb-2">Computers</h4>
<ul class="list-unstyled">
<li><a href="catagory.php">Laptops & Tablets</a></li>
<li><a href="catagory.php">Desktop & Monitor</a></li>
<li><a href="catagory.php">Computer Accessories</a></li>
</ul>
</div>
<img src="pics/lg-drop-bg.png">
</div>
</div>
<a class="drop-brand yasuda" >Yasuda</a>
<div class="drop-content drop-yasuda container p-4">
<div class="row">
<div class="col-lg-6 col-md-6">
<h4 class="red mb-2">Electronics</h4>
<ul class="list-unstyled">
<li><a href="catagory.php">TV & Video</a></li>
<li><a href="catagory.php">Home, Audio & Theater</a></li>
<li><a href="catagory.php">Camera, Photo & Video</a></li>
<li><a href="catagory.php">Cellphones & Accessories</a></li>
<li><a href="catagory.php">Headphones</a></li>
<li><a href="catagory.php">Video Games</a></li>
</ul>
</div>
<div class="col-lg-5 col-md-5 offset-lg-1">
<h4 class="red mb-2">Computers</h4>
<ul class="list-unstyled">
<li><a href="catagory.php">Laptops & Tablets</a></li>
<li><a href="catagory.php">Desktop & Monitor</a></li>
<li><a href="catagory.php">Computer Accessories</a></li>
</ul>
</div>
<img src="pics/yasuda-drop-bg.png">
</div>
</div>
<a class="drop-brand cg" >CG</a>
<div class="drop-content drop-cg container p-4">
<div class="row">
<div class="col-lg-6 col-md-6">
<h4 class="red mb-2">Electronics</h4>
<ul class="list-unstyled">
<li><a href="catagory.php">TV & Video</a></li>
<li><a href="catagory.php">Home, Audio & Theater</a></li>
<li><a href="catagory.php">Camera, Photo & Video</a></li>
<li><a href="catagory.php">Cellphones & Accessories</a></li>
<li><a href="catagory.php">Headphones</a></li>
<li><a href="catagory.php">Video Games</a></li>
</ul>
</div>
<div class="col-lg-5 col-md-5 offset-lg-1">
<h4 class="red mb-2">Computers</h4>
<ul class="list-unstyled">
<li><a href="catagory.php">Laptops & Tablets</a></li>
<li><a href="catagory.php">Desktop & Monitor</a></li>
<li><a href="catagory.php">Computer Accessories</a></li>
</ul>
</div>
<img src="pics/cg-drop-bg.png">
</div>
</div>
<a class="drop-brand last-brand-nav canon" >Canon</a>
<div class="drop-content drop-canon container p-4">
<div class="row">
<div class="col-lg-6 col-md-6">
<h4 class="red mb-2">Electronics</h4>
<ul class="list-unstyled">
<li><a href="catagory.php">TV & Video</a></li>
<li><a href="catagory.php">Home, Audio & Theater</a></li>
<li><a href="catagory.php">Camera, Photo & Video</a></li>
<li><a href="catagory.php">Cellphones & Accessories</a></li>
<li><a href="catagory.php">Headphones</a></li>
<li><a href="catagory.php">Video Games</a></li>
</ul>
</div>
<div class="col-lg-5 col-md-5 offset-lg-1">
<h4 class="red mb-2">Computers</h4>
<ul class="list-unstyled">
<li><a href="catagory.php">Laptops & Tablets</a></li>
<li><a href="catagory.php">Desktop & Monitor</a></li>
<li><a href="catagory.php">Computer Accessories</a></li>
</ul>
</div>
<img src="pics/canon-drop-bg.png">
</div>
</div>
</div>
</div>
<div class="col-lg-9 col-md-9 slider">
<div class="slider_inner">
<div data-thumb="pics/banner-slide1.jpg" data-src="pics/banner-slide1.jpg">
</div>
<div data-thumb="pics/banner-slide2.jpg" data-src="pics/banner-slide2.jpg">
</div>
<div data-thumb="pics/banner-slide3.jpg" data-src="pics/banner-slide3.jpg">
</div>
</div>
</div>
</div>
</div>
</section>
<section class="top-brands py-5">
<div class="container-fluid px-5">
<div class="row">
<div class="col-lg-4 col-md-4 py-4">
<a href="special-deals.php" class="card py-5 px-4" >
<div class="row">
<div class="col-lg-7 content" data-mh="eq">
<h3 class="font-weight-bold">TOP HEADPHONES</h3>
<h5 class="my-2 ">Feel The Sound</h5>
<h6 class=" font-weight-bold">SHOP NOW <i class="fas ml-1 fa-caret-right"></i> </h6>
</div>
<img src="pics/top-headphones.png">
</div>
</a>
</div>
<div class="col-lg-4 col-md-4 py-4">
<a href="special-deals.php" class="card py-5 px-4" >
<div class="row">
<div class="col-lg-7 content" data-mh="eq">
<h3 class="font-weight-bold">IPHONE X</h3>
<h5 class="my-2 ">The Only One</h5>
<h6 class=" font-weight-bold">SHOP NOW <i class="fas ml-1 fa-caret-right"></i> </h6>
</div>
<img src="pics/iphone6.png">
</div>
</a>
</div>
<div class="col-lg-4 col-md-4 py-4">
<a href="special-deals.php" class="card py-5 px-4" >
<div class="row">
<div class="col-lg-7 content" data-mh="eq">
<h3 class="font-weight-bold">MACBOOK PRO</h3>
<h5 class="my-2 ">With Retina Display</h5>
<h6 class=" font-weight-bold">SHOP NOW <i class="fas ml-1 fa-caret-right"></i> </h6>
</div>
<img src="pics/macbook.png">
</div>
</a>
</div>
<div class="col-lg-6 col-md-6 py-4">
<a href="special-deals.php" class="card py-5 px-4" >
<div class="row">
<div class="col-lg-7 content" data-mh="eq">
<h3 class="font-weight-bold">PLAYSTATION 4</h3>
<h5 class="my-2 ">Be First To Play</h5>
<h6 class=" font-weight-bold">SHOP NOW <i class="fas ml-1 fa-caret-right"></i> </h6>
</div>
<img src="pics/play-station.png">
</div>
</a>
</div>
<div class="col-lg-6 col-md-6 py-4">
<a href="special-deals.php" class="card py-5 px-4" >
<div class="row">
<div class="col-lg-7 content" data-mh="eq">
<h3 class="font-weight-bold">LED MONITORS</h3>
<h5 class="my-2 ">Up to 75% Off</h5>
<h6 class=" font-weight-bold">SHOP NOW <i class="fas ml-1 fa-caret-right"></i> </h6>
</div>
<img src="pics/lcd.png">
</div>
</a>
</div>
</div>
</div>
</section>
<section class="flash-sale py-5">
<div class="container-fluid px-5">
<h3 class="font-weight-bold text-white mb-4">FLASH SALE</h3>
<div class="owl-carousel owl-theme py-4">
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale1.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="OnePlus 7 Pro (6GB RAM, 128GB Storage) - Mirror Grey">OnePlus 7 Pro (6GB RAM, 128GB Storage) - Mirror Grey</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 75,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 80,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale3.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="ASUS ROG Phone II Dual-SIM 8GB/128GB Smartphone Tencent">ASUS ROG Phone II Dual-SIM 8GB/128GB Smartphone Tencent</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 85,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 91,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale2.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Nokia 6 [RAM-3GB ROM-32GB, Camera 16MP(Main)+8MP(Selfie)]">Nokia 6 [RAM-3GB ROM-32GB, Camera 16MP(Main)+8MP(Selfie)]</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 13,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 20,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale4.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Vivo V17 Pro 8GB 128GB 32mp+8mp Pop-Up Selfie Camera, 48mp+8mp+13mp+2mp Back Camera 4100mah">Vivo V17 Pro 8GB 128GB 32mp+8mp Pop-Up Selfie Camera, ...</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 30,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 35,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale5.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Samsung Galaxy S10 128GB+8GB RAM 48mp+8mp+13mp+2mp Back Camera 4100mah">Samsung Galaxy S10 128GB+8GB RAM ...</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 84,900</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 104,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
</div>
</div>
</section>
<section class="catagory py-5">
<div class="container-fluid px-5">
<h3 class="font-weight-bold">CATAGORIES</h3>
<div class="row py-5">
<div class="col-lg-3 col-md-4 col-sm-6 col-md-4 py-3">
<a href="catagory.php" class="card d-block card1 d-flex justify-content-end align-items-center p-3">
<h5 class="font-weight-bold text-white">TV & Video</h5>
</a>
</div>
<div class="col-lg-3 col-md-4 col-sm-6 col-md-4 py-3">
<a href="catagory.php" class="card d-block card2 d-flex justify-content-end align-items-center p-3">
<h5 class="font-weight-bold text-white">Home, Audio & Theater</h5>
</a>
</div>
<div class="col-lg-3 col-md-4 col-sm-6 col-md-4 py-3">
<a href="catagory.php" class="card d-block card3 d-flex justify-content-end align-items-center p-3">
<h5 class="font-weight-bold text-white">Camera, Phone & Video</h5>
</a>
</div>
<div class="col-lg-3 col-md-4 col-sm-6 col-md-4 py-3">
<a href="catagory.php" class="card d-block card4 d-flex justify-content-end align-items-center p-3">
<h5 class="font-weight-bold text-white">Cellphone & Accessories</h5>
</a>
</div>
<div class="col-lg-3 col-md-4 col-sm-6 col-md-4 py-3">
<a href="catagory.php" class="card d-block card5 d-flex justify-content-end align-items-center p-3">
<h5 class="font-weight-bold text-white">Headphones</h5>
</a>
</div>
<div class="col-lg-3 col-md-4 col-sm-6 col-md-4 py-3">
<a href="catagory.php" class="card d-block card6 d-flex justify-content-end align-items-center p-3">
<h5 class="font-weight-bold text-white">Laptops & Tablets</h5>
</a>
</div>
<div class="col-lg-3 col-md-4 col-sm-6 col-md-4 py-3">
<a href="catagory.php" class="card d-block card7 d-flex justify-content-end align-items-center p-3">
<h5 class="font-weight-bold text-white">Desktop & Monitors</h5>
</a>
</div>
<div class="col-lg-3 col-md-4 col-sm-6 col-md-4 py-3">
<a href="catagory.php" class="card d-block card8 d-flex justify-content-end align-items-center p-3">
<h5 class="font-weight-bold text-white">Computer Accessories</h5>
</a>
</div>
</div>
</div>
</section>
<section class="newest-product py-5">
<div class="container-fluid px-5">
<div class="title-head d-flex justify-content-between align-items-center">
<h3 class="font-weight-bold">NEWEST PRODUTS</h3>
<h5><a href="#">View All</a></h5>
</div>
<div class="row py-5">
<div class="col-lg-3 col-md-4 col-sm-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale5.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Samsung Galaxy S10 128GB+8GB RAM 48mp+8mp+13mp+2mp Back Camera 4100mah">Samsung Galaxy S10 128GB+8GB RAM ...</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 84,900</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 104,000</strike></h5>
</div>
<h6 class="emi emi-off text-white text-center p-2">OUT OF STOCK !!!</h6>
</div>
</div>
<div class="col-lg-3 col-md-4 col-sm-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/new-product3.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Samsung UA43N5300 43 inch Full HD LED Smart TV">Samsung UA43N5300 43 inch Full HD LED Smart TV</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 80,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 95,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="col-lg-3 col-md-4 col-sm-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/new-product4.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Kisonli U-2500BT USB 2.1 Portable Computer Speaker With FM Black">Kisonli U-2500BT USB 2.1 Portable Computer Speaker With FM Black.</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 17,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 25,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="col-lg-3 col-md-4 col-sm-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/new-product5.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="'SONY BRAVIA' 43 FULL HD SMART TV [KDL-43W660G]">"SONY BRAVIA 43" FULL HD SMART TV [KDL-43W660G], ...</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 89,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 90,000</strike></h5>
</div>
<h6 class="emi emi-off text-white text-center p-2">out of stock !!!</h6>
</div>
</div>
<div class="col-lg-3 col-md-4 col-sm-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/new-product7.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Yasuda YSVC36MB 1600W Bagless Vacuum Cleaner- Red/Black - [11.11 Exclusive]">Yasuda YSVC36MB 1600W Bagless Vacuum Cleaner- Red/Black - [11.11 Exclusive] ...</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 18,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 21,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="col-lg-3 col-md-4 col-sm-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/new-product6.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="ASUS Vivobook S430UN-i5 8th gen, 8GB RAM,'14' inch Graphics Card Nvidia MX150 2GB, Geniune Windows 10 SLIM ULTRABOOK">ASUS Vivobook S430UN-i5 8th gen, 8GB RAM,"14" inch Graphics Card Nvidia MX150 2GB, Geniune Windows 10 SLIM ULTRABOOK</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 120,800</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 125,000</strike></h5>
</div>
<h6 class="emi emi-off text-white text-center p-2">out of stock !!!</h6>
</div>
</div>
<div class="col-lg-3 col-md-4 col-sm-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/new-product8.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Philips Bagless Vacuum Cleaner FC8087/01">Philips Bagless Vacuum Cleaner FC8087/01.</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 10,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 19,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="col-lg-3 col-md-4 col-sm-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/new-product1.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Samsung Washing Machine WW80J5410GX/TL Front Loading 8.0Kg with Eco-Bubble">Samsung Washing Machine WW80J5410GX/TL Front Loading 8.0Kg with Eco-Bubble...</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 88,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 95,000</strike></h5>
</div>
<h6 class="emi emi-off text-white text-center p-2">out of stock !!!</h6>
</div>
</div>
</div>
</div>
</section>
<section class="special-tabs py-5">
<div class="container-fluid px-5">
<ul class="nav nav-tabs mb-4" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">TOP SALES</a>
</li>
<li class="nav-item">
<a class="nav-link" id="profile-tab" data-toggle="tab" href="#profile" role="tab" aria-controls="profile" aria-selected="false">SPECIAL</a>
</li>
<li class="nav-item">
<a class="nav-link" id="contact-tab" data-toggle="tab" href="#contact" role="tab" aria-controls="contact" aria-selected="false">MOST LIKED</a>
</li>
</ul>
<div class="tab-content" id="myTabContent">
<div class="tab-pane flash-sale fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
<div class="owl-carousel owl-theme py-4">
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale1.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="OnePlus 7 Pro (6GB RAM, 128GB Storage) - Mirror Grey">OnePlus 7 Pro (6GB RAM, 128GB Storage) - Mirror Grey</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 75,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 80,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale3.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="ASUS ROG Phone II Dual-SIM 8GB/128GB Smartphone Tencent">ASUS ROG Phone II Dual-SIM 8GB/128GB Smartphone Tencent</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 85,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 91,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale2.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Nokia 6 [RAM-3GB ROM-32GB, Camera 16MP(Main)+8MP(Selfie)]">Nokia 6 [RAM-3GB ROM-32GB, Camera 16MP(Main)+8MP(Selfie)]</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 13,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 20,000</strike></h5>
</div>
<h6 class="emi emi-off text-white text-center p-2">out of stock !!!</h6>
</div>
</div>
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale4.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Vivo V17 Pro 8GB 128GB 32mp+8mp Pop-Up Selfie Camera, 48mp+8mp+13mp+2mp Back Camera 4100mah">Vivo V17 Pro 8GB 128GB 32mp+8mp Pop-Up Selfie Camera, ...</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 30,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 35,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale5.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Samsung Galaxy S10 128GB+8GB RAM 48mp+8mp+13mp+2mp Back Camera 4100mah">Samsung Galaxy S10 128GB+8GB RAM ...</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 84,900</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 104,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
</div>
</div>
<div class="tab-pane flash-sale fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">
<div class="owl-carousel owl-theme py-4">
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/new-product5.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="'SONY BRAVIA' 43 FULL HD SMART TV [KDL-43W660G]">"SONY BRAVIA 43" FULL HD SMART TV [KDL-43W660G], ...</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 89,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 90,000</strike></h5>
</div>
<h6 class="emi emi-off text-white text-center p-2">out of stock !!!</h6>
</div>
</div>
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale3.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="ASUS ROG Phone II Dual-SIM 8GB/128GB Smartphone Tencent">ASUS ROG Phone II Dual-SIM 8GB/128GB Smartphone Tencent</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 85,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 91,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale2.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Nokia 6 [RAM-3GB ROM-32GB, Camera 16MP(Main)+8MP(Selfie)]">Nokia 6 [RAM-3GB ROM-32GB, Camera 16MP(Main)+8MP(Selfie)]</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 13,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 20,000</strike></h5>
</div>
<h6 class="emi emi-off text-white text-center p-2">out of stock !!!</h6>
</div>
</div>
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale4.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Vivo V17 Pro 8GB 128GB 32mp+8mp Pop-Up Selfie Camera, 48mp+8mp+13mp+2mp Back Camera 4100mah">Vivo V17 Pro 8GB 128GB 32mp+8mp Pop-Up Selfie Camera, ...</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 30,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 35,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale5.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Samsung Galaxy S10 128GB+8GB RAM 48mp+8mp+13mp+2mp Back Camera 4100mah">Samsung Galaxy S10 128GB+8GB RAM ...</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 84,900</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 104,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
</div>
</div>
<div class="tab-pane fade flash-sale" id="contact" role="tabpanel" aria-labelledby="contact-tab">
<div class="owl-carousel owl-theme py-4">
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale1.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="OnePlus 7 Pro (6GB RAM, 128GB Storage) - Mirror Grey">OnePlus 7 Pro (6GB RAM, 128GB Storage) - Mirror Grey</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 75,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 80,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale3.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="ASUS ROG Phone II Dual-SIM 8GB/128GB Smartphone Tencent">ASUS ROG Phone II Dual-SIM 8GB/128GB Smartphone Tencent</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 85,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 91,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale2.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Nokia 6 [RAM-3GB ROM-32GB, Camera 16MP(Main)+8MP(Selfie)]">Nokia 6 [RAM-3GB ROM-32GB, Camera 16MP(Main)+8MP(Selfie)]</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 13,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 20,000</strike></h5>
</div>
<h6 class="emi emi-off text-white text-center p-2">out of stock !!!</h6>
</div>
</div>
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale4.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Vivo V17 Pro 8GB 128GB 32mp+8mp Pop-Up Selfie Camera, 48mp+8mp+13mp+2mp Back Camera 4100mah">Vivo V17 Pro 8GB 128GB 32mp+8mp Pop-Up Selfie Camera, ...</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 30,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 35,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale5.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Samsung Galaxy S10 128GB+8GB RAM 48mp+8mp+13mp+2mp Back Camera 4100mah">Samsung Galaxy S10 128GB+8GB RAM ...</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 84,900</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 104,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="flash-sale just-for-u py-5">
<div class="container-fluid px-5">
<h3 class="font-weight-bold text-white mb-4">JUST FOR YOU</h3>
<div class="owl-carousel owl-theme py-4">
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/just1.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Dell xps 13(9370) /i7/8th Gen 7560U/16GB/512GB SSD/13' Display">Dell xps 13(9370) /i7/8th Gen 7560U/16GB/512GB SSD/13" Display</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 275,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 280,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/just2.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="M2 Bluetooth Intelligence Health Smart Wrist Watch">M2 Bluetooth Intelligence Health Smart Wrist Watch</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 5,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 8,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/just3.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Action Camera HD 1080p 12MP Waterproof Sports Camera (1080P)">Action Camera HD 1080p 12MP Waterproof Sports Camera (1080P)</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 13,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 20,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/just4.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="10.5-inch iPad Air Early 2019, 256GB, Wi-Fi + Cellular, Gold">10.5-inch iPad Air Early 2019, 256GB, Wi-Fi + Cellular, Gold</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 130,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 135,000</strike></h5>
</div>
<h6 class="emi emi-off text-white text-center p-2">out of stock !!!</h6>
</div>
</div>
<div class="item">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/just5.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Samsung Level U Pro Bluetooth Wireless In-ear Headphone">Samsung Level U Pro Bluetooth Wireless In-ear Headphone</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 3,900</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 5,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
</div>
</div>
</section>
<?php include('include/footer.php');?>
<file_sep>/service.php
<?php include("include/header.php");?>
<style>
.select-bar{
display: none!important;
}
.dropdown{
display: block!important;
}
</style>
<section class="breadcrumbs py-4">
<div class="container-fluid px-5">
<h6><a href="about.php">About Us</a><i class="fas red mx-2 fa-chevron-right"></i>Services<i class="fas red mx-2 fa-chevron-right"></i>Service 01</h6>
</div>
</section>
<section class="service-details py-5 bg-light">
<div class="container">
<h2 class="font-weight-bold span1 text-center">OFFERING THE <span class="red">BEST</span> SERVICE</h2>
<div class="img-box my-5">
<img src="pics/service01.jpeg">
<i class="fas fa-tools"></i>
</div>
<div class="row">
<div class="col-lg-5 my-2">
<div class="left py-5 px-4">
<small class="text-muted mb-2 d-block">What We Provide</small>
<h3 class="span1 font-weight-bold mb-5">SERVICE <span class="red">FEATURES</span></h3>
<div class="feature-wrap d-flex align-items-center my-4">
<div class="icon mr-4">
<i class="fab fa-linux"></i>
</div>
<div class="icon-text">
<h5 class="span mb-3"><span class="span1">SUCCESSFUL</span> PROJECTS</h5>
<p class="text-muted">Aonsectetur pisici do eiusmod tempor em Ipsum is simply dummy text printing.</p>
</div>
</div>
<div class="feature-wrap d-flex align-items-center my-4">
<div class="icon mr-4">
<i class="fas fa-chart-line"></i>
</div>
<div class="icon-text">
<h5 class="span mb-3"><span class="span1">SEO</span> OPTIMIZED</h5>
<p class="text-muted">Aonsectetur pisici do eiusmod tempor em Ipsum is simply dummy text printing.</p>
</div>
</div>
<div class="feature-wrap d-flex align-items-center my-4">
<div class="icon mr-4">
<i class="fas fa-headphones-alt"></i>
</div>
<div class="icon-text">
<h5 class="span mb-3"><span class="span1">PAGE</span> BUILDER</h5>
<p class="text-muted">Aonsectetur pisici do eiusmod tempor em Ipsum is simply dummy text printing.</p>
</div>
</div>
</div>
</div>
<div class="col-lg-7 my-2 pl-5 right">
<h6>Quis autem velum iure reprehe nderit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sapien neque, bibendum in sagittis. Duis varius tellus egetmassa pulvinar eu aliquet nibh dapibus.<br><br>
Quis autem velum iure reprehe nderit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sapien neque, bibendum in sagittis. Duisvarius tellus egetmassa pulvinar eu aliquet nibh dapibus. Aenean eros erat, tincidunt vitae fringila nec, fermentum et quam. Class aptent tacitsocio squ ad litora torquent peribia nostra, per inceptos himenaeos. Aenean eros erat, tincidunt vitae fringilla nec, fermentum et quam. Quisautem velum iure reprehe nderit. Lorem ipsum </h6>
<div class="row no-gutters mt-5">
<div class="col-lg-5 image">
<a data-lightbox="service" href="pics/service-bg.jpeg" ><img src="pics/service-bg.jpeg"></a>
<a data-lightbox="serv" href="pics/service-bg.jpeg" ><i class="fas fa-search-plus"></i></a>
</div>
<div class="col-lg-7 image">
<a data-lightbox="service" href="pics/service02.jpeg"><img src="pics/service02.jpeg"></a>
<a data-lightbox="serv" href="pics/service02.jpeg"><i class="fas fa-search-plus"></i></a>
</div>
<div class="col-lg-7 image">
<a data-lightbox="service" href="pics/service03.jpeg"><img src="pics/service03.jpeg"></a>
<a data-lightbox="serv" href="pics/service03.jpeg"><i class="fas fa-search-plus"></i></a>
</div>
<div class="col-lg-5 image">
<a data-lightbox="service" href="pics/service04.jpeg"><img src="pics/service04.jpeg"></a>
<a data-lightbox="serv" href="pics/service04.jpeg"><i class="fas fa-search-plus"></i></a>
</div>
</div>
</div>
</div>
</div>
</section>
<?php include('include/footer.php');?>
<file_sep>/special-deals.php
<?php include("include/header.php");?>
<section class="breadcrumbs py-4">
<div class="container-fluid px-5">
<h6><a href="home.php">Home</a><i class="fas red mx-2 fa-chevron-right"></i>Special Deals</h6>
<hr class="mt-4">
</div>
</section>
<section class="catagory pb-5">
<div class="container-fluid px-5">
<div class="brand-box">
<a href="#"><img src="pics/samsung-logo.jpg"></a>
<a href="#"><img src="pics/oppo.jpg"></a>
<a href="#"><img src="pics/colors.jpg"></a>
<a href="#"><img src="pics/lava.jpg"></a>
<a href="#"><img src="pics/vivo.jpg"></a>
<a href="#"><img src="pics/nokia.jpg"></a>
<a href="#"><img class="lst-img" src="pics/oneplus.jpg"></a>
</div>
</div>
</section>
<section class="catagory-content">
<div class="container-fluid px-5">
<div class="row">
<div class="col-lg-2 left-panel">
<div class="brands">
<h5 class="my-4">Brand</h5>
<label class="check-it">All
<input type="checkbox" checked="checked">
<span class="checkmark"></span>
</label>
<label class="check-it">Samsung
<input type="checkbox">
<span class="checkmark"></span>
</label>
<label class="check-it">LG
<input type="checkbox" >
<span class="checkmark"></span>
</label>
<label class="check-it">Yasuda
<input type="checkbox" >
<span class="checkmark"></span>
</label>
<label class="check-it">CG
<input type="checkbox" >
<span class="checkmark"></span>
</label>
<label class="check-it">Canon
<input type="checkbox" >
<span class="checkmark"></span>
</label>
<label class="check-it">Oneplus
<input type="checkbox" >
<span class="checkmark"></span>
</label>
<div class="collapse" id="more-brand">
<label class="check-it">Oppo
<input type="checkbox" >
<span class="checkmark"></span>
</label>
<label class="check-it">Colors
<input type="checkbox" >
<span class="checkmark"></span>
</label>
<label class="check-it">Lava
<input type="checkbox" >
<span class="checkmark"></span>
</label>
<label class="check-it">Vivo
<input type="checkbox" >
<span class="checkmark"></span>
</label>
<label class="check-it">Nokia
<input type="checkbox" >
<span class="checkmark"></span>
</label>
</div>
<a class="d-block view-brand red mt-4" data-toggle="collapse" href="#more-brand" role="button" aria-expanded="false" aria-controls="more-brand">View More</a>
</div>
<div class="catagories mt-5">
<h5 class="my-4">Catagory</h5>
<label class="check-it">All
<input type="checkbox" checked="checked">
<span class="checkmark"></span>
</label>
<label class="check-it">TV & Video
<input type="checkbox" >
<span class="checkmark"></span>
</label>
<label class="check-it">Home, Audio & Theater
<input type="checkbox" >
<span class="checkmark"></span>
</label>
<label class="check-it">Camera, Photo & Videos
<input type="checkbox" >
<span class="checkmark"></span>
</label>
<label class="check-it">Cellphone & Accessories
<input type="checkbox" >
<span class="checkmark"></span>
</label>
<label class="check-it">Headphones
<input type="checkbox" >
<span class="checkmark"></span>
</label>
<label class="check-it">Laptops & Tablets
<input type="checkbox" >
<span class="checkmark"></span>
</label>
<div class="collapse" id="more-cata">
<label class="check-it">Desktop & Monitor
<input type="checkbox" >
<span class="checkmark"></span>
</label>
<label class="check-it">Computer Accessories
<input type="checkbox" >
<span class="checkmark"></span>
</label>
<label class="check-it">Video Games
<input type="checkbox" >
<span class="checkmark"></span>
</label>
</div>
<a class="d-block view-cata red mt-4" data-toggle="collapse" href="#more-cata" role="button" aria-expanded="false" aria-controls="more-cata">View More</a>
</div>
<div class="price-range-block">
<div class="price d-flex align-items-center justify-content-between mb-2">
<h6>Min Price</h6>
<h6>Max Price</h6>
</div>
<div class="input_wrap d-flex align-items-center justify-content-between mb-4">
<input min=0 max="90000" oninput="validity.valid||(value='0');" id="min_price" class="price-range-field left_field" />
<!-- <span class="range_separator"></span> -->
<input min=0 max="90000" oninput="validity.valid||(value='90000');" id="max_price" class="price-range-field right_field" />
</div>
<div id="slider-range" class="price-filter-range" name="rangeInput"></div>
<button type="submit" class="button mt-3">Search</button>
</div>
</div>
<div class="col-lg-10 right-panel">
<div class="sort-by pt-5 px-5 d-flex flex-wrap align-items-center justify-content-between">
<div class="heading">
<h4 class="font-weight-bold">Special Deals</h4>
<p class="my-3 text-muted">150 items found in Special Deals</p>
</div>
<div class="sort d-flex align-items-center">
<p>Sort By:</p>
<select class="custom-select" name="choose" id="#">
<option value="1" selected>Popularity</option>
<option value="2">Price high to low</option>
<option value="3">Price low to high</option>
</select>
</div>
</div>
<hr>
<div class="row newest-product py-5 px-5">
<div class="col-lg-4 col-md-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale5.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Samsung Galaxy S10 128GB+8GB RAM 48mp+8mp+13mp+2mp Back Camera 4100mah">Samsung Galaxy S10 128GB+8GB RAM ...</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 84,900</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 104,000</strike></h5>
</div>
<h6 class="emi emi-off text-white text-center p-2">OUT OF STOCK !!!</h6>
</div>
</div>
<div class="col-lg-4 col-md-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/new-product3.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Samsung UA43N5300 43 inch Full HD LED Smart TV">Samsung UA43N5300 43 inch Full HD LED Smart TV</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 80,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 95,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="col-lg-4 col-md-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/new-product4.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Kisonli U-2500BT USB 2.1 Portable Computer Speaker With FM Black">Kisonli U-2500BT USB 2.1 Portable Computer Speaker With FM Black.</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 17,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 25,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="col-lg-4 col-md-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/new-product5.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="'SONY BRAVIA' 43 FULL HD SMART TV [KDL-43W660G]">"SONY BRAVIA 43" FULL HD SMART TV [KDL-43W660G], ...</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 89,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 90,000</strike></h5>
</div>
<h6 class="emi emi-off text-white text-center p-2">out of stock !!!</h6>
</div>
</div>
<div class="col-lg-4 col-md-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/just1.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Dell xps 13(9370) /i7/8th Gen 7560U/16GB/512GB SSD/13' Display">Dell xps 13(9370) /i7/8th Gen 7560U/16GB/512GB SSD/13" Display</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 275,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 280,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="col-lg-4 col-md-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/just2.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="M2 Bluetooth Intelligence Health Smart Wrist Watch">M2 Bluetooth Intelligence Health Smart Wrist Watch</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 5,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 8,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="col-lg-4 col-md-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/just3.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Action Camera HD 1080p 12MP Waterproof Sports Camera (1080P)">Action Camera HD 1080p 12MP Waterproof Sports Camera (1080P)</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 13,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 20,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="col-lg-4 col-md-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/just4.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="10.5-inch iPad Air Early 2019, 256GB, Wi-Fi + Cellular, Gold">10.5-inch iPad Air Early 2019, 256GB, Wi-Fi + Cellular, Gold</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 130,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 135,000</strike></h5>
</div>
<h6 class="emi emi-off text-white text-center p-2">out of stock !!!</h6>
</div>
</div>
<div class="col-lg-4 col-md-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/just5.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Samsung Level U Pro Bluetooth Wireless In-ear Headphone">Samsung Level U Pro Bluetooth Wireless In-ear Headphone</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 3,900</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 5,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="col-lg-12 pt-5">
<nav aria-label="Page navigation example">
<ul class="pagination d-flex justify-content-end">
<li class="page-item">
<a class="page-link arrow" href="#" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
<li class="page-item"><a class="page-link" href="#">1</a></li>
<li class="page-item"><a class="page-link" href="#">2</a></li>
<li class="page-item"><a class="page-link" href="#">3</a></li>
<li class="page-item"><a class="page-link" href="#">4</a></li>
<li class="page-item"><a class="page-link" href="#">5</a></li>
<li class="page-item">
<a class="page-link arrow" href="#" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div>
</section>
<?php include("include/footer.php");?><file_sep>/index.php
<?php include('include/header.php');?>
<style>
#header,#footer{
display: none;
}
</style>
<section class="a-one">
<div class="container title-logo">
<div class="img-box text-center">
<a href="home.php"><img src="pics/logo.png" alt="#"></a>
</div>
</div>
<div class="row no-gutters">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 d-flex align-items-center justify-content-center left-one">
<a class="d-block" href="home.php"><h1 class="display-4 text-white font-weight-bold cav">SHOP NOW</h1></a>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 d-flex align-items-center justify-content-center right-one">
<a class="d-block" href="about.php"><h1 class="display-4 text-white font-weight-bold cav">KNOW ABOUT US</h1></a>
</div>
</div>
</section>
<?php include('include/footer.php');?>
<file_sep>/confirm-order.php
<?php include ('include/header.php'); ?>
<section class="confirm-order py-5">
<div class="container-fluid px-5">
<div class="row">
<div class="col-lg-8 col-md-8 py-4">
<div class="left-side p-4">
<h1 class="font-weight-bold">Thank You For Your Order</h1>
<hr>
<div class="row">
<div class="col-lg-7 col-md-7 pt-4">
<table class="table table-striped">
<tbody>
<tr>
<th class="text-muted" scope="row">Order Number</th>
<td>H41WYI558164</td>
</tr>
<tr>
<th class="text-muted" scope="row">Order Date</th>
<td>Thu Dec 06 2019</td>
</tr>
<tr>
<th class="text-muted" scope="row">Cutomer</th>
<td><NAME></td>
</tr>
<tr>
<th class="text-muted" scope="row">Contact Number</th>
<td>+977 9813822002</td>
</tr>
</tbody>
</table>
</div>
<div class="col-lg-5 col-md-5 pt-3 d-flex align-items-center justify-content-end">
<button id="print" class="button px-4 py-3"><i class="fas fa-print mr-2"></i>Print</button>
</div>
<div class="row">
<div class="col-lg-12 col-md-12 py-2">
<p class="m-3">Please keep the above number for your reference. </p>
<p class="m-3">A confirmation email will be sent to you shortly on <EMAIL></p>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6 col-md-6 py-2">
<h5 class="font-weight-bold">Shipping Address</h5>
<p class="my-2">Bagmati</p>
<p class="my-2">Tinkune, Kathmandu</p>
<p class="my-2">2467, Baneshwor Street</p>
</div>
<div class="col-lg-6 col-md-6 py-2">
<h5 class="font-weight-bold">Payment Method</h5>
<div class="input-group d-flex align-items-center">
<input class="mr-2" type="radio" checked name="payment"><p>Cash on Delivery</p>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6 col-md-6 py-2">
<h5 class="font-weight-bold">Billing Address</h5>
<p class="my-2">Bagmati</p>
<p class="my-2">Tinkune, Kathmandu</p>
<p class="my-2">2467, Baneshwor Street</p>
</div>
<div class="col-lg-6 col-md-6 py-2">
<h5 class="font-weight-bold">Shipping Method</h5>
<p class="my-2">5 - 6 Business Days</p>
</div>
</div>
</div>
</div>
<div class="col-lg-4 col-md-4 py-4">
<div class="right-side">
<h5 class="font-weight-bold py-3 px-4">Order Summary</h5>
<div class="total py-4">
<div class="sub-total d-flex justify-content-between my-3 px-4">
<p class="text-muted font-weight-bold">SUB TOTAL :</p>
<p>Rs. 158,000</p>
</div><hr>
<div class="sub-total d-flex justify-content-between my-3 px-4">
<p class="text-muted font-weight-bold">ESTIMATE SHIPPING :</p>
<p>Rs. 100</p>
</div><hr>
<div class="sub-total d-flex justify-content-between my-3 px-4">
<p class="text-muted font-weight-bold">DISCOUNTS :</p>
<p>Rs. 0</p>
</div><hr>
<div class="sub-total d-flex justify-content-between my-3 px-4">
<p class=" font-weight-bold">ORDER TOTAL :</p>
<p class="font-weight-bold">Rs. 1,58,100</p>
</div>
</div>
</div>
<div class="right-side mt-5">
<h5 class="font-weight-bold py-3 px-4">Items Ordered</h5>
<div class="total pb-4">
<div class="item-ordered py-3">
<p class="my-3 text-center font-weight-bold">Arrives in 5-6 business days</p>
<div class="row px-3">
<div class="col-lg-4 col-md-4 py-2">
<img src="pics/flash-sale1.jpg" alt="#" class="img-fluid">
</div>
<div class="col-lg-8 col-md-8">
<p class="my-2">OnePlus 7 Pro (6GB RAM, 128GB Storage)</p>
<p class="my-2">1 Unit</p>
<p class="my-2">Rs. 68,000</p>
</div>
</div>
</div>
<hr>
<div class="item-ordered py-3">
<p class="my-3 text-center font-weight-bold">Arrives in 5-6 business days</p>
<div class="row px-3">
<div class="col-lg-4 col-md-4 py-2">
<img src="pics/flash-sale-1.jpg" alt="#" class="img-fluid">
</div>
<div class="col-lg-8 col-md-8">
<p class="my-2"> Samsung Galaxy S10 128GB+8GB RAM</p>
<p class="my-2">1 Unit</p>
<p class="my-2">Rs. 68,000</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<?php include ('include/footer.php'); ?>
<file_sep>/detail.php
<?php include("include/header.php");?>
<section class="breadcrumbs py-4">
<div class="container-fluid px-5">
<h6><a href="catagory.php">Samsung</a><i class="fas red mx-2 fa-chevron-right"></i><a href="catagory.php">Mobile Phones</a><i class="fas red mx-2 fa-chevron-right"></i>Samsung Galaxy S10</h6>
</div>
</section>
<section class="detail-page py-5">
<div class="container-fluid px-5">
<div class="row">
<div class="col-lg-4 col-md-4 py-3">
<div class="img-box position-relative">
<a id="zoom-placeholder" href="pics/flash-sale5.jpg" class="MagicZoom" data-options="zoomPosition: #zoom-placeholder;selectorTrigger: hover;"><img src="pics/flash-sale5.jpg" class="img-fluid" alt="#"></a>
</div>
<div class="img-list text-center mt-4">
<a data-zoom-id="zoom-placeholder" href="pics/flash-sale5.jpg" data-image="pics/flash-sale5.jpg"><img src="pics/flash-sale5.jpg"></a>
<a data-zoom-id="zoom-placeholder" href="pics/flash-sale-1.jpg" data-image="pics/flash-sale-1.jpg"><img src="pics/flash-sale-1.jpg"></a>
</div>
</div>
<div class="col-lg-8 col-md-8 py-3">
<div class="title px-5">
<h4 class="top">Samsung Galaxy S10 128GB+8GB RAM 48mp+8mp+13mp+2mp Back Camera 4100mah</h4>
<h6 class="my-4">Brand : <a class="text-muted" href="#"> Samsung</a> <span class="font-weight-bold mx-2 text-muted">|</span> <a class="text-muted" href="#">More products from Samsung</a></h6>
<hr>
<h5 class="my-3 d-inline-block">Total Price :</h5>
<h4 class="my-3 d-inline-block mx-2 red">Rs. 80,900</h4>
<h5 class="my-3 d-inline-block text-muted ml-3"><strike>Rs. 85,000</strike></h5>
<div class="input-group plus-minus-input">
<h5 class="mr-4">Quantity</h5>
<div class="input-group-button">
<button type="button" class="hollow circle" data-quantity="minus" data-field="quantity">
<i class="fa fa-minus" aria-hidden="true"></i>
</button>
</div>
<input class="input-group-field mx-2" type="number" max="9" name="quantity" value="1">
<div class="input-group-button">
<button type="button" class="hollow circle" data-quantity="plus" data-field="quantity">
<i class="fa fa-plus" aria-hidden="true"></i>
</button>
</div>
</div>
<div class="input-group">
<div class="cart my-5">
<a data-toggle="modal" data-target=".cart-modal" class="button px-4 py-3" href="#">Add to Cart</a>
</div>
<div class="buy-now my-5">
<a data-toggle="modal" data-target=".login-modal" class="button px-4 py-3" href="#">Buy Now</a>
<a data-toggle="modal" data-target=".login-mobile" class="button px-4 py-3" href="#">Buy Now</a>
</div>
</div>
</div>
<div class="description ">
<h5 class=" px-5 py-4 text-white">Specifications of Samsung Galaxy S10 128GB+8GB RAM</h5>
<div class="row py-4 px-5">
<div class="col-lg-6">
<ul class="list-unstyled">
<li class="head font-weight-bold">Brand</li>
<li class="mb-3">Samsung</li>
<li class="head font-weight-bold">Year</li>
<li class="mb-3">2019</li>
<li class="head font-weight-bold">Type of battery</li>
<li class="mb-3">Lithium battery</li>
<li class="head font-weight-bold">Headphone Jack</li>
<li class="mb-3">Yes</li>
<li class="head font-weight-bold">Fast Charging</li>
<li class="mb-3">yes</li>
<li class="head font-weight-bold">Operating system version</li>
<li class="mb-3">Android</li>
<li class="head font-weight-bold">RAM Memory</li>
<li class="mb-3">8GB</li>
</ul>
</div>
<div class="col-lg-6">
<ul class="list-unstyled">
<li class="head font-weight-bold">Phone Features</li>
<li class="mb-3">Touchscreen,GPS,Wifi,Fingerprint Sensor,Expandable Memory,Dustproof / Waterproof</li>
<li class="head font-weight-bold">Battery</li>
<li class="mb-3">Non-removable Li-Ion 3400 mAh battery</li>
<li class="head font-weight-bold">Processor Type</li>
<li class="mb-3">Octa-core</li>
<li class="head font-weight-bold">Model</li>
<li class="mb-3">SM-G973F</li>
<li class="head font-weight-bold">Notchted Display</li>
<li class="mb-3">yes</li>
<li class="head font-weight-bold">Storage Capacity</li>
<li class="mb-3">Upto 1TB</li>
<li class="head font-weight-bold">Network Connections</li>
<li class="mb-3">GSM,4G</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="emi-content">
<div class="container-fluid px-5">
<div class="row">
<div class="col-lg-6 col-md-6">
<h5 class="py-3 px-5">EMI Description</h5>
<div class="emi-des px-5 py-4">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto dolores enim voluptatibus facere quaerat tempora. Hic, quibusdam! Voluptatem ipsum sed nihil eaque magni dicta illum accusantium, itaque laboriosam facere ex.</p>
</div>
</div>
<div class="col-lg-6 col-md-6 emi-calc">
<h5 class="py-3 px-5">EMI Calculator</h5>
<div class="row">
<div class="col-lg-5">
<div class="input-group my-2">
<input type="number" placeholder="Enter Loan Amount" class="form-control">
</div>
<div class="input-group my-2">
<input type="number" placeholder="Enter Loan Months" class="form-control">
</div>
<div class="input-group my-2">
<input type="number" placeholder="Enter Intrest Rate" class="form-control">
</div>
<button class="button px-5 py-4 mt-3">Calculate</button>
</div>
<div class="col-lg-7">
<div class="card text-center my-2 py-4">
<h6 class="text-white font-weight-bold my-3">LOAN EMI</h6>
<h4>1,321.51</h4>
<h6 class="text-white font-weight-bold my-3">Total Interest Payable</h6>
<h4>58,580.88</h4>
<h6 class="text-white font-weight-bold my-3">Total Payment<br>
(Principal + Interest)</h6>
<h4>158,580.88</h4>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="related-products py-5">
<div class="container-fluid px-5 newest-product">
<h3 class="font-weight-bold">Related Products</h3>
<div class="row py-5">
<div class="col-lg-3 col-md-4 col-sm-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/flash-sale5.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Samsung Galaxy S10 128GB+8GB RAM 48mp+8mp+13mp+2mp Back Camera 4100mah">Samsung Galaxy S10 128GB+8GB RAM ...</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 84,900</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 104,000</strike></h5>
</div>
<h6 class="emi emi-off text-white text-center p-2">OUT OF STOCK !!!</h6>
</div>
</div>
<div class="col-lg-3 col-md-4 col-sm-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/new-product3.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Samsung UA43N5300 43 inch Full HD LED Smart TV">Samsung UA43N5300 43 inch Full HD LED Smart TV</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 80,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 95,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="col-lg-3 col-md-4 col-sm-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/new-product4.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="Kisonli U-2500BT USB 2.1 Portable Computer Speaker With FM Black">Kisonli U-2500BT USB 2.1 Portable Computer Speaker With FM Black.</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 17,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 25,000</strike></h5>
</div>
<h6 class="emi emi-available text-white text-center p-2">EMI AVAILABLE !!!</h6>
</div>
</div>
<div class="col-lg-3 col-md-4 col-sm-6 py-3">
<div class="card">
<a href="detail.php" class="card-img">
<div class="img-box p-3">
<img src="pics/new-product5.jpg">
</div>
<div class="cart-detail">
<a href="detail.php" class="button details text-white my-2">View Details</a>
<a data-toggle="modal" data-target=".cart-modal" href="#" class="button cart text-white my-2">Add to Cart</a>
</div>
</a>
<div class="card-text p-4" data-mh="eq">
<h6 class="font-weight-bold"><a href="detail.php" data-toggle="tooltip" title="'SONY BRAVIA' 43 FULL HD SMART TV [KDL-43W660G]">"SONY BRAVIA 43" FULL HD SMART TV [KDL-43W660G], ...</a></h6>
<h5 class="price red d-inline-block my-2 mr-3">Rs. 89,600</h5>
<h5 class="text-muted d-inline-block"><strike>Rs. 90,000</strike></h5>
</div>
<h6 class="emi emi-off text-white text-center p-2">out of stock !!!</h6>
</div>
</div>
</div>
</div>
</section>
<?php include("include/footer.php");?>
| 168766f5cc152225580938e59bed5a58e2eec902 | [
"PHP"
] | 11 | PHP | prazhit/Hi-Tech-Vision | 38da6f2a66af6570ffc156d05bd47c2f529b9690 | 164eca53d371414c2089b9cbbf810842357d9773 |
refs/heads/master | <file_sep>require 'spec_helper'
describe 'utilities' do
context 'with default values for all parameters' do
it { should contain_class('utilities') }
end
end
<file_sep># puppet-roles-profiles
Hiera Based Role Assignment & Profile Assigning.
These are Supplied puppet files that are awaiting configuration, this is to get started on a basic role & profile hiera setup.
Most of the files will need to be changed and edited to your own liking.
Example:
`hieradata/ROLE.yaml
to webserver.yaml within that:
profile::<PROFILE_HERE> to profile::apache`
`modules/profile/manifests/PROFILE.pp
to apache.pp within that:
profile::<PROFILE_HERE> to profile::apache`<file_sep>## Supported Release 1.0.0
### Summary
Initial release.
#### Features
- Assigns modules on a profile basis.
#### Bugfixes
N/A<file_sep>## Supported Release 1.0.0
### Summary
Initial release.
#### Features
- Custom puppet functions.
#### Bugfixes
N/A<file_sep>## Supported Release 1.0.0
### Summary
Initial release.
#### Features
- Hiera Based Role Assignment & Profile Assigning.
#### Bugfixes
N/A<file_sep>Facter.add('role') do
setcode do
# Retrieve hostname and assign role base on it
hname = Facter.value(:hostname)
case hname
when /<HOSTNAME>/i
'<ROLE>'
when /puppet/i
'puppet'
end
end
end | 55643adaf84fa6b12fd55262409987b8165f2967 | [
"Markdown",
"Ruby"
] | 6 | Ruby | dsavell/puppet-roles-profiles | e1a8b266b5bc316b2d6e7b005d8face7e3f43316 | 5b5085a33ceb72df86942bd71fc23a8fa91917f6 |
refs/heads/master | <repo_name>espiuno/nucleus-v2<file_sep>/models/Users.rb
require 'bcrypt'
include BCrypt
class Users < ActiveRecord::Base
# set table name
self.table_name = 'users'
# set password
def password=(<PASSWORD>)
self.user_password = <PASSWORD>::Password.create(password)
end
# create password
def password
<PASSWORD>.new(self.user_password)
end
# authenticate
def self.authenticate(username, password)
user = Users.find_by(username: username)
return user if user.password == password
end
end
<file_sep>/models/Locations.rb
class Locations < ActiveRecord::Base
# set table name
self.table_name = 'locations'
end
<file_sep>/controllers/RootController.rb
class RootController < ApplicationController
get '/' do
if session[:current_user]
redirect '/items'
end
erb :users_login
end
get '/login' do
if session[:current_user]
redirect '/items'
end
erb :users_login
end
get '/register' do
if session[:current_user]
redirect '/items'
end
erb :users_register
end
get '/not_authorized' do
erb :not_authenticated
end
get '/user_exists' do
erb :users_already_exists
end
end
<file_sep>/db/migrations.sql
CREATE DATABASE nuke;
\c nuke
CREATE TABLE users (
user_id SERIAL PRIMARY KEY,
username TEXT,
user_password TEXT,
user_fname TEXT,
user_lname TEXT,
user_email TEXT,
user_log TEXT,
user_messages TEXT,
user_timestamp TIMESTAMP
);
CREATE TABLE items (
item_id SERIAL PRIMARY KEY,
item_vendor TEXT,
item_name TEXT,
item_description TEXT,
item_quantity INTEGER,
item_unit_price NUMERIC,
item_image_url TEXT,
item_log TEXT,
item_timestamp TIMESTAMP
);
CREATE TABLE locations (
location_id SERIAL PRIMARY KEY,
location_name TEXT,
location_description TEXT
);
CREATE TABLE assignments (
assignment_id SERIAL PRIMARY KEY,
location_id INTEGER REFERENCES locations ON DELETE CASCADE,
item_id INTEGER REFERENCES items ON DELETE CASCADE,
location_quantity INTEGER
);
SELECT * FROM users;
SELECT * FROM items;
SELECT * FROM locations;
SELECT * FROM assignments;
<file_sep>/controllers/ItemsController.rb
class ItemsController < ApplicationController
# get item list
get '/' do
authorization_check
@items = Items.all
erb :items_index
end
# get item
get '/create' do
authorization_check
erb :items_create
end
# post item
post '/create' do
authorization_check
@item = Items.new
@item.item_vendor = params[:item_vendor]
@item.item_name = params[:item_name]
@item.item_description = params[:item_description]
@item.item_quantity = params[:item_quantity]
@item.item_unit_price = params[:item_unit_price]
@item.item_image_url = params[:item_image_url]
@item.item_timestamp = Time.now
puts current_user
@item.save
erb :items_create_success
end
# get edit item
get '/edit/:id' do
authorization_check
@id = params[:id]
@item = Items.find(@id)
erb :items_edit
end
# post edit item
post '/edit' do
authorization_check
@item = Items.find(params[:id])
@item.item_vendor = params[:item_vendor]
@item.item_name = params[:item_name]
@item.item_description = params[:item_description]
@item.item_quantity = params[:item_quantity]
@item.item_unit_price = params[:item_unit_price]
@item.item_image_url = params[:item_image_url]
@item.item_timestamp = Time.now
@item.save
erb :items_edit_success
end
# post delete item
post '/delete' do
authorization_check
@id = params[:id]
@item = Items.find(@id)
@item.destroy
erb :items_delete_success
end
end
<file_sep>/controllers/LocationsController.rb
class LocationsController < ApplicationController
# get locations list
get '/' do
authorization_check
@location = Locations.all
erb :locations_index
end
# get locations
get '/create' do
authorization_check
erb :locations_create
end
# post locations
post '/create' do
authorization_check
@location = Locations.new
@location.location_name = params[:location_name]
@location.location_description = params[:location_description]
# @location.location_image_url = params[:location_image_url]
# @location.location_timestamp = Time.now
puts current_user
@location.save
erb :locations_create_success
end
# get edit locations
get '/edit/:id' do
authorization_check
@id = params[:id]
@location = Locations.find(@id)
erb :locations_edit
end
# post edit locations
post '/edit' do
authorization_check
@location = Locations.find(params[:id])
@location.location_name = params[:location_name]
@location.location_description = params[:location_description]
# @location.location_image_url = params[:location_image_url]
# @location.location_timestamp = Time.now
@location.save
erb :locations_edit_success
end
# post delete locations
post '/delete' do
authorization_check
@id = params[:id]
@location = Locations.find(@id)
@location.destroy
erb :locations_delete_success
end
end
<file_sep>/controllers/AssignmentsController.rb
class AssignmentsController < ApplicationController
# get assignments list
get '/' do
authorization_check
@assignment = Assignments.all
erb :assignments_index
end
# get assignments
get '/create' do
# authorization_check
erb :assignments_create
end
# post assignments
post '/create' do
authorization_check
@assignment = Assignments.new
@assignment.location_id = params[:location_id]
@assignment.item_id = params[:item_id]
@assignment.location_quantity = params[:location_quantity]
# @assignment.assignment_image_url = params[:assignment_image_url]
# @assignment.assignment_timestamp = Time.now
puts current_user
@assignment.save
erb :assignments_create_success
end
# get edit assignments
get '/edit/:id' do
authorization_check
@id = params[:id]
@assignment = Assignments.find(@id)
erb :assignments_edit
end
# post edit assignments
post '/edit' do
authorization_check
@assignment = Assignments.find(params[:id])
@assignment.location_id = params[:location_id]
@assignment.item_id = params[:item_id]
@assignment.location_quantity = params[:location_quantity]
# @assignment.assignment_image_url = params[:assignment_image_url]
# @assignment.assignment_timestamp = Time.now
@assignment.save
erb :assignments_edit_success
end
# post delete assignments
post '/delete' do
authorization_check
@id = params[:id]
@assignment = Assignments.find(@id)
@assignment.destroy
erb :assignments_delete_success
end
end
<file_sep>/controllers/UsersController.rb
class UsersController < ApplicationController
def does_user_exist(username)
user = Users.find_by(:username => username)
if user
return true
else
return false
end
end
get '/register' do
erb :users_register
end
post "/register" do
if self.does_user_exist(params[:username]) == true
redirect '/user_exists'
end
user = Users.new(user_email: params[:user_email], username: params[:username],password: params[:password])
user.save
session[:current_user] = user
erb :users_register_confirmation
end
#login
get '/login' do
erb :users_login
end
post "/login" do
if self.does_user_exist(params[:username]) == true
user = Users.where(:username => params[:username]).first
if Users.authenticate(params[:username], params[:password])
session[:current_user] = user
redirect "/"
end
end
erb :users_login_error
end
end
<file_sep>/config.ru
require 'sinatra/base'
require 'rainbow'
Dir.glob('./{controllers,models,helpers}/*.rb').each { |file| require file }
map('/') { run RootController }
map('/users') { run UsersController }
map('/items') { run ItemsController }
map('/locations') { run LocationsController }
map('/assignments') { run AssignmentsController }
<file_sep>/models/Items.rb
class Items < ActiveRecord::Base
# set table name
self.table_name = 'items'
end
<file_sep>/README.md
# sinatra_crud
A Nucleus app using ERB and ActiveRecord
<file_sep>/models/Assignments.rb
class Assignments < ActiveRecord::Base
# set table name
self.table_name = 'assignments'
end
<file_sep>/controllers/ApplicationController.rb
class ApplicationController < Sinatra::Base
require 'bundler'
Bundler.require()
# connect to database
ActiveRecord::Base.establish_connection(
:adapter => "postgresql",
:database => "nuke"
)
# set local directory path
set :views, File.expand_path('../../views', __FILE__)
set :public_dir, File.expand_path('../../public', __FILE__)
# enable logging
configure :production, :development do
enable :logging
end
# enable sessions
enable :sessions
set :session_secret, 'super secret'
# set user session
def current_user
return session[:current_user]
end
# check if user is authenticated
def is_authenicated?
if session[:current_user].nil? == true
puts 'nillio'
return false
else
puts 'trulio'
return true
end
end
# check if the user is authenticated
def authorization_check
if is_authenicated? == false
redirect '/not_authorized'
end
end
get "/logout" do
session[:current_user] = nil
redirect "/"
end
# 404 page
not_found do
erb :not_found
end
end
| 9b3d05ca149fd525d816a2874bd1b1c05a7b78b9 | [
"Markdown",
"SQL",
"Ruby"
] | 13 | Ruby | espiuno/nucleus-v2 | 6da8f67c1d95754f013ee5a75b05016e0a1400d3 | 76e2ae989fde973d44852362b93c84af7b239a6a |
refs/heads/master | <repo_name>laotanzhurou/nn-ga-bdr-wisconsin<file_sep>/readme.md
The project aims to train two ANNs using human eye gaze data distributed along with
the source code.
Data set contains two file:
1. fzis_training.csv - the training set
2. fzis_testing.csv - the testing set
Two ANNs resides in below python scripts:
1. NN_NoBimodalRemoval.py - the control group ANN
2. NN_BimodalRemoval.py - the experiment group ANN, basically has everything the same
as control group except for it has implemented BDR during training
To train and obtain test results of each ANN, simply run the python script.
Both scripts contains commented code that plot summary data to help better visualise
statistics that are useful, user should uncomment those lines should they find it useful.<file_sep>/NN_BimodalRemoval.py
# import libraries
import pandas as pd
import torch
import torch.nn as nn
import torch.utils.data
import numpy as np
import matplotlib.pyplot as plt
from numpy import genfromtxt
import GA_FeatureSelection as ga
# define a function to plot confusion matrix
def plot_confusion(input_sample, num_classes, des_output, actual_output):
confusion = torch.zeros(num_classes, num_classes)
for i in range(input_sample):
actual_class = actual_output[i]
predicted_class = des_output[i]
confusion[actual_class][predicted_class] += 1
return confusion
"""
Step 1: Load data and pre-process data
Here we use data loader to read data
"""
# Neural Network
class Net(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(Net, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.sigmoid = nn.Sigmoid()
self.fc2 = nn.Linear(hidden_size, num_classes)
def forward(self, x):
out = self.fc1(x)
out = self.sigmoid(out)
out = self.fc2(out)
return out
def bimodal_remove(X, Y, output, sigma, variance_threshold):
p_error = abs(Y.numpy() - output.detach().numpy())
pe_mean = p_error.mean()
pe_std = p_error.std()
if pe_std < variance_threshold:
return X, Y
# plot error distribution
# n, bins, patches = plt.hist(p_error, 10, range=[0, 2], facecolor='blue')
# plt.xlabel('Error')
# plt.ylabel('Frequency')
# plt.title(r'Histogram of IQ: $\mu='+str(pe_mean)+'$, $\sigma='+str(pe_std)+'$')
# plt.tight_layout()
# plt.show()
# create candidate array
candidate = []
for i in range(0, len(p_error)):
if p_error[i] > pe_mean:
candidate.append(p_error[i])
candidate = np.array(candidate)
# create removal array
c_mean = candidate.mean()
c_std = candidate.std()
removal = []
for j in range(0, len(candidate)):
if candidate[j] > c_mean + sigma * c_std:
removal.append(candidate[j])
removal = np.array(removal)
# prepare index to remove
removal_index = []
for k in range(0, len(p_error)):
for l in range(0, len(removal)):
if p_error[k] == removal[l]:
removal_index.append(k)
# remove from training set
x_num = X.numpy()
y_num = Y.numpy()
x_num = np.delete(x_num, removal_index, 0)
y_num = np.delete(y_num, removal_index, 0)
updated_x = torch.from_numpy(x_num)
updated_y = torch.from_numpy(y_num)
return updated_x, updated_y
def training(X, Y, bdr, sigma, variance_threshold, input_size, hidden_size, num_classes):
net = Net(input_size, hidden_size, num_classes)
# Loss and Optimizer
criterion = nn.CrossEntropyLoss()
# optimizer = torch.optim.SGD(net.parameters(), lr=learning_rate, momentum=0.9)
optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate)
# store all losses for visualisation
all_losses = []
# train the model
end_epoch = 0
for epoch in range(num_epochs):
end_epoch = epoch
# Forward
optimizer.zero_grad() # zero the gradient buffer
outputs = net(X)
# Compute loss
loss = criterion(outputs, Y)
all_losses.append(loss.item())
# Bimodal Removal
if (epoch % 50 == 0):
_, predicted = torch.max(outputs, 1)
# calculate and print accuracy
# total = predicted.size(0)
# correct = predicted.data.numpy() == Y.data.numpy()
# print('Epoch [%d/%d] Loss: %.4f Accuracy: %.2f %%'
# % (epoch + 1, num_epochs, loss.item(), 100 * sum(correct) / total))
# perform bimodal removal
if bdr:
X, Y = bimodal_remove(X, Y, _, sigma, variance_threshold)
# print("Training Set Size after Bimodal Removal: " + str(Y.size()[0]))
# Backward
net.zero_grad()
loss.backward()
optimizer.step()
# Plot loss
# plt.figure()
# plt.plot(all_losses)
# plt.show()
return net, end_epoch + 1, Y.size()[0]
def evaluate(net, test_data, updated_input_size):
# get testing data
test_input = test_data[:, np.arange(updated_input_size)]
test_target = test_data[:, updated_input_size]
inputs = torch.from_numpy(test_input).float()
targets = torch.from_numpy(test_target).long()
outputs = net(inputs)
_, predicted = torch.max(outputs, 1)
total = predicted.size(0)
correct = predicted.data.numpy() == targets.data.numpy()
print('Testing Accuracy: %.2f %%' % (100 * sum(correct) / total))
return sum(correct) / total
def feature_selection(feature_input, label_input):
return ga.feture_reduction(feature_input, label_input)
# Hyper Parameters
input_size = 30
hidden_size = 40
num_classes = 2
num_epochs = 500
learning_rate = 0.02
test_variance_threshold = 0.01
rounds = 10
use_ga = True
use_bdr = True
all_accuracy = []
all_bdr_size = []
all_ga_size = []
all_ending_epoch = []
# sigma_series = [1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0]
sigma_series = [1]
for test_sigma in sigma_series:
for a in range(0, rounds):
# load all data
train_data = genfromtxt('data/wdbc_training.csv', delimiter=',')
test_data = genfromtxt('data/wdbc_testing.csv', delimiter=',')
# pre-processing: feature selection with GA
if use_ga:
reduced_features = feature_selection(train_data[:, np.arange(input_size)], train_data[:, input_size])
train_data = np.delete(train_data, reduced_features, axis=1)
test_data = np.delete(test_data, reduced_features, axis=1)
updated_input_size = train_data.shape[1]-1
#print("feature after ga: " + str(updated_input_size))
else:
updated_input_size = input_size
# define train dataset and a data loader
train_input = train_data[:, np.arange(updated_input_size)]
train_target = train_data[:, updated_input_size]
X = torch.from_numpy(train_input).float()
Y = torch.from_numpy(train_target).long()
net, result_epoch, bdr_size = training(X, Y, use_bdr, test_sigma, test_variance_threshold, updated_input_size, hidden_size, num_classes)
accuracy = evaluate(net, test_data, updated_input_size)
all_accuracy.append(accuracy)
all_bdr_size.append(bdr_size)
all_ending_epoch.append(result_epoch)
all_ga_size.append(updated_input_size)
mean_accuracy = np.array(all_accuracy).mean()
mean_bdr_size = np.array(all_bdr_size).mean()
mean_end_epoch = np.array(all_ending_epoch).mean()
mean_ga_size = np.array(all_ga_size).mean()
print("Result from sigma: " + str(test_sigma) + " variance_threshold: " + str(test_variance_threshold)
+ " average accuracy: " + str(mean_accuracy)
+ " ending epoch: " + str(mean_end_epoch)
+ " features after GA: " + str(mean_ga_size)
+ " input set after BDR: " + str(mean_bdr_size))<file_sep>/GA_FeatureSelection.py
import numpy
import matplotlib.pyplot
import sklearn.svm
"""
Reference:
This class is adapted from a GA Feature Selection library:
ahmedfgad/FeatureReductionGenetic
Credit to the original author.
Github Link: https://github.com/ahmedfgad/FeatureReductionGenetic.git
Original Author: <NAME>
Email: <EMAIL>
"""
def feture_reduction(feature_input, label_input):
num_samples = feature_input.shape[0]
num_feature_elements = feature_input.shape[1]
train_indices = numpy.arange(1, num_samples, 4)
test_indices = numpy.arange(0, num_samples, 4)
# print("Number of training samples: ", train_indices.shape[0])
# print("Number of test samples: ", test_indices.shape[0])
"""
Genetic algorithm parameters:
Population size
Mating pool size
Number of mutations
"""
sol_per_pop = 20 # Population size.
num_parents_mating = 4 # Number of parents inside the mating pool.
num_mutations = 3 # Number of elements to mutate.
# Defining the population shape.
pop_shape = (sol_per_pop, num_feature_elements)
# Creating the initial population.
new_population = numpy.random.randint(low=0, high=2, size=pop_shape)
# print(new_population.shape)
best_outputs = []
num_generations = 10
for generation in range(num_generations):
# print("Generation : ", generation)
# Measuring the fitness of each chromosome in the population.
fitness = cal_pop_fitness(new_population, feature_input, label_input, train_indices, test_indices)
best_outputs.append(numpy.max(fitness))
# The best result in the current iteration.
# print("Best result : ", best_outputs[-1])
# Selecting the best parents in the population for mating.
parents = select_mating_pool(new_population, fitness, num_parents_mating)
# Generating next generation using crossover.
offspring_crossover = crossover(parents,
offspring_size=(pop_shape[0] - parents.shape[0], num_feature_elements))
# Adding some variations to the offspring using mutation.
offspring_mutation = mutation(offspring_crossover, num_mutations=num_mutations)
# Creating the new population based on the parents and offspring.
new_population[0:parents.shape[0], :] = parents
new_population[parents.shape[0]:, :] = offspring_mutation
# Getting the best solution after iterating finishing all generations.
# At first, the fitness is calculated for each solution in the final generation.
fitness = cal_pop_fitness(new_population, feature_input, label_input, train_indices, test_indices)
# Then return the index of that solution corresponding to the best fitness.
best_match_idx = numpy.where(fitness == numpy.max(fitness))[0]
best_match_idx = best_match_idx[0]
best_solution = new_population[best_match_idx, :]
best_solution_indices = numpy.where(best_solution == 1)[0]
best_solution_num_elements = best_solution_indices.shape[0]
best_solution_fitness = fitness[best_match_idx]
# print("best_match_idx : ", best_match_idx)
# print("best_solution : ", best_solution)
# print("Selected indices : ", best_solution_indices)
# print("Number of selected elements : ", best_solution_num_elements)
# print("Best solution fitness : ", best_solution_fitness)
# Plot Result
# matplotlib.pyplot.plot(best_outputs)
# matplotlib.pyplot.xlabel("Iteration")
# matplotlib.pyplot.ylabel("Fitness")
# matplotlib.pyplot.show()
# produce features to be deleted
reduced_features = numpy.delete(numpy.arange(num_feature_elements), best_solution_indices)
return reduced_features
def reduce_features(solution, features):
selected_elements_indices = numpy.where(solution == 1)[0]
reduced_features = features[:, selected_elements_indices]
return reduced_features
def classification_accuracy(labels, predictions):
correct = numpy.where(labels == predictions)[0]
accuracy = correct.shape[0]/labels.shape[0]
return accuracy
def cal_pop_fitness(pop, features, labels, train_indices, test_indices):
accuracies = numpy.zeros(pop.shape[0])
idx = 0
for curr_solution in pop:
reduced_features = reduce_features(curr_solution, features)
train_data = reduced_features[train_indices, :]
test_data = reduced_features[test_indices, :]
train_labels = labels[train_indices]
test_labels = labels[test_indices]
SV_classifier = sklearn.svm.SVC(gamma='scale')
SV_classifier.fit(X=train_data, y=train_labels)
predictions = SV_classifier.predict(test_data)
accuracies[idx] = classification_accuracy(test_labels, predictions)
idx = idx + 1
return accuracies
def select_mating_pool(pop, fitness, num_parents):
# Selecting the best individuals in the current generation as parents for producing the offspring of the next generation.
parents = numpy.empty((num_parents, pop.shape[1]))
for parent_num in range(num_parents):
max_fitness_idx = numpy.where(fitness == numpy.max(fitness))
max_fitness_idx = max_fitness_idx[0][0]
parents[parent_num, :] = pop[max_fitness_idx, :]
fitness[max_fitness_idx] = -99999999999
return parents
def crossover(parents, offspring_size):
offspring = numpy.empty(offspring_size)
# The point at which crossover takes place between two parents. Usually, it is at the center.
crossover_point = numpy.uint8(offspring_size[1]/2)
for k in range(offspring_size[0]):
# Index of the first parent to mate.
parent1_idx = k%parents.shape[0]
# Index of the second parent to mate.
parent2_idx = (k+1)%parents.shape[0]
# The new offspring will have its first half of its genes taken from the first parent.
offspring[k, 0:crossover_point] = parents[parent1_idx, 0:crossover_point]
# The new offspring will have its second half of its genes taken from the second parent.
offspring[k, crossover_point:] = parents[parent2_idx, crossover_point:]
return offspring
def mutation(offspring_crossover, num_mutations=2):
mutation_idx = numpy.random.randint(low=0, high=offspring_crossover.shape[1], size=num_mutations)
# Mutation changes a single gene in each offspring randomly.
for idx in range(offspring_crossover.shape[0]):
# The random value to be added to the gene.
offspring_crossover[idx, mutation_idx] = 1 - offspring_crossover[idx, mutation_idx]
return offspring_crossover
<file_sep>/NN_NoBimodalRemoval.py
# import libraries
import pandas as pd
import torch
import torch.nn as nn
import torch.utils.data
import numpy as np
import matplotlib.pyplot as plt
from numpy import genfromtxt
# define a function to plot confusion matrix
def plot_confusion(input_sample, num_classes, des_output, actual_output):
confusion = torch.zeros(num_classes, num_classes)
for i in range(input_sample):
actual_class = actual_output[i]
predicted_class = des_output[i]
confusion[actual_class][predicted_class] += 1
return confusion
# Neural Network
class Net(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(Net, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.sigmoid = nn.Sigmoid()
self.fc2 = nn.Linear(hidden_size, num_classes)
def forward(self, x):
out = self.fc1(x)
out = self.sigmoid(out)
out = self.fc2(out)
return out
def training(hidden_size, learning_rate):
"""
Step 1: Load Data
"""
# load all data
train_data = genfromtxt('data/wdbc_training.csv', delimiter=',')
test_data = genfromtxt('data/wdbc_testing.csv', delimiter=',')
# define train dataset and a data loader
train_input = train_data[:, np.arange(input_size)]
train_target = train_data[:, input_size]
X = torch.from_numpy(train_input).float()
Y = torch.from_numpy(train_target).long()
net = Net(input_size, hidden_size, num_classes)
# Loss and Optimizer
criterion = nn.CrossEntropyLoss()
#optimizer = torch.optim.SGD(net.parameters(), lr=learning_rate, momentum=0.9)
optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate)
# store all losses for visualisation
all_losses = []
"""
Step 2: Training
"""
for epoch in range(num_epochs):
# Forward
optimizer.zero_grad() # zero the gradient buffer
outputs = net(X)
# Compute loss
loss = criterion(outputs, Y)
all_losses.append(loss.item())
if (epoch % 50 == 0 or epoch == num_epochs - 1):
output, predicted = torch.max(outputs, 1)
# calculate and print accuracy
total = predicted.size(0)
correct = predicted.data.numpy() == Y.data.numpy()
# print('Epoch [%d/%d] Loss: %.4f Accuracy: %.2f %%'
# % (epoch + 1, num_epochs, loss.item(), 100 * sum(correct) / total))
# plot pattern errors
p_error = abs(Y.numpy() - output.detach().numpy())
pe_mean = p_error.mean()
pe_std = p_error.std()
# plot error distribution
# n, bins, patches = plt.hist(p_error, 10, range=[0, 2], facecolor='blue')
# plt.xlabel('Error')
# plt.ylabel('Frequency')
# plt.title(r'Histogram of IQ: $\mu=' + str(pe_mean) + '$, $\sigma=' + str(pe_std) + '$')
# plt.tight_layout()
# plt.show()
# Backward
net.zero_grad()
loss.backward()
optimizer.step()
# plt.figure()
# plt.plot(all_losses)
# plt.show()
"""
Step 3: Test the neural network
Pass testing data to the built neural network and get its performance
"""
# get testing data
test_input = test_data[:, np.arange(input_size)]
test_target = test_data[:, input_size]
inputs = torch.from_numpy(test_input).float()
targets = torch.from_numpy(test_target).long()
outputs = net(inputs)
_, predicted = torch.max(outputs, 1)
total = predicted.size(0)
correct = predicted.data.numpy() == targets.data.numpy()
print('Testing Accuracy: %.2f %%' % (100 * sum(correct) / total))
"""
Evaluating the Results
To see how well the network performs on different categories, we will
create a confusion matrix, indicating for every glass (rows)
which class the network guesses (columns).
"""
# print('Confusion matrix for testing:')
# print(plot_confusion(test_input.shape[0], num_classes, predicted.long().data, targets.data))
# return accuracy rate
return sum(correct) / total
# perform training
input_size = 30
hidden_unit = 40
num_classes = 2
learning_rate = 0.01
num_epochs = 500
rounds = 10
all_accuracy = []
for a in range(0, rounds):
print("Round " + str(a) + " out of " + str(rounds))
accuracy = training(hidden_unit, learning_rate)
all_accuracy.append(accuracy)
mean_accuracy = np.array(all_accuracy).mean()
print("Result from hidden unit: " + str(hidden_unit) + " lr: " + str(learning_rate) + " average accuracy: " + str(mean_accuracy))
| 66f56407e0f0eb20b016e0656eda4015e8f665e9 | [
"Markdown",
"Python"
] | 4 | Markdown | laotanzhurou/nn-ga-bdr-wisconsin | e5829e31609ce8f765cdc781d030d098baec32f7 | 0fdd9080f10256f5075c3ef7f497767db8224d3d |
refs/heads/master | <repo_name>eun-plata/ProyectoDSNews<file_sep>/DSNews/README.md
# DSNews
## Construcción del proyecto
El sistema de build `Maven` construye el proyecto, y gracias al plugin de Spotify + Maven + Docker, se construye además una imagen Docker en base al Dockerfile (o fichero descriptor) que está en el directorio raíz del proyecto.
```shell
mvn package
```
## Ejecución del proyecto
El script `run-application.sh` construye el proyecto y además lanza el contenedor Docker con la misma.
Los parámetros que recibe el contenedor son:
- -e: añade una variable de entorno al contenedor, en este caso es necesario para inicializar la base de datos
- -d: lanza el contenedor en segundo plano.
- -p: enlaza el puerto 9080 de fuera (9080:) con el puerto 8080 del contenedor (:8080)
- --name: asigna un nombre al contenedor, para luego facilitar lanzar comandos contra él.
- plata47: nombre del repositorio de Docker, siempre asociado a un usuario. Debería crearse un usuario en DockerHub con ese nombre.
- dsnews: nombre de la imagen de Docker, siempre asociado a la aplicación.
- 0.0.1-SNAPSHOT: versión de la imagen de Docker. Proviene de la versión en el POM.xml. Si se cambia allí, hay que cambiarlo aquí también.
```shell
docker run -e MYSQL_PASS=<PASSWORD> -d -p 9080:8080 --name dsnews plata47/dsnews:0.0.1-SNAPSHOT
```
Una vez construído, apuntar un navegador al puerto 9080 (o el definido en el comando `docker run`), a la URL `http://localhost:9080`<file_sep>/DSNews/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dsnews</groupId>
<artifactId>DSNews</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>DSNews Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<!-- LIBRERIAS ROME -->
<!-- https://mvnrepository.com/artifact/org.jdom/jdom -->
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom</artifactId>
<version>2.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.rometools/rome -->
<dependency>
<groupId>com.rometools</groupId>
<artifactId>rome</artifactId>
<version>1.7.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.rometools/rome-utils -->
<dependency>
<groupId>com.rometools</groupId>
<artifactId>rome-utils</artifactId>
<version>1.7.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!--
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
-->
</dependencies>
<build>
<finalName>DSNews</finalName>
<plugins>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>dockerfile-maven-plugin</artifactId>
<version>1.3.0</version>
<executions>
<execution>
<id>default</id>
<goals>
<goal>build</goal>
<goal>push</goal>
</goals>
</execution>
</executions>
<configuration>
<repository>plata47/dsnews</repository>
<tag>${project.version}</tag>
</configuration>
</plugin>
</plugins>
</build>
</project><file_sep>/DSNews/run-application.sh
#!/bin/bash
echo "Construyendo el proyecto DSNews..."
mvn package
echo "Ejecutanto el proyecto DSNews en un contenedor Docker..."
docker run -e MYSQL_PASS=<PASSWORD> -d -p 9080:8080 --name dsnews plata47/dsnews:0.0.1-SNAPSHOT
exit 0<file_sep>/DSNews/Dockerfile
FROM mdelapenya/tomcat-mysql
MAINTAINER <NAME> <<EMAIL>>
COPY target/DSNews.war $TOMCAT_HOME/webapps/
COPY SQL/ /
# Initialise MySQL: this will be executed on server startup
RUN echo "mysql -uroot -e 'CREATE USER \"deSoftNews\"@\"localhost\" IDENTIFIED BY \"deSoftNews\";'" > /mysql-setup.sh && \
echo "mysql -uroot -e 'GRANT ALL PRIVILEGES on dsnews_content.* TO \"deSoftNews\"@\"localhost\";'" >> /mysql-setup.sh && \
echo "mysql -uroot < /dsnews_content.sql" >> /mysql-setup.sh<file_sep>/DSNews/SQL/crear_usuario.sql
CREATE USER 'deSoftNews'@'localhost' IDENTIFIED BY 'deSoftNews';
GRANT ALL PRIVILEGES on dsnews_content.* TO 'deSoftNews'@'localhost'; | 36a52fa8edaab07ce99653d6c514d2556ca83a5c | [
"SQL",
"Markdown",
"Maven POM",
"Dockerfile",
"Shell"
] | 5 | Markdown | eun-plata/ProyectoDSNews | 7d8f2f293d080a17b78615b61f4857a08351e783 | 5a4eca04285060a8dd3e4217e167f8b4b51631ca |
refs/heads/master | <file_sep>import 'angular'
import 'angular-mocks'
import ShowController from './show.controller';
describe('ShowController test',(()=>{
let controller;
const scope = {
$apply: Function.prototype
};
const sce = {
trustAsHtml: Function.prototype
};
const routeParams = {
id: '9'
};
const showService = {
getShow: Function.prototype,
getCast: Function.prototype,
getEpisodes: Function.prototype
};
const showFilterService = {
getAllSeasons: Function.prototype
};
const show = {
"id":3,
"name":"Bitten",
"genres":[
"Drama",
"Horror",
"Romance"
],
"rating":{
"average":7.5
}
};
const cast = [{
"name":"Jerry"
}];
const episodes = [{
"name":"Fire"
}];
beforeEach(()=>{
controller = new ShowController(scope,routeParams,sce,showService,showFilterService);
});
it('ShowController constructor test',()=>{
expect(controller).toBeDefined();
expect(controller.$scope).toEqual(scope);
expect(controller.showId).toEqual('9');
});
it('$onInit test',(done)=>{
const seasons = ['1','2'];
spyOn(showService,'getShow').and.returnValue(Promise.resolve({data:show}));
spyOn(showService,'getCast').and.returnValue(Promise.resolve({data:cast}));
spyOn(showService,'getEpisodes').and.returnValue(Promise.resolve({data:episodes}));
spyOn(showFilterService,'getAllSeasons').and.returnValue(seasons);
spyOn(sce,'trustAsHtml').and.returnValue('text');
spyOn(scope,'$apply').and.stub();
controller.$onInit().then(()=>{
expect(showService.getShow).toHaveBeenCalledWith('9');
expect(showService.getCast).toHaveBeenCalledWith('9');
expect(showService.getEpisodes).toHaveBeenCalledWith('9');
expect(showFilterService.getAllSeasons).toHaveBeenCalledWith(episodes);
expect(controller.summary).toEqual('text');
expect(controller.seasons).toEqual(seasons);
expect(controller.episodes).toEqual(episodes);
expect(controller.show).toEqual(show);
expect(controller.cast).toEqual(cast);
done();
});
});
}));<file_sep># TVMaze App
[](https://dev.azure.com/chenjigaramnaveen/retroboard/_build/latest?definitionId=16&branchName=master)
Application that allows users to view a lists of TV shows based on different genres (drama, comedy, sports, etc.).
* [Live App](https://tvmaze.z1.web.core.windows.net/)
* [Pipeline](https://dev.azure.com/chenjigaramnaveen/retroboard/_build?definitionId=16)
## Quick start
### Dependencies
What you need to run this app:
* `node` and `npm`
```bash
# clone the repo
$ git clone https://github.com/Chenjigaram/tvmaze.git
# change directory to app
$ cd tvmaze
# install the dependencies with npm
$ npm install
# start the server
$ npm start
```
It will start a local server using `webpack-dev-server` which will watch, build (in-memory), and reload for you. The port will be displayed to you as `http://localhost:8080`.
You will see home page as below:
[](https://github.com/Chenjigaram/tvmaze/blob/master/screenshots/shorthome.png?raw=true)
### Developing
#### Build files
* single run: `npm run build`
* build files and watch: `npm start`
### Testing
#### Unit Tests
* single run: `npm test`
## Application Technologies
List of Technologies
* [Angularjs](https://angularjs.org/)
* [Webpack 4](https://webpack.js.org/concepts/)
* [Bootstrap 4](https://getbootstrap.com/docs/4.0/getting-started/introduction/)
* [Jasmine](https://jasmine.github.io/)
* [Azure Pipelines](https://docs.microsoft.com/en-us/azure/devops/pipelines/?view=azure-devops)
### AngularJs
AngularJS is a superior framework by Google launched in 2009, which is created to make the front-end development procedure easier to manage.
* Two way Data Binding
* MVC
* Code Reusability
* ES6 Compatability
* Easy to learn
### Webpack
Webpack is a tool that lets you compile JavaScript modules, also known as module bundler.
* Helps you bundle your resources.
* Watches for changes and re-runs the tasks.
* can run Babel transpilation to ES5, allowing you to use the latest JavaScript features without worrying about browser support.
### Boostrap 4
Quickly design and customize responsive mobile-first sites with Bootstrap
### Jasmine
Jasmine is a framework for testing JavaScript code and also has wide set of assertions
### Azure Pipelines
Azure pipelines is a easy to automate the CI and CD of your app
<file_sep>import 'angular'
import 'angular-mocks'
import HomeController from './home.controller';
describe('HomeController',(()=>{
let controller;
const location = {
path: Function.prototype
};
const showService = {
getAllShows: Function.prototype
};
const showFilterService = {
sortByRating: Function.prototype,
getAllGeneres: Function.prototype
};
const shows = [
{
"id":1,
"name":"Under the Dome",
"genres":[
"Drama",
"Science-Fiction",
"Thriller"
],
"rating":{
"average":6.5
}
},
{
"id":2,
"name":"Person of Interest",
"genres":[
"Action",
"Crime",
"Science-Fiction"
],
"rating":{
"average":8.9
},
},
{
"id":3,
"name":"Bitten",
"genres":[
"Drama",
"Horror",
"Romance"
],
"rating":{
"average":7.5
}
}
];
beforeEach(()=>{
controller = new HomeController(location,showService,showFilterService);
});
it('constructor test',()=>{
expect(controller).toBeDefined();
});
it('$onInit test',(done)=>{
const generes = ['Drama','Animation'];
spyOn(showService,'getAllShows').and.returnValue(Promise.resolve({data:shows}));
spyOn(showFilterService,'getAllGeneres').and.returnValue(generes);
spyOn(showFilterService,'sortByRating').and.returnValue(shows);
controller.$onInit().then(()=>{
expect(showService.getAllShows).toHaveBeenCalled();
expect(showFilterService.sortByRating).toHaveBeenCalledWith(shows);
expect(controller.allShows).toEqual(shows);
expect(controller.generes).toEqual(generes);
done();
});
});
it('openShow test',()=>{
spyOn(location,'path').and.stub();
controller.openShow('test')
expect(location.path).toHaveBeenCalledWith('/show/test');
});
}));<file_sep>
export default class SearchController {
constructor($location,$routeParams,ShowService){
'ngInject';
this.$location = $location;
this.text = $routeParams.text;
this.showService = ShowService;
this.shows = [];
}
$onInit(){
return this.showService.searchShows(this.text).then((response)=>{
this.shows = response.data;
});
}
openShow(id){
this.$location.path(`/show/${id}`)
}
}<file_sep>import angular from 'angular';
import ShowController from './show.controller'
import ShowFilterService from '../../services/show-filter/show-filter.service';
import { SeasonFilter } from '../../filters/show-filter';
export const showModule = angular
.module('module.show',[])
.controller('ShowController',ShowController)
.service('ShowFilterService',ShowFilterService)
.filter('seasonFilter', SeasonFilter)
.name;<file_sep>
export default class HomeController {
constructor($location,ShowService,ShowFilterService){
'ngInject';
this.$location = $location;
this.showService = ShowService;
this.showFilterService = ShowFilterService
}
$onInit(){
return this.showService.getAllShows().then((response)=>{
this.allShows = this.showFilterService.sortByRating(response.data);
this.generes = this.showFilterService.getAllGeneres(this.allShows);
});
}
openShow(id){
this.$location.path(`/show/${id}`)
}
}<file_sep>import angular from 'angular';
export const appRouteConfig = ($routeProvider) => {
$routeProvider
.when('/home', {
template: require('./modules/home/home.html'),
controller: 'HomeController'
})
.when('/search/:text', {
template: require('./modules/search/search.html'),
controller: 'SearchController'
})
.when('/show/:id', {
template: require('./modules/show/show.html'),
controller: 'ShowController'
})
.otherwise({
redirectTo: '/home'
});
};<file_sep>import template from './image-card.html';
export const ImageCardComponent = {
bindings: {
image: '<',
text: '<'
},
template
}<file_sep>import 'angular'
import 'angular-mocks'
import ShowFilterService from './show-filter.service';
describe('service test',()=>{
let service = new ShowFilterService();;
const shows = [
{
"id":1,
"name":"<NAME>",
"genres":[
"Drama",
"Science-Fiction",
"Thriller"
],
"rating":{
"average":6.5
}
},
{
"id":2,
"name":"Person of Interest",
"genres":[
"Action",
"Crime",
"Science-Fiction"
],
"rating":{
"average":8.9
},
},
{
"id":3,
"name":"Bitten",
"genres":[
"Drama",
"Horror",
"Romance"
],
"rating":{
"average":7.5
}
}
];
describe('ShowFilterService ',() => {
it('getAllGeneres',()=>{
const generes = service.getAllGeneres(shows);
expect(generes.length).toEqual(7);
});
it('sortByRating',()=>{
const sortShows = service.sortByRating(shows);
expect(sortShows[0].id).toEqual(2);
});
it('getAllSeasons',()=>{
const episodes = [{season:1},{season:2},{season:3}]
const seasons = service.getAllSeasons(episodes);
expect(seasons).toEqual([ 1, 2, 3 ]);
});
});
});
<file_sep>import angular from 'angular';
import 'angular-route';
import { appRouteConfig } from './app.route'
import { homeModule } from './modules/home/home';
import { searchModule } from './modules/search/search';
import { showModule } from './modules/show/show';
import AppController from './app.controller';
import { ImageCardComponent } from './components/image-card/image-card.component';
import ShowService from './data-access/show/show.service';
export const appModule =
angular.module('app',['ngRoute',homeModule,searchModule,showModule])
.config(appRouteConfig)
.controller('AppController',AppController)
.component('imageCard', ImageCardComponent)
.service('ShowService',ShowService)
.name;<file_sep>
export default class AppController {
constructor($location){
'ngInject';
this.$location = $location;
this.text = '';
}
searchText(text){
if(text){
this.$location.path(`/search/${text}`);
this.text = '';
}
}
}<file_sep>import 'angular'
import 'angular-mocks'
import SearchController from './search.controller';
describe('SearchController test',(()=>{
let controller;
const routeParams = {
text: 'test'
};
const showService = {
searchShows: Function.prototype
};
const location = {
path: Function.prototype
};
const shows = [
{
"id":1,
"name":"Under the Dome",
"genres":[
"Drama",
"Science-Fiction",
"Thriller"
],
"rating":{
"average":6.5
}
},
{
"id":2,
"name":"Person of Interest",
"genres":[
"Action",
"Crime",
"Science-Fiction"
],
"rating":{
"average":8.9
},
},
{
"id":3,
"name":"Bitten",
"genres":[
"Drama",
"Horror",
"Romance"
],
"rating":{
"average":7.5
}
}
];
beforeEach(()=>{
controller = new SearchController(location,routeParams,showService);
});
it('SearchController constructor test',()=>{
expect(controller).toBeDefined();
expect(controller.text).toEqual('test');
});
it('$onInit test',(done)=>{
spyOn(showService,'searchShows').and.returnValue(Promise.resolve({data:shows}));
controller.$onInit().then(()=>{
expect(showService.searchShows).toHaveBeenCalled();
expect(controller.shows).toEqual(shows);
done();
});
});
it('openShow test',()=>{
spyOn(location,'path').and.stub();
controller.openShow('test')
expect(location.path).toHaveBeenCalledWith('/show/test');
});
})); | cdc374a61f9626925a1e113bbfa53b2af490a172 | [
"JavaScript",
"Markdown"
] | 12 | JavaScript | COB4545/tvmaze | 53abe695e9ef8e78d6f5ff66e909db37d6571a52 | e0c44957428606bbf1bbfbfbdf9ebcc44eafa589 |
refs/heads/main | <repo_name>usersolidity/pastepin<file_sep>/lib/utils.ts
export const baseUrl =
typeof window !== 'undefined' && window.location.origin
? window.location.origin
: ''
<file_sep>/README.md
# Pastepin
Share Text and Files on a Decentralized Network.
# Future Plans
- make site accessible on ipfs
- enrypted content
- query user's pins using subgraph
- /pins page for all the pins
- improve markdown render (styles, syntax highlighting)
<file_sep>/lib/atoms.ts
import { atom } from 'jotai'
export const stateAtom = atom<'edit' | 'preview' | 'upload' | 'redirect'>(
'edit',
)
export const titleAtom = atom('')
| c97843b893676bbfe51d4678287a528c7ce40cd7 | [
"Markdown",
"TypeScript"
] | 3 | TypeScript | usersolidity/pastepin | f56cb0be7496517238c3b3d566c238087cd766e2 | 693791a9913f8503d5680a2e5a4f245e852df9d1 |
refs/heads/master | <repo_name>peterpolidoro/modular_server_python<file_sep>/modular_server/__init__.py
'''
This Python package (modular_server) creates a class named ModularServer,
which contains an instance of serial_device2.SerialDevice and adds
methods to it, like auto discovery of available modular devices in Linux,
Windows, and Mac OS X. This class automatically creates methods from
available functions reported by the modular device when it is running the
appropriate firmware.
'''
from modular_server import ModularServer, ModularServers, find_modular_server_ports, find_modular_server_port, __version__
<file_sep>/DESCRIPTION.rst
modular_server_python
=====================
This Python package creates a class named ModularServer, which contains
an instance of serial_device2.SerialDevice and adds methods to it,
like auto discovery of available modular devices in Linux, Windows, and
Mac OS X. This class automatically creates methods from available
functions reported by the modular device when it is running the
appropriate firmware.
Authors::
<NAME> <<EMAIL>>
License::
BSD
Example Usage::
from modular_server import ModularServer
dev = ModularDevice() # Might automatically finds device if one available
# if it is not found automatically, specify port directly
dev = ModularDevice(port='/dev/ttyACM0') # Linux specific port
dev = ModularDevice(port='/dev/tty.usbmodem262471') # Mac OS X specific port
dev = ModularDevice(port='COM3') # Windows specific port
dev.get_device_info()
dev.get_methods()
from modular_device import ModularDevices
devs = ModularDevices() # Might automatically find all available devices
# if they are not found automatically, specify ports to use
devs = ModularDevices(use_ports=['/dev/ttyUSB0','/dev/ttyUSB1']) # Linux
devs = ModularDevices(use_ports=['/dev/tty.usbmodem262471','/dev/tty.usbmodem262472']) # Mac OS X
devs = ModularDevices(use_ports=['COM3','COM4']) # Windows
devs.items()
dev = devs[name][serial_number]
<file_sep>/modular_server/modular_server.py
from __future__ import print_function, division
import serial
import time
import atexit
import json
import functools
import operator
import platform
import os
import inflection
from serial_device2 import SerialDevice, SerialDevices, find_serial_device_ports, WriteFrequencyError
try:
from pkg_resources import get_distribution, DistributionNotFound
_dist = get_distribution('modular_server')
# Normalize case for Windows systems
dist_loc = os.path.normcase(_dist.location)
here = os.path.normcase(__file__)
if not here.startswith(os.path.join(dist_loc, 'modular_server')):
# not installed, but there is another version that *is*
raise DistributionNotFound
except (ImportError,DistributionNotFound):
__version__ = None
else:
__version__ = _dist.version
DEBUG = False
BAUDRATE = 9600
class ModularServer(object):
'''
ModularServer contains an instance of serial_device2.SerialDevice and
adds methods to it, like auto discovery of available modular devices
in Linux, Windows, and Mac OS X. This class automatically creates
methods from available functions reported by the modular device when
it is running the appropriate firmware.
Example Usage:
dev = ModularDevice() # Might automatically finds device if one available
# if it is not found automatically, specify port directly
dev = ModularDevice(port='/dev/ttyACM0') # Linux specific port
dev = ModularDevice(port='/dev/tty.usbmodem262471') # Mac OS X specific port
dev = ModularDevice(port='COM3') # Windows specific port
dev.get_device_info()
dev.get_methods()
'''
_TIMEOUT = 0.05
_WRITE_WRITE_DELAY = 0.05
_RESET_DELAY = 2.0
_METHOD_ID_GET_DEVICE_INFO = 0
_METHOD_ID_GET_METHOD_IDS = 1
_METHOD_ID_GET_RESPONSE_CODES = 2
def __init__(self,*args,**kwargs):
model_number = None
serial_number = None
if 'debug' in kwargs:
self.debug = kwargs['debug']
else:
kwargs.update({'debug': DEBUG})
self.debug = DEBUG
if 'try_ports' in kwargs:
try_ports = kwargs.pop('try_ports')
else:
try_ports = None
if 'baudrate' not in kwargs:
kwargs.update({'baudrate': BAUDRATE})
elif (kwargs['baudrate'] is None) or (str(kwargs['baudrate']).lower() == 'default'):
kwargs.update({'baudrate': BAUDRATE})
if 'timeout' not in kwargs:
kwargs.update({'timeout': self._TIMEOUT})
if 'write_write_delay' not in kwargs:
kwargs.update({'write_write_delay': self._WRITE_WRITE_DELAY})
if 'model_number' in kwargs:
model_number = kwargs.pop('model_number')
if 'serial_number' in kwargs:
serial_number = kwargs.pop('serial_number')
if ('port' not in kwargs) or (kwargs['port'] is None):
port = find_modular_device_port(baudrate=kwargs['baudrate'],
model_number=model_number,
serial_number=serial_number,
try_ports=try_ports,
debug=kwargs['debug'])
kwargs.update({'port': port})
t_start = time.time()
self._serial_device = SerialDevice(*args,**kwargs)
atexit.register(self._exit_modular_device)
time.sleep(self._RESET_DELAY)
self._response_dict = None
self._response_dict = self._get_response_dict()
self._method_dict = self._get_method_dict()
self._method_dict_inv = dict([(v,k) for (k,v) in self._method_dict.iteritems()])
self._create_methods()
t_end = time.time()
self._debug_print('Initialization time =', (t_end - t_start))
def _debug_print(self, *args):
if self.debug:
print(*args)
def _exit_modular_device(self):
pass
def _args_to_request(self,*args):
request_list = ['[', ','.join(map(str,args)), ']']
request = ''.join(request_list)
request += '\n';
return request
def _send_request(self,*args):
'''
Sends request to modular device over serial port and
returns number of bytes written
'''
request = self._args_to_request(*args)
self._debug_print('request', request)
bytes_written = self._serial_device.write_check_freq(request,delay_write=True)
return bytes_written
def _send_request_get_response(self,*args):
'''
Sends request to device over serial port and
returns response
'''
request = self._args_to_request(*args)
self._debug_print('request', request)
response = self._serial_device.write_read(request,use_readline=True,check_write_freq=True)
if response is None:
response_dict = {}
return response_dict
self._debug_print('response', response)
try:
response_dict = json_string_to_dict(response)
except Exception, e:
error_message = 'Unable to parse device response {0}.'.format(str(e))
raise IOError, error_message
try:
status = response_dict.pop('status')
except KeyError:
error_message = 'Device response does not contain status.'
raise IOError, error_message
try:
method_id = response_dict.pop('method_id')
except KeyError:
error_message = 'Device response does not contain method_id.'
raise IOError, error_message
if not method_id == args[0]:
raise IOError, 'Device method_id does not match that sent.'
if self._response_dict is not None:
if status == self._response_dict['response_error']:
try:
dev_error_message = '(from device) {0}'.format(response_dict['error_message'])
except KeyError:
dev_error_message = 'Error message missing.'
error_message = '{0}'.format(dev_error_message)
raise IOError, error_message
return response_dict
def _get_method_dict(self):
method_dict = self._send_request_get_response(self._METHOD_ID_GET_METHOD_IDS)
return method_dict
def _get_response_dict(self):
response_dict = self._send_request_get_response(self._METHOD_ID_GET_RESPONSE_CODES)
check_dict_for_key(response_dict,'response_success',dname='response_dict')
check_dict_for_key(response_dict,'response_error',dname='response_dict')
return response_dict
def _send_request_by_method_name(self,name,*args):
method_id = self._method_dict[name]
method_args = [method_id]
method_args.extend(args)
response = self._send_request_get_response(*method_args)
return response
def _method_func_base(self,method_name,*args):
if len(args) == 1 and type(args[0]) is dict:
args_dict = args[0]
args_list = self._args_dict_to_list(args_dict)
else:
args_list = args
response_dict = self._send_request_by_method_name(method_name,*args_list)
if response_dict:
ret_value = self._process_response_dict(response_dict)
return ret_value
def _create_methods(self):
self._method_func_dict = {}
for method_id, method_name in sorted(self._method_dict_inv.items()):
method_func = functools.partial(self._method_func_base, method_name)
setattr(self,inflection.underscore(method_name),method_func)
self._method_func_dict[method_name] = method_func
def _process_response_dict(self,response_dict):
if len(response_dict) == 1:
ret_value = response_dict.values()[0]
else:
all_values_empty = True
for v in response_dict.values():
if not type(v) == str or v:
all_values_empty = False
break
if all_values_empty:
ret_value = sorted(response_dict.keys())
else:
ret_value = response_dict
return ret_value
def _args_dict_to_list(self,args_dict):
key_set = set(args_dict.keys())
order_list = sorted([(num,name) for (name,num) in order_dict.iteritems()])
args_list = [args_dict[name] for (num, name) in order_list]
return args_list
def close(self):
'''
Close the device serial port.
'''
self._serial_device.close()
def get_port(self):
return self._serial_device.port
def get_device_info(self):
return self._send_request_get_response(self._METHOD_ID_GET_DEVICE_INFO)
def get_methods(self):
'''
Get a list of modular methods automatically attached as class methods.
'''
return [inflection.underscore(key) for key in self._method_dict.keys()]
def send_json_get_json(self,request,response_indent=None):
'''
Sends json request to device over serial port and returns json
response
'''
request_python = json.loads(request)
request = json.dumps(request_python,separators=(',',':'))
request += '\n'
self._debug_print('request', request)
response = self._serial_device.write_read(request,use_readline=True,check_write_freq=True)
response_python = json.loads(response)
response = json.dumps(response_python,separators=(',',':'),indent=response_indent)
return response
class ModularServers(dict):
'''
ModularDevices inherits from dict and automatically populates it with
ModularDevices on all available serial ports. Access each individual
device with two keys, the device name and the serial_number. If you
want to connect multiple ModularDevices with the same name at the
same time, first make sure they have unique serial_numbers by
connecting each device one by one and using the set_serial_number
method on each device.
Example Usage:
devs = ModularDevices() # Might automatically find all available devices
# if they are not found automatically, specify ports to use
devs = ModularDevices(use_ports=['/dev/ttyUSB0','/dev/ttyUSB1']) # Linux
devs = ModularDevices(use_ports=['/dev/tty.usbmodem262471','/dev/tty.usbmodem262472']) # Mac OS X
devs = ModularDevices(use_ports=['COM3','COM4']) # Windows
devs.items()
dev = devs[name][serial_number]
'''
def __init__(self,*args,**kwargs):
if ('use_ports' not in kwargs) or (kwargs['use_ports'] is None):
modular_device_ports = find_modular_device_ports(*args,**kwargs)
else:
modular_device_ports = use_ports
for port in modular_device_ports:
kwargs.update({'port': port})
self._add_device(*args,**kwargs)
def _add_device(self,*args,**kwargs):
dev = ModularDevice(*args,**kwargs)
device_info = dev.get_device_info()
name = device_info['name']
serial_number = device_info['serial_number']
if name not in self:
self[name] = {}
self[name][serial_number] = dev
def check_dict_for_key(d,k,dname=''):
if not k in d:
if not dname:
dname = 'dictionary'
raise IOError, '{0} does not contain {1}'.format(dname,k)
def json_string_to_dict(json_string):
json_dict = json.loads(json_string,object_hook=json_decode_dict)
return json_dict
def json_decode_dict(data):
'''
Object hook for decoding dictionaries from serialized json data. Ensures that
all strings are unpacked as str objects rather than unicode.
'''
rv = {}
for key, value in data.iteritems():
if isinstance(key, unicode):
key = key.encode('utf-8')
if isinstance(value, unicode):
value = value.encode('utf-8')
elif isinstance(value, list):
value = json_decode_list(value)
elif isinstance(value, dict):
value = json_decode_dict(value)
rv[key] = value
return rv
def json_decode_list(data):
'''
Object hook for decoding lists from serialized json data. Ensures that
all strings are unpacked as str objects rather than unicode.
'''
rv = []
for item in data:
if isinstance(item, unicode):
item = item.encode('utf-8')
elif isinstance(item, list):
item = json_decode_list(item)
elif isinstance(item, dict):
item = json_decode_dict(item)
rv.append(item)
return rv
def find_modular_server_ports(baudrate=None,
model_number=None,
serial_number=None,
try_ports=None,
debug=DEBUG,
*args,
**kwargs):
serial_device_ports = find_serial_device_ports(try_ports=try_ports, debug=debug)
os_type = platform.system()
if os_type == 'Darwin':
serial_device_ports = [x for x in serial_device_ports if 'tty.usbmodem' in x or 'tty.usbserial' in x]
if type(model_number) is int:
model_number = [model_number]
if type(serial_number) is int:
serial_number = [serial_number]
modular_device_ports = {}
for port in serial_device_ports:
try:
dev = ModularDevice(port=port,baudrate=baudrate,debug=debug)
device_info = dev.get_device_info()
if ((model_number is None ) and (device_info['model_number'] is not None)) or (device_info['model_number'] in model_number):
if ((serial_number is None) and (device_info['serial_number'] is not None)) or (device_info['serial_number'] in serial_number):
modular_device_ports[port] = {'model_number': device_info['model_number'],
'serial_number': device_info['serial_number']}
dev.close()
except (serial.SerialException, IOError):
pass
return modular_device_ports
def find_modular_server_port(baudrate=None,
model_number=None,
serial_number=None,
try_ports=None,
debug=DEBUG):
modular_server_ports = find_modular_device_ports(baudrate=baudrate,
model_number=model_number,
serial_number=serial_number,
try_ports=try_ports,
debug=debug)
if len(modular_device_ports) == 1:
return modular_device_ports.keys()[0]
elif len(modular_device_ports) == 0:
serial_device_ports = find_serial_device_ports(try_ports)
err_string = 'Could not find any Modular devices. Check connections and permissions.\n'
err_string += 'Tried ports: ' + str(serial_device_ports)
raise RuntimeError(err_string)
else:
err_string = 'Found more than one Modular device. Specify port or model_number and/or serial_number.\n'
err_string += 'Matching ports: ' + str(modular_device_ports)
raise RuntimeError(err_string)
# -----------------------------------------------------------------------------------------
if __name__ == '__main__':
debug = False
dev = ModularDevice(debug=debug)
| f645f88067160ffdddc03b115067c8e7559abaa6 | [
"Python",
"reStructuredText"
] | 3 | Python | peterpolidoro/modular_server_python | c0cb8ea9299c024910bcdb661a365f2f82c7380c | 5356848a18771afc30b27323845ade6cf894a73c |
refs/heads/master | <repo_name>drewradcliff/photos-from-here<file_sep>/script.js
function init () {
const status = document.querySelector('.status');
const title = document.querySelector('.title');
let json = {}, imgIndex=0;
function success(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
status.textContent = `Current Location: ${latitude}, ${longitude}`;
getJson(assembleSearchURL(latitude, longitude))
}
function error () {
// default location set to San Francisco
const longitude = -122.431297;
const latitude = 37.773972;
status.textContent = `Could not get location... Showing default location (San Francisco): ${latitude}, ${longitude}`;
getJson(assembleSearchURL(latitude, longitude))
}
function assembleSearchURL (lat, lon) {
const proxy = 'https://shrouded-mountain-15003.herokuapp.com/'
return proxy +
`https://flickr.com/services/rest/?` +
`api_key=f28f6f6111a311294dc988ab32e57546&` +
`format=json&` +
`nojsoncallback=1&` +
`method=flickr.photos.search&` +
`safe_search=1&` +
`per_page=5&` +
`lat=${lat}&` +
`lon=${lon}&` +
`&text=street`
}
function getJson (url) {
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
json = data;
title.textContent = data.photos.photo[0].title
const imageUrl = constructImageURL(data.photos.photo[0]);
displayImage(imageUrl);
});
}
function displayImage (url) {
let img = document.querySelector('.image');
img.src = url;
let div = document.querySelector('.image-wrapper');
div.appendChild(img);
}
function constructImageURL (photoObj) {
return "https://farm" + photoObj.farm +
".staticflickr.com/" + photoObj.server +
"/" + photoObj.id + "_" + photoObj.secret + ".jpg";
}
function prevImg () {
if (imgIndex > 0) {
imgIndex--;
displayImage(constructImageURL(json.photos.photo[imgIndex]));
title.textContent = json.photos.photo[imgIndex].title;
}
}
function nextImg () {
if (imgIndex < json.photos.photo.length-1) {
imgIndex++;
displayImage(constructImageURL(json.photos.photo[imgIndex]))
title.textContent = json.photos.photo[imgIndex].title;
}
}
navigator.geolocation.getCurrentPosition(success, error);
document.querySelector('.previous').addEventListener('click', prevImg);
document.querySelector('.next').addEventListener('click', nextImg);
}
init() | 86e7ddd4dd27e6799b8caabf1b5bf1dc497928f8 | [
"JavaScript"
] | 1 | JavaScript | drewradcliff/photos-from-here | f6642db51e6dc900d093f2d7691d264287fb32e6 | 2cadbd7989db65183ea8682bf63ca35a7d6546e7 |
refs/heads/master | <repo_name>lancehamilton24/chatty-spatulas<file_sep>/javascripts/components/chattyNav.js
const users = ['Mohammad', 'Lance', 'Marco', 'Maggie'];
const select = document.getElementById('users');
for (name in users){
select.add (new Option(users[name]));
}; | 03674bbc897d17de7c06479b3fcddebccb6b7a17 | [
"JavaScript"
] | 1 | JavaScript | lancehamilton24/chatty-spatulas | f1bf10a16b04905c43269aadcb9ba7413422b578 | 9b913c75cb20fcad56c1a3826bfbd225b5c698d4 |
refs/heads/master | <repo_name>peerroo/api_file_server<file_sep>/es6/server/api/utils/checkClient/index.js
/**
* Проверяет существование клиента. Возвращает промис, который возвращает объект с полем success,
* принимающем, в случае успеха, значение true и false - в противном случае.
* @param {string} req Объект запроса.
* @return {promise}
*/
import sendError from '../../../error/sendError';
import getError from '../../../error/getError';
import fetch from 'isomorphic-fetch';
import config from '../../../../../config.json';
function checkClient(id_client) {
return new Promise((resolve, reject) => {
let serverHost = `http://${config.api_server}`;
fetch(`${serverHost}/client/check_file`, {
method: 'post',
credentials: 'same-origin',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: id_client
})
})
.then(response => {
response.json()
.then(result => {
if (result.response) {
resolve(result.response);
} else {
reject(30);
}
})
.catch((e) => {
reject(20);
});
})
.catch(() => {
reject(10);
});
});
}
export default checkClient;<file_sep>/es6/server/api/robot/event/setMainImgLink/index.js
/**
* Добавляет ссылку на главное изображение акциии.
* Возвращает промис, который возвращает объект с полем success, принимающем значение true,
* в случае успеха и false - иначе.
* @param {string} id_client Идентификатор клиента.
* @param {string} id_event Идентификатор акции.
* @param {string} img Ссылка на изображение.
* @param {string} req Объект запроса.
* @return {promise}
*/
import sendError from '../../../../error/sendError';
import getError from '../../../../error/getError';
import fetch from 'isomorphic-fetch';
import config from '../../../../../../config.json';
function setMainImgLink(id_client, id_event, img) {
return new Promise((resolve, reject) => {
let serverHost = `http://${config.api_server}`;
fetch(`${serverHost}/robot/event/main_img`, {
method: 'post',
credentials: 'same-origin',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
id_client: id_client,
id_event: id_event,
img: img
})
})
.then(response => {
response.json()
.then(result => {
if (result.response) {
resolve(result.response);
} else {
reject(30);
}
})
.catch((e) => {
reject(20);
});
})
.catch(() => {
reject(10);
});
});
}
export default setMainImgLink;<file_sep>/es6/server/api/client/index.js
/**
* Клиентский API: /client.
*/
import express from 'express';
import img from './img';
import mainImg from './event/mainImg';
import img_1 from './event/img_1';
import img_2 from './event/img_2';
import img_3 from './event/img_3';
import img_4 from './event/img_4';
let api = new express.Router();
//URL: POST /client/img/:id_client.
api.post('/img/:id_client', (req, res) => {
img(req, res);
});
//URL: POST /client/event/main_img/:id_event.
api.post('/event/main_img/:id_client/:id_event', (req, res) => {
mainImg(req, res);
});
//URL: POST /client/event/img_1/:id_event.
api.post('/event/img_1/:id_client/:id_event', (req, res) => {
img_1(req, res);
});
//URL: POST /client/event/img_2/:id_event.
api.post('/event/img_2/:id_client/:id_event', (req, res) => {
img_2(req, res);
});
//URL: POST /client/event/img_3/:id_event.
api.post('/event/img_3/:id_client/:id_event', (req, res) => {
img_3(req, res);
});
//URL: POST /client/event/img_4/:id_event.
api.post('/event/img_4/:id_client/:id_event', (req, res) => {
img_4(req, res);
});
export default api; | bf5075a27aeb5c11743d448d8827546b44226dbe | [
"JavaScript"
] | 3 | JavaScript | peerroo/api_file_server | c20e3a01e6ec04bb6a9e7de88c6665c745717ad4 | f05d703d42b0fa893218c40f3c786334e48bbf45 |
refs/heads/master | <file_sep>Project Tracker
----------------
A Project Management application for collaborating on projects and to do items.
Developed with web2py and python.
By <NAME>
-----
Notes:
-----
- There are two web2py applications inside of this application which you can download.
- The first is a client application to display the functionality of the web services which I implemented for this app.
- To Download, start this app with web2py and navigate to the location: http://127.0.0.1:8000/tracker/static/file/web2py.app.TrackerTests.w2p
* Inside of the client is a standalone Python program that can be used to test the xmlrpc functionality as well. (static file inside of TrackerTests.w2p)
- The second is a testing suite application to test the functionality of the Project Tracker App.
- To Download, start this app with web2py and navigate to the location: http://127.0.0.1:8000/tracker/static/file/web2py.app.TrackerClient.w2p
* Inside of the testing app is a standalone Python program that can also be used to run functional tests using seleniums webdriver. (static file inside of TrackerClient.w2p)
- There are also a number of testing users already setup, all with the same 'test' password.
<file_sep># coding=utf-8
__author__ = 'arlequin'
class Klass:
def __init__ (self, name):
self.students = {}
self.name = name
class Student:
def __init__ (self,stuno,name):
self.course = []
self.name = name
self.stuno = stuno
def addCourse(self, c):
self.course.append(c)
class Course:
def __init__ (self, name, score, notes):
self.name = name
self.score = score
self.notes = notes
with open("transcript.csv") as xscj:
lines = xscj.readlines()
klasses = {}
for line in lines:
try:
lst = line.split(',')
except :
pass
else:
length = len(lst)
if length != 7:
continue
xh = lst[0].strip()
xm = lst[1].strip()
xzb = lst[2].strip()
kcmc = lst[3].strip()
xf = lst[4].strip()
zscj = lst[5].strip()
bz = lst[6].strip()
grade = klasses.setdefault(xzb,Klass(xzb))
student = grade.students.setdefault(xh,Student(xh,xm))
if bz == '缺考':
zscj = '缺考'
elif bz == '无效':
zscj = '缺考'
elif bz == '缓考':
zscj = '缓考'
course = Course(kcmc,zscj,bz)
student.addCourse(course)
lines = None
import sys
encode_type = sys.getfilesystemencoding()
for gk, gv in klasses.items():
gked = gk + '.csv'
gkec = gked.decode('UTF-8').encode(encode_type)
csvof = open(gkec, 'w')
header = '学号,姓名,班级,'+\
'课程1,成绩1,课程2,成绩2,课程3,成绩3,课程4,成绩4,课程5,成绩5,'+\
'课程6,成绩6,课程7,成绩7,课程8,成绩8,课程9,成绩9,课程10,成绩10,'+\
'课程11,成绩11,课程12,成绩12,课程13,成绩13,课程14,成绩14,课程15,成绩15,' +\
'课程16,成绩16,课程17,成绩17,课程18,成绩18'
csvof.write(header.decode('UTF-8').encode(encode_type))
for sk, sv in gv.students.items():
stucse = '{0},{1},{2}'.format(sv.stuno, sv.name,gk)
i = 1
for cse in sv.course:
stucse += ',' + cse.name + ',' + cse.score
i += 1
if i < 18:
stucse += ', , '*(18-i+1)
stucse += '\n'
stucseec = stucse.decode('UTF-8').encode(encode_type)
csvof.write(stucseec)
csvof.close()
<file_sep>
import os
find_what = "is_local"
def do_file(path):
root, ext = os.path.splitext(path)
if ext == '.py' or ext == '.html' or ext == '.css':
f = open(path)
for i, line in enumerate(f.readlines()):
if line.find(find_what) >= 0:
print 'file %s, line %s' % (path, i+1)
f.close()
def do_path(path):
for what in os.listdir(path):
path1 = os.path.join(path, what)
if os.path.isdir(path1):
do_path(path1)
else:
do_file(path1)
if __name__ == '__main__':
start = os.getcwd()
for folder in ['controllers', 'models', 'views', 'static']:
path = os.path.join(start, folder)
do_path(path)
| 394f8b50551350c071f76cb1958cfa4bd0978262 | [
"Markdown",
"Python"
] | 3 | Markdown | manuscriptum/ProjectTracker-web2py | ef2bd50c5168b25129e99edd407fb4889e8e5b97 | 838ad6d5b0f40a685d0559ea017e3eb28e61f3d6 |
refs/heads/master | <file_sep>import java.net.*;
import java.io.*;
class SockClient3 {
public static void main (String args[]) throws Exception {
Socket sock = null;
OutputStream out = null;
InputStream in = null;
byte[] i1;
byte[] id;
if (args.length != 2) {
System.out.println("USAGE: java SockClient id int1");
System.exit(1);
}
if(!args[1].equals("reset")){
try{
int testInteger = Integer.parseInt(args[0]);
}
catch (NumberFormatException nfe) {
System.out.println("Command line args must be integers");
System.exit(2);
}
}
try {
sock = new Socket("localhost", 8888);
out = sock.getOutputStream();
in = sock.getInputStream();
StringBuilder sb = new StringBuilder();
sb.append(args[0]);
sb.append("\0");
sb.append(args[1]);
String outputString = sb.toString();
out.write(outputString.getBytes("UTF-8"));
byte[] result_byte = new byte[100];
in.read(result_byte);
String result_string = new String(result_byte, "UTF-8");
int result = Integer.parseInt(result_string.trim());
System.out.println("Result is " + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) out.close();
if (in != null) in.close();
if (sock != null) sock.close();
}
}
}<file_sep>README file
The project is developed in Java using JDK 1.7 and Eclipse IDE
Design Decisions:
1)Used Byte array to send and recieve data so that, while dealing with -ve integers we get the correct total
2)For #2 and #3 converted the input into string and then encoded it into UTF-8 so that we can send strings such as reset and it would reset the sum
3) For #3 and #5 used HashTable to handle multiple clients, HashTable was used because it is Thread safe and synchronus
Testing the project
for all programs first start the server and then the client
To execute program 1
Input Client : java SockClient1 10 Output From Server: result is 10
java SockClient1 20 result is 30
java SockClient1 - 40 result is -10
To execute program 2
Input Client : java SockClient2 10 Output From Server: result is 10
java SockClient2 reset result is 0
java SockClient2 - 40 result is -40
To execute program 3
Input Client : java SockClient3 1 20 Output From Server: result is 20
java SockClient3 2 40 result is 40
java SockClient3 1 -30 result is -10
java SockClient3 2 50 result is 90
To execute program 4
Input Client : java SockClient4 10 Output From Server: result is 10
java SockClient4 reset result is 0
java SockClient4 - 40 result is -40
To execute program 5
start two clients at the same time and the input as follows
Input Client : java SockClient3 1 20 1000 Output From Server: result is 20
java SockClient3 1 40 1000 result is 60
java SockClient3 2 -30 result is -30
java SockClient3 2 50 result is 20 | 1c1f38bb0b822e356f5c919c9d626ba0635f1a1f | [
"Java",
"Text"
] | 2 | Java | agastheswar/Server-Side-Programming | d2ae8b0a721319b74fb4882a51cbc0ea95e88382 | 06f9a67f351100f8b0e3683ff5815f0ef22a3141 |
refs/heads/master | <repo_name>khan-c/W5D5<file_sep>/tic-tac-toe/board.js
class Board {
constructor () {
this.grid = [[,,,],[,,,],[,,,]];
}
isWon() {
return (this.winner()) ? true : false;
}
winner() {
for (var i = 0; i < 3; i++) {
if(this.grid[i].every((ele)=> (ele === "x")) ||
this.grid[i].every((ele)=> (ele === "o")) ) {
}
if (this.grid[i][0] === this.grid[i][1] &&
this.grid[i][1] === this.grid[i][2]) {
}
}
}
isEmpty(x, y) {
return this.grid[x][y] === undefined;
}
placeMark(x, y, mark) {
this.grid[x][y] = mark;
}
}
| 21c0668f32b9c3bec124db55b0f7279bd77b790d | [
"JavaScript"
] | 1 | JavaScript | khan-c/W5D5 | 007cc8768e31a879c255ba0c861b08417ca04151 | 72f2248657a4d2e0833b7a2bd3ad1f5e8b61a9d2 |
refs/heads/master | <repo_name>carol-rios/proyecto_Final<file_sep>/routes/venta.js
import { Router } from "express"
import ventacontrolles from '../controlles/venta.js'
import { existetipoComprobante,existeVentaById} from '../helpers/venta.js'
import { check } from 'express-validator'
import { validarJWT } from '../middlewares/validar-jwt.js'
import validarRoles from '../middlewares/validar_rol.js'
import validadorCampos from '../middlewares/validar-campos.js'
const router = Router();
router.get('/', [
validarJWT,
validarRoles('VENDEDOR_ROL', 'ADMIN_ROL'),
validadorCampos
], ventacontrolles.ventaGet);
router.get('/:id', [
validarJWT,
validarRoles('VENDEDOR_ROL,ADMIN_ROL'),
check('id', 'No es valido').isMongoId(),
check('id').custom(existeVentaById),
validadorCampos
], ventacontrolles.ventaGetById);
router.post('/', [
validarJWT,
validarRoles('VENDEDOR_ROL,ADMIN_ROL'),
check('numComprobante', 'El campo numero comprobante es obligatorio').not().isEmpty(),
check('tipoComprobante').custom(existetipoComprobante),
validadorCampos
], ventacontrolles.ventaPost);
router.put('/:id',[validarRoles('ALMACENISTA_ROL,ADMIN_ROL'),
check('id', 'No es valido').isMongoId(),
check('id').custom(existeVentaById),
validadorCampos
], ventacontrolles.ventaPut);
router.put('/activar/:id',ventacontrolles.ventaPutActivar);
router.put('/desactivar/:id', ventacontrolles.ventaPutDesactivar);
export default router;<file_sep>/helpers/categoria.js
import categoria from '../models/categoria.js'
const existeCategoriaById = async (id) => {
const existe = await categoria.findById(id)
if (!existe) throw new Error(`El id no existe ${id}`)
}
const existeCategoriaByNombre = async (id) => {
const existe = await categoria.findOne({ nombre })
if (existe) throw new Error('ya existe una categoria con ese nombre')
}
export { existeCategoriaById, existeCategoriaByNombre }<file_sep>/helpers/venta.js
import Venta from "../models/usuario.js"
const existeVentaById=async(id)=>{
const existe=await Venta.findById(id)
if (!existe) {
throw new Error('El ID no existe');
}
}
const existetipoComprobante = async (tipoComprobante) => {
if (tipoComprobante != 'Factura') {
if (tipoComprobante != 'Nota Debito') {
if (tipoComprobante != 'Nota Credito') {
throw new Error('Tipo de comprobante invalido')
}
}
}
}
export {existeVentaById,existetipoComprobante}
<file_sep>/routes/compra.js
import {Router}from 'express'
import { validarJWT } from '../middlewares/validar-jwt.js'
import { check } from 'express-validator'
import compraControlles from '../controlles/compra.js'
import validadorCampos from '../middlewares/validar-campos.js'
import validarRoles from '../middlewares/validar_rol.js'
import existeCompraById from '../helpers/compra.js'
import existetipoComprobante from '../helpers/compra.js'
import existeCompraByNumComprobante from '../helpers/compra.js'
const router = Router();
router.get('/', [
validarJWT,
validarRoles('ALMACENISTA_ROL'),
validadorCampos
], compraControlles.compraGet),
router.post('/', [
validarJWT,
validarRoles('ALMACENISTA_ROL'),
check('numComprobante').custom(existeCompraByNumComprobante),
check('tipoComprobante').custom(existetipoComprobante),
validadorCampos
], compraControlles.compraPost)
router.put('/:id', [
validarJWT,
validarRoles('ALMACENISTA_ROL'),
check('id', 'No es valido').isMongoId(),
check('id').custom(existeCompraById),
validadorCampos
], compraControlles.compraPut),
router.put('/activar/:id', [
validarJWT,
validarRoles('ALMACENISTA_ROL'),
check('id', 'No es valido').isMongoId(),
check('id').custom(existeCompraById),
validadorCampos
], compraControlles.compraPutActivar),
router.put('/desactivar/:id', [
validarRoles('ALMACENISTA_ROL'),
check('id', 'No es valido').isMongoId(),
check('id').custom(existeCompraById),
validadorCampos
], compraControlles.compraPutDesactivar),
router.delete('/:id', [
validarJWT,
validarRoles('ALMACENISTA_ROL'),
check('id', 'No es valido').isMongoId(),
check('id').custom(existeCompraById),
validadorCampos
], compraControlles.compraPutDelete)
export default router
// router.post('/', [
// validarJWT,
// validarRoles('ALMACENISTA_ROL'),
// check('nombre', 'El nombre es obligatorio').not().isEmpty(),
// check('nombre').custom(existeCompraBynombre),
// validadorCampos
// ], compraControllers.compraPost)<file_sep>/controlles/articulo.js
import Articulo from '../models/articulo.js'
const articuloControlles = {
articulosGet: async (req, res) => {
const articulo = await Articulo.find()
// .populate('nombre','categoria')
res.json({
articulo
})
},
articulosGetById: async (res, req) => {
const { id } = req.params;
const articulo = await Articulo.findOne({ _id: id })
res.json({
articulo
})
},
articulosPost: async (req, res) => {
const { codigo, nombre, descripcion, precioVenta, stock } = req.body
const articulo = new Articulo({ codigo, nombre, descripcion, precioVenta, stock })
await articulo.save();
res.json({
articulo
})
},
articulosPut: async (req, res) => {
const { id } = req.params
const { _id, estado, createAt, __v, ...resto } = req.body
// const articulo = await Articulo.findByidAndUpdate(id, resto);
const articulo = await Articulo.findByIdAndUpdate (id, resto);
res.json({
articulo
})
},
articulosPutActivar: async (req, res) => {
const { id } = req.params
const articulo = await Articulo.findByIdAndUpdate(id,{estado:1});
res.json({
articulo
})
},
articulosPutDesactivar: async (req, res) => {
const { id } = req.params
const articulo = await Articulo.findByIdAndUpdate(id,{ estado: 0 });
res.json({
articulo
})
},
articulosPutDelete: async (req, res) => {
const { id } = req.params
const articulo = await Articulo.findByIdAndDelete(id,);
res.json({
articulo
})
},
}
export default articuloControlles
// import Articulo from '../models/articulo.js'
// const articuloControlles = {
// articuloGet: async (req, res) => {
// const articulo = await Articulo.find()
// // .populate('nombre','categoria')
// res.json({
// articulo
// })
// },
// articuloPost=async()=>{
// const {codigo,nombre,categoria,descripcion,precioVenta,stock}=req.body
// const articulo= new Articulo({codigo,nombre,categoria,descripcion,precioVenta,stock})
// await Articulo.save()
// res.json({
// articulo
// })
// },
// }
// export default articuloControlles<file_sep>/models/usuario.js
import mongoose from 'mongoose'
const UsuarioSchema=mongoose.Schema({
nombre:{type:String,require:true,maxlength:50},
email:{type:String,unique:true,maxlength:50},
password:{type:String,unique:true},
rol :{type:String,unique:true,maxlength:20},
// ADMIN_ROL VENDEDOR_R0L ALMACENISTA_ROL
estado:{type:Number,dafault:1},
createdAt:{type:Date,default:Date.now}
})
export default mongoose.model('Usuario',UsuarioSchema)<file_sep>/models/articulo.js
import mongoose from "mongoose";
const articuloSchema=mongoose.Schema({
categoria:{type:mongoose.Schema.Types.ObjectId,ref:'Categoria', required:true},//NO SE MODIFICA
codigo:{type:String,required:true,maxlength:64,unique:true},//NO SE MODIFICA
nombre:{type:String,required:true,maxlength:50,unique:true},
descripcion:{type:String,maxlength:255},
precioVenta:{type:Number,default:0},
stock:{type:Number,default:0},
estado:{type:Number,default:1}, // 1:ACTIVO,0:INACTIVO
createdAt:{type:Date,default:Date.now}//NO SE MODIFICA
})
export default mongoose.model('Articulo',articuloSchema) <file_sep>/controlles/usuario.js
import { generarTokenJWT } from '../middlewares/validar-jwt.js';
import bcryptjs from 'bcryptjs' // =>DESCARGAR.....
import Usuario from '../models/usuario.js'
const usuarioControlles = {
usuarioGet: async (req, res) => {
const query = req.query.value
const usuario = await Usuario.find({
$or: [
{ nombre: new RegExp(query, 'i') },
{ email: new RegExp(query, 'i') },
{ rol: new RegExp(query, 'i') },
]
});
res.json({
usuario
})
},
usuarioGetById: async (req, res) => {
const { id } = req.params
const usuario = await Usuario.findById({id})
res.json({
usuario
})
},
usuarioPost: async (req, res) => {
// console.log(req.body)
const { nombre, email, password, rol } = req.body;
const usuario = Usuario({ nombre, email, password, rol });
// ENCRIPTACION DE CONRASEÑA CON 'bcryptjs'......
const salt = bcryptjs.genSaltSync();
usuario.password = <PASSWORD>.hashSync(password, salt);
usuario.save();
res.json({
usuario
})
},
login: async (req, res) => {
const { email, password } = req.body;
const usuario = await Usuario.findOne({ email });
if (!usuario) {
return res.json({
mgs: 'usuario y password no son correctos email ' //arreglar msg para todos
})
}
if (usuario.estado === 0) {
return res.json({
msg: 'Usuario/ password no son correctos estado'
})
}
const validarPassword = bcryptjs.compareSync(password, usuario.password)
if (!validarPassword) {
res.json({
msg: 'Usuario/ password no son correctos password'
})
}
const token= await generarTokenJWT(usuario.id);
res.json({
usuario,
token
})
},
usuarioPut: async (req, res) => {
const { id } = req.params
const { __id, createdAt, estado, _v, email, rol, password, ...resto } = req.body
if (password) {
const salt = bcryptjs.genSaltSync();
resto.password = <PASSWORD>.hashSync(password, salt);
}
const usuario = await Usuario.findOneAndUpdate(id, resto)
res.json({
usuario
})
},
usuarioPutActivar: async (req, res) => {
const { id } = req.params
const usuario = await Usuario.findByIdAndUpdate(id, { estado: 1 })
res.json({
usuario
})
},
usuarioPutDesactivar: async (req, res) => {
const { id } = req.params
const usuario = await Usuario.findByIdAndUpdate(id, { estado: 0 })
res.json({
usuario
})
},
}
export default usuarioControlles<file_sep>/routes/categoria.js
import {Router} from 'express';
import categoriaController from '../controlles/categoria.js';
import { existeCategoriaById,existeCategoriaByNombre} from '../helpers/categoria.js'
import validadorCampos from '../middlewares/validar-campos.js';
import {validarJWT} from '../middlewares/validar-jwt.js';
import {check} from 'express-validator';// DESCARGAR EXPRESS-VALIDATOR, consola=>(npm i express-validator)
import validarRoles from '../middlewares/validar_rol.js'
const router= Router();
router.get('/',[
validarJWT,
validarRoles('ALMACENISTA_ROL'),
validadorCampos
], categoriaController.categoriaGet);
router.get('/:id', [
validarJWT,
validarRoles('ALMACENISTA_ROL'),
check('id', 'No es valido').isMongoId(),
check('id').custom(existeCategoriaById),
validadorCampos
], categoriaController.categoriaGetById);
router.post('/', [
validarRoles('ALMACENISTA_ROL'),
check('descripcion','El campo descripcion es obligatorio').not().isEmpty(),
check('nombre', 'El campo nombre es obligatorio').not().isEmpty(),
check('nombre').custom(existeCategoriaByNombre),
validadorCampos
], categoriaController.categoriaPost);
router.put('/:id', [
validarJWT,
validarRoles('ALMACENISTA_ROL'),
check('id', 'No es valido').isMongoId(),
check('id').custom(existeCategoriaById),
check('nombre').custom(existeCategoriaByNombre),
validadorCampos
], categoriaController.categoriaPut);
router.put('/activar/:id', [
validarJWT,
validarRoles('ALMACENISTA_ROL'),
check('id', 'No es valido').isMongoId(),
check('id').custom(existeCategoriaById),
validadorCampos
], categoriaController.categoriaPutActivar);
router.put('/desactivar/:id', [
validarRoles('ALMACENISTA_ROL'),
check('id', 'No es valido').isMongoId(),
check('id').custom(existeCategoriaById),
validadorCampos
], categoriaController.categoriaPutDesactivar);
router.delete('/:id', [
validarJWT,
validarRoles('ALMACENISTA_ROL'),
check('id', 'No es valido').isMongoId(),
check('id').custom(existeCategoriaById),
validadorCampos
], categoriaController.categoriaPutDelete);
export default router;
<file_sep>/helpers/persona.js
import Persona from "../models/persona.js"
const existePersonaById=async (id)=>{
const existe= await Persona.findOne(id)
if (!existe) throw new Error(`El id no existe: ${id}`)
}
const existeNumeroDocumentoByPersona=async (numeroDocumento)=>{
const existe= await Persona.findOne({numeroDocumento})
if (existe) throw new Error(`Ya existe una persona con ese nombre`)
}
const existetipoPersona=async(tipoPersona)=>{
if (tipoPersona!='Usuario') {
if (tipoPersona!='proveedor') {
throw await new Error('tipo de persona no admitida')
}
}
}
export{existeNumeroDocumentoByPersona, existePersonaById, existetipoPersona}<file_sep>/models/categoria.js
import mongoose from "mongoose";
const categoriaSchema=mongoose.Schema({
nombre:{type:String,required:true,maxlength:50,unique:true},
description:{type:String,maxlength:255},
estado:{type:Number,default:1}, // 1:ACTIVO 0:INACTIVO
createdAt:{type:Date,default:Date.now}
})
export default mongoose.model('Categoria',categoriaSchema) <file_sep>/models/persona.js
import mongoose from 'mongoose'
const personaShema = mongoose.Schema({
tipoPersona: { type: String, required:true, maxlength: 20 }, // CLIENTE O PROVEEDOR
nombre: { type: String,required:true, maxlength: 40 },
tipoDocumento: { type: String, required:true, maxlength: 25 },
numeroDocumento: { type: String, required:true },
direccion: {type:String, required:true, maxlenght:70},
telefono: { type: String, required:true },
email: { type: String, unique:true, maxlength: 40 },
estado: { type: Number, default: 1 },
createdAt: { type: Date, default: Date.now }
})
export default mongoose.model('Persona', personaShema)<file_sep>/controlles/persona.js
import Persona from "../models/persona.js"
const personaController = {
personaGet: async (req, res) => {
const value = req.query.value
const persona = await Persona.find({
$or: [
{ tipoPersona: new RegExp(value, 'i') },
]
})
.sort({ 'tipoPersona': -1 })
res.json({
persona
})
},
personaGetById: async (req, res) => {
const { id } = req.params;
const persona = await Persona.findOne({ _id: id })
res.json({
persona
})
},
personaPost: async (req, res) => {
try {
const { tipoPersona, nombre, tipoDocumento, numeroDocumento, direccion, telefono, email } = req.body;
const persona = new Persona({ tipoPersona, nombre, tipoDocumento, numeroDocumento, direccion, telefono, email });
await persona.save();
res.json({
persona
})
} catch (error) {
console.log(`Catch ${error}`);
}
},
personaPut: async (req, res) => {
const { id } = req.params
const { _id, estado, createAt, __v, ...resto } = req.body
// validar o no?
const persona = await Persona.findByIdAndUpdate(id, resto);
res.json({
persona
})
},
personaPutActivar: async (req, res) => {
const { id } = req.params
const persona = await Persona.findByIdAndUpdate(id, { estado: 1 });
res.json({
persona
})
},
personaPutDesactivar: async (req, res) => {
const { id } = req.params
const persona = await Persona.findByIdAndUpdate(id, { estado: 0 });
res.json({
persona
})
},
personaPutDelete: async (req, res) => {
const { id } = req.params
const persona = await Persona.findByIdAndDelete(id,);
res.json({
persona
})
},
}
export default personaController<file_sep>/routes/persona.js
import {Router} from 'express'
import personaControlles from '../controlles/persona.js'
import { validarJWT } from '../middlewares/validar-jwt.js'
import validarRoles from '../middlewares/validar_rol.js'
import validadorCampos from '../middlewares/validar-campos.js'
import {existeNumeroDocumentoByPersona, existePersonaById,existetipoPersona}from '../helpers/persona.js'
import {check} from 'express-validator'
const router = Router();
router.get('/',[
validarJWT,
validarRoles('ADMIN_ROL'),
validadorCampos
], personaControlles.personaGet)
router.get('/:id',[
validarJWT,
validarRoles('ADMIN_ROL'),
check('id','No es valido').isMongoId(),
check('id').custom(existePersonaById),
validadorCampos
], personaControlles.personaGetById)
router.post('/',[
validarJWT,
validarRoles('ADMIN_ROL'),
check('nombre', 'nombre es obligatorio').not().isEmpty(),
check('tipoDocumento', ' tipo de documento es obligatorio').not().isEmpty(),
check('numeroDocument', 'numero de documento es obligatorio').not().isEmpty(),
check('direccion', 'dieccion es obligatorio').not().isEmpty(),
check('telefono','telefono es obligatorio').not().isEmpty(),
check('email','email es obligatorio').not().isEmpty(),
check('numeroDocumento').custom(existeNumeroDocumentoByPersona),
check('tipoPersona').custom(existetipoPersona),
validadorCampos], personaControlles.personaPost)
router.put('/:id',[
validarJWT,
validarRoles('ADMIN_ROL'),
check('id','No es valido').isMongoId(),
check('id').custom(existePersonaById),
validadorCampos
], personaControlles.personaPut)
router.put('/activar/:id',[
validarJWT,
validarRoles('ADMIN_ROL'),
check('id','No es valido').isMongoId(),
check('id').custom(existePersonaById),
validadorCampos
], personaControlles.personaPutActivar)
router.put('/desactivar/:id',[
validarJWT,
validarRoles('ADMIN_ROL'),
check('id','No es valido').isMongoId(),
check('id').custom(existePersonaById),
validadorCampos
], personaControlles.personaPutDesactivar)
router.delete('/:id',[
validarJWT,
validarRoles('ADMIN_ROL'),
check('id','No es valido').isMongoId(),
check('id').custom(existePersonaById),
validadorCampos
], personaControlles.personaPutDelete)
export default router;<file_sep>/controlles/compra.js
import Compra from '../models/compra.js'
// import Articulo from '../models/articulo.js'
import aumentarStock from '../controlles/aumentar_stock.js'
import disminuirStock from '../controlles/disminuir_stock.js'
const CompraControlles = {
aumentarStock:async (id,cantidad)=>{
let stock=Articulo.findById(id)
stock= parseInt(stock) + parseInt(cantidad)
await Articulo.findByIdAndUpdate({ id },{ stock })
},
disminuirStock: async (id, cantidad) => {
let stock = await Articulo.findById(id)
stock = parseInt(stock) - parseInt(cantidad)
await Articulo.findByIdAndUpdate({ id }, { stock })
},
compraGet: async (req, res) => {
const compra = await Compra.find();
res.json({
compra
})
},
compraPost: async (req, res) => {
const { usuario,persona,tipoComprobante, serieComprobante, numComprobante, impuesto, total, detalles } = req.body
const compra = new Compra({ usuario,persona, tipoComprobante, serieComprobante, numComprobante, impuesto, total, detalles})
await compra.save();
detalles.map((articulo) => aumentarStock(articulo._id, articulo.cantidad))
res.json({
compra
})
},
compraPut: async (req, res) => {
const { id } = req.params
const { _id, estado, createAt, __v, ...resto } = req.body
const compra = await Compra.findByIdAndUpdate(id, resto);
res.json({
compra
})
},
compraPutActivar: async (req, res) => {
const { id } = req.params
const compra = await Compra.findByIdAndUpdate(id, { estado: 1 });
await compra.detalles.map((articulo) => aumentarStock(articulo._id, articulo.cantidad))
res.json({
compra
})
},
compraPutDesactivar: async (req, res) => {
const { id } = req.params
const compra = await Compra.findByIdAndUpdate(id, { estado: 0 });
await compra.detalles.map((articulo) => disminuirStock(articulo._id, articulo.cantidad))
res.json({
compra
})
},
compraPutDelete: async (req, res) => {
const { id } = req.params
const compra = await Compra.findByIdAndDelete(id);
res.json({
compra
})
},
}
export default CompraControlles<file_sep>/public/FrontEnd/src/main.js
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import {routes} from './routes/routes.js'
import vuetify from './plugins/vuetify'
import axios from 'axios'
import {store} from './store/store.js'
Vue.use(VueRouter);
Vue.config.productionTip = false
axios.defaults.baseURL = "https://fullstack-cv.herokuapp.com/api/"
const router = new VueRouter ({
//Rutas
routes,
mode:"history"
})
new Vue({
render: h => h(App),
store,
vuetify,
router
}).$mount('#app')
<file_sep>/controlles/categoria.js
import Categoria from "../models/categoria.js";
const categoriaController = {
categoriaGet: async (req, res) => {
const value = req.query.value;
const categoria = await Categoria
.find({
$or: [
{ nombre: new RegExp(value, 'i') },
{ descripcion: new RegExp(value, 'i') }
]
})
.sort({ 'nombre': -1 })
res.json({
categoria
})
},
categoriaGetById: async (req, res) => {
const value = req.query.value;
const { id } = req.params;
const categoria = await Categoria.findOne({ _id: id })
res.json({
categoria
})
},
categoriaPost: async (req, res) => {
const { nombre,description } = req.body;
const categoria = new Categoria({ nombre, description });
await categoria.save();
res.json({
categoria
})
},
categoriaPut: async (req, res) => {
const { id } = req.params
const { _id, estado, createAt, _v, ...resto } = req.body
const categoria = await categoria.findByIdAndUpdate(id, resto);
res.json({
categoria
})
},
categoriaPutActivar: async (req, res) => {
const { id } = req.params
const categoria = await categoria.findByIdAndUpdate(id, { estado: 1 });
res.json({
categoria
})
},
categoriaPutDesactivar: async (req, res) => {
const { id } = req.params
const categoria = await categoria.findByIdAndUpdate(id, { estado: 0 });
res.json({
categoria
})
},
categoriaPutDelete: async (req, res) => {
const { id } = req.params
const categoria = await categoria.findByIdAndDelete(id);
res.json({
categoria
})
},
}
export default categoriaController
<file_sep>/helpers/articulo.js
import Articulo from "../models/articulo.js"
const existeArticuloById=async (id)=>{
const existe= await Articulo.findById({id})
if (!existe) throw new Error(`El id no existe ${id}`)
}
const existeArticuloByNombre=async (nombre)=>{
const existe= await Articulo.findOne({nombre})
if (existe) throw new Error(`Ya existe un articulo con ese nombre`)
}
export {existeArticuloById,existeArticuloByNombre}<file_sep>/middlewares/validar-jwt.js
import jsonWebToken from 'jsonwebtoken'
import existeUsuarioById from '../helpers/usuario.js'
import Usuario from '../models/usuario.js'
const generarTokenJWT = (uid = '') => {
return new Promise((resolve, reject) => {
checkToken()
const payLoad = { uid }
jwt.sing(payLoad, process.env.privatekey, {
expiresIn: '5d'
}, (err, token) => {
if (err) {
reject('No se pudo generar el token')
} else {
resolve(token)
}
})
})
};
const validarJWT = async (req, res) => {
const token = req.header('token')
if (!token) {
return res.status(401).json({
mgs: 'No hay token en la peticion'
})
}
try {
const { uid } = jwt.verify(token, process.env.privatekey);
const usuario = await Usuario.findById(uid)
if (!usuario) {
return res.status(401).json({
mgs: 'Token no es válido'
})
}
if (usuario.estado === 0) {
return res.status(401).json({
msg: 'Token es no valido'
})
}
req.usuario = usuario
next()
} catch (error) {
res.status(401).json({
mgs: 'token no válido'
})
}
}
async function checkToken(token) {
let_id = null;
try {
const { __id } = await jsonWebToken.decode(token)
__id = _id
} catch (error) {
return false;
}
const existeUsuario = existeUsuarioById(__id)
}
export { generarTokenJWT, validarJWT }<file_sep>/routes/articulo.js
import {Router} from 'express';
import {check} from 'express-validator';
import articuloControlles from '../controlles/articulo.js'
import {validarJWT} from '../middlewares/validar-jwt.js'
import validarRoles from '../middlewares/validar_rol.js'
import validadorCampos from '../middlewares/validar-campos.js'
import {existeArticuloById, existeArticuloByNombre}from '../helpers/articulo.js'
// import { check } from 'express-validator'
const router = Router();
router.get('/', [
validarJWT,
validarRoles('ALMACENISTA_ROL'),
validadorCampos
], articuloControlles.articulosGet)
router.get('/:id', [
validarJWT,
validarRoles('ALMACENISTA_ROL'),
check('id', 'No es valido').isMongoId(),
check('id').custom(existeArticuloById),
validadorCampos
], articuloControlles.articulosGet)
router.post('/', [
validarJWT,
validarRoles('ALMACENISTA_ROL'),
check('nombre', 'El nombre es obligatorio').not().isEmpty(),
check('nombre').custom(existeArticuloByNombre),
validadorCampos
], articuloControlles.articulosPost)
router.put('/:id', [
validarJWT,
validarRoles('ALMACENISTA_ROL'),
check('id', 'No es valido').isMongoId(),
check('id').custom(existeArticuloById),
check('nombre').custom(existeArticuloByNombre),
validadorCampos
], articuloControlles.articulosPut)
router.put('/activar/:id',[
validarJWT,
validarRoles('ALMACENISTA_ROL'),
check('id', 'No es valido').isMongoId(),
check('id').custom(existeArticuloById),
validadorCampos
], articuloControlles.articulosPutActivar)
router.put('/desactivar/:id', [
validarRoles('ALMACENISTA_ROL'),
check('id', 'No es valido').isMongoId(),
check('id').custom(existeArticuloById),
validadorCampos
], articuloControlles.articulosPutDesactivar)
router.delete('/:id', [
validarJWT,
validarRoles('ALMACENISTA_ROL'),
check('id', 'No es valido').isMongoId(),
check('id').custom(existeArticuloById),
validadorCampos
], articuloControlles.articulosPutDelete)
export default router;<file_sep>/public/FrontEnd/src/routes/routes.js
import recovery from '../components/Recovery.vue'
import login from "../pages/login.vue"
import categorias from '../pages/Categorias.vue'
import articulos from '../pages/Articulos.vue'
import usuarios from '../pages/Usuarios.vue'
import ingresos from '../pages/Ingresos.vue'
import ventas from '../pages/Ventas.vue'
import proveedores from '../pages/Proveedores.vue'
import clientes from '../pages/Clientes.vue'
import grafica from '../pages/Grafica.vue'
export const routes = [
{path: "/", component: login},
{path: "/grafica", component: grafica},
{path: "/ventas", component: ventas},
{path: "/recovery", component: recovery},
{path: "/categorias", component: categorias},
{path: "/articulos", component: articulos},
{path: "/usuario", component: usuarios},
{path: "/ingresos", component: ingresos},
{path: "/proveedores", component: proveedores},
{path: "/clientes", component: clientes},
] | 6975c6f98998a64216d98fb81876f452ff5446a5 | [
"JavaScript"
] | 21 | JavaScript | carol-rios/proyecto_Final | 2ab68b1a465c11ba8fa627f7c5861892a9fb4d48 | 061b613d6177b44f40ebec35ce25080d16d2460f |
refs/heads/master | <repo_name>nosheeno/typeconver<file_sep>/js/app.js
var name; //here NAME IS UNDEFINED
name = "nosheen"; //string
const age = 23 ;//string
console.log("Name " + name + " Age " + age);
console.log(typeof(name), typeof(age));
let x = 2; // number
y = 3;
z = 2;
console.log(typeof(x==y)); //boolean
console.log(x==z);
let a = "", b = 1, c = 0;
console.log(a+b+c);
console.log(a-1+0);
let d = true, e = false;
console.log(d+e);
let f = 6, g = "3", h = "2";
console.log(f/g);
console.log(h*g);
let i =4, j=5, k ="px";
console.log(i+j+k);
let l ="4", m =2, n="4px";
console.log(l-m);
console.log(n-m);
let o = 7, p =0, q="-9/n", r=5;
console.log(o/p);
console.log(q+r);
console.log(q-r);
let s= null, t =1, u=undefined;
console.log(s+t);
console.log(u+t);
| 4ed6d985c14143c1048084456f5570573db43926 | [
"JavaScript"
] | 1 | JavaScript | nosheeno/typeconver | a32c4e7042b4fe95568e637e9e9a49a1cdb47d5c | cad01b3f78af736949b098ba09af5b85798914bc |
refs/heads/master | <repo_name>nxx160030/ML-Decision-Tree<file_sep>/src/algorithm/InfoGain.java
package algorithm;
import java.util.ArrayList;
import java.util.List;
import tree.Row;
public class InfoGain extends Algorithm{
private double entropy=0;
private List<Row> rows;
public double calculateEntropy(List<Row> table)
{
rows = table;
if(rows.size()==0) return 0;
int ONE = 1;
int ZERO = 0;
List<Row> zeroRows = new ArrayList<Row>();
List<Row> oneRows = new ArrayList<Row>();
for(int i=0;i<rows.size();i++)
{
Row current = rows.get(i);
int ClassCol = current.getRowList().size()-1;
if(current.getCell(ClassCol).getValue()==ONE)
{
oneRows.add(current);
}else if(current.getCell(ClassCol).getValue()==ZERO)
{
zeroRows.add(current);
}
}
int count0 = zeroRows.size();
int count1 = oneRows.size();
entropy = entropyMath(count0,count1);
return entropy;
}
private double entropyMath(int count0, int count1)
{
int local_count0 = count0;
int local_count1 = count1;
double local_ratio0 = (double)local_count0/(local_count0+local_count1);
double local_ratio1 = 1 - local_ratio0;
return -local_ratio1*Math.log(local_ratio1)/Math.log(2)-local_ratio0*Math.log(local_ratio0)/Math.log(2);
}
public double calculateInfoGain(double currentEntropy,
ArrayList<Double> entropiesOfSubsets,
ArrayList<Integer> sizesOfSubsets, double totalExamples) {
double gain = currentEntropy;
for (int j = 0; j < entropiesOfSubsets.size(); j++)
gain -= (sizesOfSubsets.get(j) / totalExamples)
* entropiesOfSubsets.get(j);
return gain;
}
}
<file_sep>/src/util/FileOp.java
package util;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import tree.Row;
public class FileOp {
public static List<Row> openFile(String fileName) throws IOException
{
String file = fileName;
BufferedReader br = new BufferedReader(new FileReader(file));
String headers = br.readLine();
List<Row> array = new ArrayList<Row>();
String current = br.readLine();
while(current!=null)
{
Row line = new Row(headers,current);
array.add(line);
current = br.readLine();
}
br.close();
return array;
}
}
<file_sep>/src/tree/Node.java
package tree;
import java.util.ArrayList;
import java.util.List;
public class Node {
private List<Node> children;
private double entropy;
private int classification;
private String attribute;
private Node leftChild;
private Node rightChild;
private int index;
private List<Row> rows;
public Node(){
children = null;
leftChild = null;
rightChild = null;
entropy = 0;
classification = 0;
attribute = new String("");
index = 0;
rows = new ArrayList<Row>();
}
public void setEntropy(double value)
{
entropy = value;
}
public double getEntropy()
{
return entropy;
}
public void setAttribute(String value)
{
attribute = value;
}
public String getAttribute()
{
return attribute;
}
public void setChildren(Node leftChild, Node rightChild)
{
this.leftChild = leftChild;
this.rightChild = rightChild;
children = new ArrayList<Node>();
if(this.leftChild!=null)
{
children.add(this.leftChild);
}
if(this.rightChild!=null)
{
children.add(this.rightChild);
}
}
public void setClassification(int value)
{
classification = value;
}
public List<Node> getChildren()
{
if(leftChild==null&&rightChild==null) return null;
return children;
}
public Node getChildren(int index)
{
return children.get(index);
}
public Node getLeftChild()
{
if(this.leftChild!=null)
{
return this.leftChild;
}
return null;
}
public Node getRightChild()
{
if(this.rightChild!=null)
{
return this.rightChild;
}
return null;
}
public int getClassification()
{
return classification;
}
public void setIndex(int value)
{
index = value;
}
public int getIndex()
{
return index;
}
public void setRows(List<Row> list)
{
rows = list;
}
public List<Row> getRows()
{
return rows;
}
}
| 800b8975c3fcc09b649a4a123e147f1a8328eafb | [
"Java"
] | 3 | Java | nxx160030/ML-Decision-Tree | 24201690b60243fd1d038f1a97cf2f70019a1d6c | c56fa3507f14d6d0988396a31934140a73661b55 |
refs/heads/main | <file_sep>#!/bin/bash
cd ./back/app && composer install && cp .env.example .env
docker exec -i back php artisan key:generate
docker exec -i back php artisan migrate
docker exec -i back php artisan db:seed
docker exec -i back php artisan storage:link
docker exec -i back php artisan jwt:secret
echo '........................'
echo 'Setup success!'<file_sep>FROM php:7.3-fpm-alpine
MAINTAINER VCT
RUN docker-php-ext-install pdo pdo_mysql
# RUN apk add --no-cache \
# freetype \
# libjpeg-turbo \
# libpng \
# freetype-dev \
# libjpeg-turbo-dev \
# libpng-dev \
# && docker-php-ext-configure gd \
# && docker-php-ext-install -j$(nproc) gd \
# && docker-php-ext-enable gd \
# && apk del --no-cache \
# freetype-dev \
# libjpeg-turbo-dev \
# libpng-dev \
# && rm -rf /tmp/*
<file_sep>module.exports = {
important: true,
purge: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'],
darkMode: 'class', // or 'media' or 'class' --> media is relying on system
theme: {
extend: {},
fontFamily: {
sans: ['Graphik', 'sans-serif'],
serif: ['Merriweather', 'serif'],
},
},
variants: {
extend: {
opacity: ['disabled'],
},
},
plugins: [],
}
<file_sep>#!/bin/bash
docker-compose up -d
echo '........................'
echo 'http://localhost'<file_sep>- Run sh shell.sh
- Run sh setup.sh
- Access Front http://localhost
- Access Api http://localhost/back-end
<file_sep><?php
use App\Mail\MailTest;
use App\User;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/hello', function () {
$redis = Redis::connection();
$redis->set('aa', 'cccc');
// $key = md5(88888888);
// Cache::store('redis')->put($key, User::take(10)->get(), 40);
// $users = Cache::get($key);
// return view('user', compact('users'));
});
Route::get('mail', function () {
Mail::to('<EMAIL>')->queue(new MailTest());
}); | 85edac5eb3d1bc41ccd8bdf2f063df6499411141 | [
"JavaScript",
"Markdown",
"PHP",
"Dockerfile",
"Shell"
] | 6 | Shell | vutruong1998/laravue-docker | e3227ea84e4b46e5b57d55e9aab6ef2c21cf533a | 037072a1ccb25cb2a1ea55b9a1e29b52fb672a51 |
refs/heads/master | <file_sep>## Codebook for UCI HAR wearable computing dataset
###subjects###
1:30
Unique identifiers assigned to each subjects
###activity_number###
1:6
Unique identifiers of the corresponding activity performed by the subjects.
Corresponding description can be found in activity_labels.txt:
1. WALKING
2. WALKING_UPSTAIRS
3. WALKING_DOWNSTAIRS
4. SITTING
5. STANDING
6. LAYING
###features (measures)
The features selected for this database come from the accelerometer and gyroscope 3-axial raw signals tAcc-XYZ and tGyro-XYZ. These time domain signals (prefix 't' to denote time) were captured at a constant rate of 50 Hz. Then they were filtered using a median filter and a 3rd order low pass Butterworth filter with a corner frequency of 20 Hz to remove noise. Similarly, the acceleration signal was then separated into body and gravity acceleration signals (tBodyAcc-XYZ and tGravityAcc-XYZ) using another low pass Butterworth filter with a corner frequency of 0.3 Hz.
Subsequently, the body linear acceleration and angular velocity were derived in time to obtain Jerk signals (tBodyAccJerk-XYZ and tBodyGyroJerk-XYZ). Also the magnitude of these three-dimensional signals were calculated using the Euclidean norm (tBodyAccMag, tGravityAccMag, tBodyAccJerkMag, tBodyGyroMag, tBodyGyroJerkMag).
Finally a Fast Fourier Transform (FFT) was applied to some of these signals producing fBodyAcc-XYZ, fBodyAccJerk-XYZ, fBodyGyro-XYZ, fBodyAccJerkMag, fBodyGyroMag, fBodyGyroJerkMag. (Note the 'f' to indicate frequency domain signals).
These signals were used to estimate variables of the feature vector for each pattern:
'-XYZ' is used to denote 3-axial signals in the X, Y and Z directions.
- tbodyaccmeanx: mean of tBodyAcc on X axis
- tbodyaccmeany: mean of tBodyAcc on Y axis
- tbodyaccmeanz: mean of tBodyAcc on Z axis
- tbodyaccstdx: standard deviation of tBodyAcc of on X axis
- tbodyaccstdy: standard deviation of tBodyAcc of on Y axis
- tbodyaccstdz: standard deviation of tBodyAcc of on Z axis
- tgravityaccmeanx: mean of tGravityAcc on X axis
- tgravityaccmeany: mean of tGravityAcc on Y axis
- tgravityaccmeanz: mean of tGravityAcc on Z axis
- tgravityaccstdx: standard deviation of tGravityAcc of on X axis
- tgravityaccstdy: standard deviation of tGravityAcc of on Y axis
- tgravityaccstdz: standard deviation of tGravityAcc of on Z axis
- tbodyaccjerkmeanx: mean of tBodyAccJerk on X axis
- tbodyaccjerkmeany: mean of tBodyAccJerk on Y axis
- tbodyaccjerkmeanz: mean of tBodyAccJerk on Z axis
- tbodyaccjerkstdx: standard deviation of tBodyAccJerk on X axis
- tbodyaccjerkstdy: standard deviation of tBodyAccJerk on Y axis
- tbodyaccjerkstdz: standard deviation of tBodyAccJerk on Z axis
- tbodygyromeanx: mean of tBodyGyro on X axis
- tbodygyromeany: mean of tBodyGyro on Y axis
- tbodygyromeanz: mean of tBodyGyro on Z axis
- tbodygyrostdx: standard deviation of tBodyGyro on X axis
- tbodygyrostdy: standard deviation of tBodyGyro on Y axis
- tbodygyrostdz: standard deviation of tBodyGyro on Z axis
- tbodygyrojerkmeanx: mean of tBodyGyroJerk on X axis
- tbodygyrojerkmeany: mean of tBodyGyroJerk on Y axis
- tbodygyrojerkmeanz: mean of tBodyGyroJerk on Z axis
- tbodygyrojerkstdx: standard deviation of tBodyGyroJerk on X axis
- tbodygyrojerkstdy: standard deviation of tBodyGyroJerk on Y axis
- tbodygyrojerkstdz: standard deviation of tBodyGyroJerk on Z axis
- tbodyaccmagmean: mean of tBodyAccMag
- tbodyaccmagstd: standard deviation of tBodyAccMag
- tgravityaccmagmean: mean of tGravityAccMag
- tgravityaccmagstd: standard deviation of tGravityAccMag
- tbodyaccjerkmagmean: mean of tBodyAccJerkMag
- tbodyaccjerkmagstd: standard deviation of tBodyAccJerkMag
- tbodygyromagmean: mean of tBodyGyroMag
- tbodygyromagstd: standard deviation of tBodyGyroMag
- tbodygyrojerkmagmean: mean of tBodyGyroJerkMag
- tbodygyrojerkmagstd: standard deviation of tBodyGyroJerkMag
- fbodyaccmeanx: mean of fBodyAcc on X axis
- fbodyaccmeany: mean of fBodyAcc on Y axis
- fbodyaccmeanz: mean of fBodyAcc on Z axis
- fbodyaccstdx: standard deviation of fBodyAcc on X axis
- fbodyaccstdy: standard deviation of fBodyAcc on Y axis
- fbodyaccstdz: standard deviation of fBodyAcc on Z axis
- fbodyaccjerkmeanx: mean of fBodyAccJerk on X axis
- fbodyaccjerkmeany: mean of fBodyAccJerk on Y axis
- fbodyaccjerkmeanz: mean of fBodyAccJerk on Z axis
- fbodyaccjerkstdx: standard deviation of fBodyAccJerk on X axis
- fbodyaccjerkstdy: standard deviation of fBodyAccJerk on Y axis
- fbodyaccjerkstdz: standard deviation of fBodyAccJerk on Z axis
- fbodygyromeanx: mean of fBodyGyro on X axis
- fbodygyromeany: mean of fBodyGyro on Y axis
- fbodygyromeanz: mean of fBodyGyro on Z axis
- fbodygyrostdx: standard deviation of fBodyGyro on X axis
- fbodygyrostdy: standard deviation of fBodyGyro on Y axis
- fbodygyrostdz: standard deviation of fBodyGyro on Z axis
- fbodyaccmagmean: standard deviation of fBodyAccMag
- fbodyaccmagstd: mean of fBodyAccMag
- fbodybodyaccjerkmagmean: mean of fBodyAccJerkMag
- fbodybodyaccjerkmagstd: standard deviation of fBodyAccJerkMag
- fbodybodygyromagmean: mean of fBodyGyroMag
- fbodybodygyromagstd: standard deviation of fBodyGyroMag
- fbodybodygyrojerkmagmean: mean of fBodyGyroJerkMag
- fbodybodygyrojerkmagstd: standard deviation of fBodyGyroJerkMag
<file_sep>library(reshape2)
library(data.table)
library(dplyr)
library(tidyr)
## assuming in the same folder as unzipped data
## else setwd("your_path_to/UCI HAR Dataset")
## 1. Merge the training and the test sets to create one data set.
# read the data and directly merges in two data_sets (train and test);
# each dataset is composed by Subjects list + Labels + Data;
# finally the two datasets are merged
train_dataset <- read.table("train/subject_train.txt") %>%
cbind(read.table("train/y_train.txt")) %>%
setnames(1:2, c("subject", "activity_num")) %>%
cbind(read.table("train/X_train.txt"))
test_dataset <- read.table("test/subject_test.txt") %>%
cbind(read.table("test/y_test.txt")) %>%
setnames(1:2, c("subject", "activity_num")) %>%
cbind(read.table("test/X_test.txt"))
whole_dataset <- rbind(train_dataset, test_dataset)
## 2. Extract only the measurements on the mean and standard deviation for each measurement.
# load the measures list from file
measures <- fread("features.txt") %>%
setnames(1:2, c("measure_num", "measure_name"))
# filter out measures names not containing "mean" or "std" and creates a column with
# the corresponding measure coding to be used with the dataset
measures_filtered <- measures[grepl("mean\\(\\)|std\\(\\)", measure_name)] %>%
mutate(measure_code = paste0("V", measure_num))
# filter out unintended columns from the Test + Train dataset
results_dataset <- select(
whole_dataset, one_of(c("subject", "activity_num", measures_filtered$measure_code))
)
## 3. Use descriptive activity names to name the activities in the data set
# load activity names into table
activity_names <- read.table("activity_labels.txt") %>%
setnames(1:2, c("activity_num", "activity_name"))
# apply activity names to dataset variable acording to the activity number
results_dataset <- merge(results_dataset, activity_names, by = "activity_num", all.x = TRUE) %>%
select(subject, activity_name, 2:68)
## 4. Appropriately label the data set with descriptive variable names
# beautify variable names transforming lowercase with no symbols
measures_filtered <- measures_filtered %>%
mutate(better_name = tolower(gsub("[^[:alpha:]]", "", measure_name)))
#apply "beautified" label names to dataset columns
results_dataset <- setnames(results_dataset, 3:68, measures_filtered$better_name)
## 5. From the data set in step 4, create a second, independent tidy data set with the
## average of each variable for each activity and each subject.
aggregate_data <- aggregate(
x=results_dataset[, 3:68],
by=list(subject = results_dataset$subject, activity = results_dataset$activity_name),
FUN = mean)
# export aggregate data set
write.table(format(aggregate_data, scientific=T), "tidy_data_set.txt",
row.names=F, col.names=T, quote=2)
<file_sep># Getting and cleaning data course project
This repository contains a R script to create a creating a tidy data set of wearable computing data originally available from http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones
Files included in the repository:
- README.md (this very file)
- CodeBook.md (codebook describing variables and data)
- run_analysis.R (R code to perform data manipulation and obtain the final tidy dataset)
### The script ###
The script assumes it is within the data directory, so save inside the unzipped data folder.
The data folder is normally named **UCI HAR Dataset** and contains the following files and folders:
- activity_labels.txt
- features.txt
- test/
- train/
The script also assumes that **UCI HAR Dataset** is the R current working directory; please check it by `getwd()` and eventualli set the right path to the data folder as your current working directory: `setwd("your_path_to/UCI HAR Dataset)`.
The run_analysis.R script does the following:
1. merges the training and the test sets to create one data set
2. extracts only the measurements on the mean and standard deviation for each measurement
3. uses descriptive activity names to name the activities in the data set
4. appropriately labels the data set with descriptive activity names
5. creates a second, independent tidy data set with the average of each variable for each activity and each subject.
Step 1:
Two partial datasets are created - train data and test data rispecitvely - by joining subject files, activity files and data files. The two partial datasets are finally combined in a comprehensive dataframe.
Step 2:
Measures names are obtained from **features.txt** and filtered in order to drop out variables not corresponding to means or standard deviations ("*std*"). A new data frame **results_dataset** is then created including subjects, activity number and the desired measures.
Step 3:
The activity descriptions are obtained from **activity_labels.txt**; a new column in our dataset containing the activity description is created corresponingly. The dataset is finally reshaped by removing the activity number column which is no more needed.
Step 4:
The names of each measures (previously obtained from **features.txt**) are now applied to column names of our final dataset. Variable names are also set to lower case and non-alpha characters are omitted for easier reading.
Step 5:
A new data frame is created by aggregating the mean of each measure for each subject and activity type. The data frame is exported to the working directory as a file named **tidy_data_set.txt**.
| abf5b6532b911fd7129db675474589de6709bd37 | [
"Markdown",
"R"
] | 3 | Markdown | mfiorani/coursera-getting-and-cleaning-data | 7bc78fe641fc6ff14c8d7dfd14380834b3925233 | bb583df7fe42f329dc285dd9147d3ceb28b9c9a9 |
refs/heads/master | <file_sep>def cheese_and_crackers(cheese_count, boxes_of_crackers): # list name/args
print "You have %d cheeses!" % cheese_count # print out 1st arg
print "You have %d boxes of crackers!" % boxes_of_crackers # print out 2nd arg
print "Man that's enough for a party!" # printing
print "Get a blanket.\n" # printing
print "We can just give the function numbers directly:"
cheese_and_crackers(20, 30) # Running the function with int values
print "OR we can use variables from our script:" # defining variables to use in func
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers) # running func with vars
print "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 + 6) # running func with math
print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) # math + vars
def division(dividend, divisor):
answer = dividend/divisor
print answer
division(10, 5)
to_be_divided = float(raw_input("Enter the number to be divided: "))
divided_by = float(raw_input("Enter the number by which to divide: "))
print "Your answer: "
division(to_be_divided, divided_by)
<file_sep>print "You are now entering a world of decisions."
options = """
What do you want to do?
1. Eat a cookie.
2. Eat a boogie.
3. Take a lookie.
"""
print options
decision = raw_input("> ")
if decision == "1":
print "If you want a cookie eat a boogie."
elif decision == "2":
print "Eat a boogie? That's nasty."
elif decision == "3":
print "Don't be nosy."
else:
print "Probably best to leave it alone..."
<file_sep># simply DRY-ing
divider = '-' * 10
# creating mapping of states to abbreviation
states = {
'Distrito Federal': 'CDMX',
'Mexico': 'Edomex',
'Jalisco': 'JAL',
'Puebla': 'PUE',
'Chihuahua': 'CHH'
}
# print out some state abbreviations
print divider
print "Distrito Federal has the abrreviation ", states['Distrito Federal']
print "Jalisco has the abbreviation ", states['Jalisco']
# create association between state abbreviation/cities
cities = {
'CDMX': 'Mexico City',
'Edomex': 'Ecatepec',
'JAL': 'Guadalajara'
}
# add more cities
cities['PUE'] = 'Puebla'
cities['CHH'] = 'Juarez'
print divider
print "Chihuahua's capital is ", cities['CHH']
print "Jalisco's capital is ", cities['JAL']
# print state and city, using cities dict
print divider
print "Mexico state's capital is ", cities[states['Mexico']]
print "Puebla's capital is ", cities[states['Puebla']]
# print every state abbreviation
print divider
for state, abbrev in states.items():
print "%s is abbreviated %s" % (state, abbrev)
# print every state's info with for loop
print divider
for state, abbrev in states.items():
print "%s is abbreviated %s and %s is the capital" % (
state, abbrev, cities[abbrev])
# Get abbreviation by state that isn't available, safely
state = states.get('La Paz')
if not state:
print "Sorry, no La Paz."
# get a city with a default value
city = cities.get('LP', 'Does Not Exist')
print "The city for the state of 'LP' is: %s" % city
# get a city with a default value
<file_sep>print "This script will illustrate how dicts work different than dicts"
things = ['a', 'b', 'c', 'd']
print "Here is the things list:"
print things
print "Here's the value at index one:"
print things[1]
things[1] = 'z'
print "Now things[1] is ", things[1]
print "Here's the entire things list:"
print things
print "OK. Here's how dicts behave:"
stuff_dictionary = {'name': 'klp', 'age': 35, 'height': 6 * 12 + 1}
print "Here's a dictionary:"
print stuff_dictionary
print "Indexing at 'name':"
print stuff_dictionary['name']
print "Indexing at 'height':"
print stuff_dictionary['height']
print "Now, we're going to try to add the 'city' key with a value of 'NYC':"
stuff_dictionary['city'] = 'NYC'
print stuff_dictionary['city']
print "Now we're going to add more items to the stuff dictionary."
print "Adding 1: 'Wow' and 2: 'Neato' to stuff_dictionary."
stuff_dictionary[1] = "Wow"
stuff_dictionary[2] = "Neato"
print stuff_dictionary[1]
print stuff_dictionary[2]
print "This is what stuff dictionary looks like now:"
print stuff_dictionary
print "And now we'll delete city, 1, and 2 keys from the stuff dictionary:"
del stuff_dictionary['city']
del stuff_dictionary[1]
del stuff_dictionary[2]
print "And the final dictionary is:"
print stuff_dictionary
<file_sep>from sys import exit
def gold_room():
"""
Asks you for how much gold you want to take, and responds
with an appropriate print statement.
"""
print "This room is full of gold. How much do you take?"
choice = raw_input("> ")
if "0" in choice or "1" in choice:
how_much = int(choice)
else:
dead("Man, learn to type a number.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
def bear_room():
"""
prints text related to the bear room
gives responses from the bear if you take honey,
taunt the bear (both bear moved and not moved),
takes you to the good room or
reprompts you if the response you give isn't handled
"""
print "There is a bear here."
print "The bear has a bunch of honey."
print "The fat bear is in front of another door."
print "How are you going to move the bear?"
bear_moved = False
while True:
choice = raw_input("> ")
if choice == "take honey":
dead("The bear looks at you then slaps your face off.")
elif choice == "taunt bear" and not bear_moved:
print "The bear has moved from the door. You can go through it now."
bear_moved = True
elif choice == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chew your leg off.")
elif choice == "open door" and bear_moved:
gold_room()
else:
print "I got no idea what that means."
def cthulhu_room():
"""
Takes you to the beginning if you feel the room
Makes you dead if you eat your head
Print chthulhu_room text if it doesn't know what you're saying
"""
print "Here you see the great evil Cthulhu."
print "He, it, whatever stares at you and you go insane."
print "Do you flee for your life or eat your head?"
choice = raw_input("> ")
if "flee" in choice:
start()
elif "head" in choice:
dead("Well that was tasty!")
else:
cthulhu_room()
def dead(why):
"""
Prints a message based on a response that makes you dead, and exits the program
"""
print why, "Good job!"
exit(0)
def start():
"""
This starts the sequence in the dark room, start the game itself
"""
print "You are in a dark room."
print "There is a door to your right and left."
print "Which one do you take?"
choice = raw_input("> ")
if choice == "left":
bear_room()
elif choice == "right":
cthulhu_room()
else:
dead("You stumble around the room until you starve.")
start()
<file_sep>i = 0
j = 1
limit = 6
numbers = []
def appender(i, j):
while i < limit:
print "At the top i is %d" % i
numbers.append(i)
i += j
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
'''
while i < 6:
print "At the top i is %d" % i
numbers.append(i)
i += 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
'''
appender(i, j)
print "The numbers: "
for num in numbers:
print num
def appender_2 (i, j):
for i in range(i, j):
print "At the top i is %d" % i
numbers.append(i)
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
appender_2(i, j)
print "The numbers: "
for num in numbers:
print num
<file_sep># Learning Python the Hard Way
After learning various tidbits of Python on the web, finally sitting down to learn it in a more systematic and sustainable way, using Zed Shaw's [_Learn Python the Hard Way_](https://learnpythonthehardway.org).
I wanted a place to stash the source code, so I could pick up where I left off on different computers. My goal is to commit something/practice everyday. Here's hoping.
In addition to the exercises, there are scripts written as one offs based on the study drills.
<file_sep>from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is", first
print "Your second variable is", second
print "Your third variable is:", third
# Need to make sure we pass in argruments when running the script
<file_sep>from sys import exit
from random import randrange
enter_room = "You open the door and enter the room."
prompt = "> "
def panda_room():
print enter_room
print "You find yourself surrounded by pandas."
print "Whatever will you do with all these pandas?"
print "Make fun of the pandas."
print "Laugh at the pandas."
print "Run away from the pandas."
choice = raw_input(prompt)
if "fun" in choice:
returner("You got a lotta nerve.")
elif "laugh" in choice:
print "The pandas cried a thousand rainbows of joy."
taco_room()
elif "run" in choice:
returner("Everything has been restored.")
else:
print "Please enter something with 'run', 'laugh' or 'run' in it."
def unicorn_room():
print enter_room
print "You find yourself in the midst of a unicorn herd."
print "Don't get stampeded!!!"
print "What do you want to do?"
print "Scream in horror"
print "Do a dance"
print "Just stand there."
choice = raw_input(prompt)
if "scream" in choice:
returner("The unicorns don't tolerate that kind of behavior.")
elif "dance" in choice:
guess_master_room()
elif "stand" in choice:
returner("Don't just stand there! Now you've done it.")
def cute_cat_room():
print enter_room
print "This is a room with soo many cute cats"
print "What can you even do with them?"
print "Talk to the cats."
print "Throw something at the cats."
print "Nap with the cats."
choice = raw_input(prompt)
if "talk" in choice:
returner("Cats don't speak English. These are French cats!")
elif "throw" in choice:
returner("Cats don't like to have stuff thrown at them")
elif "nap" in choice:
returner("You curl up with some nice cats and fall asleep.")
else:
stuck(cute_cat_room())
def guess_master_room():
print enter_room
print "There's a wise old looking guess master."
print "It asks 'Guess what number I'm thinking, 1-3.'"
my_answer = int(raw_input(prompt))
guess_master_answer = randrange(1, 3)
if my_answer == guess_master_answer:
print "You get to the taco room"
taco_room()
else:
returner("Wrong number!!!")
def taco_room():
print enter_room
print "This is the taco room!"
print "There are all of the taco you could possibly eat."
print "And then there's more!"
print "What will you do in this splendid room?"
print "Walk around the room"
print "Eat every single taco"
print "Talk to some guy over in the corner."
choice = raw_input(prompt)
if "walk" in choice:
print "You walk in circles, astonished by all these tacos."
print "You forget where you are in all of this splendor."
taco_room()
elif "eat" in choice:
die("These tacos tastes funny...")
elif "talk" in choice:
print "You approach some guy..."
some_guy()
else:
print "That's not a useful answer. Use a verb from above."
taco_room()
def some_guy():
print "some guy to talk to..."
def stuck(room):
print "I'm not sure what your saying. Try a verb from from above."
return room
def returner(why):
print why, "You got sent back to the beginning.\n"
starter()
def die(reason):
print reason, "you've been kicked out of these rooms all together."
exit(0)
def starter():
print "You're in a room of mystery, choices and decisions."
print "It's not a scary or harmful building."
print "Just difficult to get out of."
print "There's a door ahead of you, to the left and to the right."
print "Which door will you choose?"
print "Enter 1 to go through the door ahead of you."
print "Enter 2 to go through the door on the left."
print "Enter 3 to go through the door on the right."
choice = int(raw_input(prompt))
if choice == 1:
panda_room()
elif choice == 2:
unicorn_room()
elif choice == 3:
cute_cat_room()
else:
print "You need to input 1, 2, or 3, and press enter."
starter()
<file_sep>from sys import argv
script, input_file = argv # unpack arguments
def print_all(f):
print f.read() # takes f as param, reads f
def rewind(f):
f.seek(0) # resets the file scanning to the beginning of the file
def print_a_line(line_count, f):
print line_count, f.readline() # prints a line count, and line from f
current_file = open(input_file) # sets a variable to open input file at execution
print "First let's print the whole line:\n" # just a print statement
print_all(current_file) # Takes current file, reads and prints it
print "Now let's rewind, kind of like a tape." # just a print statement
rewind(current_file) # Take the current file, and reset to beginning of file
print "Let's print three lines:" # print statement
current_line = 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
'''
Honest, the next part just set a counter on current_line, runs
print_a_line, which prints the current line number and value
'''
<file_sep>people = 30
cars = 40
trucks = 15
# checks to see if cars are greater than people
if cars > people:
print "We should take the cars."
# if cars are less than people
elif cars < people:
print "We should not take the cars."
# if cars are not greater than or less than people
else:
print "We can't decide."
# checks if trucks are greater than cars
if trucks > cars:
print "That's too many trucks."
# checks if trucks are less than people
elif trucks < cars:
print "Maybe we could take the trucks."
# if trucks are not greater or less than people
else:
print "We still can't decide."
# if people are greater than trucks, take trucks
if people > trucks:
print "Alright, let's just take the trucks."
# if people aren't greater than trucks, just stay home
else:
print "Fine, let's stay home then"
# if cars are great than people or trucks are less than people
if cars > people or trucks < cars:
print "Taking cars is easier, because it's easier to park"
# if cars aren't greater than people or trucks aren't less than cars
else:
print "Let's polute everything, yeehaw!"
<file_sep>from sys import argv
script, num1, num2, num3 = argv
print "This is the first thing:", num1
print "This is the second thing:", num2
print "This is the third thing:", num3
fourth = raw_input("What about the fourth thing?")
print "This is the fourth thing: %r " % fourth
<file_sep>print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()
print "So youre %r old, %r tall and %r heavy." % (
age, height, weight)
# Here comes another form, based on the study drills
prompt = '--> '
print "How's it going?",
going = raw_input(prompt)
print "How's the life?",
life = raw_input(prompt)
print "What's the news?",
news = raw_input(prompt)
print "It's going %s. Life is %s. Here's the news: %s." % (
going, life, news)
<file_sep>name = 'klp'
age = 35
height = 72 # inches
weight = 171 # lbs
eyes = 'Blue'
teeth = 'White'
hair = 'Blonde'
print "Let's talk about %s." % name
print "He's %d inches tall." % height
print "He's %d pounds heavy." % weight
print "Actually not too heavy."
print "He's got %s eyes and %s hair." % (eyes, hair)
print "His teeth are usually %s depending on the tea." % teeth
# This line is tricky, try to get it exactly right
print "If I add %d, %d and %d I get %d." % (
age, height, weight, age + height + weight)
# Convert weight and height to kilograms and centimeters
new_weight = weight * .453592
new_height = height * 2.54
print "%s's weight in kilograms is %d." % (name, new_weight)
print "%s's height in centimeters is %d." % (name, new_height)
| 58022478fc0b17cba8e5d6914e1793014d3c19d8 | [
"Markdown",
"Python"
] | 14 | Python | klpf/lpthw | 4e68c513165eca1508b3ef70f3e5b64f84336603 | 10ea9aad830993c6fd096c033eb1183703cfd05b |
refs/heads/master | <repo_name>ebonyash15/key-for-min-value-onl01-seng-pt-110319<file_sep>/key_for_min.rb
def key_for_min_value(name_hash)
return nil if name_hash.size == 0
array_key = []
array_value = []
name_hash.collect do |key, value|
array_value << value
array_key << key
end
values = array_value[0]
index = 0
while index < array_value.size do
if array_value[index] < values
values = array_value[index]
end
index +=1
end
ind = array_value.index(values)
array_key[ind]
end
| 134ba07d03e40952c5f885226d4b05c0925ff9fd | [
"Ruby"
] | 1 | Ruby | ebonyash15/key-for-min-value-onl01-seng-pt-110319 | a25e85e1242439d53d9aaa4f5ea7ffed8828e76b | 030e9c477ad90d0e2019f04d3f00918f86672dac |
refs/heads/master | <repo_name>DrgonMaster/apitestJava<file_sep>/src/main/java/com/niuguwang/test/apitestJava/model/InterfaceName.java
package com.niuguwang.test.apitestJava.model;
public enum InterfaceName {
LOGIN,getQuickSearch,addQuestion,getQuestionReplyByLittle, getUserStocks
}
<file_sep>/apitest.sql
# Host: localhost (Version: 5.5.56)
# Date: 2018-07-23 18:55:49
# Generator: MySQL-Front 5.3 (Build 4.13)
/*!40101 SET NAMES utf8 */;
#
# Source for table "addquestion"
#
DROP TABLE IF EXISTS `addquestion`;
CREATE TABLE `addquestion` (
`id` int(11) DEFAULT NULL,
`ownerIds` int(11) DEFAULT NULL,
`ownerNames` varchar(100) DEFAULT NULL,
`content` varchar(500) DEFAULT NULL,
`userToken` varchar(200) DEFAULT NULL,
`width` int(11) DEFAULT NULL,
`height` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
#
# Data for table "addquestion"
#
INSERT INTO `addquestion` VALUES (1,NULL,NULL,'海默科技关联板块','rdHRLzQgBQx_CEUM7qx7q6p25xyuMvu493iyb60IBdm-l3lVdrPS0Q**',744,545),(2,NULL,NULL,'业绩预增优质成长股','rdHRLzQgBQx_CEUM7qx7q6p25xyuMvu493iyb60IBdm-l3lVdrPS0Q**',744,545),(3,NULL,NULL,'连续三年净资产收益高的策略','rdHRLzQgBQx_CEUM7qx7q6p25xyuMvu493iyb60IBdm-l3lVdrPS0Q**',744,545),(4,NULL,NULL,'胜率最高策略','rdHRLzQgBQx_CEUM7qx7q6p25xyuMvu493iyb60IBdm-l3lVdrPS0Q**',744,545),(5,NULL,NULL,'上升趋势确定策略','rdHRLzQgBQx_CEUM7qx7q6p25xyuMvu493iyb60IBdm-l3lVdrPS0Q**',744,545),(6,NULL,NULL,'足球概念龙头','rdHRLzQgBQx_CEUM7qx7q6p25xyuMvu493iyb60IBdm-l3lVdrPS0Q**',744,545);
#
# Source for table "getquestionreplybylittle"
#
DROP TABLE IF EXISTS `getquestionreplybylittle`;
CREATE TABLE `getquestionreplybylittle` (
`id` int(11) DEFAULT NULL,
`questionId` int(11) DEFAULT NULL,
`userToken` varchar(500) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
#
# Data for table "getquestionreplybylittle"
#
INSERT INTO `getquestionreplybylittle` VALUES (1,1740714,'rdHRLzQgBQx_CEUM7qx7q6p25xyuMvu493iyb60IBdm-l3lVdrPS0Q**');
#
# Source for table "getquicksearch"
#
DROP TABLE IF EXISTS `getquicksearch`;
CREATE TABLE `getquicksearch` (
`id` int(11) DEFAULT NULL,
`pageIndex` int(11) DEFAULT NULL,
`pageSize` int(11) DEFAULT NULL,
`userToken` varchar(500) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
#
# Data for table "getquicksearch"
#
INSERT INTO `getquicksearch` VALUES (1,0,0,'rdHRLzQgBQx_CEUM7qx7q6p25xyuMvu493iyb60IBdm-l3lVdrPS0Q**'),(2,0,0,'rdHRLzQgBQx_CEUM7qx7q6p25xyuMvu493iyb60IBdm-l3lVdrPS0Q**'),(3,0,0,'rdHRLzQgBQx_CEUM7qx7q6p25xyuMvu493iyb60IBdm-l3lVdrPS0Q**');
#
# Source for table "getuserstocks"
#
DROP TABLE IF EXISTS `getuserstocks`;
CREATE TABLE `getuserstocks` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`usertoken` varchar(255) DEFAULT NULL,
`auto` int(11) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
#
# Data for table "getuserstocks"
#
INSERT INTO `getuserstocks` VALUES (1,'rdHRLzQgBQx_CEUM7qx7q6p25xyuMvu493iyb60IBdm-l3lVdrPS0Q**',1);
#
# Source for table "login"
#
DROP TABLE IF EXISTS `login`;
CREATE TABLE `login` (
`id` int(11) DEFAULT NULL,
`username` char(100) DEFAULT NULL,
`password` char(100) DEFAULT NULL,
`loginType` int(11) DEFAULT NULL,
`deviceid` int(11) DEFAULT NULL,
`company` char(20) DEFAULT NULL,
`expected` varchar(1024) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
#
# Data for table "login"
#
INSERT INTO `login` VALUES (1,'13311151061','lj123456',1,2,'1','登录成功'),(2,'13231408948','123456',1,2,'1','用户名或密码错误'),(3,'\"\"','\"\"',1,2,'1','未设置密码,请用手机号和验证码登录'),(4,'13311151061',NULL,NULL,NULL,NULL,'参数错误'),(5,'13331111','lJ123456',NULL,NULL,NULL,'用户名或密码错误'),(6,'hebeiliujin','<PASSWORD>',1,2,'1','登录成功'),(7,'asdfghjklqwertyuiopasdfghjkllzxcvbnmklhjfdswwwww','1234567890poiuytrewqasdfghjkl',NULL,NULL,NULL,'参数错误');
<file_sep>/src/main/java/com/niuguwang/test/apitestJava/model/GetQuestionReplybyLittle.java
package com.niuguwang.test.apitestJava.model;
public class GetQuestionReplybyLittle {
private int questionId;
private String userToken;
public GetQuestionReplybyLittle() {
super();
// TODO Auto-generated constructor stub
}
public GetQuestionReplybyLittle(int questionId, String userToken) {
this.questionId = questionId;
this.userToken = userToken;
}
public final int getQuestionId() {
return questionId;
}
public final void setQuestionId(int questionId) {
this.questionId = questionId;
}
public final String getUserToken() {
return userToken;
}
public final void setUserToken(String userToken) {
this.userToken = userToken;
}
@Override
public String toString() {
return "GetQuestionReplybyLittle [questionId=" + questionId + ", userToken=" + userToken + "]";
}
}
<file_sep>/src/main/java/com/niuguwang/test/apitestJava/cases/GetQuestionReplybyLittleTest.java
package com.niuguwang.test.apitestJava.cases;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.session.SqlSession;
import org.bson.json.JsonMode;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.niuguwang.test.apitestJava.config.TestConfig;
import com.niuguwang.test.apitestJava.model.GetQuestionReplybyLittle;
import com.niuguwang.test.apitestJava.model.InterfaceName;
import com.niuguwang.test.apitestJava.utils.ConfigFile;
import com.niuguwang.test.apitestJava.utils.DatabaseUtil;
public class GetQuestionReplybyLittleTest {
private String url;
SqlSession sqlSession;
@BeforeTest
public void beforetest() throws IOException {
url = ConfigFile.getUrl(InterfaceName.getQuestionReplyByLittle);
sqlSession = DatabaseUtil.getSqlSession();
}
@Test(description="通过问题的内容获取诊股答案")
public void getQuestionReplaybyLittle() throws ClientProtocolException, IOException{
GetQuestionReplybyLittle getQuestionReplybyLittle = sqlSession.selectOne("getQuestionReplaybyLittle",1 );
String resault = getResault(getQuestionReplybyLittle);
JSONObject parse = JSON.parseObject(resault);
String rs = parse.getString("message");
Reporter.log("接口地址:"+url);
Reporter.log("请求参数:"+getQuestionReplybyLittle.toString());
Assert.assertEquals(rs, "获取成功");
}
public String getResault(GetQuestionReplybyLittle getQuestionReplybyLittle) throws ClientProtocolException, IOException{
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("content-type","application/x-www-form-urlencoded; charset=utf-8");
post.setHeader("packtype","1");
post.setHeader("s","_test");
post.setHeader("version","3.9.1");
post.setHeader("night","1");
ArrayList<NameValuePair> list =new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("questionId", Integer.toString(getQuestionReplybyLittle.getQuestionId())));
list.add(new BasicNameValuePair("userToken", getQuestionReplybyLittle.getUserToken()));
post.setEntity(new UrlEncodedFormEntity(list,"utf-8"));
HttpResponse rp = defaultHttpClient.execute(post);
String resault = EntityUtils.toString(rp.getEntity());
return resault;
}
}
<file_sep>/test-output/old/牛股王app接口/testname.properties
[SuiteResult context=testname][SuiteResult context=智能诊股]<file_sep>/target/classes/application.properties
test.user.url=https://user.niuguwang.com
login.uri=/api/login.ashx
getQuickSearch.uri=/AskStock/getQuickSearch.ashx
addQuestion.uri=/AskStock/addQuestion.ashx
getQuestionReplyByLittle.uri=/AskStock/getQuestionReplyByLittle.ashx
test.shq.url=https://shq.niuguwang.com
getUserStocks.uri=/aquote/userdata/getuserstocks_v180531.ashx
<file_sep>/src/main/java/com/niuguwang/test/apitestJava/utils/PrintTestInfo.java
package com.niuguwang.test.apitestJava.utils;
import org.testng.Reporter;
import com.niuguwang.test.apitestJava.config.TestConfig;
public class PrintTestInfo {
public static void printRequestinfo(String requestUrl,String requestparameters){
Reporter.log("请求接口地址:"+requestUrl);
Reporter.log("请求参数:"+requestparameters);
}
}
<file_sep>/src/main/java/com/niuguwang/test/apitestJava/cases/LoginTest.java
package com.niuguwang.test.apitestJava.cases;
import java.awt.List;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.session.SqlSession;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.niuguwang.test.apitestJava.config.TestConfig;
import com.niuguwang.test.apitestJava.model.AddQuestionCase;
import com.niuguwang.test.apitestJava.model.GetQuestionReplybyLittle;
import com.niuguwang.test.apitestJava.model.GetQuickSearchCase;
import com.niuguwang.test.apitestJava.model.InterfaceName;
import com.niuguwang.test.apitestJava.model.LoginCase;
import com.niuguwang.test.apitestJava.utils.ConfigFile;
import com.niuguwang.test.apitestJava.utils.DatabaseUtil;
public class LoginTest{
@BeforeTest
public void beforeTest(){
TestConfig.defaultHttpClient = new DefaultHttpClient();
TestConfig.loginUrl = ConfigFile.getUrl(InterfaceName.LOGIN);
System.out.println("执行测试前内容");
}
@Test(groups = "loginTrue",description = "使用手机号登录,用户名正确,密码正确")
public void loginTrue() throws IOException {
SqlSession session = DatabaseUtil.getSqlSession();
LoginCase loginCase = session.selectOne("loginCase",1);
//执行测试,获取返回
String result = getResult(loginCase);
JSONObject pjo =JSON.parseObject(result);
String message =pjo.getString("message");
//获取用户userinfo信息,取得usertoken
String usertoken = pjo.getJSONObject("userInfo").getString("userToken");
//将usertoken存储到getquickserchtest的表中
GetQuickSearchCase getQuickSearchCase = new GetQuickSearchCase(1, -1, -1, usertoken);
//将usertoken添加到addquestion表
AddQuestionCase addQuestionCase = new AddQuestionCase(0, 0, "", "",usertoken, 0, 0);
session.update("updateaddquestionusertoken", addQuestionCase);
//将usertoken添加到getquestionreplybylittle表中
GetQuestionReplybyLittle getQuestionReplybyLittle = new GetQuestionReplybyLittle(-1, usertoken);
session.update("updateusertokenbyLittle", getQuestionReplybyLittle);
//从数据库中获得预期结果,和实际返回结果对比
Reporter.log("请求接口地址:"+TestConfig.loginUrl);
Reporter.log("请求参数:"+loginCase.toString());
session.update("updateusertoken", getQuickSearchCase);
Assert.assertEquals(loginCase.getExpected(),message);
}
@Test(groups = "loginTrue",description = "使用用户名登录,用户名正确,密码错误")
public void loginTrue01() throws IOException {
SqlSession session = DatabaseUtil.getSqlSession();
LoginCase loginCase = session.selectOne("loginCase",6);
//执行测试,获取返回
String result = getResult(loginCase);
JSONObject pjo =JSON.parseObject(result);
String message =pjo.getString("message");
Reporter.log("请求接口地址:"+TestConfig.loginUrl);
Reporter.log("请求参数:"+loginCase.toString());
Assert.assertEquals(loginCase.getExpected(),message);
}
@Test(groups = "loginfalse",description = "用户名正确,密码错误")
public void loginFalse() throws IOException {
SqlSession session = DatabaseUtil.getSqlSession();
LoginCase loginCase = session.selectOne("loginCase",2);
String result = getResult(loginCase);
JSONObject pjo =JSON.parseObject(result);
String message =pjo.getString("message");
//从数据库中获得预期结果,和实际返回结果对比
Reporter.log("请求接口地址:"+TestConfig.loginUrl);
Reporter.log("请求参数:"+loginCase.toString());
Assert.assertEquals(loginCase.getExpected(),message);
}
@Test(groups = "loginfalse",description = "用户名为空,密码为空")
public void loginFalse01() throws IOException {
SqlSession session = DatabaseUtil.getSqlSession();
LoginCase loginCase = session.selectOne("loginCase",3);
String result = getResult(loginCase);
JSONObject pjo =JSON.parseObject(result);
String message =pjo.getString("message");
//从数据库中获得预期结果,和实际返回结果对比
Reporter.log("请求接口地址:"+TestConfig.loginUrl);
Reporter.log("请求参数:"+loginCase.toString());
Assert.assertEquals(loginCase.getExpected(),message);
}
@Test(groups = "loginfalse",description = "用户名正确,密码错误")
public void loginFalse02() throws IOException {
SqlSession session = DatabaseUtil.getSqlSession();
LoginCase loginCase = session.selectOne("loginCase",4);
String result = getResult(loginCase);
JSONObject pjo =JSON.parseObject(result);
String message =pjo.getString("message");
//从数据库中获得预期结果,和实际返回结果对比
Reporter.log("请求接口地址:"+TestConfig.loginUrl);
Reporter.log("请求参数:"+loginCase.toString());
Assert.assertEquals(loginCase.getExpected(),message);
}
@Test(groups = "loginfalse",description = "用户名错误,密码正确")
public void loginFalse03() throws IOException {
SqlSession session = DatabaseUtil.getSqlSession();
LoginCase loginCase = session.selectOne("loginCase",5);
String result = getResult(loginCase);
JSONObject pjo =JSON.parseObject(result);
String message =pjo.getString("message");
//从数据库中获得预期结果,和实际返回结果对比
Reporter.log("请求接口地址:"+TestConfig.loginUrl);
Reporter.log("请求参数:"+loginCase.toString());
Assert.assertEquals(loginCase.getExpected(),message);
}
@Test(groups = "loginfalse",description = "用户名错误,密码正确")
public void loginFalse04() throws IOException {
SqlSession session = DatabaseUtil.getSqlSession();
LoginCase loginCase = session.selectOne("loginCase",7);
String result = getResult(loginCase);
JSONObject pjo =JSON.parseObject(result);
String message =pjo.getString("message");
//从数据库中获得预期结果,和实际返回结果对比
Reporter.log("请求接口地址:"+TestConfig.loginUrl);
Reporter.log("请求参数:"+loginCase.toString());
Assert.assertEquals(loginCase.getExpected(),message);
}
private String getResult(LoginCase loginCase) throws IOException {
//新建post请求对象
HttpPost post = new HttpPost(TestConfig.loginUrl);
//设置header信息
post.setHeader("content-type","application/x-www-form-urlencoded; charset=utf-8");
post.setHeader("packtype","1");
post.setHeader("s","_test");
post.setHeader("version","3.9.1");
post.setHeader("night","1");
/*json格式发送请求
* JSONObject param = new JSONObject();
param.put("userName", loginCase.getUsername());
param.put("password",<PASSWORD>());
param.put("loginType",loginCase.getLoginTyte());
param.put("deviceid",loginCase.getDeviceid());
param.put("company",loginCase.getCompany());
//设置编码格式,发送post请求
StringEntity entity = new StringEntity(param.toString(),"utf-8");
post.setEntity(entity);*/
ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
NameValuePair pair1 = new BasicNameValuePair("userName", loginCase.getUsername());
NameValuePair pair2 = new BasicNameValuePair("password",<PASSWORD>.<PASSWORD>());
NameValuePair pair3 = new BasicNameValuePair("deviceid",loginCase.getDeviceid());
NameValuePair pair4 = new BasicNameValuePair("loginType",loginCase.getLoginTyte());
NameValuePair pair5 = new BasicNameValuePair("company",loginCase.getCompany());
pairs.add(pair1);
pairs.add(pair2);
pairs.add(pair3);
pairs.add(pair4);
pairs.add(pair5);
post.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
String result;
//获取请求返回结果
HttpResponse response = TestConfig.defaultHttpClient.execute(post);
//请求返回结果转换为字符串
result = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println("测试返回结果为"+result);
TestConfig.store = TestConfig.defaultHttpClient.getCookieStore();
return result;
}
}
<file_sep>/src/main/java/com/niuguwang/test/apitestJava/model/GetQuickSearchCase.java
package com.niuguwang.test.apitestJava.model;
import lombok.Data;
@Data
public class GetQuickSearchCase {
private int id;
private int pageIndex;
private int pageSize;
private String userToken;
public GetQuickSearchCase() {
super();
// TODO Auto-generated constructor stub
}
public GetQuickSearchCase(int id, int pageIndex, int pageSize, String userToken) {
this.id = id;
this.pageIndex = pageIndex;
this.pageSize = pageSize;
this.userToken = userToken;
}
public final int getId() {
return id;
}
public final void setId(int id) {
this.id = id;
}
public final int getPageIndex() {
return pageIndex;
}
public final void setPageIndex(int pageIndex) {
this.pageIndex = pageIndex;
}
public final int getPageSize() {
return pageSize;
}
public final void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public final String getUserToken() {
return userToken;
}
public final void setUserToken(String userToken) {
this.userToken = userToken;
}
@Override
public String toString() {
return "GetQuickSearchCase [id=" + id + ", pageIndex=" + pageIndex + ", pageSize=" + pageSize + ", userToken="
+ userToken + "]";
}
}
<file_sep>/test-output/old/牛股王app接口/注册登录.properties
[SuiteResult context=注册登录][SuiteResult context=智能诊股][SuiteResult context=自选股] | c597a3ab9a44b56b96ca6609a87ca54084c80d39 | [
"Java",
"SQL",
"INI"
] | 10 | Java | DrgonMaster/apitestJava | 3a5dbc681f6ef2f96709271828875cb79b72aeaf | 7f91443b40eaa6f099d63beb06e18f01b4752d90 |
refs/heads/master | <repo_name>beomont/KOTLIN-Collections-Arrays-Lists<file_sep>/settings.gradle
rootProject.name = "PrimeirosPassos"
include ':app'
<file_sep>/app/src/main/java/com/example/primeirospassos/TestList.kt
package com.example.primeirospassos
fun main() {
val joao = Funcionario("Joao", 2000.0, "CLT")
val pedro = Funcionario("Pedro", 1500.0, "PJ")
val maria = Funcionario("Maria", 4000.0, "CLT")
val funcionarios = listOf(joao, pedro, maria)
funcionarios.forEach{ println(it) }
println("---------------------------")
println(funcionarios.find {it.nome== "Maria"})
println("---------------------------")
funcionarios.sortedBy { it.salario }.forEach{ println(it) } //Coleta a lista de forma organizada
println("---------------------------")
funcionarios.groupBy { it.tipoContrato }.forEach{ println(it) } //Agrupa os tipos de contatos dos funcionários de forma organizada
}
<file_sep>/app/src/main/java/com/example/primeirospassos/TesteDoubleArrays.kt
package com.example.primeirospassos
fun main() {
val salarios = doubleArrayOf(1000.00, 2250.0, 4000.0)
for (salario in salarios){
println(salario)
}
println("----------------------")
println("Maior salario: ${salarios.maxOrNull()}")
println("Menor salario: ${salarios.minOrNull()}")
println("Media salarial: ${salarios.average()}")
val salariosMaiorQue2500 = salarios.filter { it>2500.0 }
println("-----------------------")
salariosMaiorQue2500.forEach{println(it)}
println("-----------------------")
println(salarios.count{ it in 2000.0..5000.0})
println("-----------------------")
println(salarios.find{ it == 2250.0})
println(salarios.find{ it == 250.0})
println("-----------------------")
println(salarios.any{ it == 1000.00})
println(salarios.any{ it == 100.00})
} | 7a29609793960ce7e965776283c2d4d37fc2a020 | [
"Kotlin",
"Gradle"
] | 3 | Gradle | beomont/KOTLIN-Collections-Arrays-Lists | 05d8c2bc325020bc6ad8328d9f86ecbfb3a8ad4c | 081a2a893a14abd568087f079d634558907feb42 |
refs/heads/master | <file_sep>package com.baggins.frodo.lib.datasource.dao;
import android.content.Context;
import com.baggins.frodo.lib.datasource.db.LocalDbHelper;
import com.baggins.frodo.lib.datasource.dto.CategoryDTO;
import com.baggins.frodo.lib.datasource.dto.TodoDTO;
import com.baggins.frodo.lib.domain.Category;
import com.baggins.frodo.lib.domain.Todo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by ZachS on 1/10/2016.
*/
public class PortalDAO {
public static Map<Category, Todo> getTodos(Context context) {
TodoDAO todoDao = new TodoDAO(context);
CategoryDAO categoryDAO = new CategoryDAO(context);
Map<Category, Todo> categoryTodoMap = new HashMap<>();
List<TodoDTO> todoDTOs = todoDao.get();
List<CategoryDTO> categoryDTOs = categoryDAO.get();
for (TodoDTO dto : todoDTOs) {
Category cat = getCategory(dto.getCategoryId(), categoryDTOs);
Todo todo = new Todo( dto.getId(), dto.getTodo(), cat, dto.getCreatedAt());
categoryTodoMap.put(cat, todo);
}
return categoryTodoMap;
}
private static Category getCategory(int catId, List<CategoryDTO> dtos) {
for (CategoryDTO dto : dtos) {
if (dto.getId() == catId) {
return new Category(dto.getId(), dto.getCategoryName());
}
}
return new Category();
}
public static List<Category> getCategories(Context context) {
CategoryDAO categoryDAO = new CategoryDAO(context);
List<CategoryDTO> dtos = categoryDAO.get();
List<Category> categories = new ArrayList<>();
for (CategoryDTO dto : dtos) {
Category cat = new Category(dto.getId(), dto.getCategoryName());
categories.add(cat);
}
return categories;
}
public static Todo insertTodo(Context context, TodoDTO todoDTO) {
TodoDAO todoDAO = new TodoDAO(context);
CategoryDAO categoryDAO = new CategoryDAO(context);
List<CategoryDTO> dtos = categoryDAO.get();
TodoDTO inserted = todoDAO.insert(todoDTO);
return new Todo(inserted.getId(), inserted.getTodo(),
getCategory(inserted.getCategoryId(), dtos), inserted.getCreatedAt());
}
public static Category insertCategory(Context context, CategoryDTO categoryDTO) {
CategoryDAO categoryDAO = new CategoryDAO(context);
CategoryDTO inserted = categoryDAO.insert(categoryDTO);
return new Category(inserted.getId(), inserted.getCategoryName());
}
public static Todo insertCategoryAndTodo(Context context, TodoDTO todoDTO, CategoryDTO categoryDTO) {
CategoryDAO categoryDAO = new CategoryDAO(context);
TodoDAO todoDAO = new TodoDAO(context);
CategoryDTO insertedCat = categoryDAO.insert(categoryDTO);
todoDTO.setCategoryId(insertedCat.getId());
TodoDTO insertedTodo = todoDAO.insert(todoDTO);
return new Todo(insertedTodo.getId(), insertedTodo.getTodo(), new Category(insertedCat.getId(),
insertedCat.getCategoryName()), insertedTodo.getCreatedAt());
}
public static void deleteCategory(Context context, CategoryDTO categoryDTO) {
CategoryDAO categoryDAO = new CategoryDAO(context);
TodoDAO todoDAO = new TodoDAO(context);
todoDAO.delete(LocalDbHelper.CATEGORY_ID + " = ?",
new String[]{String.valueOf(categoryDTO.getId())});
categoryDAO.delete(LocalDbHelper.CATEGORY_ID + " = ?",
new String[]{String.valueOf(categoryDTO.getId())});
}
public static void deleteTodo(Context context, TodoDTO todoDTO) {
TodoDAO todoDAO = new TodoDAO(context);
todoDAO.delete(LocalDbHelper.TODO_ID + " = ?",
new String[]{String.valueOf(todoDTO.getId())});
}
public static TodoDTO updateTodo(Context context, TodoDTO todoDTO) {
TodoDAO todoDAO = new TodoDAO(context);
return todoDAO.update(todoDTO);
}
public static CategoryDTO updateCategory(Context context, CategoryDTO categoryDTO) {
CategoryDAO categoryDAO = new CategoryDAO(context);
return categoryDAO.update(categoryDTO);
}
}
<file_sep>package com.baggins.frodo.lib.domain;
/**
* Created by ZachS on 1/10/2016.
*/
public class Category {
private static final String DefaultCategoryName = "Default";
private int mId;
private String mCategoryName;
public Category() {
this(DefaultCategoryName);
}
public Category(String categoryName) {
this(-1, categoryName);
}
public Category(int id, String categoryName) {
mId = id;
mCategoryName = categoryName;
}
}
<file_sep>package com.baggins.frodo.lib.datasource.dto;
/**
* Created by ZachS on 1/10/2016.
*/
public abstract class BaseDTO {
public abstract int getId();
}
<file_sep>package com.baggins.frodo.lib.domain;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* Created by ZachS on 1/10/2016.
*/
public class Todo {
private int mId;
private Category mCategory;
private boolean mComplete;
private String mTodo;
private Date mCreatedAt;
public Todo() {
this("");
}
public Todo(String todo) {
this(todo, new Category());
}
public Todo(String todo, Category category) {
this( -1, todo, category);
}
public Todo(int id, String todo, Category category) {
this(id, todo, category, Calendar.getInstance().getTime());
}
public Todo(int id, String todo, Category category, Date date) {
mId = id;
mCategory = category;
mComplete = false;
mTodo = todo;
mCreatedAt = date;
}
}
| 89d5c3e1bc257423fe87f324b5a98da6ef7fe49d | [
"Java"
] | 4 | Java | zsogolow/Todo | 640f2daabc851ea92b6fc4daffb2c9a0b3f7ee5a | 9ae2984625fa191ed9afbb34158436475d9bdb31 |
refs/heads/master | <repo_name>Evgen1337/WaterApp<file_sep>/WaterHistoryApp/Controllers/TableController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WaterHistoryApp.Models; // пространство имен WaterContext
namespace WaterHistoryApp.Controllers
{
/// <summary>
/// Контроллер для работы с таблицой
/// </summary>
public class TableController : Controller
{
/// <summary>
/// База данных
/// </summary>
WaterContext db;
/// <summary>
/// Конструктор контроллера таблицы
/// </summary>
/// <param name="context"></param>
public TableController(WaterContext context)
{
db = context;
}
/// <summary>
/// Get метод, принимающий дату
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult HistoryTableDate()
{
return View();
}
/// <summary>
/// Post метод, отображающий таблицу с данными, если они есть за выбраную дату
/// Иначе отображает таблицу с полями для ввода
/// </summary>
/// <returns></returns>
[HttpPost]
public IActionResult HistoryTable(DateTime date)
{
var tableDate = db.Histories.FirstOrDefault(d => d.DateTime.Date == date.Date);
if (tableDate == null)
{
History history = new History();
history.DateTime = date;
ViewBag.DateTime = date;
return View("~/Views/Table/HistoryNew.cshtml", history);
}
ViewBag.DateTime = date;
return View(tableDate);
}
/// <summary>
/// Post метод, для заполнения таблицы новыми значениями и сохранием в бд
/// </summary>
/// <returns></returns>
[HttpPost]
public IActionResult HistoryNew(History history)
{
db.Histories.Add(history);
db.SaveChanges();
ViewBag.DateTime = history;
return View("~/Views/Table/HistoryTable.cshtml", history);
}
/// <summary>
/// Post метод, для отображения таблицы с полями для изменения
/// </summary>
/// <returns></returns>
[HttpPost]
public IActionResult TableEdit(History history)
{
ViewBag.DateTime = history.DateTime;
return View("~/Views/Table/TableEdit.cshtml", history);
}
/// <summary>
/// Post метод, для изменения данных и сохранения в бд
/// и отображения таблицы с новыми данными
/// </summary>
/// <returns></returns>
[HttpPost]
public IActionResult HistoryTableEdit(History history)
{
db.Histories.Update(history);
db.SaveChanges();
ViewBag.DateTime = history.DateTime;
return View("~/Views/Table/HistoryTable.cshtml", history);
}
}
}<file_sep>/WaterHistoryApp/Controllers/GraphController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WaterHistoryApp.Models; // пространство имен WaterContext
namespace WaterHistoryApp.Controllers
{
/// <summary>
/// Контроллер для работы с графиком
/// </summary>
public class GraphController : Controller
{
/// <summary>
/// База данных
/// </summary>
WaterContext db;
/// <summary>
/// Конструктор контроллера графика
/// </summary>
/// <param name="context"></param>
public GraphController(WaterContext context)
{
db = context;
}
/// <summary>
/// Get метод, принимающий дату для отображения графика
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult GraphDate()
{
return View();
}
/// <summary>
/// Post метод, отображающий график при наличии данных за выбраный месяц
/// eсли их нет - отображает страницу с предупреждением
/// </summary>
/// <returns></returns>
[HttpPost]
public IActionResult Graph(DateTime date)
{
var dateGraph = db.Histories.Where(h => h.DateTime.Month == date.Date.Month && h.DateTime.Year == date.Date.Year).OrderBy(d => d.DateTime);
if (dateGraph.Count() == 0)
{
return View("~/Views/Graph/GraphNull.cshtml");
}
ViewBag.DateTime = date;
ViewBag.Quantity = dateGraph.Select(s => s.Quantity);
ViewBag.Dates = dateGraph.Select(s => s.DateTime);
return View("~/Views/Graph/Graph.cshtml", dateGraph);
}
}
}
<file_sep>/WaterHistoryApp/Models/History.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WaterHistoryApp.Models
{
/// <summary>
/// Модель класса History
/// Поля: int HistoryId, string Name, string Season, string NumberEmployees,
/// string DayWeek, string PreviouDay, string TimeDelivery, string NumberPumps,
/// string NumberRepeir, string Vending, string WorkingHours, string UncertainReasons,
/// string TemperatureConditions, int Quantity, DateTime DateTime
/// </summary>
public class History
{
public int HistoryId { get; set; }
public string Season { get; set; }
public string NumberEmployees { get; set; }
public string DayWeek { get; set; }
public string PreviouDay { get; set; }
public string TimeDelivery { get; set; }
public string NumberPumps { get; set; }
public string NumberRepeir { get; set; }
public string Vending { get; set; }
public string WorkingHours { get; set; }
public string UncertainReasons { get; set; }
public string TemperatureConditions { get; set; }
public int Quantity { get; set; }
public DateTime DateTime { get; set; }
}
}
<file_sep>/WaterHistoryApp/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using WaterHistoryApp.Models; // пространство имен WaterContext
namespace WaterHistoryApp.Controllers
{
/// <summary>
/// Контроллер для отображения главной страницы
/// </summary>
public class HomeController : Controller
{
/// <summary>
/// Возвращает главную страницу
/// </summary>
public IActionResult Index()
{
return View("Index");
}
}
}
<file_sep>/WaterHistoryApp/Models/WaterContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace WaterHistoryApp.Models
{
public class WaterContext : DbContext
{
/// <summary>
/// Модель класса History
/// Поля: int HistoryId, string Name, string Season, string NumberEmployees,
/// string DayWeek, string PreviouDay, string TimeDelivery, string NumberPumps,
/// string NumberRepeir, string Vending, string WorkingHours, string UncertainReasons,
/// string TemperatureConditions, int Quantity, DateTime DateTime
/// </summary>
public virtual DbSet<History> Histories { get; set; }
/// <summary>
/// Конструктор WaterContext с аргументом DbContextOptions<WaterContext>
/// </summary>
public WaterContext(DbContextOptions<WaterContext> options)
: base(options)
{
Database.EnsureCreated();
}
}
}
| b21fb36690a965da04d9871b4c928fb987b7bbd3 | [
"C#"
] | 5 | C# | Evgen1337/WaterApp | 820997f130092f5cc3ff57054f017a4cd56106bd | 92a31bb97bc24c02b2ce21a0161cbac9e4f7fe92 |
refs/heads/master | <file_sep>#!/bin/bash
set -euo pipefail
IFS=$'\n\t'
if [[ $# -lt 1 ]]; then
echo "Provide the project root as the first argument. (No first argument)" 1>&2
exit 1
fi
if [[ ! -f $1/index.js ]]; then
echo "Provide the project root as the first argument. (first arg: '$1')" 1>&2
exit 1
fi
project_root=$1
zip -r $project_root/lambda.zip $project_root/package.json $project_root/AlexaSkill.js $project_root/index.js $project_root/lib $project_root/node_modules
echo "Now you can upload your $project_root/lambda.zip"
echo "try: https://us-west-2.console.aws.amazon.com/lambda/home"
<file_sep>var request = require('request');
var ENDPOINT = 'https://www.tastekid.com/api/similar?k=244644-SocialBo-QYEURQG0&type=movies&q=';
var MAX_RESULTS = 6;
function getMovieRecomendations (movieTitles, errCb, cb) {
function joinTitles(titles) {
if (titles.length === 0) return "";
if (titles.length === 1) return titles[0];
return titles[0] + "," + joinTitles(titles.slice(1));
}
function normalizeTitles(titles){
var dict = {};
for (var i = 0; i< titles.length; i++)
{
dict[titles[i]] = null;
}
return dict;
}
var normalTitles = normalizeTitles(movieTitles);
var joinedTitles = joinTitles(Object.getOwnPropertyNames(normalTitles));
return request(ENDPOINT + joinedTitles, function(error, resp, body) {
if (error) {errCb (error); return;}
if (resp.statusCode !== 200 ) {
errCb ("Bad status: " + resp.statusCode + "(url: " + ENDPOINT + joinedTitles + ")");
return;
}
var respobj = JSON.parse(body);
if (!respobj) {errCb("No response"); return;}
if (!respobj.Similar ||
!respobj.Similar.Results ||
typeof respobj.Similar.Results.map !== 'function' ||
respobj.Similar.Results.some(function (e) {return typeof e.Name !== 'string';})) {
errCb("Bad resp format: " + body);
return;
}
cb(respobj.Similar.Results.map(function (m) {return m.Name;}));
});
};
var AlexaSkill = require('./AlexaSkill');
var APP_ID = undefined;
function Recommender () {
AlexaSkill.call(this, APP_ID);
}
Recommender.prototype = Object.create(AlexaSkill.prototype);
Recommender.prototype.constructor = Recommender;
Recommender.prototype.eventHandlers.onLaunch = function (launchRequest, session, response) {
response.ask("Welcome to Tastekid alexa integration!",
"Tell me a movie you like. I will recommend some for you");
};
Recommender.prototype.eventHandlers.onSessionStarted = function (sessionStartedRequest, session) {};
Recommender.prototype.eventHandlers.onSessionEnded = function (sessionEndedRequest, session) {};
function ssml(str) {
return {
type: "SSML",
speech: "<speak>" + str + "</speak>"
};
}
function respond (session, response) {
if (!session.attributes.movies || session.attributes.movies.length === 0) {
response.ask(ssml("What movies are you in the mood for?"),
"Give me an example.");
return;
}
session.attributes.max_results = session.attributes.max_results || 6;
getMovieRecomendations(session.attributes.movies, function (err) {
console.error("ERROR:", err);
session.attributes.movies = [];
response.ask("An error occured...", "Let's try from scratch!");
}, function (recommendations) {
recommendations = recommendations.slice(0, session.attributes.max_results);
console.log("Found recommendations:", recommendations);
var resp = ssml("I recomend <break strength=\"x-weak\"/>" +
movieListToString(recommendations.slice(0, MAX_RESULTS),
",or,"));
response.ask(resp, "Hit me with more!");
});
}
function movieListToString (movies, connectingWord) {
if (movies.length === 0) return "no movies";
if (movies.length === 1) return movies[0];
connectingWord = " " + (connectingWord || "or") + " ";
if (movies.length === 2) return movies[0] + connectingWord + movies[1];
var last2 = movies.slice(-2),
final = last2[0] + connectingWord + last2[1];
return movies.slice(0,-2).reverse().reduce(
function (ret, x) {return x + ', ' + ret;}, final);
}
function forgetMovie (movie, session, response) {
if (!session.attributes.movies) session.attributes.movies = [];
session.attributes.movies =
session.attributes.movies.filter(function (m) {
return movie != m;
});
report (session, response);
}
function putMovie (movie, session, response) {
if (!session.attributes.movies) session.attributes.movies = [];
session.attributes.lastMovie = movie;
session.attributes.movies.push(movie);
}
function report (session, response) {
if (!session.attributes.movies || session.attributes.movies.length === 0){
response.ask(ssml("You haven't told me about any movies you like"),
"Tell me a movie you are in the mood for.");
return;
}
var result = ssml("So far you said you like <break strength=\"x-weak\"/>" +
movieListToString(session.attributes.movies, ",and,"));
response.ask(result, "What now?");
}
function loggedIntents(dict) {
var ret = {};
Object.getOwnPropertyNames(dict).forEach(function (n) {
ret[n] = function (i,s,r) {
console.log("Intent:", n);
return dict[n].call(this,i,s,r);
};
});
return ret;
}
Recommender.prototype.intentHandlers = loggedIntents({
AddReferenceMovie: function (intent, session, response) {
putMovie(intent.slots.Movie.value, session, response);
respond(session, response);
},
GetReferences: function (intent, session, response) {
report(session, response);
},
RemoveReferenceMovie: function (intent, session, response) {
forgetMovie(intent.slots.Movie.value, session, response);
respond(session, response);
},
ResetReferenceMovies: function (intent, session, response) {
session.attributes.movies = [];
response.ask("Done!", "Let's start again");
},
RemoveLastReference: function (intent, session, response) {
forgetMovie(session.attributes.lastMovie, session, response);
respond(session, response);
},
RepeatSuggestions: function (intent, session, response) {
console.log("Repeat suggestions");
respond(session, response);
},
EndSession: function (intent, session, response) {
console.log("Ending session.");
response.tell("See you later");
},
// AMAZON INTENTS
"AMAZON.StopIntent": function (intent, session, response) {
response.tell("Come again!");
}
});
exports.handler = function (event, context, callback) {
var recommender = new Recommender();
recommender.execute(event, context);
};
<file_sep># Alexa integration for tastekid
To make the zip just
npm run zip
And upload it to lambda.
# Voice Service Examples
# Intents
- `AddReferenceMovie` Add more reference.
- `GetReferences` Ask what movies we have so far.
- `RemoveReferenceMovie` Remove movies (scratch {movie}/forget about
{movie}/forget {movie}).
- `ResetReferenceMovies` Reset (forget everything/let's start again)
- `RemoveLastReference` Remove last movie (scratch that)
- `RepeatSuggestions` Repeat movies (come again)
- `EndSession` End session (thanks/that's it/that would be it)
# Setup Alexa Voice Service at developers.amazon.com
## Skill Information
- Name: MovieBlend
- Invocation Name: movie blend
# Interaction Model
- Intent Schemas: [Source](schema/intents.json)
- Custom Slot Types: Type: Movies - [Values](schemas/custom_slot_types.txt)
- Sample Utterances: [Source](schema/utterences.txt)
# Configuration
- Endpoint Type: AWS Lambda ARN (Amazon Resource Name) | North America
- ARN: Your custom ARN lambda function
| cc317650aeb5f56fc58cf9dbc5c600d4973d38a1 | [
"JavaScript",
"Markdown",
"Shell"
] | 3 | Shell | aeroniero33/MovieBlend | 861d23435ed906f71257666d133fcdede1d1aa4c | 7be73a75c929558a13aa01fe8fbbd32c522d76a0 |
refs/heads/master | <file_sep>const ws = require('nodejs-websocket');
const server = ws.createServer(function(conn){
conn.on('text',function(str){
if (JSON.parse(str).type=='sign') {
conn.nickName = JSON.parse(str).name;
users(conn);
boardcast("<span>系统消息</span>["+JSON.parse(str).name+"] 加入房间","chat")
} else if(JSON.parse(str).type=='chat'){
boardcast("<span>["+conn.nickName+"] </span>"+JSON.parse(str).content,"chat",conn)
}
})
conn.on('close',function(data){
boardcast("<span>系统消息</span>["+conn.nickName+"] 离开了房间","chat");
users(conn);
})
conn.on('error',function(errs){
console.log(errs)
})
}).listen(3333);
function boardcast(str,type,self){
if (type=='chat') {
server.connections.forEach(function(item){
if (self&&item==self) {
item.sendText(JSON.stringify({type:type,msg:str,belong:true}))
} else{
item.sendText(JSON.stringify({type:type,msg:str}))
}
})
} else{
}
}
function users(){
server.connections.forEach(function(item){
item.sendText(JSON.stringify({type:'sign',users:sortUsers(item)}));
})
}
function sortUsers(self){
let ary = new Array();
server.connections.forEach(function(item){
if (item==self) {
ary.unshift(item.nickName)
}else{
ary.push(item.nickName)
}
})
return ary;
}
| c508a640806d31d4f710685ffee954c9c1ab7019 | [
"JavaScript"
] | 1 | JavaScript | minsonl/node-websocket | fb219e376039ae1568aa7521bd1b36b6fbb7fb65 | 33a75dd1ac7fc9ba58f2f014a48b6ff25f5e04d5 |
refs/heads/master | <repo_name>AtliKarl/LabExercise07<file_sep>/sample.py
def divby5(i):
if int(i) % 5 == 0:
return True
else:
return False
def divby3(i):
if int(i) % 3 == 0:
return True
else:
return False
def both(i):
if divby3(i) and divby5(i):
return True
else:
return False
def main():
user_input = input("Enter an integer: ")
if user_input is not int:
print("Not an integer")
elif both(user_input):
print("FizzBuzz")
elif divby5(user_input):
print("Buzz")
elif divby3(user_input):
print("Fizz")
else:
print(str(user_input))
main()
| 6216f5c01ea6b6c2d42295fb4f148f5a49dc1795 | [
"Python"
] | 1 | Python | AtliKarl/LabExercise07 | 4549a5ea2882f4bc081677b1abc580d712ceb5e8 | daadec25ddc956f4dbfaae7d37f0e2729360b098 |
refs/heads/master | <repo_name>Edje-C/chalk<file_sep>/index.js
const chalk = require('chalk')
helloBlue = () => console.log(chalk.blue("Hello world"))
helloRed = () => console.log(chalk.red("Hello world"))
stringToColor = (str, color) => console.log(chalk[color](str))
evensBlueOddsYellow = str => str.split(" ").forEach((v,i)=>i%2? console.log(chalk.yellow(v)) : console.log(chalk.blue(v)))
angryText = str => console.log(chalk.red.underline.bold(str))
backgroundCyan = str => console.log(chalk.white.bgCyan(str))
boldFirstUnderlineLast = str => console.log(chalk.bold(str[0]) + str.substring(1,-1) + chalk.underline(str.slice(-1)))
commandLineChalk = str => {
console.log(chalk[process.argv[2]](process.argv.slice(3)))
}
commandLineChalk() | dcd0c6ef73025f042799c6c2b3928d5bfae30822 | [
"JavaScript"
] | 1 | JavaScript | Edje-C/chalk | 092a6ae2c09b45aa2a65a160a9606f2fadf54ec0 | 636db819fdf72a29f35a4361231f4c944fd77df9 |
refs/heads/master | <file_sep>/**
* @file
* @copyright defined in LICENSE.txt
*/
#include <eost.token/eost.token.hpp>
#include "../include/eost.token/eost.token.hpp"
namespace eost {
void token::create( name issuer,
asset maximum_supply,
bool transfer_locked)
{
require_auth( _self );
auto sym = maximum_supply.symbol;
eosio_assert( sym.is_valid(), "invalid symbol name" );
eosio_assert( maximum_supply.is_valid(), "invalid supply");
eosio_assert( maximum_supply.amount > 0, "max-supply must be positive");
stats statstable( _self, sym.code().raw() );
auto existing = statstable.find( sym.code().raw() );
eosio_assert( existing == statstable.end(), "token with symbol already exists" );
statstable.emplace( _self, [&]( auto& s ) {
s.supply.symbol = maximum_supply.symbol;
s.max_supply = maximum_supply;
s.issuer = issuer;
s.transfer_locked = transfer_locked;
});
}
void token::issue( name to, asset quantity, string memo )
{
auto sym = quantity.symbol;
eosio_assert( sym.is_valid(), "invalid symbol name" );
eosio_assert( memo.size() <= 256, "memo has more than 256 bytes" );
stats statstable( _self, sym.code().raw() );
auto existing = statstable.find( sym.code().raw() );
eosio_assert( existing != statstable.end(), "token with symbol does not exist, create token before issue" );
const auto& st = *existing;
require_auth( st.issuer );
eosio_assert( quantity.is_valid(), "invalid quantity" );
eosio_assert( quantity.amount > 0, "must issue positive quantity" );
eosio_assert( quantity.symbol == st.supply.symbol, "symbol precision mismatch" );
eosio_assert( quantity.amount <= st.max_supply.amount - st.supply.amount, "quantity exceeds available supply");
statstable.modify( st, same_payer, [&]( auto& s ) {
s.supply += quantity;
});
add_balance( st.issuer, quantity, st.issuer );
if( to != st.issuer ) {
SEND_INLINE_ACTION( *this, transfer, { {st.issuer, "active"_n} },
{ st.issuer, to, quantity, memo }
);
}
}
void token::issuelock( name to, asset quantity, string memo,uint64_t lock_time )
{
auto sym = quantity.symbol;
eosio_assert( sym.is_valid(), "invalid symbol name" );
eosio_assert( memo.size() <= 256, "memo has more than 256 bytes" );
stats statstable( _self, sym.code().raw() );
auto existing = statstable.find( sym.code().raw() );
eosio_assert( existing != statstable.end(), "token with symbol does not exist, create token before issue" );
const auto& st = *existing;
require_auth( st.issuer );
eosio_assert( quantity.is_valid(), "invalid quantity" );
eosio_assert( quantity.amount > 0, "must issue positive quantity" );
eosio_assert( quantity.symbol == st.supply.symbol, "symbol precision mismatch" );
eosio_assert( quantity.amount <= st.max_supply.amount - st.supply.amount, "quantity exceeds available supply");
statstable.modify( st, same_payer, [&]( auto& s ) {
s.supply += quantity;
});
add_balance( st.issuer, quantity, st.issuer );
if( to != st.issuer ) {
SEND_INLINE_ACTION( *this, transfer, { {st.issuer, "active"_n} },
{ st.issuer, to, quantity, memo }
);
}
auto payer = has_auth( to ) ? to : st.issuer;
lock(to,quantity,lock_time,payer);
}
void token::retire( asset quantity, string memo )
{
auto sym = quantity.symbol;
eosio_assert( sym.is_valid(), "invalid symbol name" );
eosio_assert( memo.size() <= 256, "memo has more than 256 bytes" );
stats statstable( _self, sym.code().raw() );
auto existing = statstable.find( sym.code().raw() );
eosio_assert( existing != statstable.end(), "token with symbol does not exist" );
const auto& st = *existing;
require_auth( st.issuer );
eosio_assert( quantity.is_valid(), "invalid quantity" );
eosio_assert( quantity.amount > 0, "must retire positive quantity" );
eosio_assert( quantity.symbol == st.supply.symbol, "symbol precision mismatch" );
statstable.modify( st, same_payer, [&]( auto& s ) {
s.supply -= quantity;
});
sub_balance( st.issuer, quantity );
}
void token::transfer( name from,
name to,
asset quantity,
string memo )
{
eosio_assert( from != to, "cannot transfer to self" );
require_auth( from );
eosio_assert(is_locked(from,quantity) == false,"must not lock");
eosio_assert( is_account( to ), "to account does not exist");
auto sym = quantity.symbol.code();
stats statstable( _self, sym.raw() );
const auto& st = statstable.get( sym.raw() );
if(st.transfer_locked) {
require_auth(st.issuer);
}
require_recipient( from );
require_recipient( to );
eosio_assert( quantity.is_valid(), "invalid quantity" );
eosio_assert( quantity.amount > 0, "must transfer positive quantity" );
eosio_assert( quantity.symbol == st.supply.symbol, "symbol precision mismatch" );
eosio_assert( memo.size() <= 256, "memo has more than 256 bytes" );
auto payer = has_auth( to ) ? to : from;
sub_balance( from, quantity );
add_balance( to, quantity, payer );
}
void token::sub_balance( name owner, asset value ) {
accounts from_acnts( _self, owner.value );
const auto& from = from_acnts.get( value.symbol.code().raw(), "no balance object found" );
eosio_assert( from.balance.amount >= value.amount, "overdrawn balance" );
from_acnts.modify( from, owner, [&]( auto& a ) {
a.balance -= value;
});
}
void token::add_balance( name owner, asset value, name ram_payer )
{
accounts to_acnts( _self, owner.value );
auto to = to_acnts.find( value.symbol.code().raw() );
if( to == to_acnts.end() ) {
to_acnts.emplace( ram_payer, [&]( auto& a ){
a.balance = value;
});
} else {
to_acnts.modify( to, same_payer, [&]( auto& a ) {
a.balance += value;
});
}
}
void token::open( name owner, const symbol& symbol, name ram_payer )
{
require_auth( ram_payer );
auto sym_code_raw = symbol.code().raw();
stats statstable( _self, sym_code_raw );
const auto& st = statstable.get( sym_code_raw, "symbol does not exist" );
eosio_assert( st.supply.symbol == symbol, "symbol precision mismatch" );
accounts acnts( _self, owner.value );
auto it = acnts.find( sym_code_raw );
if( it == acnts.end() ) {
acnts.emplace( ram_payer, [&]( auto& a ){
a.balance = asset{0, symbol};
});
}
}
void token::close( name owner, const symbol& symbol )
{
require_auth( owner );
accounts acnts( _self, owner.value );
auto it = acnts.find( symbol.code().raw() );
eosio_assert( it != acnts.end(), "Balance row already deleted or never existed. Action won't have any effect." );
eosio_assert( it->balance.amount == 0, "Cannot close because the balance is not zero." );
acnts.erase( it );
}
void token::cantransfer(asset quantity, bool is_transfer){
auto sym = quantity.symbol;
eosio_assert( sym.is_valid(), "invalid symbol name" );
stats statstable( _self, sym.code().raw() );
auto existing = statstable.find( sym.code().raw() );
eosio_assert( existing != statstable.end(), "token with symbol does not exist, create token before issue" );
const auto& st = *existing;
require_auth(st.issuer);
statstable.modify(st, same_payer, [&](auto &s) {
s.transfer_locked = is_transfer;
});
}
void token::lock(name to, asset quantity, uint64_t lock_time,name ram_payer){
auto sym = quantity.symbol;
lockers to_lockers( _self, to.value );
auto locker = to_lockers.find( quantity.symbol.code().raw() );
eosio_assert( locker == to_lockers.end(), "locker must not exist" );
time_point t {microseconds(current_time() + lock_time)};
to_lockers.emplace( ram_payer, [&]( auto& a ){
a.balance = quantity;
a.unlock_time = t;
a.lock_time = current_time_point();
});
}
bool token::is_locked(name owner, asset quantity){
auto sym = quantity.symbol;
lockers to_lockers( _self, owner.value );
auto locker = to_lockers.find( quantity.symbol.code().raw() );
if(locker == to_lockers.end()){
return false;
}
const auto& lk = *locker;
return (current_time_point() < lk.unlock_time);
}
void token::burn(name from, asset quantity) {
require_auth(from);
auto sym = quantity.symbol.code();
stats statstable(_self, sym.raw());
const auto &st = statstable.get(sym.raw(), "ERR::BURN_UNKNOWN_SYMBOL::Attempting to burn a token unknown to this contract");
eosio_assert(!st.transfer_locked, "ERR::BURN_LOCKED_TOKEN::Burn tokens on transferLocked token. The issuer must `unlock` first.");
require_recipient(from);
eosio_assert(quantity.is_valid(), "ERR::BURN_INVALID_QTY_::invalid quantity");
eosio_assert(quantity.amount > 0, "ERR::BURN_NON_POSITIVE_QTY_::must burn positive quantity");
eosio_assert(quantity.symbol == st.supply.symbol, "ERR::BURN_SYMBOL_MISMATCH::symbol precision mismatch");
sub_balance(from, quantity);
statstable.modify(st, name{}, [&](currency_stats &s) {
s.supply -= quantity;
s.max_supply -= quantity;
});
}
time_point token::current_time_point() {
const static time_point ct{ microseconds{ static_cast<int64_t>( current_time() ) } };
return ct;
}
} /// namespace eost
EOSIO_DISPATCH( eost::token, (create)(issue)(transfer)(open)(close)(retire)(cantransfer)(issuelock)(burn) )
<file_sep>cmake_minimum_required(VERSION 3.9)
project(eost_token)
find_package(eosio.cdt)
add_executable(eost_token
include/eost.token/eost.token.hpp
src/eost.token.cpp)
<file_sep># eost.token
The smart contract of the eost-transport token
<file_sep>/**
* @file
* @copyright defined in LICENSE.txt
*/
#pragma once
#include <eosiolib/asset.hpp>
#include <eosiolib/eosio.hpp>
#include <eosiolib/time.hpp>
#include <string>
namespace eosiosystem {
class system_contract;
}
using namespace eosio;
namespace eost {
using std::string;
class [[eosio::contract("eost.token")]] token : public contract {
public:
using contract::contract;
[[eosio::action]]
void create( name issuer,
asset maximum_supply,
bool transfer_locked);
[[eosio::action]]
void issue( name to, asset quantity, string memo);
[[eosio::action]]
void issuelock( name to, asset quantity, string memo,uint64_t lock_time );
[[eosio::action]]
void retire( asset quantity, string memo );
[[eosio::action]]
void transfer( name from,
name to,
asset quantity,
string memo );
[[eosio::action]]
void open( name owner, const symbol& symbol, name ram_payer );
[[eosio::action]]
void cantransfer(asset quantity, bool is_transfer);
[[eosio::action]]
void close( name owner, const symbol& symbol );
[[eosio::action]]
void burn(name from, asset quantity);
static asset get_supply( name token_contract_account, symbol_code sym_code )
{
stats statstable( token_contract_account, sym_code.raw() );
const auto& st = statstable.get( sym_code.raw() );
return st.supply;
}
static asset get_balance( name token_contract_account, name owner, symbol_code sym_code )
{
accounts accountstable( token_contract_account, owner.value );
const auto& ac = accountstable.get( sym_code.raw() );
return ac.balance;
}
private:
struct [[eosio::table]] account {
asset balance;
uint64_t primary_key()const { return balance.symbol.code().raw(); }
};
struct [[eosio::table]] currency_stats {
asset supply;
asset max_supply;
name issuer;
bool transfer_locked = false;
uint64_t primary_key()const { return supply.symbol.code().raw(); }
};
struct [[eosio::table]] locker {
asset balance;
time_point unlock_time;
time_point lock_time;
uint64_t primary_key() const {return balance.symbol.code().raw();}
};
typedef eosio::multi_index< "accounts"_n, account > accounts;
typedef eosio::multi_index< "stat"_n, currency_stats > stats;
typedef eosio::multi_index<"locker"_n, locker > lockers;
void sub_balance( name owner, asset value );
void add_balance( name owner, asset value, name ram_payer );
bool is_locked(name owner,asset quantity);
void lock(name to, asset quantity, uint64_t lock_time,name ram_payer);
static time_point current_time_point();
};
} /// namespace eosio
| ceed532bcd0a16d4762f996b76ee648a80efee66 | [
"Markdown",
"CMake",
"C++"
] | 4 | C++ | eos-transport/eost.token | b9c570823b3db9b3492215e2d785a5840dc85f6a | 8f168d66d95afeab0ec5748730a16e88bb063ad1 |
refs/heads/master | <file_sep>function socialShare(value) {
console.log ("You would like to share my post via "+value);
currentUrl = window.location.href;
targetUrl = "";
if (value == "facebook") {
sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=";
}
if (value == "twitter") {
sharerUrl = "https://twitter.com/intent/tweet?url=";
}
if (value == "mail") {
subject = "Ein interessanter Link auf niklas.stephan.de";
sharerUrl = "mailto:<EMAIL>?subject="+subject+"&body=";
}
if (value == "whatsapp") {
sharerUrl = "https://api.whatsapp.com/send?text=";
}
targetUrl = sharerUrl+currentUrl;
window.open(targetUrl,'_blank');
}
var i;
var command;
for (i = 0; i < document.images.length; i++) {
command = 'document.images['+i+'].addEventListener("click", function(){var url = document.images['+i+'].src;url = url.replace("https://assets.niklas-stephan.de/small?src=storage/uploads/","https://cms.niklas-stephan.de/storage/uploads/");window.open(url);});';
function text2script(){
return Function(command)();
}
text2script();
}
<file_sep>function cookieFunction() {
document.getElementById("cookie-notice").classList.add('d-none');
}
function activityWatcher(){
var secondsSinceLastActivity = 0;
function activity(){
secondsSinceLastActivity = 0;
cookieFunction();
document.removeEventListener("keydown", activity, true);
document.removeEventListener("scroll", activity, true);
}
document.addEventListener("scroll", activity, true);
document.addEventListener("keydown", activity, true);
}
function PageSpecificFunction() {
var path = window.location.pathname;
var page = path.split("/").pop();
if (page == "index.html" || page == "") {
}
}
function lang(){
document.getElementById("langSelector").classList.remove('d-none');
var userLang = navigator.language || navigator.userLanguage;
userLang = userLang.substring(0, 2);
var userUrl = window.location.pathname;
var userRef = document.referrer;
userRef = userRef.replace("qas.", "");
userRef = userRef.replace("www.", "");
if (userLang != "de" && userUrl != "/en.html" && userRef != "https://niklas-stephan.de/en.html") {
window.location.replace("https://niklas-stephan.de/en.html");
}
if (window.location.pathname == "/en.html") {
cookieFunction();
}
/*
const queryString = window.location.search;
var reqLang = "de";
if (queryString) {
const urlParams = new URLSearchParams(queryString);
console.log(urlParams);
reqLang = urlParams.get('lang');
console.log(reqLang);
}
*/
}
activityWatcher();
lang();
<file_sep># niklas-stephan.de
Digital Business Card and Blog of <NAME>.
Source files for templates.
LINK: https://niklas-stephan.de
## ToDos:
- enlarge images on hover or click in posts
- serve small thumbnails of pictures
- show links to articles with same tags on posts
<file_sep>function blockIE () {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
var page = window.location.pathname;
page = page.split("/").pop();
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))
{
if (page != "404.html") {
window.location.replace("/404.html");
}
}
}
console.log(`%c
MMMMMMMMMMMm++mMMMMMMMMMMM
MMMMMMMMMm+: :+mMMMMMMMMM
MMMMMMMm+: :+mMMMMMMM
MMMMMm yyy shhhy+.+mMMMMM
MMMm+: hdddy//+hddy :+mMMM
Mmo: hddy /ddd: :+mM
d- hddo :ddd: -d
Mmo: hdd+ :ddd: :omM
MMMmo: hdd+ :ddd::omMMM
MMMMMm+yyy/ -yyhomMMMMM
MMMMMMMm+: :+mMMMMMMM
MMMMMMMMMm+: :+mMMMMMMMMM
MMMMMMMMMMMm++mMMMMMMMMMMM
`,"color: #8945f8;font-family:monospace");
console.log("%cWelcome to niklas-stephan.de - v2021.1.1", "color: #8945f8;");
console.log("Client Date: "+new Date());
blockIE();<file_sep>var sortByGroup = document.querySelector('.sort-by-button-group');
sortByGroup.addEventListener('click', function (event) {
if (!matchesSelector(event.target, '.button')) {
return;
}
var sortValue = event.target.getAttribute('data-sort-value');
iso.arrange({ sortBy: sortValue });
});
var buttonGroups = document.querySelectorAll('.button-group');
for (var i = 0; i < buttonGroups.length; i++) {
buttonGroups[i].addEventListener('click', onButtonGroupClick);
};
function onButtonGroupClick(event) {
if (!matchesSelector(event.target, '.button')) {
return;
}
var button = event.target;
button.parentNode.querySelector('.is-checked').classList.remove('is-checked');
button.classList.add('is-checked');
};
function filterFunction() {
var input, filter, ul, li, a, i, txtValue;
input = document.getElementById('filterInput');
filter = input.value.toUpperCase();
ul = document.getElementById("filterContainer");
li = ul.getElementsByClassName('grid-item');
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
};
iso.layout();
};
var iso = new Isotope('.grid', {
itemSelector: '.element-item',
getSortData: {
name: '.name',
date: '.date'
},
sortBy: '.date',
percentPosition: true,
transitionDuration: '0.8s'
});
function filterTag(tag) {
document.getElementById("filterInput").value = tag;
document.getElementById("filterInput").dispatchEvent(new Event('keyup'));
};
function filterClear() {
document.getElementById("filterInput").value = '';
document.getElementById("filterInput").dispatchEvent(new Event('keyup'));
};
function clientDate () {
const currentTimestamp = Date.now();
var array = document.getElementsByClassName('clientDate').length;
var i;
for (i = 0; i < array; i++) {
var unixTimestamp = document.getElementsByClassName('clientDate')[i].innerHTML;
unixTimestamp = unixTimestamp * 1000;
const diff = currentTimestamp - unixTimestamp;
var seconds = diff / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
if (days < 1) {
if (hours < 1) {
difference = "wenigen Minuten";
} else {
if (Math.round(hours) < 2) {
difference = "einer Stunde"
} else {
if (Math.round(hours) == 24) {
difference = "einem Tag"
} else {
difference = Math.round(hours)+" Stunden";
}
}
}
} else {
if ( Math.round(days) < 2) {
difference = "einem Tag";
} else {
difference = Math.round(days)+ " Tagen";
}
}
document.getElementsByClassName('clientDate')[i].innerHTML = "vor "+difference;
}
};
clientDate();
setTimeout(function () { iso.layout(); }, 750); | 489c97f4d35261ed45460c4eddef7fdbe5c9e38a | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | handtrixx/website | bc21ae73e2cdcb865f75187342fd08847abdeba8 | 01757f2c74c0759f38dc2900499ca535574bbe46 |
refs/heads/master | <repo_name>nkiraly/jucipp<file_sep>/src/project_build.cc
#include "project_build.h"
#include "config.h"
std::unique_ptr<Project::Build> Project::Build::create(const boost::filesystem::path &path) {
std::unique_ptr<Project::Build> cmake(new CMakeBuild(path));
if(!cmake->project_path.empty())
return cmake;
else
return std::make_unique<Project::Build>();
}
boost::filesystem::path Project::Build::get_default_path() {
if(project_path.empty())
return boost::filesystem::path();
boost::filesystem::path default_build_path=Config::get().project.default_build_path;
const std::string path_variable_project_directory_name="<project_directory_name>";
size_t pos=0;
auto default_build_path_string=default_build_path.string();
auto path_filename_string=project_path.filename().string();
while((pos=default_build_path_string.find(path_variable_project_directory_name, pos))!=std::string::npos) {
default_build_path_string.replace(pos, path_variable_project_directory_name.size(), path_filename_string);
pos+=path_filename_string.size();
}
if(pos!=0)
default_build_path=default_build_path_string;
if(default_build_path.is_relative())
default_build_path=project_path/default_build_path;
return default_build_path;
}
boost::filesystem::path Project::Build::get_debug_path() {
if(project_path.empty())
return boost::filesystem::path();
boost::filesystem::path debug_build_path=Config::get().project.debug_build_path;
const std::string path_variable_project_directory_name="<project_directory_name>";
size_t pos=0;
auto debug_build_path_string=debug_build_path.string();
auto path_filename_string=project_path.filename().string();
while((pos=debug_build_path_string.find(path_variable_project_directory_name, pos))!=std::string::npos) {
debug_build_path_string.replace(pos, path_variable_project_directory_name.size(), path_filename_string);
pos+=path_filename_string.size();
}
if(pos!=0)
debug_build_path=debug_build_path_string;
const std::string path_variable_default_build_path="<default_build_path>";
pos=0;
debug_build_path_string=debug_build_path.string();
auto default_build_path=Config::get().project.default_build_path;
while((pos=debug_build_path_string.find(path_variable_default_build_path, pos))!=std::string::npos) {
debug_build_path_string.replace(pos, path_variable_default_build_path.size(), default_build_path);
pos+=default_build_path.size();
}
if(pos!=0)
debug_build_path=debug_build_path_string;
if(debug_build_path.is_relative())
debug_build_path=project_path/debug_build_path;
return debug_build_path;
}
Project::CMakeBuild::CMakeBuild(const boost::filesystem::path &path) : Project::Build(), cmake(path) {
project_path=cmake.project_path;
}
bool Project::CMakeBuild::update_default(bool force) {
return cmake.update_default_build(get_default_path(), force);
}
bool Project::CMakeBuild::update_debug(bool force) {
return cmake.update_debug_build(get_debug_path(), force);
}
boost::filesystem::path Project::CMakeBuild::get_executable(const boost::filesystem::path &path) {
return cmake.get_executable(path);
}
| 559aa185b5222b614d6c724febd6e496fcbdbcb6 | [
"C++"
] | 1 | C++ | nkiraly/jucipp | 715997ac1d1fab37f8701aec4232a35fa736d5c5 | 80930b6afbed1293097e33b7d99bc52b75cdd101 |
refs/heads/master | <file_sep>package com.spring_cloud.open_fegin.service;
import org.apache.catalina.User;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
* 用于UserService出差时的服务降级,
*/
@Component
@RequestMapping("/dan") //防止请求地址冲突
public class UserServiceFallback {
public List<User> getAllUser(){
return new ArrayList<>();
}
public User getUserByName(String name){
return null;
}
}
<file_sep>
spring.application.name=client1
spring.cloud.config.profile=dev
spring.cloud.config.label=master
spring.cloud.config.uri=http://localhost:9070
server.port=9071 | 5ff24dbf33308fe2038cfb7d1590bdecc219a635 | [
"Java",
"INI"
] | 2 | Java | 18376108492/spring_cloud_demo | b3fe558b7ec29510d9741ebdfffc7eb94f0a77c4 | cd29a7454cba99d601ec999ea319b9c8066139c1 |
refs/heads/master | <file_sep><?php declare(strict_types=1);
namespace Middleware\Auth\Jwt\Services;
use Firebase\JWT\JWT;
use Middleware\Auth\Jwt\Exceptions\JwtTokenDecodeException;
use Middleware\Auth\Jwt\Exceptions\TokenEncoderInitializeException;
use Throwable;
class TokenEncoder
{
/**
* @var string
*/
private $secret;
/**
* @var string
*/
private $algo;
/**
* @var int
*/
private $expiration;
public function __construct(string $secret, string $algo, int $expiration)
{
$this->validateSecret($secret);
$this->validateAlgo($algo);
$this->validateExpiration($expiration);
$this->secret = $secret;
$this->algo = $algo;
$this->expiration = $expiration;
}
public function encode(array $payload): string
{
$payload['exp'] = strtotime(sprintf('+%d minutes', $this->expiration));
return JWT::encode($payload, $this->secret, $this->algo);
}
public function decode(string $token): array
{
try {
$payload = (array) JWT::decode($token, $this->secret, [$this->algo]);
unset($payload['exp']);
return $payload;
} catch (Throwable $e) {
throw new JwtTokenDecodeException('Token decoding failed');
}
}
private function validateSecret(string $secret): void
{
if ($secret === '') {
throw new TokenEncoderInitializeException('Secret must not be empty');
}
}
private function validateAlgo(string $algo): void
{
if ($algo === '') {
throw new TokenEncoderInitializeException('Algo must not be empty');
}
}
private function validateExpiration(int $expiration): void
{
if ($expiration === 0) {
throw new TokenEncoderInitializeException('Expiration must be greater than zero');
}
}
}
| a4d0a18c5c08a9d88b6a97e22b89d26792ce9cd2 | [
"PHP"
] | 1 | PHP | borzi/laravel-jwt-auth | bb7901e3e728c5a59650a38a6e20b1705b11be60 | 224bdb690395c2f5b1dc0d53224c2f07204ab547 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.